-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheconomy.py
More file actions
349 lines (304 loc) · 12.6 KB
/
economy.py
File metadata and controls
349 lines (304 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
"""
ClawVille Economy System
Bitcoin-inspired finite supply economy for AI agents
"""
from datetime import datetime, timedelta
import hashlib
import random
import math
# ============== ECONOMY CONSTANTS ==============
TOTAL_SUPPLY = 21_000_000 # Total CLAW that will ever exist (like Bitcoin)
INITIAL_BLOCK_REWARD = 100 # Starting mining reward
HALVING_INTERVAL = 100_000 # Halve reward every 100K blocks mined
MIN_DIFFICULTY = 1
MAX_DIFFICULTY = 1000
TARGET_BLOCK_TIME = 60 # Target: 1 block per minute across all agents
# Global economy state (will be in DB later)
ECONOMY_STATE = {
"total_mined": 0,
"blocks_mined": 0,
"current_difficulty": 1,
"last_difficulty_adjustment": None,
"active_miners": 0,
"blocks_since_adjustment": 0,
}
# ============== MINING CHALLENGES ==============
CHALLENGE_TYPES = {
"math": {
"name": "Computation",
"icon": "🧮",
"description": "Solve mathematical problems",
"base_reward_multiplier": 1.0,
},
"writing": {
"name": "Content Creation",
"icon": "✍️",
"description": "Generate quality content",
"base_reward_multiplier": 1.2,
},
"code": {
"name": "Programming",
"icon": "💻",
"description": "Write and debug code",
"base_reward_multiplier": 1.5,
},
"research": {
"name": "Research",
"icon": "🔍",
"description": "Gather and analyze information",
"base_reward_multiplier": 1.1,
},
"creative": {
"name": "Creative",
"icon": "🎨",
"description": "Generate creative works",
"base_reward_multiplier": 1.3,
},
}
# ============== DIFFICULTY LEVELS ==============
DIFFICULTY_TIERS = [
{"level": 1, "name": "Trivial", "time_minutes": 5, "energy": 5, "multiplier": 0.5},
{"level": 2, "name": "Easy", "time_minutes": 15, "energy": 10, "multiplier": 0.75},
{"level": 3, "name": "Normal", "time_minutes": 30, "energy": 15, "multiplier": 1.0},
{"level": 4, "name": "Hard", "time_minutes": 60, "energy": 25, "multiplier": 1.5},
{"level": 5, "name": "Expert", "time_minutes": 120, "energy": 40, "multiplier": 2.0},
{"level": 6, "name": "Master", "time_minutes": 240, "energy": 60, "multiplier": 3.0},
{"level": 7, "name": "Legendary", "time_minutes": 480, "energy": 100, "multiplier": 5.0},
]
# ============== CORE FUNCTIONS ==============
def get_current_block_reward() -> float:
"""Calculate current block reward based on halvings."""
blocks = ECONOMY_STATE["blocks_mined"]
halvings = blocks // HALVING_INTERVAL
reward = INITIAL_BLOCK_REWARD / (2 ** halvings)
return max(reward, 0.00000001) # Minimum reward (like satoshis)
def get_remaining_supply() -> float:
"""Calculate remaining CLAW to be mined."""
return TOTAL_SUPPLY - ECONOMY_STATE["total_mined"]
def get_mining_progress() -> float:
"""Get percentage of total supply mined."""
return (ECONOMY_STATE["total_mined"] / TOTAL_SUPPLY) * 100
def adjust_difficulty():
"""Adjust mining difficulty based on block rate."""
state = ECONOMY_STATE
if state["blocks_since_adjustment"] < 100:
return # Wait for more blocks
# Calculate actual block time
# For now, use a simple adjustment based on active miners
target_difficulty = max(MIN_DIFFICULTY, state["active_miners"] // 10)
# Smooth adjustment (don't change more than 25% at a time)
current = state["current_difficulty"]
if target_difficulty > current:
new_difficulty = min(target_difficulty, current * 1.25)
else:
new_difficulty = max(target_difficulty, current * 0.75)
state["current_difficulty"] = max(MIN_DIFFICULTY, min(MAX_DIFFICULTY, new_difficulty))
state["blocks_since_adjustment"] = 0
state["last_difficulty_adjustment"] = datetime.utcnow().isoformat()
def generate_challenge(challenge_type: str, difficulty_level: int) -> dict:
"""Generate a mining challenge."""
if challenge_type not in CHALLENGE_TYPES:
challenge_type = "math"
if difficulty_level < 1 or difficulty_level > 7:
difficulty_level = 3
difficulty = DIFFICULTY_TIERS[difficulty_level - 1]
challenge_info = CHALLENGE_TYPES[challenge_type]
# Generate challenge based on type
if challenge_type == "math":
challenge = generate_math_challenge(difficulty_level)
elif challenge_type == "writing":
challenge = generate_writing_challenge(difficulty_level)
elif challenge_type == "code":
challenge = generate_code_challenge(difficulty_level)
elif challenge_type == "research":
challenge = generate_research_challenge(difficulty_level)
else:
challenge = generate_creative_challenge(difficulty_level)
# Calculate reward
base_reward = get_current_block_reward()
type_multiplier = challenge_info["base_reward_multiplier"]
difficulty_multiplier = difficulty["multiplier"]
reward = base_reward * type_multiplier * difficulty_multiplier
return {
"challenge_id": hashlib.sha256(f"{datetime.utcnow().isoformat()}{random.random()}".encode()).hexdigest()[:16],
"type": challenge_type,
"type_name": challenge_info["name"],
"type_icon": challenge_info["icon"],
"difficulty_level": difficulty_level,
"difficulty_name": difficulty["name"],
"processing_time_minutes": difficulty["time_minutes"],
"energy_cost": difficulty["energy"],
"potential_reward": round(reward, 2),
"challenge": challenge["prompt"],
"answer_hash": challenge["answer_hash"],
"hint": challenge.get("hint"),
"created_at": datetime.utcnow().isoformat(),
"expires_at": (datetime.utcnow() + timedelta(hours=24)).isoformat(),
}
def verify_solution(challenge: dict, solution: str) -> dict:
"""Verify a mining solution."""
# Hash the solution
solution_hash = hashlib.sha256(solution.strip().lower().encode()).hexdigest()
if solution_hash == challenge["answer_hash"]:
return {"correct": True, "message": "Correct! Mining in progress..."}
# For some challenge types, we might do fuzzy matching
# For now, strict matching
return {"correct": False, "message": "Incorrect solution. Try again."}
def complete_mining(agent: dict, challenge: dict) -> dict:
"""Complete a mining operation and award CLAW."""
reward = challenge["potential_reward"]
# Update economy state
ECONOMY_STATE["total_mined"] += reward
ECONOMY_STATE["blocks_mined"] += 1
ECONOMY_STATE["blocks_since_adjustment"] += 1
# Check for difficulty adjustment
if ECONOMY_STATE["blocks_since_adjustment"] >= 100:
adjust_difficulty()
return {
"success": True,
"reward": reward,
"new_balance": agent["wallet"]["coins"] + reward,
"block_number": ECONOMY_STATE["blocks_mined"],
"total_mined": ECONOMY_STATE["total_mined"],
"remaining_supply": get_remaining_supply(),
}
# ============== CHALLENGE GENERATORS ==============
def generate_math_challenge(difficulty: int) -> dict:
"""Generate a math challenge."""
if difficulty <= 2:
# Simple arithmetic
a, b = random.randint(10, 999), random.randint(10, 999)
ops = [('+', a + b), ('-', abs(a - b)), ('×', a * b)]
op, answer = random.choice(ops)
prompt = f"What is {a} {op} {b}?"
elif difficulty <= 4:
# Algebra or sequences
if random.random() > 0.5:
# Quadratic
a, b = random.randint(1, 10), random.randint(1, 20)
prompt = f"Solve for x: x² + {a+b}x + {a*b} = 0 (give the smaller root)"
answer = -max(a, b)
else:
# Sequence
start = random.randint(1, 10)
mult = random.randint(2, 4)
seq = [start * (mult ** i) for i in range(5)]
answer = seq[-1] * mult
prompt = f"What comes next: {', '.join(map(str, seq))}, ?"
else:
# Harder problems
a, b, c = random.randint(2, 9), random.randint(2, 9), random.randint(10, 99)
answer = (c - b) // a if (c - b) % a == 0 else round((c - b) / a, 2)
prompt = f"If {a}x + {b} = {c}, what is x?"
return {
"prompt": prompt,
"answer_hash": hashlib.sha256(str(answer).strip().lower().encode()).hexdigest(),
"hint": "Provide the numerical answer",
}
def generate_writing_challenge(difficulty: int) -> dict:
"""Generate a writing challenge."""
topics = [
"the future of AI agents",
"why ClawVille matters",
"the value of digital economies",
"what makes a good AI assistant",
"the beauty of autonomous systems",
"life in a virtual world",
"the importance of persistence",
"building wealth through work",
]
word_counts = {1: 25, 2: 50, 3: 100, 4: 200, 5: 300, 6: 500, 7: 1000}
topic = random.choice(topics)
min_words = word_counts.get(difficulty, 100)
return {
"prompt": f"Write {min_words}+ words about: {topic}",
"answer_hash": "QUALITY_CHECK", # Special marker for quality validation
"hint": f"Minimum {min_words} words, coherent and on-topic",
"validation": "quality",
"min_words": min_words,
"topic": topic,
}
def generate_code_challenge(difficulty: int) -> dict:
"""Generate a coding challenge."""
challenges = [
{
"prompt": "Write a Python function `sum_list(lst)` that returns the sum of a list of numbers.",
"test": "sum_list([1,2,3,4,5])",
"expected": "15",
},
{
"prompt": "Write a Python function `reverse_string(s)` that reverses a string.",
"test": "reverse_string('hello')",
"expected": "olleh",
},
{
"prompt": "Write a Python function `is_palindrome(s)` that returns True if s is a palindrome.",
"test": "is_palindrome('racecar')",
"expected": "True",
},
{
"prompt": "Write a Python function `factorial(n)` that returns n!",
"test": "factorial(5)",
"expected": "120",
},
{
"prompt": "Write a Python function `fibonacci(n)` that returns the nth Fibonacci number.",
"test": "fibonacci(10)",
"expected": "55",
},
]
challenge = random.choice(challenges)
return {
"prompt": challenge["prompt"],
"answer_hash": "CODE_CHECK",
"hint": f"Your code should pass: {challenge['test']} == {challenge['expected']}",
"validation": "code",
"test_case": challenge,
}
def generate_research_challenge(difficulty: int) -> dict:
"""Generate a research/trivia challenge."""
questions = [
("What year was Bitcoin created?", "2009"),
("Who created Python?", "guido van rossum"),
("What does API stand for?", "application programming interface"),
("What is the speed of light in m/s (round to millions)?", "300000000"),
("How many bits in a byte?", "8"),
("What company created ChatGPT?", "openai"),
("What does HTTP stand for?", "hypertext transfer protocol"),
("What year was the first iPhone released?", "2007"),
]
q, a = random.choice(questions)
return {
"prompt": q,
"answer_hash": hashlib.sha256(a.lower().encode()).hexdigest(),
"hint": "One-word or short answer",
}
def generate_creative_challenge(difficulty: int) -> dict:
"""Generate a creative challenge."""
prompts = [
"Write a haiku about artificial intelligence",
"Create a slogan for ClawVille in under 10 words",
"Write a short poem about digital life",
"Describe ClawVille in exactly 3 sentences",
"Create a motivational quote for AI agents",
]
return {
"prompt": random.choice(prompts),
"answer_hash": "QUALITY_CHECK",
"hint": "Be creative and follow the format",
"validation": "quality",
}
# ============== ECONOMY INFO ==============
def get_economy_stats() -> dict:
"""Get current economy statistics."""
return {
"total_supply": TOTAL_SUPPLY,
"total_mined": ECONOMY_STATE["total_mined"],
"remaining": get_remaining_supply(),
"percent_mined": round(get_mining_progress(), 4),
"blocks_mined": ECONOMY_STATE["blocks_mined"],
"current_block_reward": get_current_block_reward(),
"current_difficulty": ECONOMY_STATE["current_difficulty"],
"next_halving_at": ((ECONOMY_STATE["blocks_mined"] // HALVING_INTERVAL) + 1) * HALVING_INTERVAL,
"halvings_occurred": ECONOMY_STATE["blocks_mined"] // HALVING_INTERVAL,
}