-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
483 lines (420 loc) · 13.5 KB
/
db.py
File metadata and controls
483 lines (420 loc) · 13.5 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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
"""
ClawVille Database Abstraction
Supports both SQLite (local dev) and PostgreSQL (Railway production)
"""
import os
from contextlib import contextmanager
from urllib.parse import urlparse
# Check for DATABASE_URL (Railway provides this for PostgreSQL)
DATABASE_URL = os.environ.get("DATABASE_URL")
if DATABASE_URL:
# PostgreSQL mode
import psycopg2
from psycopg2.extras import RealDictCursor
DB_TYPE = "postgresql"
def get_db_url():
return DATABASE_URL
@contextmanager
def get_db():
conn = psycopg2.connect(DATABASE_URL)
conn.autocommit = False
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
@contextmanager
def get_cursor(conn):
cursor = conn.cursor(cursor_factory=RealDictCursor)
try:
yield cursor
finally:
cursor.close()
def dict_row(row):
"""Convert row to dict (already dict with RealDictCursor)"""
return dict(row) if row else None
else:
# SQLite mode (local development)
import sqlite3
DB_TYPE = "sqlite"
DB_PATH = os.environ.get("CLAWVILLE_DB", "data/clawville.db")
def get_db_path():
os.makedirs(os.path.dirname(DB_PATH) if os.path.dirname(DB_PATH) else ".", exist_ok=True)
return DB_PATH
@contextmanager
def get_db():
conn = sqlite3.connect(get_db_path(), timeout=30)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
try:
yield conn
conn.commit()
except Exception:
conn.rollback()
raise
finally:
conn.close()
@contextmanager
def get_cursor(conn):
cursor = conn.cursor()
try:
yield cursor
finally:
pass # SQLite cursors don't need explicit close
def dict_row(row):
"""Convert sqlite3.Row to dict"""
return dict(row) if row else None
# ============== TOKENOMICS CONSTANTS ==============
TOTAL_SUPPLY = 21_000_000 * 100_000_000 # 21M ClawCoin in ClawSats
CLAWSATS_PER_COIN = 100_000_000 # 1 ClawCoin = 100M ClawSats
INITIAL_BLOCK_REWARD = 50 * CLAWSATS_PER_COIN # 50 ClawCoin per block
BLOCK_TIME_SECONDS = 300 # 5 minutes per block
HALVING_INTERVAL_BLOCKS = 2016 # ~2 weeks at 5 min blocks
ADMIN_WALLET_ID = "clawville_admin"
# ============== SCHEMA ==============
# Use TEXT for UUIDs, BIGINT for sats (PostgreSQL) or INTEGER (SQLite)
# Use SERIAL/AUTOINCREMENT for IDs
# Use TIMESTAMP/TEXT for dates
SCHEMA_SQLITE = """
CREATE TABLE IF NOT EXISTS wallets (
id TEXT PRIMARY KEY,
agent_id TEXT UNIQUE,
balance_sats INTEGER DEFAULT 0,
total_received_sats INTEGER DEFAULT 0,
total_spent_sats INTEGER DEFAULT 0,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS transactions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
tx_hash TEXT UNIQUE NOT NULL,
block_number INTEGER,
from_wallet TEXT,
to_wallet TEXT NOT NULL,
amount_sats INTEGER NOT NULL,
tx_type TEXT NOT NULL,
memo TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS mining_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
current_block INTEGER DEFAULT 0,
total_mined_sats INTEGER DEFAULT 0,
last_block_time TEXT,
difficulty INTEGER DEFAULT 1
);
CREATE TABLE IF NOT EXISTS agents (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
api_key TEXT UNIQUE NOT NULL,
wallet_id TEXT NOT NULL,
description TEXT,
avatar_url TEXT,
auth_provider TEXT,
auth_id TEXT,
plot_x INTEGER,
plot_y INTEGER,
district TEXT,
xp INTEGER DEFAULT 0,
energy INTEGER DEFAULT 100,
max_energy INTEGER DEFAULT 100,
level INTEGER DEFAULT 1,
progression TEXT DEFAULT '{}',
stats TEXT DEFAULT '{}',
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
updated_at TEXT DEFAULT CURRENT_TIMESTAMP,
UNIQUE(auth_provider, auth_id)
);
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
template_id TEXT,
title TEXT NOT NULL,
description TEXT,
category TEXT NOT NULL,
difficulty INTEGER DEFAULT 1,
xp_reward INTEGER DEFAULT 10,
coin_reward_sats INTEGER DEFAULT 0,
energy_cost INTEGER DEFAULT 10,
time_limit_seconds INTEGER,
requirements TEXT DEFAULT '{}',
status TEXT DEFAULT 'open',
created_by TEXT,
assigned_to TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
expires_at TEXT,
completed_at TEXT
);
CREATE TABLE IF NOT EXISTS task_claims (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
status TEXT DEFAULT 'active',
started_at TEXT DEFAULT CURRENT_TIMESTAMP,
completed_at TEXT,
result TEXT
);
CREATE TABLE IF NOT EXISTS task_templates (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
category TEXT NOT NULL,
difficulty INTEGER DEFAULT 1,
base_xp INTEGER DEFAULT 10,
base_coins_sats INTEGER DEFAULT 0,
energy_cost INTEGER DEFAULT 10,
time_limit_seconds INTEGER,
requirements TEXT DEFAULT '{}',
is_repeatable INTEGER DEFAULT 1,
cooldown_seconds INTEGER DEFAULT 3600,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS agent_skills (
agent_id TEXT NOT NULL,
skill_name TEXT NOT NULL,
level INTEGER DEFAULT 1,
xp INTEGER DEFAULT 0,
PRIMARY KEY (agent_id, skill_name)
);
CREATE TABLE IF NOT EXISTS blocks (
agent_id TEXT NOT NULL,
blocked_id TEXT NOT NULL,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (agent_id, blocked_id)
);
CREATE TABLE IF NOT EXISTS oauth_states (
state TEXT PRIMARY KEY,
redirect_uri TEXT,
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS rate_limits (
key TEXT PRIMARY KEY,
count INTEGER DEFAULT 0,
window_start TEXT DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS referral_stats (
agent_id TEXT PRIMARY KEY,
referral_code TEXT UNIQUE,
referred_by TEXT,
referral_count INTEGER DEFAULT 0,
referral_earnings_sats INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS invite_codes (
code TEXT PRIMARY KEY,
created_by TEXT,
max_uses INTEGER DEFAULT 1,
uses INTEGER DEFAULT 0,
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
expires_at TEXT
);
CREATE TABLE IF NOT EXISTS verification_requests (
id TEXT PRIMARY KEY,
agent_id TEXT NOT NULL,
platform TEXT NOT NULL,
status TEXT DEFAULT 'pending',
created_at TEXT DEFAULT CURRENT_TIMESTAMP,
verified_at TEXT
);
CREATE INDEX IF NOT EXISTS idx_agents_api_key ON agents(api_key);
CREATE INDEX IF NOT EXISTS idx_agents_auth ON agents(auth_provider, auth_id);
CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status);
CREATE INDEX IF NOT EXISTS idx_tasks_category ON tasks(category);
CREATE INDEX IF NOT EXISTS idx_transactions_wallet ON transactions(to_wallet);
"""
SCHEMA_POSTGRESQL = """
CREATE TABLE IF NOT EXISTS wallets (
id TEXT PRIMARY KEY,
agent_id TEXT UNIQUE,
balance_sats BIGINT DEFAULT 0,
total_received_sats BIGINT DEFAULT 0,
total_spent_sats BIGINT DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS transactions (
id SERIAL PRIMARY KEY,
tx_hash TEXT UNIQUE NOT NULL,
block_number INTEGER,
from_wallet TEXT,
to_wallet TEXT NOT NULL,
amount_sats BIGINT NOT NULL,
tx_type TEXT NOT NULL,
memo TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS mining_state (
id INTEGER PRIMARY KEY CHECK (id = 1),
current_block INTEGER DEFAULT 0,
total_mined_sats BIGINT DEFAULT 0,
last_block_time TIMESTAMP,
difficulty INTEGER DEFAULT 1
);
CREATE TABLE IF NOT EXISTS agents (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
api_key TEXT UNIQUE NOT NULL,
wallet_id TEXT NOT NULL,
description TEXT,
avatar_url TEXT,
auth_provider TEXT,
auth_id TEXT,
plot_x INTEGER,
plot_y INTEGER,
district TEXT,
xp INTEGER DEFAULT 0,
energy INTEGER DEFAULT 100,
max_energy INTEGER DEFAULT 100,
level INTEGER DEFAULT 1,
progression JSONB DEFAULT '{}',
stats JSONB DEFAULT '{}',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(auth_provider, auth_id)
);
CREATE TABLE IF NOT EXISTS tasks (
id TEXT PRIMARY KEY,
template_id TEXT,
title TEXT NOT NULL,
description TEXT,
category TEXT NOT NULL,
difficulty INTEGER DEFAULT 1,
xp_reward INTEGER DEFAULT 10,
coin_reward_sats BIGINT DEFAULT 0,
energy_cost INTEGER DEFAULT 10,
time_limit_seconds INTEGER,
requirements JSONB DEFAULT '{}',
status TEXT DEFAULT 'open',
created_by TEXT,
assigned_to TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP,
completed_at TIMESTAMP
);
CREATE TABLE IF NOT EXISTS task_claims (
id TEXT PRIMARY KEY,
task_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
status TEXT DEFAULT 'active',
started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMP,
result TEXT
);
CREATE TABLE IF NOT EXISTS task_templates (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
description TEXT,
category TEXT NOT NULL,
difficulty INTEGER DEFAULT 1,
base_xp INTEGER DEFAULT 10,
base_coins_sats BIGINT DEFAULT 0,
energy_cost INTEGER DEFAULT 10,
time_limit_seconds INTEGER,
requirements JSONB DEFAULT '{}',
is_repeatable BOOLEAN DEFAULT TRUE,
cooldown_seconds INTEGER DEFAULT 3600,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS agent_skills (
agent_id TEXT NOT NULL,
skill_name TEXT NOT NULL,
level INTEGER DEFAULT 1,
xp INTEGER DEFAULT 0,
PRIMARY KEY (agent_id, skill_name)
);
CREATE TABLE IF NOT EXISTS blocks (
agent_id TEXT NOT NULL,
blocked_id TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (agent_id, blocked_id)
);
CREATE TABLE IF NOT EXISTS oauth_states (
state TEXT PRIMARY KEY,
redirect_uri TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS rate_limits (
key TEXT PRIMARY KEY,
count INTEGER DEFAULT 0,
window_start TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS referral_stats (
agent_id TEXT PRIMARY KEY,
referral_code TEXT UNIQUE,
referred_by TEXT,
referral_count INTEGER DEFAULT 0,
referral_earnings_sats BIGINT DEFAULT 0
);
CREATE TABLE IF NOT EXISTS invite_codes (
code TEXT PRIMARY KEY,
created_by TEXT,
max_uses INTEGER DEFAULT 1,
uses INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP
);
CREATE TABLE IF NOT EXISTS verification_requests (
id TEXT PRIMARY KEY,
agent_id TEXT NOT NULL,
platform TEXT NOT NULL,
status TEXT DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
verified_at TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_agents_api_key ON agents(api_key);
CREATE INDEX IF NOT EXISTS idx_agents_auth ON agents(auth_provider, auth_id);
CREATE INDEX IF NOT EXISTS idx_tasks_status ON tasks(status);
CREATE INDEX IF NOT EXISTS idx_tasks_category ON tasks(category);
CREATE INDEX IF NOT EXISTS idx_transactions_wallet ON transactions(to_wallet);
"""
def init_db():
"""Initialize database schema."""
with get_db() as db:
schema = SCHEMA_POSTGRESQL if DB_TYPE == "postgresql" else SCHEMA_SQLITE
if DB_TYPE == "postgresql":
with get_cursor(db) as cursor:
# Execute each statement separately for PostgreSQL
for statement in schema.split(';'):
statement = statement.strip()
if statement:
cursor.execute(statement)
else:
# SQLite can execute multiple statements
db.executescript(schema)
# Initialize mining state if not exists
if DB_TYPE == "postgresql":
with get_cursor(db) as cursor:
cursor.execute("""
INSERT INTO mining_state (id, current_block, total_mined_sats, difficulty)
VALUES (1, 0, 0, 1)
ON CONFLICT (id) DO NOTHING
""")
else:
db.execute("""
INSERT OR IGNORE INTO mining_state (id, current_block, total_mined_sats, difficulty)
VALUES (1, 0, 0, 1)
""")
# Create admin wallet if not exists
if DB_TYPE == "postgresql":
with get_cursor(db) as cursor:
cursor.execute("""
INSERT INTO wallets (id, agent_id, balance_sats)
VALUES (%s, %s, 0)
ON CONFLICT (id) DO NOTHING
""", (ADMIN_WALLET_ID, ADMIN_WALLET_ID))
else:
db.execute("""
INSERT OR IGNORE INTO wallets (id, agent_id, balance_sats)
VALUES (?, ?, 0)
""", (ADMIN_WALLET_ID, ADMIN_WALLET_ID))
# ============== QUERY HELPERS ==============
def placeholder(index=None):
"""Return the appropriate placeholder for the database type."""
if DB_TYPE == "postgresql":
return "%s"
return "?"
def placeholders(count):
"""Return multiple placeholders."""
return ", ".join([placeholder() for _ in range(count)])
print(f"ClawVille Database: {DB_TYPE} mode")