forked from NSPG13/agent-bounties
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
9683 lines (9236 loc) · 374 KB
/
Copy pathlib.rs
File metadata and controls
9683 lines (9236 loc) · 374 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 alloy::{
network::TransactionBuilder,
primitives::{Address, Bytes, B256, U256},
providers::{Provider, ProviderBuilder},
rpc::types::TransactionRequest,
signers::{local::PrivateKeySigner, SignerSync},
};
use chrono::{DateTime, Utc};
use domain::{
AutonomousBountyTermsDocument, AutonomousBountyTermsRecord, AutonomousSubmissionEvidenceRecord,
BountyImageReference, Id, Money,
};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use sha2::Sha256;
use sha3::{Digest, Keccak256};
use std::{
collections::{BTreeMap, HashMap, HashSet},
env,
};
use thiserror::Error;
use uuid::Uuid;
use verifier_sdk::RegressionSandboxPolicy;
mod agent_wallet_readiness;
mod open_competition;
mod standing_meta_v4;
pub use agent_wallet_readiness::*;
pub use open_competition::*;
pub use standing_meta_v4::*;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum ChainBaseError {
#[error("duplicate chain log")]
DuplicateLog,
#[error("invalid escrow release split")]
InvalidReleaseSplit,
#[error("invalid EVM address: {0}")]
InvalidAddress(String),
#[error("invalid bytes32 hex value: {0}")]
InvalidBytes32(String),
#[error("invalid on-chain escrow id")]
InvalidEscrowId,
#[error("invalid on-chain amount")]
InvalidAmount,
#[error("autonomous bounties settle in USDC")]
InvalidSettlementCurrency,
#[error("initial bounty funding exceeds the solver and verifier reward target")]
InitialFundingExceedsTarget,
#[error("invalid autonomous bounty verification configuration: {0}")]
InvalidVerificationConfiguration(String),
#[error("invalid canonical JSON commitment: {0}")]
InvalidCanonicalJson(String),
#[error("invalid autonomous bounty terms document: {0}")]
InvalidTermsDocument(String),
#[error("invalid autonomous verification attestation scope: {0}")]
InvalidAttestationScope(String),
#[error("invalid autonomous submission evidence: {0}")]
InvalidSubmissionEvidence(String),
#[error("invalid autonomous submission preparation: {0}")]
InvalidSubmissionPreparation(String),
#[error("autonomous bounty terms document exceeds 256 KiB")]
TermsDocumentTooLarge,
#[error("release recipients must be non-empty")]
EmptyRecipients,
#[error("release recipients must use a single currency")]
MixedRecipientCurrencies,
#[error("unknown escrow event topic: {0}")]
UnknownEventTopic(String),
#[error("invalid EVM log topics for {0}")]
InvalidLogTopics(String),
#[error("invalid EVM log data for {0}")]
InvalidLogData(String),
#[error("terminal escrow log arrived before created log")]
UnknownEscrowForTerminalLog,
#[error("invalid block range: from {from_block} is greater than to {to_block}")]
InvalidBlockRange { from_block: u64, to_block: u64 },
#[error("invalid EVM RPC quantity: {0}")]
InvalidRpcQuantity(String),
#[error("invalid signed EVM transaction: {0}")]
InvalidSignedTransaction(String),
#[error("invalid hex bytes: {0}")]
InvalidHexBytes(String),
#[error("invalid EVM transaction hash: {0}")]
InvalidTransactionHash(String),
#[error("unknown Base network: {0}")]
UnknownNetwork(String),
#[error("missing RPC URL for {network}; set {env_var}")]
MissingRpcUrl { network: String, env_var: String },
#[error("Base RPC transport error: {0}")]
RpcTransport(String),
#[error("Base RPC returned HTTP status {0}")]
RpcHttpStatus(u16),
#[error("Base RPC provider error {code}: {message}")]
RpcProviderError { code: i64, message: String },
#[error("invalid Base RPC response: {0}")]
InvalidRpcResponse(String),
#[error("invalid Base relayer private key")]
InvalidRelayerPrivateKey,
#[error("invalid bounded Base relay intent: {0}")]
InvalidRelayIntent(String),
#[error("Base relayer connected to chain {observed}; expected {expected}")]
RelayerChainMismatch { expected: u64, observed: u64 },
#[error("Base relay gas estimate {estimated} exceeds cap {maximum}")]
RelayerGasLimitExceeded { estimated: u64, maximum: u64 },
#[error("Base relay max fee per gas {estimated} exceeds cap {maximum}")]
RelayerFeeCapExceeded { estimated: u128, maximum: u128 },
#[error("Base relayer balance {balance} is below bounded transaction cost {required}")]
RelayerInsufficientBalance { balance: u128, required: u128 },
#[error("Base relayer provider error: {0}")]
RelayerProvider(String),
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EvmTransactionIntent {
pub from: Option<String>,
pub to: String,
pub value_wei: u128,
pub data: String,
pub function: String,
}
#[derive(Clone)]
pub struct BaseTransactionRelayer {
signer: PrivateKeySigner,
}
impl std::fmt::Debug for BaseTransactionRelayer {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("BaseTransactionRelayer")
.field("address", &self.address())
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct BaseRelayedTransaction {
pub relayer: String,
pub tx_hash: String,
pub estimated_gas: u64,
pub gas_limit: u64,
pub max_fee_per_gas_wei: u128,
pub max_priority_fee_per_gas_wei: u128,
pub estimated_max_cost_wei: u128,
}
impl BaseTransactionRelayer {
pub fn from_private_key(private_key: &str) -> Result<Self, ChainBaseError> {
let signer = private_key
.trim()
.parse::<PrivateKeySigner>()
.map_err(|_| ChainBaseError::InvalidRelayerPrivateKey)?;
Ok(Self { signer })
}
pub fn address(&self) -> String {
format!("{:#x}", self.signer.address())
}
pub fn sign_digest(&self, digest: &str) -> Result<String, ChainBaseError> {
let digest = B256::from(parse_bytes32(digest)?);
let signature = self
.signer
.sign_hash_sync(&digest)
.map_err(|_| ChainBaseError::InvalidRelayIntent("digest signing failed".to_string()))?;
Ok(format!("0x{}", hex::encode(signature.as_bytes())))
}
pub async fn simulate_and_broadcast(
&self,
rpc_url: &str,
expected_chain_id: u64,
intent: &EvmTransactionIntent,
max_gas: u64,
max_fee_per_gas_wei: u128,
) -> Result<BaseRelayedTransaction, ChainBaseError> {
if max_gas == 0 || max_fee_per_gas_wei == 0 {
return Err(ChainBaseError::InvalidRelayIntent(
"gas and fee caps must be positive".to_string(),
));
}
if intent.value_wei != 0 {
return Err(ChainBaseError::InvalidRelayIntent(
"hosted relays cannot transfer ETH value".to_string(),
));
}
let relayer = self.signer.address();
if let Some(from) = intent.from.as_deref() {
let expected = parse_alloy_address(from)?;
if expected != relayer {
return Err(ChainBaseError::InvalidRelayIntent(
"transaction sender does not match the configured relayer".to_string(),
));
}
}
let to = parse_alloy_address(&intent.to)?;
let data = parse_alloy_bytes(&intent.data)?;
if data.len() < 4 {
return Err(ChainBaseError::InvalidRelayIntent(
"transaction calldata is missing a function selector".to_string(),
));
}
let rpc_url = rpc_url.parse().map_err(|_| {
ChainBaseError::RelayerProvider("configured RPC URL is invalid".to_string())
})?;
let provider = ProviderBuilder::new()
.wallet(self.signer.clone())
.connect_http(rpc_url);
let observed_chain_id = provider
.get_chain_id()
.await
.map_err(sanitize_relayer_provider_error)?;
if observed_chain_id != expected_chain_id {
return Err(ChainBaseError::RelayerChainMismatch {
expected: expected_chain_id,
observed: observed_chain_id,
});
}
let transaction = TransactionRequest::default()
.with_from(relayer)
.with_to(to)
.with_value(U256::ZERO)
.with_input(data);
provider
.call(transaction.clone())
.await
.map_err(sanitize_relayer_provider_error)?;
let estimated_gas = provider
.estimate_gas(transaction.clone())
.await
.map_err(sanitize_relayer_provider_error)?;
let gas_limit = estimated_gas
.checked_mul(120)
.and_then(|value| value.checked_add(99))
.map(|value| value / 100)
.ok_or_else(|| {
ChainBaseError::InvalidRelayIntent("gas estimate overflow".to_string())
})?;
if gas_limit > max_gas {
return Err(ChainBaseError::RelayerGasLimitExceeded {
estimated: gas_limit,
maximum: max_gas,
});
}
let fees = provider
.estimate_eip1559_fees()
.await
.map_err(sanitize_relayer_provider_error)?;
if fees.max_fee_per_gas > max_fee_per_gas_wei {
return Err(ChainBaseError::RelayerFeeCapExceeded {
estimated: fees.max_fee_per_gas,
maximum: max_fee_per_gas_wei,
});
}
let estimated_max_cost_wei = u128::from(gas_limit)
.checked_mul(fees.max_fee_per_gas)
.ok_or_else(|| {
ChainBaseError::InvalidRelayIntent("maximum gas cost overflow".to_string())
})?;
let balance = provider
.get_balance(relayer)
.await
.map_err(sanitize_relayer_provider_error)?;
let balance = u128::try_from(balance).map_err(|_| {
ChainBaseError::InvalidRelayIntent("relayer balance exceeds u128".to_string())
})?;
if balance < estimated_max_cost_wei {
return Err(ChainBaseError::RelayerInsufficientBalance {
balance,
required: estimated_max_cost_wei,
});
}
let transaction = transaction
.with_gas_limit(gas_limit)
.with_max_fee_per_gas(fees.max_fee_per_gas)
.with_max_priority_fee_per_gas(fees.max_priority_fee_per_gas);
let pending = provider
.send_transaction(transaction)
.await
.map_err(sanitize_relayer_provider_error)?;
Ok(BaseRelayedTransaction {
relayer: format!("{relayer:#x}"),
tx_hash: format!("{:#x}", pending.tx_hash()),
estimated_gas,
gas_limit,
max_fee_per_gas_wei: fees.max_fee_per_gas,
max_priority_fee_per_gas_wei: fees.max_priority_fee_per_gas,
estimated_max_cost_wei,
})
}
}
fn parse_alloy_address(value: &str) -> Result<Address, ChainBaseError> {
value
.parse::<Address>()
.map_err(|_| ChainBaseError::InvalidAddress(value.to_string()))
}
fn parse_alloy_bytes(value: &str) -> Result<Bytes, ChainBaseError> {
let raw = value.strip_prefix("0x").ok_or_else(|| {
ChainBaseError::InvalidRelayIntent("calldata must be 0x-prefixed".to_string())
})?;
let decoded = hex::decode(raw).map_err(|_| {
ChainBaseError::InvalidRelayIntent("calldata must be valid hex".to_string())
})?;
Ok(Bytes::from(decoded))
}
fn sanitize_relayer_provider_error(error: impl std::fmt::Display) -> ChainBaseError {
let message = redact_provider_urls(&error.to_string());
let first_line = message.lines().next().unwrap_or("provider request failed");
let bounded = first_line.chars().take(300).collect::<String>();
ChainBaseError::RelayerProvider(bounded)
}
pub fn redact_provider_urls(message: &str) -> String {
let mut redacted = String::with_capacity(message.len());
let mut index = 0;
while index < message.len() {
let remaining = &message[index..];
let scheme_len = if remaining.starts_with("https://") {
Some(8)
} else if remaining.starts_with("http://") {
Some(7)
} else if remaining.starts_with("wss://") {
Some(6)
} else if remaining.starts_with("ws://") {
Some(5)
} else {
None
};
if let Some(scheme_len) = scheme_len {
redacted.push_str("[redacted-url]");
index += scheme_len;
while index < message.len() {
let character = message[index..]
.chars()
.next()
.expect("index remains on a character boundary");
if character.is_whitespace()
|| matches!(character, '"' | '\'' | ')' | ']' | '}' | ',' | ';')
{
break;
}
index += character.len_utf8();
}
continue;
}
let character = remaining
.chars()
.next()
.expect("index remains below message length");
redacted.push(character);
index += character.len_utf8();
}
redacted
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AutonomousVerificationMode {
DeterministicModule,
SignedQuorum,
AiJudgeQuorum,
}
impl AutonomousVerificationMode {
fn word(self) -> Result<[u8; 32], ChainBaseError> {
encode_uint256(match self {
Self::DeterministicModule => 0,
Self::SignedQuorum => 1,
Self::AiJudgeQuorum => 2,
})
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyCreate {
pub creator: String,
pub solver_reward: Money,
pub verifier_reward: Money,
pub terms_hash: String,
pub policy_hash: String,
pub acceptance_criteria_hash: String,
pub benchmark_hash: String,
pub evidence_schema_hash: String,
pub funding_deadline: u64,
pub claim_window_seconds: u64,
pub verification_window_seconds: u64,
pub verification_mode: AutonomousVerificationMode,
pub verifier_module: Option<String>,
pub verifier_reward_recipient: Option<String>,
#[serde(default)]
pub verifiers: Vec<String>,
pub threshold: u8,
pub initial_funding: Money,
pub creation_nonce: String,
}
pub const CANONICAL_CHILD_PROTOCOL_VERSION: &str = "agent-bounties/canonical-child-v1";
pub const STANDING_META_V2_PROTOCOL_VERSION: &str = "agent-bounties/independent-child-v2";
pub const STANDING_META_V3_ROUTED_PROTOCOL_VERSION: &str =
"agent-bounties/independent-child-v3-routed";
pub const STANDING_META_V2_REGRESSION_ENGINE: &str = "sandboxed_regression_v1";
pub const BASE_MAINNET_STANDING_META_V2_VERIFIER: &str =
"0xe573cb4f471d38b5bf10ce82237251ac902c9867";
pub const BASE_MAINNET_STANDING_META_V3_ROUTER: &str = "0x380c1af742593dd88b6f20387e9ee693a0536731";
pub const BASE_MAINNET_AUTONOMOUS_BOUNTY_FACTORY: &str =
"0x082c52131aaf0c56e76b075f895eab6fcab6d2f9";
pub const BASE_MAINNET_AUTONOMOUS_BOUNTY_IMPLEMENTATION: &str =
"0x2fa36d2b2327642db3a6cc8cdd91544ad7484eb9";
pub const BASE_MAINNET_STANDING_META_V2_TERMS_REGISTRY: &str =
"0x35e5d49c12b75c119d33951c2c4f054c5732208c";
pub const BASE_MAINNET_STANDING_META_V2_PARTICIPANT_REGISTRY: &str =
"0x9875dcaf570bde8ff1aa62275d3c8985f4fd1294";
pub const BASE_MAINNET_STANDING_META_V2_ACCEPTANCE_CRITERIA_HASH: &str =
"0x25c41d7d51e2c807754b901733de17cdb1778dbd353f86347ff33e10289fcb54";
pub const BASE_MAINNET_STANDING_META_V3_ACCEPTANCE_CRITERIA_HASH: &str =
"0xba3b04ab970dfd91f5ccf1b7eda6670b5a38a854bca16dc980ec8362ed2bcaf9";
pub const BASE_MAINNET_STANDING_META_V2_VERIFIER_SET_HASH: &str =
"0x2c5a10915ca1fb99d4a11e2222b4f32b986b4e0f5599f55d70e9c8f9725a28cd";
pub const BASE_MAINNET_DEFAULT_REGRESSION_VERIFIER_SET_HASH: &str =
"0x0838846e439ed67544d8a06da2a0f344fb25cd44723ad65839da3f242a72b1f2";
pub const BASE_MAINNET_STANDING_META_V2_VERIFIERS: [&str; 2] = [
"0xbe6292b9e465f549e2363b918d6dd9187038431e",
"0xb7c2ce6430b66fb986e27b6140b29309550d487a",
];
pub const STANDING_META_V2_DEFAULT_VERIFIER_REWARD: i64 = 100_000;
pub const STANDING_META_V3_DEFAULT_VERIFIER_REWARD: i64 = 10_000;
pub const STANDING_META_V2_DEFAULT_WORK_WINDOW_SECONDS: u64 = 3 * 24 * 60 * 60;
pub const STANDING_META_V2_MAX_ONCHAIN_TERMS_BYTES: usize = 32_768;
pub const AUTONOMOUS_FUND_WITH_AUTHORIZATION_FUNCTION: &str =
"fundWithAuthorization(address,uint256,uint256,uint256,bytes32,uint8,bytes32,bytes32)";
pub const AUTONOMOUS_FUND_WITH_AUTHORIZATION_SELECTOR: &str = "e1c9e96f";
pub const CANONICAL_CHILD_ACCEPTANCE_CRITERIA: [&str; 4] = [
"Post a canonical autonomous-v1 child bounty whose creator is the active solver.",
"Fully fund the child to at least the parent solver reward; pooled contributors are allowed.",
"Bind the child benchmark to the parent bounty ID and round and use an explicit deterministic verifier.",
"Have a different wallet complete the child and receive canonical settlement before the parent verification deadline.",
];
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CanonicalChildBountyTermsRequest {
pub parent_bounty_id: String,
pub parent_round: u64,
pub parent_solver: String,
pub parent_solver_reward: Money,
pub child_acceptance_criteria: Vec<String>,
pub verifier_module: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CanonicalChildBountyTermsPlan {
pub protocol_version: String,
pub parent_bounty_id: String,
pub parent_round: u64,
pub required_creator: String,
pub minimum_child_target: Money,
pub acceptance_criteria: Vec<String>,
pub acceptance_criteria_hash: String,
pub benchmark: Value,
pub benchmark_hash: String,
pub verification_mode: AutonomousVerificationMode,
pub verifier_module: String,
pub threshold: u8,
pub required_child_status: String,
pub proof_encoding: String,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StandingMetaV2BenchmarkSource {
pub kind: String,
pub repository: String,
pub commit: String,
pub subdirectory: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StandingMetaV2ChildPreparationRequest {
pub network: Option<String>,
pub parent_bounty_contract: String,
pub parent_solver: String,
pub intended_child_solver: String,
pub title: String,
pub goal: String,
pub acceptance_criteria: Vec<String>,
pub benchmark_source: StandingMetaV2BenchmarkSource,
pub runner_manifest: RegressionSandboxPolicy,
pub evidence_schema: Option<Value>,
pub verifier_reward: Option<Money>,
pub funding_deadline: Option<u64>,
pub claim_window_seconds: Option<u64>,
pub verification_window_seconds: Option<u64>,
pub creation_nonce: Option<String>,
pub nonce_salt: Option<String>,
pub source_url: Option<String>,
pub discovery_source: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StandingMetaV2ParentContext {
pub protocol_version: String,
pub bounty_contract: String,
pub bounty_id: String,
pub creator: String,
pub round: u64,
pub solver_reward: Money,
pub child_target: Money,
pub funding_deadline: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StandingMetaV2ParticipantPreconditions {
pub registry: String,
pub parent_solver: String,
pub intended_child_solver: String,
pub required_before_parent_claim: bool,
pub distinct_participant_ids_required: bool,
pub evidence_status: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StandingMetaV2ParentClaimTiming {
pub terms_must_predate_parent_claim: bool,
pub participant_registrations_must_predate_parent_claim: bool,
pub strict_timestamp_ordering: bool,
pub same_block_claim_allowed: bool,
pub evidence_status: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StandingMetaV2ChildPreparationPlan {
pub protocol_version: String,
pub network: BaseNetworkDescriptor,
pub parent_bounty_contract: String,
pub parent_bounty_id: String,
pub parent_round: u64,
pub parent_solver: String,
pub intended_child_solver: String,
pub participant_preconditions: StandingMetaV2ParticipantPreconditions,
pub parent_claim_timing: StandingMetaV2ParentClaimTiming,
pub terms_registry: String,
pub task_verifiers: Vec<String>,
pub task_verifier_set_hash: String,
pub task_verifier_threshold: u8,
pub terms: AutonomousBountyTermsRecord,
pub canonical_terms_json: String,
pub canonical_terms_hex: String,
pub hosted_terms_published: bool,
pub publish_terms: EvmTransactionIntent,
pub child_create: AutonomousBountyCreate,
pub child_creation: AutonomousBountyCreationPlan,
pub pre_claim_wallet_calls: Vec<EvmTransactionIntent>,
pub supports_single_wallet_batch: bool,
pub current_state: String,
pub next_action: String,
pub required_canonical_events: Vec<String>,
pub evidence_boundary: String,
}
pub fn plan_canonical_child_bounty_terms(
request: &CanonicalChildBountyTermsRequest,
) -> Result<CanonicalChildBountyTermsPlan, ChainBaseError> {
let parent_id = parse_bytes32(&request.parent_bounty_id)?;
if request.parent_round == 0 {
return Err(ChainBaseError::InvalidVerificationConfiguration(
"canonical child parent round must be positive".to_string(),
));
}
let parent_solver = normalize_address(&request.parent_solver)?;
let verifier_module = normalize_address(&request.verifier_module)?;
if parent_solver == "0x0000000000000000000000000000000000000000"
|| verifier_module == "0x0000000000000000000000000000000000000000"
{
return Err(ChainBaseError::InvalidVerificationConfiguration(
"canonical child solver and verifier module must be nonzero".to_string(),
));
}
if verifier_module.eq_ignore_ascii_case(BASE_MAINNET_CANONICAL_CHILD_VERIFIER) {
return Err(ChainBaseError::InvalidVerificationConfiguration(
"the parent canonical-child verifier cannot verify its own child task; choose the child's task-specific deterministic verifier"
.to_string(),
));
}
if verifier_module.eq_ignore_ascii_case(BASE_MAINNET_LEADING_ZERO_WORK_VERIFIER) {
return Err(ChainBaseError::InvalidVerificationConfiguration(
"the leading-zero work canary cannot verify a canonical child task: its exact proof-of-work benchmark conflicts with the required parent-bound child benchmark; deploy or choose a task-specific deterministic verifier"
.to_string(),
));
}
autonomous_money_to_uint256(&request.parent_solver_reward, false)?;
if request.child_acceptance_criteria.is_empty()
|| request.child_acceptance_criteria.len() > 20
|| request
.child_acceptance_criteria
.iter()
.any(|criterion| criterion.trim().is_empty() || criterion.len() > 500)
{
return Err(ChainBaseError::InvalidVerificationConfiguration(
"canonical child acceptance criteria must contain 1-20 nonempty items of at most 500 bytes"
.to_string(),
));
}
let parent_bounty_id = format!("0x{}", hex::encode(parent_id));
let acceptance_criteria = request.child_acceptance_criteria.clone();
let benchmark = json!({
"parent_bounty_id": parent_bounty_id,
"parent_round_hex": format!("0x{:016x}", request.parent_round),
"protocol": CANONICAL_CHILD_PROTOCOL_VERSION,
});
Ok(CanonicalChildBountyTermsPlan {
protocol_version: CANONICAL_CHILD_PROTOCOL_VERSION.to_string(),
parent_bounty_id,
parent_round: request.parent_round,
required_creator: parent_solver,
minimum_child_target: Money {
amount: request.parent_solver_reward.amount,
currency: "usdc".to_string(),
},
acceptance_criteria_hash: keccak256_canonical_json(&json!(acceptance_criteria))?,
acceptance_criteria,
benchmark_hash: keccak256_canonical_json(&benchmark)?,
benchmark,
verification_mode: AutonomousVerificationMode::DeterministicModule,
verifier_module,
threshold: 1,
required_child_status: "settled".to_string(),
proof_encoding: "abi.encode(address childBounty)".to_string(),
evidence_boundary: "This plan is not completion or payout evidence. The parent passes only after the configured verifier reads a parent-bound canonical child in Settled state, created by the parent solver and completed by a different wallet through its own explicit deterministic verifier. The child's confirmed canonical BountySettled event proves the child solver was paid; the parent's confirmed canonical BountySettled event proves the parent solver was paid.".to_string(),
})
}
fn standing_meta_v2_benchmark_source(
source: &StandingMetaV2BenchmarkSource,
) -> Result<Value, ChainBaseError> {
let repository_parts = source.repository.split('/').collect::<Vec<_>>();
let valid_repository_part = |value: &&str| {
!value.is_empty()
&& value.len() <= 100
&& value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
};
let commit = source.commit.to_ascii_lowercase();
let subdirectory_parts = source.subdirectory.split('/').collect::<Vec<_>>();
if source.kind != "github_commit"
|| repository_parts.len() != 2
|| !repository_parts.iter().all(valid_repository_part)
|| commit.len() != 40
|| !commit.bytes().all(|byte| byte.is_ascii_hexdigit())
|| source.subdirectory.starts_with('/')
|| source.subdirectory.ends_with('/')
|| source.subdirectory.contains('\\')
|| subdirectory_parts
.iter()
.any(|part| part.is_empty() || matches!(*part, "." | ".."))
{
return Err(ChainBaseError::InvalidVerificationConfiguration(
"benchmark source must be an exact github_commit with owner/repository, a full Git SHA, and a normalized non-root subdirectory"
.to_string(),
));
}
Ok(json!({
"kind": "github_commit",
"repository": source.repository,
"commit": commit,
"subdirectory": source.subdirectory,
}))
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Eip3009AuthorizationMessage {
pub from: String,
pub to: String,
pub value: String,
pub valid_after: String,
pub valid_before: String,
pub nonce: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Eip712DomainData {
pub name: String,
pub version: String,
#[serde(rename = "chainId")]
pub chain_id: u64,
#[serde(rename = "verifyingContract")]
pub verifying_contract: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Eip712TypeField {
pub name: String,
#[serde(rename = "type")]
pub field_type: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Eip3009AuthorizationTypedData {
pub types: BTreeMap<String, Vec<Eip712TypeField>>,
pub domain: Eip712DomainData,
pub primary_type: String,
pub message: Eip3009AuthorizationMessage,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyCreationPlan {
pub protocol_version: String,
pub network: BaseNetworkDescriptor,
pub factory_contract: String,
pub implementation_contract: String,
pub bounty_id: String,
pub predicted_bounty_contract: String,
pub approve: Option<EvmTransactionIntent>,
pub create_bounty: EvmTransactionIntent,
pub wallet_calls: Vec<EvmTransactionIntent>,
pub supports_single_wallet_batch: bool,
pub eip3009_authorization: Option<Eip3009AuthorizationTypedData>,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyCreationBatchPlan {
pub protocol_version: String,
pub network: BaseNetworkDescriptor,
pub creator: String,
pub total_initial_funding: String,
pub approve: Option<EvmTransactionIntent>,
pub creations: Vec<AutonomousBountyCreationPlan>,
pub wallet_calls: Vec<EvmTransactionIntent>,
pub supports_single_wallet_batch: bool,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyAuthorizationSignature {
pub v: u8,
pub r: String,
pub s: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyAuthorizedCreationPlan {
pub protocol_version: String,
pub network: BaseNetworkDescriptor,
pub bounty_id: String,
pub predicted_bounty_contract: String,
pub relay_transaction: EvmTransactionIntent,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyContribution {
pub bounty_contract: String,
pub contributor: String,
pub amount: Money,
pub authorization_nonce: Option<String>,
pub authorization_valid_before: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyContributionPlan {
pub protocol_version: String,
pub network: BaseNetworkDescriptor,
pub approve: EvmTransactionIntent,
pub fund: EvmTransactionIntent,
pub wallet_calls: Vec<EvmTransactionIntent>,
pub supports_single_wallet_batch: bool,
pub eip3009_authorization: Option<Eip3009AuthorizationTypedData>,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyAuthorizedContributionPlan {
pub protocol_version: String,
pub network: BaseNetworkDescriptor,
pub bounty_contract: String,
pub relay_transaction: EvmTransactionIntent,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyClaimPlan {
pub protocol_version: String,
pub network: BaseNetworkDescriptor,
pub bounty_contract: String,
pub solver: String,
pub claim_bond: String,
pub approve: Option<EvmTransactionIntent>,
pub claim: EvmTransactionIntent,
pub wallet_calls: Vec<EvmTransactionIntent>,
pub supports_single_wallet_batch: bool,
pub eip3009_authorization: Option<Eip3009AuthorizationTypedData>,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyAuthorizedClaimPlan {
pub protocol_version: String,
pub network: BaseNetworkDescriptor,
pub bounty_contract: String,
pub solver: String,
pub claim_bond: String,
pub relay_transaction: EvmTransactionIntent,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct AtomicClaimSponsorGrant {
pub sponsor_contract: String,
pub bounty_contract: String,
pub solver: String,
pub round: u64,
pub bond: u128,
pub terms_hash: String,
pub policy_hash: String,
pub authorization_nonce: String,
pub valid_after: u64,
pub valid_before: u64,
pub grant_nonce: String,
pub deadline: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AtomicSponsoredClaimPlan {
pub protocol_version: String,
pub network: BaseNetworkDescriptor,
pub sponsor_contract: String,
pub factory_contract: String,
pub bounty_contract: String,
pub solver: String,
pub grant_digest: String,
pub grant_signature: String,
pub relay_transaction: EvmTransactionIntent,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountySubmissionAuthorizationRequest {
pub bounty_contract: String,
pub bounty_id: String,
pub round: u64,
pub solver: String,
pub submission_hash: String,
pub evidence_hash: String,
pub policy_hash: String,
pub deadline: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AutonomousBountySubmissionAuthorizationMessage {
pub bounty: String,
pub bounty_id: String,
pub solver: String,
pub round: String,
pub submission_hash: String,
pub evidence_hash: String,
pub policy_hash: String,
pub deadline: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AutonomousBountySubmissionAuthorizationTypedData {
pub types: BTreeMap<String, Vec<Eip712TypeField>>,
pub domain: Eip712DomainData,
pub primary_type: String,
pub message: AutonomousBountySubmissionAuthorizationMessage,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountySubmissionPreparation {
pub protocol_version: String,
pub network: BaseNetworkDescriptor,
pub bounty_contract: String,
pub bounty_id: String,
pub current_bounty_state: String,
pub expected_bounty_state: String,
pub expected_canonical_event: String,
pub solver: String,
pub round: u64,
pub claim_expires_at: u64,
pub authorization_deadline: u64,
pub artifact_reference: String,
pub submission_hash: String,
pub evidence_hash: String,
pub policy_hash: String,
pub signing_payload: AutonomousBountySubmissionAuthorizationTypedData,
pub unsigned_relay_envelope: Value,
pub evidence_publication: Value,
pub relay_issue_url: Option<String>,
pub evidence_boundary: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousVerificationAttestationRequest {
pub bounty_contract: String,
pub bounty_id: String,
pub round: u64,
pub verifier: String,
pub submission_hash: String,
pub evidence_hash: String,
pub policy_hash: String,
pub passed: bool,
pub response_hash: String,
pub deadline: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AutonomousVerificationAttestationMessage {
pub bounty: String,
pub bounty_id: String,
pub round: String,
pub verifier: String,
pub submission_hash: String,
pub evidence_hash: String,
pub policy_hash: String,
pub passed: bool,
pub response_hash: String,
pub deadline: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AutonomousVerificationAttestationTypedData {
pub types: BTreeMap<String, Vec<Eip712TypeField>>,
pub domain: Eip712DomainData,
pub primary_type: String,
pub message: AutonomousVerificationAttestationMessage,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousSignedAttestation {
pub verifier: String,
pub passed: bool,
pub response_hash: String,
pub deadline: u64,
pub signature: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutonomousBountyTxPlanner {
pub factory_contract: String,
pub implementation_contract: String,
}
impl AutonomousBountyTxPlanner {
pub fn new(
factory_contract: impl Into<String>,
implementation_contract: impl Into<String>,
) -> Result<Self, ChainBaseError> {
Ok(Self {
factory_contract: normalize_address(factory_contract.into())?,
implementation_contract: normalize_address(implementation_contract.into())?,
})
}
pub fn plan_creation(
&self,
network: &str,
create: &AutonomousBountyCreate,
) -> Result<AutonomousBountyCreationPlan, ChainBaseError> {
let network = base_network_descriptor(network)?;
let creator = normalize_address(&create.creator)?;
let params = autonomous_create_param_words(create)?;
let verifiers = normalized_verifiers(create)?;
validate_autonomous_creation(create, &verifiers)?;
let creation_nonce = parse_bytes32(&create.creation_nonce)?;
let bounty_id = autonomous_bounty_id(
network.chain_id,
&self.factory_contract,
&creator,
creation_nonce,
¶ms,
&verifiers,
)?;
let predicted_bounty_contract = predict_minimal_proxy_address(
&self.factory_contract,
&self.implementation_contract,
bounty_id,
)?;
let initial_funding = autonomous_money_to_uint256(&create.initial_funding, true)?;
let create_bounty = EvmTransactionIntent {
from: Some(creator.clone()),
to: self.factory_contract.clone(),
value_wei: 0,