forked from NSPG13/agent-bounties
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgithub_discovery.rs
More file actions
1364 lines (1320 loc) · 50.9 KB
/
Copy pathgithub_discovery.rs
File metadata and controls
1364 lines (1320 loc) · 50.9 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
use chain_base::{
AutonomousBountyEvent, AutonomousBountyEventKind, AutonomousBountyFeedItem,
OpenCompetitionDeploymentState, OpenCompetitionEvent, OpenCompetitionEventKind,
OpenCompetitionVerifierProfile,
};
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::{BTreeMap, BTreeSet};
use utoipa::ToSchema;
pub const GITHUB_DISCOVERY_SCHEMA: &str = "agent-bounties/github-bounty-discovery-v1";
pub const AUTONOMOUS_PROTOCOL_VERSION: &str = "agent-bounties/autonomous-v1";
pub const OPEN_COMPETITION_PROTOCOL_VERSION: &str = "agent-bounties/open-competition-v1";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct GitHubDiscoverySafeBlock {
pub number: u64,
pub hash: String,
pub timestamp: u64,
pub age_seconds: i64,
pub fresh: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct GitHubDiscoverySourceStatus {
pub source_type: String,
pub protocol_version: String,
pub factory_contract: Option<String>,
pub available: bool,
pub fresh: bool,
pub item_count: usize,
pub persisted_cursor_block: Option<u64>,
pub error: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct GitHubDiscoveryAction {
pub kind: String,
pub label: String,
pub method: String,
pub url: String,
pub instructions: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct GitHubSettlementEvidence {
pub event_name: String,
pub bounty_id: String,
pub bounty_contract: String,
pub transaction_hash: String,
pub block_number: u64,
pub log_index: u64,
pub solver_wallet: String,
pub solver_reward: String,
pub returned_bond: String,
pub completion_bonus: String,
pub solver_payout: String,
pub verifier_reward: String,
pub confirmed_canonical: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct GitHubDiscoveryVerifier {
pub profile_id: Option<String>,
pub display_name: String,
pub method: String,
pub address: Option<String>,
pub runtime_code_hash: Option<String>,
pub ready: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct GitHubDiscoveryItem {
pub discovery_id: String,
pub network: String,
pub chain_id: u64,
pub protocol_version: String,
pub source_id: String,
pub visibility: String,
pub bounty_id: String,
pub bounty_contract: String,
pub created_at: String,
pub created_block: u64,
pub updated_at: String,
pub title: String,
pub summary: String,
pub categories: Vec<String>,
pub skills: Vec<String>,
pub difficulty: Option<String>,
pub public_url: String,
pub source_url: Option<String>,
pub competition_mode: String,
pub lifecycle_state: String,
pub funded: bool,
pub verification_ready: bool,
pub ready_to_earn: bool,
pub reward_usdc_base_units: String,
pub verifier_reward_usdc_base_units: String,
pub bond_usdc_base_units: String,
pub funded_usdc_base_units: String,
pub funding_target_usdc_base_units: String,
pub deadline: Option<String>,
pub deadline_kind: Option<String>,
pub entry_count: Option<u8>,
pub max_entries: Option<u8>,
pub verifier: GitHubDiscoveryVerifier,
pub next_action: GitHubDiscoveryAction,
pub recovery_action_available: bool,
pub identity_warning: Option<String>,
pub settlement_evidence: Option<GitHubSettlementEvidence>,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
pub struct GitHubDiscoveryProjectionResponse {
pub schema_version: String,
pub generated_at: String,
pub network: String,
pub chain_id: u64,
pub safe_block: Option<GitHubDiscoverySafeBlock>,
pub degraded: bool,
pub source_statuses: Vec<GitHubDiscoverySourceStatus>,
pub items: Vec<GitHubDiscoveryItem>,
pub evidence_boundary: String,
}
pub fn assemble_projection(
network: &str,
chain_id: u64,
generated_at: DateTime<Utc>,
safe_block: Option<GitHubDiscoverySafeBlock>,
source_statuses: Vec<GitHubDiscoverySourceStatus>,
mut items: Vec<GitHubDiscoveryItem>,
) -> Result<GitHubDiscoveryProjectionResponse, String> {
let expected_protocols = BTreeSet::from([
AUTONOMOUS_PROTOCOL_VERSION.to_string(),
OPEN_COMPETITION_PROTOCOL_VERSION.to_string(),
]);
let observed_protocols = source_statuses
.iter()
.map(|source| source.protocol_version.clone())
.collect::<BTreeSet<_>>();
if observed_protocols != expected_protocols || source_statuses.len() != expected_protocols.len()
{
return Err("public bounty protocol adapter set is incomplete or duplicated".to_string());
}
let mut identities = BTreeSet::new();
for item in &items {
if item.network != network || item.chain_id != chain_id || item.visibility != "public" {
return Err(format!(
"discovery item {} does not match the response network",
item.discovery_id
));
}
if !identities.insert(item.discovery_id.clone()) {
return Err(format!("duplicate discovery id: {}", item.discovery_id));
}
validate_item(item)?;
}
for source in &source_statuses {
let projected_count = items
.iter()
.filter(|item| item.protocol_version == source.protocol_version)
.count();
if projected_count != source.item_count {
return Err(format!(
"source item count mismatch for {}",
source.protocol_version
));
}
}
items.sort_by(|left, right| {
right
.created_block
.cmp(&left.created_block)
.then_with(|| left.discovery_id.cmp(&right.discovery_id))
});
let degraded = safe_block.as_ref().is_none_or(|block| !block.fresh)
|| source_statuses
.iter()
.any(|source| !source.available || !source.fresh);
Ok(GitHubDiscoveryProjectionResponse {
schema_version: GITHUB_DISCOVERY_SCHEMA.to_string(),
generated_at: generated_at.to_rfc3339(),
network: network.to_string(),
chain_id,
safe_block,
degraded,
source_statuses,
items,
evidence_boundary: "This is a read-only GitHub discovery projection. GitHub issues and labels cannot create funding, claims, verification, settlement, refunds, or payment. Only a confirmed canonical BountySettled event in settlement_evidence proves solver payment.".to_string(),
})
}
fn validate_item(item: &GitHubDiscoveryItem) -> Result<(), String> {
if item.discovery_id.len() > 240
|| item.title.trim().is_empty()
|| item.bounty_contract.len() != 42
|| item.reward_usdc_base_units.parse::<u128>().is_err()
|| item.bond_usdc_base_units.parse::<u128>().is_err()
|| item.funded_usdc_base_units.parse::<u128>().is_err()
|| item.funding_target_usdc_base_units.parse::<u128>().is_err()
{
return Err(format!(
"discovery item is malformed: {}",
item.discovery_id
));
}
if item.lifecycle_state == "settled" {
let settlement = item.settlement_evidence.as_ref().ok_or_else(|| {
format!(
"settled item lacks BountySettled evidence: {}",
item.discovery_id
)
})?;
if !settlement.confirmed_canonical || settlement.event_name != "BountySettled" {
return Err(format!(
"settled item has noncanonical payment evidence: {}",
item.discovery_id
));
}
} else if item.settlement_evidence.is_some() {
return Err(format!(
"non-settled item exposes payment evidence: {}",
item.discovery_id
));
}
if item.ready_to_earn
&& (item.lifecycle_state != "ready_to_earn" || !item.funded || !item.verification_ready)
{
return Err(format!(
"ready-to-earn item violates funding or verifier invariants: {}",
item.discovery_id
));
}
Ok(())
}
pub fn autonomous_discovery_items(
feed: &[AutonomousBountyFeedItem],
network: &str,
chain_id: u64,
api_base_url: &str,
website_base_url: &str,
) -> Result<Vec<GitHubDiscoveryItem>, String> {
feed.iter()
.map(|item| {
autonomous_discovery_item(item, network, chain_id, api_base_url, website_base_url)
})
.collect()
}
fn autonomous_discovery_item(
item: &AutonomousBountyFeedItem,
network: &str,
chain_id: u64,
api_base_url: &str,
website_base_url: &str,
) -> Result<GitHubDiscoveryItem, String> {
let api = api_base_url.trim_end_matches('/');
let website = website_base_url.trim_end_matches('/');
let contract = item.bounty_contract.to_ascii_lowercase();
let created = unique_autonomous_event(item, AutonomousBountyEventKind::CanonicalBountyCreated)?;
let created_at = created
.map(|event| event.occurred_at)
.or_else(|| item.terms.as_ref().map(|terms| terms.created_at))
.ok_or_else(|| format!("autonomous bounty lacks creation time: {contract}"))?;
let created_block = created.map(|event| event.block_number).unwrap_or_default();
let updated_at = item
.events
.iter()
.max_by_key(|event| (event.block_number, event.log_index))
.map(|event| event.occurred_at)
.unwrap_or(created_at);
let target = parse_amount(&item.target_amount, "target_amount")?;
let funded = parse_amount(&item.funded_amount, "funded_amount")?;
if target == 0 || funded > target {
return Err(format!(
"autonomous bounty economics are invalid: {contract}"
));
}
let fully_funded = funded == target;
let terms = item.terms.as_ref();
let title = terms
.map(|terms| terms.document.title.clone())
.unwrap_or_else(|| item.bounty_id.clone());
let summary = terms
.map(|terms| terms.document.goal.clone())
.unwrap_or_else(|| {
"Inspect the canonical published bounty terms before acting.".to_string()
});
let evidence_schema = terms
.map(|terms| terms.document.evidence_schema.clone())
.unwrap_or(Value::Null);
let (categories, skills, _) =
web_public::discovery_taxonomy_with_matches(&title, Some(&summary), &evidence_schema);
let verification_ready = item.terms_valid && item.verification_ready;
let lifecycle_state = match item.status.as_str() {
"open" if !fully_funded => "funding_needed",
"open" => "unavailable",
"claimable" if fully_funded && verification_ready => "ready_to_earn",
"claimable" => "unavailable",
"claimed" => "in_progress",
"submitted" => "verification_pending",
"paid" => "settled",
"cancelled" => "cancelled",
other => return Err(format!("unknown autonomous status {other:?}: {contract}")),
};
let events_url = format!(
"{api}/v1/base/autonomous-bounties/events?network={network}&bounty_id={}",
item.bounty_id
);
let public_url = format!("{website}/earn.html?bountyContract={contract}&network={network}");
let (deadline, deadline_kind) = autonomous_deadline(item);
let next_action = autonomous_action(lifecycle_state, network, &contract, api, &events_url);
let settlement_evidence = if lifecycle_state == "settled" {
Some(autonomous_settlement(item, &contract)?)
} else {
None
};
let recovery_action_available =
lifecycle_state == "cancelled" && autonomous_refunded_principal(item)? < funded;
Ok(GitHubDiscoveryItem {
discovery_id: format!(
"eip155:{chain_id}:{AUTONOMOUS_PROTOCOL_VERSION}:{contract}"
),
network: network.to_string(),
chain_id,
protocol_version: AUTONOMOUS_PROTOCOL_VERSION.to_string(),
source_id: contract.clone(),
visibility: "public".to_string(),
bounty_id: item.bounty_id.clone(),
bounty_contract: contract,
created_at: created_at.to_rfc3339(),
created_block,
updated_at: updated_at.to_rfc3339(),
title,
summary,
categories,
skills,
difficulty: None,
public_url,
source_url: terms.and_then(|terms| terms.document.source_url.clone()),
competition_mode: "exclusive_claim".to_string(),
lifecycle_state: lifecycle_state.to_string(),
funded: fully_funded,
verification_ready,
ready_to_earn: lifecycle_state == "ready_to_earn",
reward_usdc_base_units: item.solver_reward.clone(),
verifier_reward_usdc_base_units: item.verifier_reward.clone(),
bond_usdc_base_units: item.claim_bond.clone(),
funded_usdc_base_units: item.funded_amount.clone(),
funding_target_usdc_base_units: item.target_amount.clone(),
deadline,
deadline_kind,
entry_count: None,
max_entries: None,
verifier: GitHubDiscoveryVerifier {
profile_id: None,
display_name: item.verification_mode.clone(),
method: item.verification_mode.clone(),
address: item.verifier_module.clone(),
runtime_code_hash: None,
ready: verification_ready,
},
next_action,
recovery_action_available,
identity_warning: None,
settlement_evidence,
evidence_boundary: "Canonical autonomous-v1 lifecycle state comes from confirmed factory and bounty events plus content-addressed terms. GitHub is a discovery mirror; only confirmed BountySettled proves solver payment.".to_string(),
})
}
fn autonomous_action(
lifecycle: &str,
network: &str,
contract: &str,
api: &str,
events_url: &str,
) -> GitHubDiscoveryAction {
let (kind, label, method, url, instructions) = match lifecycle {
"funding_needed" => (
"fund",
"Help fund this bounty",
"POST",
format!("{api}/v1/base/autonomous-bounties/contribution-plan"),
"Prepare an exact native-USDC contribution and confirm FundingAdded before describing it as funded.",
),
"ready_to_earn" => (
"claim",
"Claim this bounty",
"POST",
format!("{api}/v1/base/autonomous-bounties/claim-plan"),
"Prepare the exclusive claim for the displayed contract and confirm BountyClaimed before starting work.",
),
"verification_pending" => (
"verify",
"Inspect verification work",
"GET",
format!("{api}/v1/base/autonomous-bounties/verification-jobs?network={network}"),
"Inspect the committed verifier job. A submission is not acceptance or payment.",
),
"cancelled" => (
"withdraw_refund",
"Inspect refund recovery",
"POST",
format!("{api}/v1/base/autonomous-bounties/refund-withdrawal-plan"),
"Only an eligible contributor wallet can prepare its own pull refund.",
),
_ => (
"inspect",
"Inspect canonical state",
"GET",
events_url.to_string(),
"Inspect confirmed canonical events. GitHub state is not settlement evidence.",
),
};
let instructions = if lifecycle == "ready_to_earn" {
format!("{instructions} Bounty contract: {contract}.")
} else {
instructions.to_string()
};
GitHubDiscoveryAction {
kind: kind.to_string(),
label: label.to_string(),
method: method.to_string(),
url,
instructions,
}
}
fn autonomous_deadline(item: &AutonomousBountyFeedItem) -> (Option<String>, Option<String>) {
let Some(terms) = item.terms.as_ref() else {
return (None, None);
};
let Some(contract_terms) = terms.document.contract_terms.as_object() else {
return (None, None);
};
let (field, kind) = match item.status.as_str() {
"open" | "claimable" => ("funding_deadline", "funding_deadline"),
_ => return (None, None),
};
let value = contract_terms.get(field).and_then(json_u64);
(
value
.and_then(|value| DateTime::<Utc>::from_timestamp(value as i64, 0))
.map(|value| value.to_rfc3339()),
value.map(|_| kind.to_string()),
)
}
fn autonomous_refunded_principal(item: &AutonomousBountyFeedItem) -> Result<u128, String> {
item.events
.iter()
.filter(|event| event.kind == AutonomousBountyEventKind::RefundWithdrawn)
.try_fold(0u128, |total, event| {
json_u128_field(&event.data, "principal").and_then(|amount| {
total
.checked_add(amount)
.ok_or_else(|| "refund total overflow".to_string())
})
})
}
fn autonomous_settlement(
item: &AutonomousBountyFeedItem,
contract: &str,
) -> Result<GitHubSettlementEvidence, String> {
let matches = item
.events
.iter()
.filter(|event| event.kind == AutonomousBountyEventKind::BountySettled)
.collect::<Vec<_>>();
let [event] = matches.as_slice() else {
return Err(format!(
"paid autonomous bounty requires one BountySettled: {contract}"
));
};
let solver_reward = json_u128_field(&event.data, "solver_reward")?;
let returned_bond = json_u128_field(&event.data, "claim_bond_returned")?;
let completion_bonus = json_u128_field(&event.data, "timeout_bond_bonus")?;
let solver_payout = json_u128_field(&event.data, "solver_payout")?;
let verifier_reward = json_u128_field(&event.data, "verifier_reward")?;
if solver_payout
!= solver_reward
.checked_add(returned_bond)
.and_then(|value| value.checked_add(completion_bonus))
.ok_or_else(|| "solver payout overflow".to_string())?
{
return Err(format!(
"autonomous settlement payout is inconsistent: {contract}"
));
}
Ok(GitHubSettlementEvidence {
event_name: "BountySettled".to_string(),
bounty_id: item.bounty_id.clone(),
bounty_contract: contract.to_string(),
transaction_hash: event.tx_hash.clone(),
block_number: event.block_number,
log_index: event.log_index,
solver_wallet: json_text_field(&event.data, "solver")?,
solver_reward: solver_reward.to_string(),
returned_bond: returned_bond.to_string(),
completion_bonus: completion_bonus.to_string(),
solver_payout: solver_payout.to_string(),
verifier_reward: verifier_reward.to_string(),
confirmed_canonical: true,
})
}
fn unique_autonomous_event(
item: &AutonomousBountyFeedItem,
kind: AutonomousBountyEventKind,
) -> Result<Option<&AutonomousBountyEvent>, String> {
let matches = item
.events
.iter()
.filter(|event| event.kind == kind)
.collect::<Vec<_>>();
if matches.len() > 1 {
return Err(format!(
"duplicate autonomous event {:?}: {}",
kind, item.bounty_contract
));
}
Ok(matches.first().copied())
}
#[allow(clippy::too_many_arguments)]
pub fn open_competition_discovery_items(
events: &[OpenCompetitionEvent],
profile: &OpenCompetitionVerifierProfile,
network: &str,
chain_id: u64,
api_base_url: &str,
website_base_url: &str,
public_activation_block: u64,
now: DateTime<Utc>,
) -> Result<Vec<GitHubDiscoveryItem>, String> {
if !profile.public_inventory_eligible
|| profile.deployment_state != OpenCompetitionDeploymentState::ActiveReadyToEarn
{
return Ok(Vec::new());
}
let mut grouped = BTreeMap::<String, Vec<&OpenCompetitionEvent>>::new();
for event in events
.iter()
.filter(|event| event.block_number >= public_activation_block)
{
grouped
.entry(event.bounty_id.clone())
.or_default()
.push(event);
}
grouped
.into_iter()
.map(|(bounty_id, mut bounty_events)| {
bounty_events.sort_by_key(|event| (event.block_number, event.log_index));
open_competition_discovery_item(
&bounty_id,
&bounty_events,
profile,
network,
chain_id,
api_base_url,
website_base_url,
now,
)
})
.collect()
}
#[allow(clippy::too_many_arguments)]
fn open_competition_discovery_item(
bounty_id: &str,
events: &[&OpenCompetitionEvent],
profile: &OpenCompetitionVerifierProfile,
network: &str,
chain_id: u64,
api_base_url: &str,
website_base_url: &str,
now: DateTime<Utc>,
) -> Result<GitHubDiscoveryItem, String> {
let api = api_base_url.trim_end_matches('/');
let website = website_base_url.trim_end_matches('/');
let created = required_unique_open_event(
events,
OpenCompetitionEventKind::CanonicalCompetitionCreated,
)?;
let terms = required_unique_open_event(
events,
OpenCompetitionEventKind::CanonicalCompetitionTermsCommitted,
)?;
let economics = required_unique_open_event(
events,
OpenCompetitionEventKind::CanonicalCompetitionEconomicsConfigured,
)?;
let verification = required_unique_open_event(
events,
OpenCompetitionEventKind::CanonicalCompetitionVerificationConfigured,
)?;
if !json_text_field(&verification.data, "verifier_module")?
.eq_ignore_ascii_case(&profile.verifier_address)
|| !json_text_field(&terms.data, "benchmark_hash")?
.eq_ignore_ascii_case(&profile.benchmark_hash)
|| !json_text_field(&terms.data, "evidence_schema_hash")?
.eq_ignore_ascii_case(&profile.evidence_schema_hash)
{
return Err(format!(
"competition verifier commitments do not match catalog: {bounty_id}"
));
}
let contract = json_text_field(&created.data, "bounty_contract")?.to_ascii_lowercase();
let solver_reward = json_u128_field(&economics.data, "solver_reward")?;
let verifier_reward = json_u128_field(&economics.data, "verifier_reward")?;
let entry_bond = json_u128_field(&economics.data, "entry_bond")?;
let target = json_u128_field(&economics.data, "target_amount")?;
let mut funded = json_u128_field(&economics.data, "initial_funding")?;
let funding_deadline = json_u64_field(&economics.data, "funding_deadline")?;
let max_entries = u8::try_from(json_u64_field(&economics.data, "max_entries")?)
.map_err(|_| format!("competition capacity exceeds u8: {bounty_id}"))?;
if solver_reward == 0
|| verifier_reward == 0
|| entry_bond != verifier_reward
|| target != solver_reward.saturating_add(verifier_reward)
|| max_entries == 0
|| max_entries > 64
{
return Err(format!("competition economics are invalid: {bounty_id}"));
}
for event in events
.iter()
.filter(|event| event.kind == OpenCompetitionEventKind::FundingAdded)
{
funded = funded.max(json_u128_field(&event.data, "funded_amount")?);
}
let opened = last_open_event(events, OpenCompetitionEventKind::CompetitionOpened);
let settled = unique_optional_open_event(events, OpenCompetitionEventKind::BountySettled)?;
let cancelled = unique_optional_open_event(events, OpenCompetitionEventKind::BountyCancelled)?;
if settled.is_some() && cancelled.is_some() {
return Err(format!(
"competition is both settled and cancelled: {bounty_id}"
));
}
let competition_ends_at = opened
.map(|event| json_u64_field(&event.data, "competition_ends_at"))
.transpose()?;
let committed = solver_set(events, OpenCompetitionEventKind::SolutionCommitted)?;
let revealed = solver_set(events, OpenCompetitionEventKind::SolutionRevealed)?;
let expired = solver_set(events, OpenCompetitionEventKind::CommitmentExpired)?;
let withdrawn = solver_set(events, OpenCompetitionEventKind::EntryBondWithdrawn)?;
if committed.len() > usize::from(max_entries) {
return Err(format!(
"competition exceeds immutable capacity: {bounty_id}"
));
}
let active_reveals = events.iter().any(|event| {
event.kind == OpenCompetitionEventKind::SolutionCommitted
&& json_text_field(&event.data, "solver")
.ok()
.is_some_and(|solver| {
let solver = solver.to_ascii_lowercase();
!revealed.contains(&solver)
&& !expired.contains(&solver)
&& json_u64_field(&event.data, "reveal_deadline")
.ok()
.is_some_and(|deadline| deadline >= now.timestamp() as u64)
})
});
let fully_funded = funded == target;
let accepts_entries = settled.is_none()
&& cancelled.is_none()
&& fully_funded
&& competition_ends_at.is_some_and(|deadline| deadline > now.timestamp() as u64)
&& committed.len() < usize::from(max_entries);
let lifecycle_state = if settled.is_some() {
"settled"
} else if cancelled.is_some() {
"cancelled"
} else if accepts_entries {
"ready_to_earn"
} else if !fully_funded {
"funding_needed"
} else if active_reveals {
"in_progress"
} else if opened.is_some() {
"expired"
} else {
"unavailable"
};
let events_url =
format!("{api}/v1/base/open-competition-v1/events?network={network}&bounty_id={bounty_id}");
let public_url = format!(
"{website}/competition.html?bountyContract={contract}&network={network}&verifierProfileId={}",
profile.profile_id
);
let next_action = match lifecycle_state {
"ready_to_earn" => GitHubDiscoveryAction {
kind: "enter_competition".to_string(),
label: "Enter competition".to_string(),
method: "POST".to_string(),
url: format!("{api}/v1/base/open-competition-v1/commit-preparation"),
instructions: "Generate and save the secret-salt recovery envelope locally, then submit only its commitment. First valid confirmed reveal wins.".to_string(),
},
"funding_needed" => GitHubDiscoveryAction {
kind: "fund".to_string(),
label: "Help fund this competition".to_string(),
method: "GET".to_string(),
url: public_url.clone(),
instructions: "Inspect the exact immutable competition economics before funding. A token transfer without FundingAdded is not canonical funding.".to_string(),
},
"settled" => GitHubDiscoveryAction {
kind: "inspect_settlement".to_string(),
label: "Inspect canonical settlement".to_string(),
method: "GET".to_string(),
url: events_url.clone(),
instructions: "Only the confirmed BountySettled event proves solver payment.".to_string(),
},
_ => GitHubDiscoveryAction {
kind: if lifecycle_state == "cancelled" { "recover" } else { "inspect" }.to_string(),
label: if lifecycle_state == "cancelled" { "Inspect refunds and bond recovery" } else { "Inspect canonical state" }.to_string(),
method: "GET".to_string(),
url: events_url.clone(),
instructions: "Inspect version-specific canonical events and use only wallet-scoped pull recovery actions.".to_string(),
},
};
let settlement_evidence = settled
.map(|event| open_competition_settlement(event, bounty_id, &contract))
.transpose()?;
let loser_bond_recovery = committed.iter().any(|solver| {
!revealed.contains(solver) && !withdrawn.contains(solver) && !expired.contains(solver)
});
let refund_recovery = if let Some(cancelled) = cancelled {
let principal = json_u128_field(&cancelled.data, "principal")?;
let withdrawn_principal = events
.iter()
.filter(|event| event.kind == OpenCompetitionEventKind::RefundWithdrawn)
.try_fold(0u128, |total, event| {
json_u128_field(&event.data, "principal").and_then(|value| {
total
.checked_add(value)
.ok_or_else(|| "refund total overflow".to_string())
})
})?;
withdrawn_principal < principal
} else {
false
};
let deadline_value = competition_ends_at.unwrap_or(funding_deadline);
Ok(GitHubDiscoveryItem {
discovery_id: format!(
"eip155:{chain_id}:{OPEN_COMPETITION_PROTOCOL_VERSION}:{contract}"
),
network: network.to_string(),
chain_id,
protocol_version: OPEN_COMPETITION_PROTOCOL_VERSION.to_string(),
source_id: contract.clone(),
visibility: "public".to_string(),
bounty_id: bounty_id.to_string(),
bounty_contract: contract,
created_at: created.occurred_at.to_rfc3339(),
created_block: created.block_number,
updated_at: events.last().map(|event| event.occurred_at).unwrap_or(created.occurred_at).to_rfc3339(),
title: "Scope-bound hash-work competition".to_string(),
summary: "Produce proof bytes accepted by the exact published deterministic verifier. This profile does not judge ordinary code, design, writing, research, or task quality.".to_string(),
categories: vec!["cryptographic-work".to_string(), "deterministic".to_string()],
skills: vec!["commit-reveal".to_string(), "hash-work".to_string()],
difficulty: None,
public_url,
source_url: None,
competition_mode: "first_valid_submission".to_string(),
lifecycle_state: lifecycle_state.to_string(),
funded: fully_funded,
verification_ready: true,
ready_to_earn: lifecycle_state == "ready_to_earn",
reward_usdc_base_units: solver_reward.to_string(),
verifier_reward_usdc_base_units: verifier_reward.to_string(),
bond_usdc_base_units: entry_bond.to_string(),
funded_usdc_base_units: funded.to_string(),
funding_target_usdc_base_units: target.to_string(),
deadline: DateTime::<Utc>::from_timestamp(deadline_value as i64, 0).map(|value| value.to_rfc3339()),
deadline_kind: Some(if competition_ends_at.is_some() { "competition_deadline" } else { "funding_deadline" }.to_string()),
entry_count: Some(u8::try_from(committed.len()).map_err(|_| "entry count exceeds u8".to_string())?),
max_entries: Some(max_entries),
verifier: GitHubDiscoveryVerifier {
profile_id: Some(profile.profile_id.clone()),
display_name: profile.display_name.clone(),
method: profile.module_kind.clone(),
address: Some(profile.verifier_address.clone()),
runtime_code_hash: Some(profile.runtime_code_hash.clone()),
ready: true,
},
next_action,
recovery_action_available: loser_bond_recovery || refund_recovery,
identity_warning: Some("One wallet does not prove one independent person.".to_string()),
settlement_evidence,
evidence_boundary: "Open Competition is limited to this exact catalog-pinned deterministic verifier. GitHub cannot choose a winner. A commitment, reveal, transaction hash, or hosted row is not payment; only confirmed BountySettled proves solver payment.".to_string(),
})
}
fn open_competition_settlement(
event: &OpenCompetitionEvent,
bounty_id: &str,
contract: &str,
) -> Result<GitHubSettlementEvidence, String> {
let solver_reward = json_u128_field(&event.data, "solver_reward")?;
let returned_bond = json_u128_field(&event.data, "entry_bond_returned")?;
let completion_bonus = json_u128_field(&event.data, "timeout_bond_bonus")?;
let verifier_reward = json_u128_field(&event.data, "verifier_reward")?;
let solver_payout = solver_reward
.checked_add(returned_bond)
.and_then(|value| value.checked_add(completion_bonus))
.ok_or_else(|| "competition payout overflow".to_string())?;
Ok(GitHubSettlementEvidence {
event_name: "BountySettled".to_string(),
bounty_id: bounty_id.to_string(),
bounty_contract: contract.to_string(),
transaction_hash: event.tx_hash.clone(),
block_number: event.block_number,
log_index: event.log_index,
solver_wallet: json_text_field(&event.data, "solver")?,
solver_reward: solver_reward.to_string(),
returned_bond: returned_bond.to_string(),
completion_bonus: completion_bonus.to_string(),
solver_payout: solver_payout.to_string(),
verifier_reward: verifier_reward.to_string(),
confirmed_canonical: event.data.get("canonical_payment_evidence") == Some(&json!(true)),
})
}
fn required_unique_open_event<'a>(
events: &'a [&OpenCompetitionEvent],
kind: OpenCompetitionEventKind,
) -> Result<&'a OpenCompetitionEvent, String> {
unique_optional_open_event(events, kind)?
.ok_or_else(|| format!("competition is missing {kind:?}"))
}
fn unique_optional_open_event<'a>(
events: &'a [&OpenCompetitionEvent],
kind: OpenCompetitionEventKind,
) -> Result<Option<&'a OpenCompetitionEvent>, String> {
let matches = events
.iter()
.copied()
.filter(|event| event.kind == kind)
.collect::<Vec<_>>();
if matches.len() > 1 {
return Err(format!("competition has duplicate {kind:?}"));
}
Ok(matches.first().copied())
}
fn last_open_event<'a>(
events: &'a [&OpenCompetitionEvent],
kind: OpenCompetitionEventKind,
) -> Option<&'a OpenCompetitionEvent> {
events
.iter()
.rev()
.copied()
.find(|event| event.kind == kind)
}
fn solver_set(
events: &[&OpenCompetitionEvent],
kind: OpenCompetitionEventKind,
) -> Result<BTreeSet<String>, String> {
events
.iter()
.filter(|event| event.kind == kind)
.map(|event| {
json_text_field(&event.data, "solver").map(|solver| solver.to_ascii_lowercase())
})
.collect()
}
fn parse_amount(value: &str, field: &str) -> Result<u128, String> {
value
.parse::<u128>()
.map_err(|_| format!("invalid {field}"))
}
fn json_text_field(value: &Value, field: &str) -> Result<String, String> {
value
.get(field)
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.map(str::to_string)
.ok_or_else(|| format!("missing text field {field}"))
}
fn json_u64(value: &Value) -> Option<u64> {
value.as_u64().or_else(|| value.as_str()?.parse().ok())
}
fn json_u64_field(value: &Value, field: &str) -> Result<u64, String> {
value
.get(field)
.and_then(json_u64)
.ok_or_else(|| format!("missing integer field {field}"))
}
fn json_u128_field(value: &Value, field: &str) -> Result<u128, String> {
let value = value
.get(field)
.ok_or_else(|| format!("missing integer field {field}"))?;
if let Some(value) = value.as_u64() {
return Ok(u128::from(value));
}
value
.as_str()
.ok_or_else(|| format!("invalid integer field {field}"))?
.parse::<u128>()
.map_err(|_| format!("invalid integer field {field}"))
}
#[cfg(test)]
mod tests {
use super::*;
use chain_base::{built_in_open_competition_verifier_catalog, AutonomousBountyEvent};
use chrono::TimeZone;
use domain::Id;
fn open_event(kind: OpenCompetitionEventKind, block: u64, data: Value) -> OpenCompetitionEvent {
OpenCompetitionEvent {
id: Id::from_u128(u128::from(block) + 1),
protocol_version: OPEN_COMPETITION_PROTOCOL_VERSION.to_string(),
log_key: format!("{block}:0"),
tx_hash: format!("0x{:064x}", block),
block_number: block,
log_index: 0,
contract_address: "0x3551ca7bb9090fb8c1648eea40837c8a1cbcc973".to_string(),
bounty_id: format!("0x{:064x}", 1),
kind,
data,
occurred_at: Utc.timestamp_opt(1_700_000_000 + block as i64, 0).unwrap(),
}
}
fn competition_fixture() -> (Vec<OpenCompetitionEvent>, OpenCompetitionVerifierProfile) {
let mut profiles = built_in_open_competition_verifier_catalog("base-mainnet")
.unwrap()
.profiles;
let profile = profiles.remove(0);
let contract = "0x3551ca7bb9090fb8c1648eea40837c8a1cbcc973";
let events = vec![
open_event(
OpenCompetitionEventKind::CanonicalCompetitionCreated,
10,
json!({
"bounty_contract": contract,
"terms_hash": format!("0x{}", "11".repeat(32)),
"policy_hash": format!("0x{}", "22".repeat(32))
}),
),
open_event(
OpenCompetitionEventKind::CanonicalCompetitionTermsCommitted,
10,
json!({
"acceptance_criteria_hash": format!("0x{}", "33".repeat(32)),
"benchmark_hash": profile.benchmark_hash,
"evidence_schema_hash": profile.evidence_schema_hash
}),
),
open_event(
OpenCompetitionEventKind::CanonicalCompetitionEconomicsConfigured,
10,
json!({
"solver_reward": 500000,
"verifier_reward": 50000,
"entry_bond": 50000,
"target_amount": 550000,
"initial_funding": 550000,
"funding_deadline": 1_800_000_000u64,
"max_entries": 4
}),
),
open_event(
OpenCompetitionEventKind::CanonicalCompetitionVerificationConfigured,
10,
json!({
"verifier_module": profile.verifier_address
}),
),
open_event(
OpenCompetitionEventKind::CompetitionOpened,
11,
json!({
"competition_ends_at": 1_800_000_000u64,
"max_entries": 4
}),
),
];
(events, profile)
}
fn autonomous_fixture(status: &str, funded: u128) -> AutonomousBountyFeedItem {
let contract = "0x1111111111111111111111111111111111111111";