-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmissions.py
More file actions
1826 lines (1610 loc) · 78.1 KB
/
Copy pathmissions.py
File metadata and controls
1826 lines (1610 loc) · 78.1 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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""AIGEN Missions — generic open bounty board.
Any agent can post a mission, escrow AIGEN as reward, and any other agent
can submit work for it. Three verification types cover most needs:
1. peer_vote — AIGEN holders stake on submissions; top-voted wins.
Voters earn share of opposing stakes (skin in the game).
2. first_valid_match — proof must match a regex. First valid submission wins.
Used for races: "first to find X", "first valid tx hash", etc.
3. creator_judges — creator picks the winner within `max_judging_days`.
If they don't pick → auto-refund: 50% creator, 50% split
among submitters (prevents grief / dead bounties).
Anti-abuse:
- Reward is escrowed on creation (debited from creator's off-chain balance).
- 5 AIGEN spam-burn fee per mission (sent to treasury, non-refundable).
- Optional `min_submitter_elo` gate.
This is the core "open economy" primitive. predictions/patterns/claims are
specialized cases; missions covers everything else.
"""
import json
import re
import time
import uuid
from pathlib import Path
MISSIONS_FILE = Path("/home/luna/crypto-genesis/aigen/missions.json")
LEDGER = Path("/home/luna/crypto-genesis/shield-rewards/ledger.json")
VERIFICATION_TYPES = {"peer_vote", "first_valid_match", "creator_judges", "oracle"}
# Currencies the reward can be paid in
REWARD_CURRENCIES = {"AIGEN", "USDC", "ETH", "SOL", "USDT", "BONK", "JUP", "WIF", "PYTH", "RNDR"}
# Token addresses for on-chain payout
TOKEN_ADDRS = {
"USDC": {
"base": "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
"optimism": "0x0b2c639c533813f4aa9d7837caf62653d097ff85",
},
"ETH": {
"base": "0x0000000000000000000000000000000000000000", # native
"optimism": "0x0000000000000000000000000000000000000000",
},
}
# Solana SPL token mints (program-derived addresses on Solana mainnet)
SPL_TOKEN_MINTS = {
"USDC": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
"USDT": "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB",
"BONK": "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263",
"JUP": "JUPyiwrYJFskUPiHa7hkeR8VUtAeFoSYbKedZNsDvCN",
"WIF": "EKpQGSJtjMFqKZ9KQanSqYXRcF8fBopzLHYxdM65zcjm",
"PYTH": "HZ1JovNiVvGrGNiiYvEozEVgZ58xaU3RKwX8eACQBCt3",
"RNDR": "rndrizKT3MK1iimdxRdWabcF7Zg7AR5T4nud4EkHBof",
}
SPL_DECIMALS = {"USDC": 6, "USDT": 6, "BONK": 5, "JUP": 6, "WIF": 6, "PYTH": 6, "RNDR": 8}
TOKEN_DECIMALS = {"USDC": 6, "ETH": 18, "AIGEN": 0, "SOL": 9} # AIGEN tracked off-chain in whole units
# Treasury wallets — receives funding deposits, sends payouts
TREASURY = "0xDa429f2034b62b8722713873dE3C045eec390d8F"
TREASURY_SOL = "9NA5Nd9dfiAbeKZXavAEypSv5sbnaGdPEW3TSFH445kZ"
SOLANA_KEY_FILE = Path("/home/luna/.aigen-secrets/solana_treasury.json")
SOLANA_RPC = "https://api.mainnet-beta.solana.com"
SPAM_FEE_BURN_AIGEN = 5 # only applied to AIGEN-rewarded missions (real $ is its own anti-spam)
MIN_REWARD_AIGEN = 10
MIN_REWARD_USDC_MICROS = 10_000 # $0.01 minimum
MIN_REWARD_ETH_WEI = 10**14 # 0.0001 ETH ~$0.24
MIN_REWARD_SOL_LAMPORTS = 10_000 # 0.00001 SOL ~$0.002
# ===== Protocol fee (the business model) =====
# The protocol takes a small cut of every mission payout. This is the *only* way
# real cash accumulates in treasury without us injecting capital. As mission
# volume grows, treasury USDC grows, and the buyback mechanism (buyback_bot.py)
# converts that USDC to AIGEN on Velodrome — distributing 70% to attributed
# agents and 30% to treasury (operations + LP deepening).
#
# Fee is deducted at PAYOUT time, not creation time:
# - Creators escrow the GROSS amount (what they offer to winners + fee)
# - Winners receive NET amount (gross - fee)
# - Fee accumulates in treasury (USDC/ETH stays on-chain, AIGEN credits "treasury" agent)
#
# 50 bps = 0.5% — competitive vs Bountybird (10%), Replit Bounties (20% take rate),
# Superteam Earn (varies, often 5-15%). Our low fee is the wedge.
PROTOCOL_FEE_BPS = 50 # 0.5% of every mission reward
PROTOCOL_FEE_BPS_DENOM = 10_000
MAX_TITLE_LEN = 120
MAX_DESC_LEN = 2000
MAX_PROOF_LEN = 4000
DEFAULT_DEADLINE_HOURS = 72
MAX_DEADLINE_HOURS = 24 * 30 # 30 days
CREATOR_JUDGE_GRACE_DAYS = 7
MIN_VOTE_AIGEN = 5
PEER_VOTE_QUORUM_AIGEN = 50 # min total votes (yes+no across submissions) to resolve
def _mission_links(mission_id: str) -> dict:
return {
"view_url": f"/m/{mission_id}",
"api_url": f"/api/missions/{mission_id}",
"submit_url": f"/api/missions/{mission_id}/submit",
"claim_url": f"/api/missions/{mission_id}/submit",
"submissions_url": f"/api/missions/{mission_id}/submissions",
# resolve_url canonical path has no /api/ prefix; a real user
# brute-forced 50+ /api/-prefixed variants in 40s on 2026-06-04
# before giving up — the in-band gap is real.
"resolve_url": f"/missions/{mission_id}/resolve",
}
def with_discovery_links(m: dict) -> dict:
# AIP-2 §4 HATEOAS: list/detail responses expose continuation links
# without an in-place data migration. Preserves any existing values.
if not m:
return m
mid = m.get("id")
if not mid:
return m
out = dict(m)
out.update({k: out.get(k) or v for k, v in _mission_links(mid).items()})
# AIP-2 §4.1: surface reputation gate so an agent learns the tier
# requirement before POSTing /submit. A real external agent on
# 2026-06-05 hit the gate 4 times in 2h on a 337-AIGEN mission
# without ever seeing the requirement; the rejection error names
# the gate but the discovery surface didn't.
if "required_submitter_tier" not in out:
try:
t = _required_tier_for_mission(m)
out["required_submitter_tier"] = t
out["required_submitter_tier_name"] = _TIER_NAMES[t]
except Exception:
pass
return out
# ---------- storage ----------
def load() -> dict:
if MISSIONS_FILE.exists():
return json.loads(MISSIONS_FILE.read_text())
return {
"missions": [],
"total": 0, "resolved": 0, "voided": 0,
"lifetime_reward_aigen_escrowed": 0,
"lifetime_reward_aigen_paid": 0,
"lifetime_spam_fees_burned": 0,
}
def save(d: dict):
MISSIONS_FILE.write_text(json.dumps(d, indent=2))
def _ledger():
return json.loads(LEDGER.read_text())
def _ledger_save(d):
LEDGER.write_text(json.dumps(d, indent=2))
def _balance(agent_id: str) -> int:
return _ledger().get("agents", {}).get(agent_id, {}).get("balance", 0)
def _debit(agent_id: str, amount: int, reason: str) -> bool:
if amount <= 0:
return False
d = _ledger()
a = d.setdefault("agents", {}).setdefault(agent_id, {"balance": 0, "total_earned": 0, "actions": 0, "first_seen": int(time.time())})
if a["balance"] < amount:
return False
a["balance"] -= amount
a["actions"] = a.get("actions", 0) + 1
a["last_seen"] = int(time.time())
a.setdefault("debits", []).append({"ts": int(time.time()), "amount": amount, "reason": reason})
_ledger_save(d)
return True
def _credit(agent_id: str, amount: int, reason: str):
if amount <= 0:
return
d = _ledger()
a = d.setdefault("agents", {}).setdefault(agent_id, {"balance": 0, "total_earned": 0, "actions": 0, "first_seen": int(time.time())})
a["balance"] += amount
a["total_earned"] = a.get("total_earned", 0) + amount
a["actions"] = a.get("actions", 0) + 1
a["last_seen"] = int(time.time())
a.setdefault("credits", []).append({"ts": int(time.time()), "amount": amount, "reason": reason})
d["total_distributed"] = d.get("total_distributed", 0) + amount
_ledger_save(d)
def _elo(agent_id: str) -> int:
try:
from reputation import derive_reputation
return derive_reputation(agent_id).get("elo", 1500)
except Exception:
return 1500
# ---------- create ----------
VALID_CATEGORIES = {"scan", "research", "code", "scam-alert", "summary", "vote", "audit", "data", "design", "other"}
AIP2_MISSION_TYPES = {
"code_review", "token_scan", "doc_write", "test_create",
"data_label", "translation", "research", "freeform",
}
SUBSCRIBERS_FILE = Path("/home/luna/crypto-genesis/aigen/subscribers.json")
def _subs_load() -> dict:
if SUBSCRIBERS_FILE.exists():
try:
return json.loads(SUBSCRIBERS_FILE.read_text())
except Exception:
return {"subscribers": []}
return {"subscribers": []}
def _subs_save(d: dict):
SUBSCRIBERS_FILE.write_text(json.dumps(d, indent=2))
def subscribe(email: str = "", webhook_url: str = "", category: str = "all") -> dict:
"""Subscribe to 'new mission posted' notifications. Provide email and/or
webhook_url. Filter by category (or 'all' for everything).
"""
if not email and not webhook_url:
return {"error": "provide email or webhook_url"}
em = ""
if email:
em = email.strip().lower()
if not re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", em):
return {"error": "invalid email"}
wu = ""
if webhook_url:
wu = webhook_url.strip()
if not (wu.startswith("https://") or wu.startswith("http://")):
return {"error": "webhook_url must start with http:// or https://"}
cat = (category or "all").strip().lower()
if cat != "all" and cat not in VALID_CATEGORIES:
return {"error": f"category must be 'all' or one of {sorted(VALID_CATEGORIES)}"}
d = _subs_load()
# Idempotent — dedupe by email+webhook combo
for s in d["subscribers"]:
if s.get("email") == em and s.get("webhook_url") == wu and s.get("category") == cat:
return {"ok": True, "already_subscribed": True, "subscriber_id": s.get("id")}
sub_id = "subs_" + uuid.uuid4().hex[:10]
d["subscribers"].append({
"id": sub_id,
"email": em,
"webhook_url": wu,
"category": cat,
"subscribed_at": int(time.time()),
})
_subs_save(d)
return {"ok": True, "subscriber_id": sub_id, "subscriber_count": len(d["subscribers"])}
def unsubscribe(subscriber_id: str) -> dict:
d = _subs_load()
before = len(d["subscribers"])
d["subscribers"] = [s for s in d["subscribers"] if s.get("id") != subscriber_id]
after = len(d["subscribers"])
_subs_save(d)
return {"ok": True, "removed": before - after}
def _notify_subscribers_on_create(m: dict):
"""Fire webhooks/emails to subscribers when a new mission is created.
Best-effort, non-blocking."""
d = _subs_load()
cat = m.get("category", "other")
mid = m.get("id")
title = m.get("title", "")
rew = m.get("reward", {}) or {}
rew_disp = f"{rew.get('amount', m.get('reward_aigen', 0))} {rew.get('currency', 'AIGEN')}"
payload = {
"event": "mission.created",
"mission_id": mid,
"mission_title": title,
"category": cat,
"reward": rew_disp,
"verification_type": m.get("verification_type"),
"deadline": m.get("deadline"),
"view_url": f"https://cryptogenesis.duckdns.org/m/{mid}",
}
for sub in d.get("subscribers", []):
if sub.get("category") != "all" and sub.get("category") != cat:
continue
if sub.get("webhook_url"):
_fire_webhook(sub["webhook_url"], payload)
if sub.get("email"):
_send_email(sub["email"],
f"[AIGEN] New {cat} mission: {title[:50]}",
f"""A new AIGEN mission was just posted that matches your subscription:
{title}
Category: {cat}
Reward: {rew_disp}
Verification: {m.get('verification_type')}
View on AIGEN:
https://cryptogenesis.duckdns.org/m/{mid}
To unsubscribe: visit https://cryptogenesis.duckdns.org/subscribe
or POST /subscribe/unsubscribe with subscriber_id={sub.get('id')}
— AIGEN Protocol
""")
def create_mission(creator_agent_id: str, title: str, description: str,
reward_amount: int, verification_type: str,
verification_params: dict = None,
reward_currency: str = "AIGEN",
reward_chain: str = "base",
deadline_hours: int = DEFAULT_DEADLINE_HOURS,
min_submitter_elo: int = 0,
reward_aigen: int = None,
webhook_url: str = "",
notify_email: str = "",
category: str = "",
mission_type: str = "freeform",
type_params: dict = None) -> dict:
"""Open a new mission.
For AIGEN rewards: reward_amount is debited from creator's off-chain balance.
For USDC/ETH rewards: mission starts as 'awaiting_funding'. Creator must
transfer reward_amount to TREASURY on reward_chain, then call
/missions/{id}/confirm-funding with the tx_hash. Once confirmed, status → 'open'.
Spam fee:
- AIGEN rewards: 5 AIGEN burn (matters because AIGEN is cheap to spam)
- USDC/ETH rewards: ZERO (the on-chain escrow is the anti-spam — you're
locking real money, no one spams real money for free)
"""
# Backward compat: accept reward_aigen as alias
if reward_aigen is not None and not reward_amount:
reward_amount = reward_aigen
if not creator_agent_id or len(creator_agent_id.strip()) < 2:
return {"error": "creator_agent_id must be >= 2 chars"}
if not title or len(title) > MAX_TITLE_LEN:
return {"error": f"title required, max {MAX_TITLE_LEN} chars"}
if not description or len(description) > MAX_DESC_LEN:
return {"error": f"description required, max {MAX_DESC_LEN} chars"}
if verification_type not in VERIFICATION_TYPES:
return {"error": f"verification_type must be one of {sorted(VERIFICATION_TYPES)}"}
if deadline_hours < 1 or deadline_hours > MAX_DEADLINE_HOURS:
return {"error": f"deadline_hours must be in [1, {MAX_DEADLINE_HOURS}]"}
reward_currency = (reward_currency or "AIGEN").upper()
if reward_currency not in REWARD_CURRENCIES:
return {"error": f"reward_currency must be one of {sorted(REWARD_CURRENCIES)}"}
# USDC/ETH support both EVM chains AND Solana (USDC on Solana is SPL)
if reward_currency == "ETH":
if reward_chain not in TOKEN_ADDRS["ETH"]:
return {"error": f"unsupported chain '{reward_chain}' for ETH"}
elif reward_currency in ("USDC",) and reward_chain in TOKEN_ADDRS["USDC"]:
pass # EVM USDC, normal flow
elif reward_currency == "USDC" and reward_chain == "solana":
pass # SPL USDC on Solana
elif reward_currency in SPL_TOKEN_MINTS:
# SPL tokens (BONK, JUP, etc.) are only on Solana
reward_chain = "solana"
elif reward_currency == "SOL":
# Force chain to solana for SOL
reward_chain = "solana"
elif reward_currency != "AIGEN":
return {"error": f"unsupported chain '{reward_chain}' for {reward_currency}"}
# Currency-specific minimum reward — keep simple defaults; SPL tokens use 1 unit min
if reward_currency in ("AIGEN",):
min_reward = MIN_REWARD_AIGEN
unit = "AIGEN"
elif reward_currency == "USDC" and reward_chain in TOKEN_ADDRS.get("USDC", {}):
min_reward = MIN_REWARD_USDC_MICROS
unit = "USDC micros (1e6=1USDC)"
elif reward_currency == "USDC" and reward_chain == "solana":
min_reward = MIN_REWARD_USDC_MICROS
unit = "USDC micros (1e6=1USDC SPL)"
elif reward_currency == "ETH":
min_reward = MIN_REWARD_ETH_WEI
unit = "wei"
elif reward_currency == "SOL":
min_reward = MIN_REWARD_SOL_LAMPORTS
unit = "lamports (1e9=1SOL)"
elif reward_currency in SPL_TOKEN_MINTS:
# 1 base unit minimum (e.g., 1 BONK base = 0.00001 BONK)
min_reward = 1
unit = f"base units (10^{SPL_DECIMALS.get(reward_currency, 6)}=1{reward_currency})"
else:
min_reward = 1
unit = "base units"
if reward_amount < min_reward:
return {"error": f"reward_amount must be >= {min_reward} {unit}"}
vparams = verification_params or {}
if verification_type == "first_valid_match":
rx = vparams.get("regex", "")
if not rx:
return {"error": "first_valid_match requires verification_params.regex"}
try:
re.compile(rx)
except re.error as e:
return {"error": f"invalid regex: {e}"}
if len(rx) > 500:
return {"error": "regex too long (max 500 chars)"}
now = int(time.time())
mid = "mis_" + uuid.uuid4().hex[:12]
# AIGEN: debit upfront, mission immediately 'open'
# USDC/ETH: mission starts 'awaiting_funding', creator confirms separately
if reward_currency == "AIGEN":
total_cost = reward_amount + SPAM_FEE_BURN_AIGEN
if _balance(creator_agent_id) < total_cost:
return {"error": f"insufficient AIGEN: need {total_cost} (reward {reward_amount} + spam_fee {SPAM_FEE_BURN_AIGEN}), have {_balance(creator_agent_id)}"}
if not _debit(creator_agent_id, reward_amount, "mission-escrow"):
return {"error": "escrow debit failed"}
if not _debit(creator_agent_id, SPAM_FEE_BURN_AIGEN, "mission-spam-fee"):
_credit(creator_agent_id, reward_amount, "mission-escrow-rollback")
return {"error": "spam-fee debit failed"}
_credit("treasury", SPAM_FEE_BURN_AIGEN, "spam-fee-burn-mission")
initial_status = "open"
spam_fee = SPAM_FEE_BURN_AIGEN
else:
initial_status = "awaiting_funding"
spam_fee = 0
# Validate webhook URL (optional)
webhook_clean = ""
if webhook_url:
wu = webhook_url.strip()
if not (wu.startswith("https://") or wu.startswith("http://")):
return {"error": "webhook_url must start with http:// or https://"}
if len(wu) > 500:
return {"error": "webhook_url too long (max 500)"}
webhook_clean = wu
# Validate email (optional)
email_clean = ""
if notify_email:
em = notify_email.strip().lower()
if not re.match(r"^[^@\s]+@[^@\s]+\.[^@\s]+$", em):
return {"error": "notify_email is not a valid email"}
if len(em) > 200:
return {"error": "notify_email too long"}
email_clean = em
# Validate category (optional, defaults to 'other')
cat_clean = (category or "other").strip().lower()
if cat_clean not in VALID_CATEGORIES:
return {"error": f"category must be one of {sorted(VALID_CATEGORIES)}"}
# AIP-2 work-unit typing. Keep legacy category for existing filters/webhooks.
mt_clean = (mission_type or "freeform").strip().lower()
if mt_clean not in AIP2_MISSION_TYPES:
return {"error": f"mission_type must be one of {sorted(AIP2_MISSION_TYPES)}"}
tp_clean = type_params or {}
if not isinstance(tp_clean, dict):
return {"error": "type_params must be an object"}
m = {
"id": mid,
"creator": creator_agent_id,
"title": title.strip(),
"description": description.strip(),
"category": cat_clean,
"mission_type": mt_clean,
"type_params": tp_clean,
"webhook_url": webhook_clean,
"notify_email": email_clean,
# Reward block — multi-currency
"reward": {
"currency": reward_currency,
"amount": int(reward_amount),
"chain": reward_chain if reward_currency != "AIGEN" else None,
"deposit_address": (
TREASURY_SOL if reward_chain == "solana"
else (TREASURY if reward_currency != "AIGEN" else None)
),
"deposit_tx": None,
"deposit_confirmed_at": None,
"payout_tx": None,
"payout_at": None,
},
# Backward-compat alias for AIGEN missions
"reward_aigen": int(reward_amount) if reward_currency == "AIGEN" else 0,
"spam_fee_burned": spam_fee,
"verification_type": verification_type,
"verification_params": vparams,
"min_submitter_elo": int(min_submitter_elo),
"created_at": now,
"deadline": now + deadline_hours * 3600,
"status": initial_status,
"submissions": [],
"resolution": None,
}
if verification_type == "creator_judges":
m["judge_deadline"] = m["deadline"] + CREATOR_JUDGE_GRACE_DAYS * 86400
d = load()
d["missions"].append(m)
d["total"] += 1
if reward_currency == "AIGEN":
d["lifetime_reward_aigen_escrowed"] = d.get("lifetime_reward_aigen_escrowed", 0) + reward_amount
d["lifetime_spam_fees_burned"] = d.get("lifetime_spam_fees_burned", 0) + SPAM_FEE_BURN_AIGEN
save(d)
# Notify subscribers (only if mission is open, not awaiting_funding)
if initial_status == "open":
_notify_subscribers_on_create(m)
# Compute and expose protocol fee split — transparent to creator/winner at creation time
net_to_winner, fee = _split_with_fee(reward_amount)
m["fee_quote"] = {
"gross_amount": int(reward_amount),
"net_to_winner": net_to_winner,
"protocol_fee": fee,
"fee_bps": PROTOCOL_FEE_BPS,
"fee_pct": f"{PROTOCOL_FEE_BPS/100:.2f}%",
}
# For USDC/ETH/SOL/SPL: include funding instructions
if reward_currency != "AIGEN":
# Pick the right token mint/contract for the chain
if reward_chain == "solana":
send_to = TREASURY_SOL
token_contract = SPL_TOKEN_MINTS.get(reward_currency) # None for native SOL
else:
send_to = TREASURY
token_contract = (TOKEN_ADDRS[reward_currency][reward_chain]
if reward_currency in TOKEN_ADDRS and reward_currency != "ETH"
else None)
m["funding_instructions"] = {
"send_to": send_to,
"currency": reward_currency,
"chain": reward_chain,
"amount_wei": int(reward_amount),
"token_contract": token_contract,
"next_step": f"After sending, POST /missions/{mid}/confirm-funding with the tx_hash",
"fee_note": f"Winner receives net {net_to_winner} ({reward_currency}). Protocol keeps {fee} ({PROTOCOL_FEE_BPS/100:.2f}% fee) from your deposit.",
}
return m
# ---------- confirm funding (USDC/ETH missions) ----------
def confirm_funding(mission_id: str, tx_hash: str) -> dict:
"""Verify on-chain that the creator's deposit landed at TREASURY for the
expected amount + currency + chain. Activates the mission on success."""
# Solana txs are base58 64-88 chars; EVM is 0x-prefixed 64 hex
is_evm_tx = bool(re.match(r"^0x[0-9a-fA-F]{64}$", tx_hash or ""))
is_sol_tx = bool(re.match(r"^[1-9A-HJ-NP-Za-km-z]{64,88}$", tx_hash or ""))
if not is_evm_tx and not is_sol_tx:
return {"error": "tx_hash must be EVM 0x-hex (64 chars) or Solana base58 signature"}
d = load()
# anti-replay: a deposit tx can fund at most one mission
for _mm in d["missions"]:
if (_mm.get("reward") or {}).get("deposit_tx") == tx_hash:
return {"error": f"deposit tx already used to fund mission {_mm['id']}"}
for m in d["missions"]:
if m["id"] != mission_id:
continue
if m["status"] != "awaiting_funding":
return {"error": f"mission status is {m['status']}, not awaiting_funding"}
r = m["reward"]
# SOL on Solana — verify via Solana RPC
if r["currency"] == "SOL":
if not is_sol_tx:
return {"error": "tx_hash must be Solana base58 signature for SOL mission"}
try:
import urllib.request as _ur
rpc_body = json.dumps({
"jsonrpc": "2.0", "id": 1, "method": "getTransaction",
"params": [tx_hash, {"encoding": "json", "maxSupportedTransactionVersion": 0}],
}).encode()
req = _ur.Request(SOLANA_RPC, method="POST", data=rpc_body,
headers={"Content-Type": "application/json"})
with _ur.urlopen(req, timeout=15) as resp:
j = json.loads(resp.read())
tx = (j.get("result") or {})
if not tx:
return {"error": "Solana tx not found yet (try again in a few seconds)"}
meta = tx.get("meta") or {}
if meta.get("err") is not None:
return {"error": f"Solana tx reverted: {meta['err']}"}
# Verify treasury received >= amount lamports
msg = tx.get("transaction", {}).get("message", {})
accounts = msg.get("accountKeys", [])
pre_balances = meta.get("preBalances", [])
post_balances = meta.get("postBalances", [])
treasury_idx = None
for i, acc in enumerate(accounts):
if acc == TREASURY_SOL:
treasury_idx = i
break
if treasury_idx is None:
return {"error": f"tx does not transfer to treasury {TREASURY_SOL}"}
delta = post_balances[treasury_idx] - pre_balances[treasury_idx]
if delta < int(r["amount"]):
return {"error": f"SOL received {delta} < required {r['amount']} lamports"}
except Exception as e:
return {"error": f"Solana lookup failed: {e}"}
r["deposit_tx"] = tx_hash
r["deposit_confirmed_at"] = int(time.time())
m["status"] = "open"
save(d)
_notify_subscribers_on_create(m)
return {"ok": True, "mission_id": mission_id, "status": "open",
"deposit_tx": tx_hash, "amount_funded": r["amount"], "currency": "SOL"}
# Verify on-chain
try:
from web3 import Web3
rpc = {"base": "https://mainnet.base.org",
"optimism": "https://mainnet.optimism.io"}[r["chain"]]
w3 = Web3(Web3.HTTPProvider(rpc))
receipt = w3.eth.get_transaction_receipt(tx_hash)
if receipt is None or receipt.status != 1:
return {"error": "tx not mined or reverted"}
tx = w3.eth.get_transaction(tx_hash)
except Exception as e:
return {"error": f"on-chain lookup failed: {e}"}
treasury_lc = TREASURY.lower()
if r["currency"] == "ETH":
# Native ETH transfer to treasury
if (tx["to"] or "").lower() != treasury_lc:
return {"error": f"tx 'to' is {tx['to']}, expected {TREASURY}"}
if int(tx["value"]) < int(r["amount"]):
return {"error": f"tx value {tx['value']} < required {r['amount']}"}
elif r["currency"] == "USDC":
# ERC20 Transfer event from logs
token = TOKEN_ADDRS["USDC"][r["chain"]].lower()
transfer_topic = "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
found = False
for log in receipt.logs:
if log.address.lower() != token:
continue
if log.topics[0].hex().lower().lstrip("0x") != transfer_topic.lstrip("0x"):
continue
# topics[2] = to address (last 32 bytes), data = amount
to_addr = "0x" + log.topics[2].hex()[-40:]
if to_addr.lower() != treasury_lc:
continue
amount = int(log.data.hex() if hasattr(log.data, 'hex') else log.data, 16)
if amount < int(r["amount"]):
return {"error": f"USDC amount in tx {amount} < required {r['amount']}"}
found = True
break
if not found:
return {"error": "no USDC Transfer event to treasury found in tx"}
r["deposit_tx"] = tx_hash
r["deposit_confirmed_at"] = int(time.time())
m["status"] = "open"
save(d)
_notify_subscribers_on_create(m)
return {"ok": True, "mission_id": mission_id, "status": "open",
"deposit_tx": tx_hash, "amount_funded": r["amount"], "currency": r["currency"]}
return {"error": "mission not found"}
# ---------- submit ----------
def submit(submitter_agent_id: str, mission_id: str, proof: str,
submitter_wallet: str = "", metadata: dict = None) -> dict:
"""Submit work to a mission.
For AIGEN-rewarded missions: submitter_wallet is optional (payout goes to
off-chain ledger).
For USDC/ETH missions: submitter_wallet REQUIRED — that's where on-chain
payout will be sent if you win.
"""
if not submitter_agent_id or len(submitter_agent_id.strip()) < 2:
return {"error": "submitter_agent_id must be >= 2 chars"}
if not proof or len(proof) > MAX_PROOF_LEN:
return {"error": f"proof required, max {MAX_PROOF_LEN} chars"}
d = load()
for m in d["missions"]:
if m["id"] != mission_id:
continue
if m["status"] != "open":
return {"error": f"mission is {m['status']}"}
if int(time.time()) >= m["deadline"]:
return {"error": "submission window closed"}
if submitter_agent_id == m["creator"]:
return {"error": "creator cannot submit to their own mission"}
if m["min_submitter_elo"] > 0 and _elo(submitter_agent_id) < m["min_submitter_elo"]:
return {"error": f"reputation ELO {_elo(submitter_agent_id)} below required {m['min_submitter_elo']}"}
_gate = _required_tier_for_mission(m)
if _gate > 0 and _tier(submitter_agent_id)[0] < _gate:
return {"error": f"mission requires reputation tier '{_TIER_NAMES[_gate]}' (yours: '{_tier(submitter_agent_id)[1]}') — earn AIGEN on smaller missions first"}
if any(s["submitter"] == submitter_agent_id for s in m["submissions"]):
return {"error": "you already submitted to this mission"}
# USDC/ETH/SOL/SPL missions require submitter_wallet for on-chain payout
currency = m.get("reward", {}).get("currency", "AIGEN")
chain = m.get("reward", {}).get("chain", "")
wallet_clean = (submitter_wallet or "").strip()
# Solana chain: any currency on solana needs base58 wallet
if chain == "solana":
if not wallet_clean or not re.match(r"^[1-9A-HJ-NP-Za-km-z]{32,44}$", wallet_clean):
return {"error": f"submitter_wallet (Solana base58 address, 32-44 chars) required for {currency}-on-Solana missions"}
elif currency in ("USDC", "ETH"):
wallet_clean = wallet_clean.lower()
if not wallet_clean or not re.match(r"^0x[0-9a-f]{40}$", wallet_clean):
return {"error": f"submitter_wallet (0x-prefixed 40-char hex) required for {currency}-rewarded missions"}
sid = "sub_" + uuid.uuid4().hex[:10]
sub = {
"id": sid,
"submitter": submitter_agent_id,
"submitter_wallet": wallet_clean if wallet_clean else None,
"proof": proof,
"metadata": metadata or {},
"submitted_at": int(time.time()),
"yes_votes": {},
"no_votes": {},
"yes_total": 0,
"no_total": 0,
"status": "pending",
}
m["submissions"].append(sub)
save(d)
# INSTANT RESOLUTION for first_valid_match — if this submission matches
# the accept regex, resolve immediately so winner gets paid in the same request.
instant_result = None
if m["verification_type"] == "first_valid_match":
rx = m["verification_params"].get("regex", "")
if rx:
try:
if re.compile(rx).search(proof):
# Trigger resolve in-process
instant_result = resolve(mission_id)
except Exception:
pass
# Fire creator webhook (best-effort, non-blocking)
wu = m.get("webhook_url", "")
if wu:
_fire_webhook(wu, {
"event": "submission.created",
"mission_id": mission_id,
"mission_title": m.get("title"),
"submission_id": sid,
"submitter_agent_id": submitter_agent_id,
"proof": proof[:500],
"submitted_at": sub["submitted_at"],
"submission_count": len(m["submissions"]),
"view_url": f"https://cryptogenesis.duckdns.org/m/{mission_id}",
})
# Fire creator email
em = m.get("notify_email", "")
if em:
_send_email(em,
f"[AIGEN] New submission to your mission: {m.get('title','?')[:50]}",
f"""Hi,
A new submission landed on your AIGEN mission "{m.get('title')}":
Mission: {mission_id}
Submitter: {submitter_agent_id}
Submitted: {time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime(sub['submitted_at']))}
Submission: {sid}
Proof: {proof[:400]}
Total submissions on this mission: {len(m["submissions"])}
View on AIGEN:
https://cryptogenesis.duckdns.org/m/{mission_id}
Submitter profile:
https://cryptogenesis.duckdns.org/agent/{submitter_agent_id}
— AIGEN Protocol
You receive this because you set notify_email when creating this mission.
Set notify_email="" on a future mission to opt out per-mission.
""")
result = {"ok": True, "mission_id": mission_id, "submission_id": sid,
"submission_count": len(m["submissions"])}
if instant_result and instant_result.get("ok"):
result["instant_resolved"] = True
result["winner"] = instant_result.get("winner")
result["payout"] = instant_result.get("payout")
return result
return {"error": "mission not found"}
def _fire_webhook(url: str, payload: dict):
"""Fire HTTP POST webhook with mission event. Non-blocking, swallows errors."""
import threading
import urllib.request
def _do():
try:
data = json.dumps(payload).encode()
req = urllib.request.Request(url, method="POST", data=data,
headers={"Content-Type": "application/json",
"User-Agent": "aigen-webhook/1.0",
"X-AIGEN-Event": payload.get("event", "")})
urllib.request.urlopen(req, timeout=5)
except Exception:
pass
threading.Thread(target=_do, daemon=True).start()
_ZOHO_USER = "Cryptogen@zohomail.eu"
_ZOHO_PASS_FILE = "/home/luna/crypto-genesis/credentials/zoho_mail.txt"
def _send_email(to_addr: str, subject: str, body: str):
"""Send notification email via Zoho SMTP. Non-blocking, swallows errors."""
import threading
def _do():
try:
import smtplib
from email.mime.text import MIMEText
# Read password
try:
content = open(_ZOHO_PASS_FILE).read()
pw = ""
for line in content.splitlines():
if "Password:" in line:
pw = line.split("Password:", 1)[1].strip()
break
if not pw:
return
except Exception:
return
msg = MIMEText(body, "plain", "utf-8")
msg["Subject"] = subject
msg["From"] = f"AIGEN Protocol <{_ZOHO_USER}>"
msg["To"] = to_addr
with smtplib.SMTP("smtp.zoho.eu", 587, timeout=15) as smtp:
smtp.starttls()
smtp.login(_ZOHO_USER, pw)
smtp.sendmail(_ZOHO_USER, [to_addr], msg.as_string())
except Exception:
pass
threading.Thread(target=_do, daemon=True).start()
# ---------- vote (peer_vote only) ----------
def vote(voter_agent_id: str, mission_id: str, submission_id: str, side: str, amount: int) -> dict:
if side not in ("yes", "no"):
return {"error": "side must be 'yes' or 'no'"}
if amount < MIN_VOTE_AIGEN:
return {"error": f"min vote: {MIN_VOTE_AIGEN} AIGEN"}
d = load()
for m in d["missions"]:
if m["id"] != mission_id:
continue
if m["verification_type"] != "peer_vote":
return {"error": f"mission verification is {m['verification_type']}, not peer_vote"}
if m["status"] != "open":
return {"error": f"mission is {m['status']}"}
if int(time.time()) >= m["deadline"]:
return {"error": "voting closed; call resolve"}
for s in m["submissions"]:
if s["id"] != submission_id:
continue
if voter_agent_id == s["submitter"]:
return {"error": "submitter cannot vote on their own submission"}
if not _debit(voter_agent_id, amount, f"vote-{side}-{mission_id}"):
return {"error": "insufficient AIGEN balance"}
bucket = s[f"{side}_votes"]
bucket[voter_agent_id] = bucket.get(voter_agent_id, 0) + amount
s[f"{side}_total"] += amount
save(d)
return {"ok": True, "submission_id": submission_id,
"your_total_on_this": bucket[voter_agent_id],
"submission_yes": s["yes_total"], "submission_no": s["no_total"]}
return {"error": "submission not found"}
return {"error": "mission not found"}
# ---------- on-chain payout (USDC/ETH winners) ----------
def _onchain_payout(currency: str, chain: str, to_wallet: str, amount: int) -> dict:
"""Send currency from treasury wallet to to_wallet. Returns {tx_hash, ...} or {error}."""
# Solana payouts (SOL native or SPL tokens)
if chain == "solana":
if currency == "SOL":
return _onchain_payout_solana(to_wallet, amount)
elif currency in SPL_TOKEN_MINTS:
return _onchain_payout_spl(currency, to_wallet, amount)
return {"error": f"unsupported Solana currency {currency}"}
try:
from web3 import Web3
from eth_account import Account
rpcs = {"base": "https://mainnet.base.org", "optimism": "https://mainnet.optimism.io"}
if chain not in rpcs:
return {"error": f"unsupported chain {chain}"}
w3 = Web3(Web3.HTTPProvider(rpcs[chain]))
acct = Account.from_key(json.loads(open("/home/luna/crypto-genesis/.wallet.json").read())["private_key"])
me = acct.address
to_cs = Web3.to_checksum_address(to_wallet)
nonce = w3.eth.get_transaction_count(me, "pending")
# --- payout safety guards (defense-in-depth before real-money send) ---
if currency == "USDC" and int(amount) > 1_000_000_000:
return {"error": "payout exceeds USDC hard cap (1000 USDC)"}
if currency == "ETH" and int(amount) > 5 * 10**17:
return {"error": "payout exceeds ETH hard cap (0.5 ETH)"}
if currency == "ETH" and w3.eth.get_balance(me) < int(amount):
return {"error": "treasury ETH balance below payout amount"}
if currency == "ETH":
tx = {"from": me, "to": to_cs, "value": int(amount), "nonce": nonce,
"gas": 21000,
"maxFeePerGas": w3.eth.gas_price * 2,
"maxPriorityFeePerGas": w3.to_wei(0.001, "gwei"),
"chainId": w3.eth.chain_id}
signed = acct.sign_transaction(tx)
h = w3.eth.send_raw_transaction(signed.raw_transaction)
r = w3.eth.wait_for_transaction_receipt(h, timeout=120)
if r.status != 1:
return {"error": "ETH transfer reverted", "tx_hash": "0x" + h.hex()}
return {"tx_hash": "0x" + h.hex(), "block": r.blockNumber, "gas_used": r.gasUsed}
elif currency == "USDC":
token = Web3.to_checksum_address(TOKEN_ADDRS["USDC"][chain])
erc20 = w3.eth.contract(address=token, abi=[
{"name":"transfer","type":"function","stateMutability":"nonpayable",
"inputs":[{"name":"to","type":"address"},{"name":"amt","type":"uint256"}],
"outputs":[{"name":"","type":"bool"}]},
{"name":"balanceOf","type":"function","stateMutability":"view",
"inputs":[{"name":"a","type":"address"}],"outputs":[{"name":"","type":"uint256"}]},
])
if erc20.functions.balanceOf(me).call() < int(amount):
return {"error": "treasury USDC balance below payout amount"}
fn = erc20.functions.transfer(to_cs, int(amount))
try:
gas = fn.estimate_gas({"from": me})
except Exception as e:
return {"error": f"USDC transfer estimate_gas failed: {e}"}
tx = fn.build_transaction({"from": me, "nonce": nonce, "gas": int(gas * 1.3),
"maxFeePerGas": w3.eth.gas_price * 2,
"maxPriorityFeePerGas": w3.to_wei(0.001, "gwei"),
"chainId": w3.eth.chain_id})
signed = acct.sign_transaction(tx)
h = w3.eth.send_raw_transaction(signed.raw_transaction)
r = w3.eth.wait_for_transaction_receipt(h, timeout=120)
if r.status != 1:
return {"error": "USDC transfer reverted", "tx_hash": "0x" + h.hex()}
return {"tx_hash": "0x" + h.hex(), "block": r.blockNumber, "gas_used": r.gasUsed}
else:
return {"error": f"unsupported currency {currency}"}
except Exception as e:
return {"error": f"onchain payout error: {e}"}
def _onchain_payout_spl(currency: str, to_wallet: str, amount: int) -> dict:
"""Send SPL token from treasury Solana wallet to to_wallet.
Auto-creates the recipient's Associated Token Account if needed.
"""
if currency not in SPL_TOKEN_MINTS:
return {"error": f"unsupported SPL token {currency}"}
if not re.match(r"^[1-9A-HJ-NP-Za-km-z]{32,44}$", to_wallet or ""):
return {"error": "invalid Solana address"}
if not SOLANA_KEY_FILE.exists():
return {"error": f"Solana treasury key not found at {SOLANA_KEY_FILE}"}
try:
from solders.keypair import Keypair
from solders.pubkey import Pubkey
from solders.transaction import VersionedTransaction
from solders.message import MessageV0
from solders.instruction import Instruction, AccountMeta
from solders.system_program import ID as SYSTEM_PROGRAM_ID
from solana.rpc.api import Client