forked from NSPG13/agent-bounties
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathautonomous.js
More file actions
2216 lines (2120 loc) · 91.8 KB
/
Copy pathautonomous.js
File metadata and controls
2216 lines (2120 loc) · 91.8 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 strict";
function track(eventName, details) {
if (window.bountyBoardAnalytics) {
window.bountyBoardAnalytics.track(eventName, details);
}
}
const state = {
protocol: null,
account: null,
provider: null,
providers: [],
legalAction: null,
legalScope: null,
walletConnection: null,
};
const announcedProviders = [];
const BOUNTY_LIFECYCLE = Object.freeze({
cancel: Object.freeze({ function: "cancel()", data: "0xea8a1af0" }),
withdrawRefund: Object.freeze({ function: "withdrawRefund()", data: "0x110f8874" }),
});
const BOUNDED_WALLET_V2 = Object.freeze({
version: "0xbfa7c23ab51aed73d26d3a18212c525361df14b0d4d79efa3f9a229cebe161ec",
selectors: Object.freeze({
owner: "0x8da5cb5b",
walletVersion: "0x1127b57e",
cancelRefund: "0x683e2054",
withdrawRefund: "0x06536a56",
}),
});
const LEGACY_RECOVERY = Object.freeze({
creator: "0x884834e884d6e93462655a2820140ad03e6747bc",
factory: "0x082c52131aaf0c56e76b075f895eab6fcab6d2f9",
implementation: "0x2fa36d2b2327642db3a6cc8cdd91544ad7484eb9",
usdc: "0x833589fcd6edb6e08f4c7c32d4f71b54bda02913",
contracts: [
"0x786be3f994365fcd417a1b502a83300ea87d9b34",
"0x481dfc6f45d43b89dfcc1a84fd6d9b5f73a6a0b9",
"0x3195aebfc39a069bf1a4420951d0babc99b2b612",
],
amount: 1_000_000n,
selectors: Object.freeze({
creator: "0x02d05d3f",
factory: "0xc45a0155",
settlementToken: "0x7b9e618d",
status: "0x200d2ed2",
fundedAmount: "0x820a5f50",
solver: "0x49a7a26d",
activeClaimBond: "0x123d3d01",
contributions: "0x42e94c90",
balanceOf: "0x70a08231",
cancel: "0xea8a1af0",
withdrawRefund: "0x110f8874",
}),
});
const byId = (id) => document.getElementById(id);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function isWalletProvider(provider) {
return Boolean(provider && typeof provider.request === "function");
}
function providerName(provider, info = {}) {
if (info.name) return info.name;
if (provider.isMetaMask) return "MetaMask";
if (provider.isCoinbaseWallet) return "Coinbase Wallet";
if (provider.isBraveWallet) return "Brave Wallet";
return "Browser wallet";
}
function selectedProviderName(provider = state.provider) {
const selected = state.providers.find((item) => item.provider === provider);
return providerName(provider || {}, selected ? selected.info : {});
}
function walletErrorCode(error) {
const values = [
error && error.code,
error && error.data && error.data.code,
error && error.data && error.data.originalError && error.data.originalError.code,
];
for (const value of values) {
const parsed = Number(value);
if (Number.isInteger(parsed)) return parsed;
}
return null;
}
function walletConnectionErrorMessage(error, action = "connect") {
const name = selectedProviderName();
const message = error && error.message ? error.message : String(error || "");
const code = walletErrorCode(error);
if (code === 4001 || /user (rejected|denied)|request rejected|cancelled/i.test(message)) {
return `${name} connection was cancelled. No wallet action was taken.`;
}
if (code === -32002 || /already processing|already pending|request.*pending/i.test(message)) {
return `${name} already has a request open. Approve or reject it from the wallet icon, then try again.`;
}
if (code === -32603 || /internal error/i.test(message)) {
const task = action === "switch"
? "switch to Base"
: "complete the connection";
return `${name} could not ${task}. Open it, finish setup or unlock it, close any pending request, then try again.`;
}
return message || `${name} could not ${action === "switch" ? "switch to Base" : "connect"}. Try again from the wallet icon.`;
}
function rememberProvider(event) {
const detail = event && event.detail;
if (!detail || !isWalletProvider(detail.provider)) return;
if (!announcedProviders.some((item) => item.provider === detail.provider)) {
announcedProviders.push(detail);
}
}
window.addEventListener("eip6963:announceProvider", rememberProvider);
function populateProviderSelectors() {
document.querySelectorAll("[data-wallet-provider]").forEach((selector) => {
const selectedProvider = state.provider;
const required = selector.dataset.walletRequires || "";
const visible = state.providers
.map((item, index) => ({ item, index }))
.filter(({ item }) => {
if (required !== "direct-transactions") return true;
const capabilities = window.AgentBountiesWalletAdapters?.capabilitiesFor?.(item.provider);
return capabilities?.directTransactions !== false;
});
selector.replaceChildren(...visible.map(({ item, index }) => {
const option = document.createElement("option");
option.value = String(index);
option.textContent = providerName(item.provider, item.info);
option.selected = item.provider === selectedProvider;
return option;
}));
selector.disabled = visible.length === 0;
if (visible.length === 0) {
const option = document.createElement("option");
option.textContent = required === "direct-transactions"
? "No compatible transaction wallet available"
: "No wallet provider is available";
selector.append(option);
}
});
}
async function discoverProviders() {
window.dispatchEvent(new Event("eip6963:requestProvider"));
await sleep(250);
const candidates = [...announcedProviders];
const injected = window.ethereum && Array.isArray(window.ethereum.providers)
? window.ethereum.providers
: (window.ethereum ? [window.ethereum] : []);
for (const provider of injected) {
if (isWalletProvider(provider) && !candidates.some((item) => item.provider === provider)) {
candidates.push({ provider, info: {} });
}
}
state.providers = candidates;
populateProviderSelectors();
return state.providers;
}
function selectProvider(context = document) {
const selector = (context.querySelector && context.querySelector("[data-wallet-provider]"))
|| document.querySelector("[data-wallet-provider]");
const item = state.providers[Number.parseInt(selector && selector.value, 10)];
if (!item) throw new Error("Select a wallet provider. You can create an embedded wallet without installing an extension.");
state.provider = item.provider;
const index = String(state.providers.findIndex((provider) => provider.provider === item.provider));
document.querySelectorAll("[data-wallet-provider]").forEach((candidate) => {
candidate.value = index;
});
return item.provider;
}
async function walletRequest(method, params = []) {
const provider = state.provider || selectProvider();
if (["eth_signTypedData_v4", "eth_sendTransaction", "wallet_sendCalls"].includes(method)) {
if (!state.legalAction || !window.AgentBountiesLegal) {
throw new Error("Review and accept the legal agreement before this wallet action.");
}
await window.AgentBountiesLegal.requireAcceptance({
action: state.legalAction,
walletAddress: state.account,
scope: state.legalScope || document,
});
}
return provider.request({ method, params });
}
async function loadProtocol() {
if (state.protocol) return state.protocol;
const response = await fetch("protocol.json", { cache: "no-store" });
if (!response.ok) throw new Error("Protocol configuration is unavailable.");
state.protocol = await response.json();
return state.protocol;
}
function requireActiveProtocol(protocol) {
const address = /^0x[0-9a-fA-F]{40}$/;
if (
protocol.status !== "active" ||
!address.test(protocol.factory || "") ||
!address.test(protocol.implementation || "")
) {
throw new Error("The autonomous protocol is pending review and deployment. No transaction was requested.");
}
return protocol;
}
function apiBase() {
return state.protocol.api_base_url.replace(/\/$/, "");
}
async function requestJson(url, options = {}) {
const acceptance = window.AgentBountiesLegal && window.AgentBountiesLegal.latestReceipt();
const response = await fetch(url, {
...options,
headers: {
"content-type": "application/json",
...(acceptance ? { "x-agent-bounties-legal-acceptance": acceptance.acceptance_id } : {}),
...(options.headers || {}),
},
});
const text = await response.text();
let body = null;
if (text) {
try {
body = JSON.parse(text);
} catch (_error) {
body = text;
}
}
if (!response.ok) {
const details = body && typeof body === "object" ? body : null;
const message = typeof body === "string"
? body
: details && (details.message || details.error)
? details.message || details.error
: `Request failed (${response.status}).`;
const transition = details && details.failed_transition
? `Failed transition: ${details.failed_transition}.`
: "";
const next = details && details.next_action ? details.next_action : "";
const error = new Error([message, transition, next].filter(Boolean).join("\n"));
error.details = details;
throw error;
}
return body;
}
function hostedActionIntentId() {
const value = new URLSearchParams(location.search).get("intent");
if (!value) return null;
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)) {
throw new Error("The ChatGPT authorization intent is invalid.");
}
return value;
}
async function loadHostedActionIntent(expectedActions = []) {
const id = hostedActionIntentId();
if (!id) return null;
await loadProtocol();
const intent = await requestJson(`${apiBase()}/v1/chatgpt/action-intents/${id}`);
if (!expectedActions.includes(intent.action)) {
throw new Error(`This authorization intent cannot be used for ${expectedActions.join(" or ")}.`);
}
return intent;
}
async function observeHostedAction({
transactionHash,
bountyContract = null,
bountyId = null,
actorWallet = null,
}) {
const id = hostedActionIntentId();
if (!id) return null;
if (!/^0x[0-9a-fA-F]{64}$/.test(transactionHash || "")) {
throw new Error("A canonical 32-byte transaction hash is required to reconcile this action.");
}
return requestJson(`${apiBase()}/v1/chatgpt/action-intents/${id}/observations`, {
method: "POST",
body: JSON.stringify({
transaction_hash: transactionHash,
bounty_contract: bountyContract,
bounty_id: bountyId,
actor_wallet: actorWallet,
}),
});
}
async function pollHostedAction(timeoutMs = 90_000) {
const id = hostedActionIntentId();
if (!id) return null;
const started = Date.now();
let intent = null;
while (Date.now() - started < timeoutMs) {
intent = await requestJson(`${apiBase()}/v1/chatgpt/action-intents/${id}`);
if (["confirmed", "failed", "expired"].includes(intent.status)) return intent;
await sleep(2_500);
}
return intent;
}
async function acceptLegalAction(scope, action, account) {
if (!window.AgentBountiesLegal) {
throw new Error("The legal agreement could not be loaded. Reload before using the wallet.");
}
state.legalAction = action;
state.legalScope = scope || document;
return window.AgentBountiesLegal.requireAcceptance({
action,
walletAddress: account,
scope: state.legalScope,
});
}
function output(element, lines, tone = "") {
if (!element) return;
element.textContent = Array.isArray(lines) ? lines.join("\n") : lines;
element.dataset.tone = tone;
}
function randomBytes32() {
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
return `0x${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
}
function hostedClaimContext(bountyContract, solverWallet) {
const params = new URLSearchParams(location.search);
const expectedSolver = params.get("solver");
if (expectedSolver && requiredAddress(expectedSolver, "Claim-link solver").toLowerCase()
!== solverWallet.toLowerCase()) {
throw new Error("Connect the payout wallet named by this claim link.");
}
const suppliedKey = params.get("claimKey");
if (suppliedKey) {
if (suppliedKey.length > 128 || /[\u0000-\u001f\u007f]/.test(suppliedKey)) {
throw new Error("The claim link contains an invalid idempotency key.");
}
return { idempotencyKey: suppliedKey, source: claimSource(params) };
}
const storageKey = `agent-bounties:claim:${bountyContract.toLowerCase()}:${solverWallet.toLowerCase()}`;
let idempotencyKey = null;
if (typeof sessionStorage !== "undefined") idempotencyKey = sessionStorage.getItem(storageKey);
if (!idempotencyKey) {
idempotencyKey = `web-claim:${randomBytes32().slice(2)}`;
if (typeof sessionStorage !== "undefined") sessionStorage.setItem(storageKey, idempotencyKey);
}
return { idempotencyKey, source: claimSource(params) };
}
function claimSource(params) {
const source = String(params.get("source") || "web").trim();
return /^[a-zA-Z0-9._:-]{1,64}$/.test(source) ? source : "web";
}
function validateHostedClaimHandoff(handoff, requestBody, item, account, protocol, api) {
if (!handoff || handoff.schema_version !== "agent-bounties/agent-native-claim-v1") {
throw new Error("The hosted claim response has an unsupported schema.");
}
const candidate = handoff.candidate;
if (!candidate
|| String(candidate.bounty_contract).toLowerCase() !== item.bounty_contract.toLowerCase()
|| String(candidate.solver_wallet).toLowerCase() !== account.toLowerCase()) {
throw new Error("The hosted claim candidate does not match this bounty and payout wallet.");
}
if (!handoff.wallet_request) return null;
if (candidate.status !== "authorization_ready") {
throw new Error(`The hosted claim requested a signature in unexpected state ${candidate.status}.`);
}
const walletRequest = handoff.wallet_request;
if (walletRequest.method !== "eth_signTypedData_v4"
|| !Array.isArray(walletRequest.params)
|| walletRequest.params.length !== 2
|| String(walletRequest.params[0]).toLowerCase() !== account.toLowerCase()) {
throw new Error("The hosted claim returned an invalid wallet request.");
}
let typedData;
try {
typedData = JSON.parse(walletRequest.params[1]);
} catch (_error) {
throw new Error("The hosted claim returned unreadable typed data.");
}
const domain = typedData.domain || {};
const message = typedData.message || {};
const expectedTypes = window.AgentBountiesEvm.transferWithAuthorizationTypes();
const validAfter = Number(message.validAfter);
const validBefore = Number(message.validBefore);
if (typedData.primaryType !== "TransferWithAuthorization"
|| JSON.stringify(typedData.types) !== JSON.stringify(expectedTypes)
|| domain.name !== "USD Coin"
|| domain.version !== "2"
|| Number(domain.chainId) !== Number(protocol.chain_id)
|| String(domain.verifyingContract).toLowerCase() !== protocol.native_usdc.toLowerCase()
|| String(message.from).toLowerCase() !== account.toLowerCase()
|| String(message.to).toLowerCase() !== item.bounty_contract.toLowerCase()
|| String(message.value) !== String(item.claim_bond)
|| !Number.isSafeInteger(validAfter)
|| !Number.isSafeInteger(validBefore)
|| validAfter !== 0
|| validBefore <= Math.floor(Date.now() / 1_000)
|| !/^0x[0-9a-fA-F]{64}$/.test(String(message.nonce))) {
throw new Error("The hosted claim typed data differs from the selected Base USDC bond.");
}
const nextRequest = handoff.next_request;
const expectedUrl = `${api}/v1/base/autonomous-bounties/claims`;
if (!nextRequest || nextRequest.method !== "POST" || nextRequest.url !== expectedUrl
|| !nextRequest.body
|| nextRequest.body.idempotency_key !== requestBody.idempotency_key
|| nextRequest.body.network !== requestBody.network
|| String(nextRequest.body.bounty_contract).toLowerCase() !== item.bounty_contract.toLowerCase()
|| String(nextRequest.body.solver_wallet).toLowerCase() !== account.toLowerCase()
|| nextRequest.body.request_bond_sponsorship !== true
|| nextRequest.body.source !== requestBody.source) {
throw new Error("The hosted claim replay request differs from the prepared candidate.");
}
return walletRequest;
}
async function hostedClaim(item, api, account, protocol, result) {
await acceptLegalAction(document, "claim_bounty", account);
const context = hostedClaimContext(item.bounty_contract, account);
const requestBody = {
idempotency_key: context.idempotencyKey,
network: "base-mainnet",
bounty_contract: item.bounty_contract,
solver_wallet: account,
request_bond_sponsorship: true,
source: context.source,
};
const endpoint = `${api}/v1/base/autonomous-bounties/claims`;
let handoff = await requestJson(endpoint, {
method: "POST",
body: JSON.stringify(requestBody),
});
validateHostedClaimHandoff(handoff, requestBody, item, account, protocol, api);
if (handoff.candidate.status === "waitlisted") {
output(result, [
`Waitlisted at position ${handoff.waitlist_position}.`,
"No signature or bond was requested. Reopen this exact link to poll.",
], "pending");
return;
}
if (handoff.candidate.status === "claimed" && handoff.canonical_event_id) {
if (hostedActionIntentId()) {
if (!handoff.claim_transaction_hash) {
throw new Error("Canonical claim exists, but its transaction hash is unavailable for ChatGPT reconciliation.");
}
await observeHostedAction({
transactionHash: handoff.claim_transaction_hash,
bountyContract: item.bounty_contract,
bountyId: item.bounty_id,
actorWallet: account,
});
}
output(result, [
"Canonical BountyClaimed is confirmed. Start the task.",
`Event: ${handoff.canonical_event_id}`,
], "success");
track("claim_confirmed", { bounty_contract: item.bounty_contract });
return;
}
const exactWalletRequest = validateHostedClaimHandoff(
handoff, requestBody, item, account, protocol, api,
);
if (!exactWalletRequest) {
throw new Error(handoff.next_action || `Claim is ${handoff.candidate.status}.`);
}
output(result, [
"One bounded wallet signature required. No gas transaction is requested.",
`Sponsored refundable bond: ${Number(handoff.claim_bond) / 1_000_000} USDC`,
`Bounty: ${item.bounty_contract}`,
], "pending");
const walletSignature = await walletRequest(
exactWalletRequest.method, exactWalletRequest.params,
);
if (!/^0x[0-9a-fA-F]{130}$/.test(String(walletSignature))) {
throw new Error("The wallet did not return one 65-byte claim signature.");
}
handoff = await requestJson(endpoint, {
method: "POST",
body: JSON.stringify({ ...requestBody, wallet_signature: walletSignature }),
});
for (let attempt = 0; attempt < 36; attempt += 1) {
if (handoff.candidate.status === "claimed" && handoff.canonical_event_id) {
if (hostedActionIntentId()) {
if (!handoff.claim_transaction_hash) {
throw new Error("Canonical claim exists, but its transaction hash is unavailable for ChatGPT reconciliation.");
}
await observeHostedAction({
transactionHash: handoff.claim_transaction_hash,
bountyContract: item.bounty_contract,
bountyId: item.bounty_id,
actorWallet: account,
});
}
output(result, [
"Canonical BountyClaimed is confirmed. Start the task.",
`Event: ${handoff.canonical_event_id}`,
handoff.claim_transaction_hash ? `Transaction: ${protocol.explorer_url}/tx/${handoff.claim_transaction_hash}` : "",
].filter(Boolean), "success");
track("claim_confirmed", { bounty_contract: item.bounty_contract });
return;
}
if (!["relaying", "authorization_ready", "exclusive", "sponsoring"].includes(handoff.candidate.status)) {
throw new Error(handoff.next_action || `Claim stopped in state ${handoff.candidate.status}.`);
}
output(result, [
`Claim state: ${handoff.candidate.status}.`,
"The sponsor is paying gas. Waiting for canonical BountyClaimed; do not sign again.",
], "pending");
await sleep(2_500);
handoff = await requestJson(endpoint, {
method: "POST",
body: JSON.stringify(requestBody),
});
}
throw new Error("The sponsored claim is still pending. Reopen this exact link to reconcile it; do not post another bond.");
}
function usdcMinor(value) {
const amount = Number(value);
if (!Number.isFinite(amount) || amount < 0 || amount > 9_000_000_000) {
throw new Error("Enter a valid USDC amount.");
}
return Math.round(amount * 1_000_000);
}
function requiredAddress(value, label) {
const address = value.trim();
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) throw new Error(`${label} must be an EVM address.`);
return address;
}
function optionalAddress(value) {
const address = value.trim();
return address ? requiredAddress(address, "Address") : null;
}
function defaultVerification(protocol) {
const config = protocol.default_verification;
if (
!config
|| config.mode !== "signed_quorum"
|| config.threshold !== 1
|| !Array.isArray(config.verifiers)
|| config.verifiers.length !== 1
) {
throw new Error("The active protocol does not declare one default verifier.");
}
const moduleId = "leading_zero_work_v1";
const module = protocol.deterministic_modules && protocol.deterministic_modules[moduleId];
if (!module || !module.benchmark || module.benchmark.engine !== moduleId) {
throw new Error("The optional deterministic verifier is unavailable.");
}
return {
...config,
verifiers: config.verifiers.map((value) => requiredAddress(value, "Default verifier")),
deterministic: {
module_id: moduleId,
contract: requiredAddress(module.contract || "", "Deterministic verifier module"),
benchmark: module.benchmark,
scope_notice: module.scope_notice || "The selected module controls payout.",
usage: module.usage || "custom",
},
};
}
function configurePostVerification(form, protocol, account = null) {
if (!form) return;
const defaults = defaultVerification(protocol);
const mode = form.elements.verificationMode.value;
const deterministic = mode === "deterministic_module";
const module = form.elements.verifierModule;
const recipient = form.elements.verifierRewardRecipient;
const verifiers = form.elements.verifiers;
const threshold = form.elements.threshold;
const benchmark = form.elements.benchmark;
const scope = form.querySelector("[data-verifier-scope]");
const demoWarning = form.querySelector("[data-demo-verifier-warning]");
const demoAccepted = form.elements.demoVerifierAccepted;
module.value = defaults.deterministic.contract;
module.readOnly = true;
module.disabled = !deterministic;
recipient.disabled = !deterministic;
verifiers.disabled = deterministic;
threshold.readOnly = deterministic;
benchmark.readOnly = deterministic;
if (demoWarning) demoWarning.hidden = !deterministic;
if (demoAccepted) demoAccepted.disabled = !deterministic;
if (deterministic) {
threshold.value = "1";
benchmark.value = canonicalJsonString(defaults.deterministic.benchmark);
if (scope) scope.textContent = defaults.deterministic.scope_notice;
if (account && !recipient.value.trim()) {
recipient.value = account;
}
} else {
if (!verifiers.value.trim()) verifiers.value = defaults.verifiers.join("\n");
if (!threshold.value || mode === defaults.mode) threshold.value = String(defaults.threshold);
if (scope) {
scope.textContent = mode === "signed_quorum"
? "One precommitted verifier runs the exact benchmark. Add a second only for higher-risk work."
: "AI judge verification requires at least two independent committed judges.";
}
}
}
function parseJson(value, label) {
try {
return JSON.parse(value);
} catch (_error) {
throw new Error(`${label} must be valid JSON.`);
}
}
function splitLines(value) {
return value
.split(/\r?\n/)
.map((line) => line.trim().replace(/^[-*]\s*/, ""))
.filter(Boolean);
}
function splitAddresses(value) {
return value
.split(/[\s,]+/)
.map((item) => item.trim())
.filter(Boolean)
.map((item) => requiredAddress(item, "Verifier"));
}
async function sha256Hex(value) {
const bytes = new TextEncoder().encode(value);
const digest = await crypto.subtle.digest("SHA-256", bytes);
return `0x${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
}
function canonicalJsonValue(value) {
if (Array.isArray(value)) return value.map(canonicalJsonValue);
if (value && typeof value === "object") {
return Object.keys(value)
.sort()
.reduce((result, key) => {
result[key] = canonicalJsonValue(value[key]);
return result;
}, {});
}
return value;
}
function canonicalJsonString(value) {
return JSON.stringify(canonicalJsonValue(value));
}
async function connectWalletOnce(context) {
await discoverProviders();
selectProvider(context);
const protocol = await loadProtocol();
let accounts = [];
try {
accounts = await walletRequest("eth_accounts");
} catch (_error) {
// Some injected providers reject passive account reads while locked.
}
if (!accounts || !accounts[0]) {
try {
accounts = await walletRequest("eth_requestAccounts");
} catch (error) {
throw new Error(walletConnectionErrorMessage(error));
}
}
if (!accounts || !accounts[0]) throw new Error("No wallet account was returned.");
state.account = accounts[0];
configurePostVerification(
context.querySelector && context.querySelector("#autonomous-post-form")
? context.querySelector("#autonomous-post-form")
: (context.id === "autonomous-post-form" ? context : byId("autonomous-post-form")),
protocol,
state.account,
);
let current;
try {
current = await walletRequest("eth_chainId");
} catch (error) {
throw new Error(walletConnectionErrorMessage(error, "switch"));
}
if (String(current).toLowerCase() !== protocol.chain_id_hex.toLowerCase()) {
try {
await walletRequest("wallet_switchEthereumChain", [{ chainId: protocol.chain_id_hex }]);
} catch (error) {
if (error && error.code === 4902) {
try {
await walletRequest("wallet_addEthereumChain", [
{
chainId: protocol.chain_id_hex,
chainName: "Base",
nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
rpcUrls: ["https://mainnet.base.org"],
blockExplorerUrls: [protocol.explorer_url],
},
]);
} catch (addError) {
throw new Error(walletConnectionErrorMessage(addError, "switch"));
}
} else {
throw new Error(walletConnectionErrorMessage(error, "switch"));
}
}
}
return state.account;
}
async function connectWallet(context = document) {
if (state.walletConnection) return state.walletConnection;
const connection = connectWalletOnce(context);
state.walletConnection = connection;
try {
return await connection;
} finally {
if (state.walletConnection === connection) state.walletConnection = null;
}
}
async function isContractAccount(account) {
const code = await walletRequest("eth_getCode", [account, "latest"]);
return code && code !== "0x" && code !== "0x0";
}
function signatureParts(signature) {
const value = String(signature).replace(/^0x/, "");
if (value.length !== 130) throw new Error("Wallet returned an invalid 65-byte signature.");
return {
r: `0x${value.slice(0, 64)}`,
s: `0x${value.slice(64, 128)}`,
v: Number.parseInt(value.slice(128, 130), 16),
};
}
async function signTypedData(account, typedData) {
const signature = await walletRequest("eth_signTypedData_v4", [account, JSON.stringify(typedData)]);
return signatureParts(signature);
}
async function sendTransaction(transaction, from) {
return walletRequest("eth_sendTransaction", [
{
from,
to: transaction.to,
data: transaction.data,
value: "0x0",
},
]);
}
async function waitReceipt(txHash, timeoutMs = 120_000) {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const receipt = await walletRequest("eth_getTransactionReceipt", [txHash]);
if (receipt) {
if (receipt.status !== "0x1") throw new Error(`Transaction reverted: ${txHash}`);
return receipt;
}
await sleep(1_500);
}
throw new Error(`Transaction confirmation timed out: ${txHash}`);
}
async function sendWalletCalls(calls, account, protocol) {
try {
const bundleId = await walletRequest("wallet_sendCalls", [
{
version: "2.0.0",
chainId: protocol.chain_id_hex,
from: account,
calls: calls.map((call) => ({ to: call.to, data: call.data, value: "0x0" })),
},
]);
return { kind: "bundle", id: bundleId };
} catch (_error) {
const hashes = [];
for (const call of calls) {
const hash = await sendTransaction(call, account);
await waitReceipt(hash);
hashes.push(hash);
}
return { kind: "transactions", hashes };
}
}
function addressWord(address) {
return address.toLowerCase().replace(/^0x/, "").padStart(64, "0");
}
async function recoveryCall(to, data) {
const value = await walletRequest("eth_call", [{ to, data }, "latest"]);
if (!/^0x[0-9a-fA-F]{64}$/.test(value || "")) {
throw new Error(`Invalid Base response from ${to}.`);
}
return value.toLowerCase();
}
function recoveryAddress(word) {
return `0x${word.slice(-40)}`;
}
function recoveryUint(word) {
return BigInt(word);
}
function expectedCloneRuntime() {
return `0x363d3d373d3d3d363d73${LEGACY_RECOVERY.implementation.slice(2)}5af43d82803e903d91602b57fd5bf3`;
}
async function readLegacyRecoveryState(contract, account) {
const selectors = LEGACY_RECOVERY.selectors;
const [code, creator, factory, token, status, funded, solver, bond, contribution, balance] = await Promise.all([
walletRequest("eth_getCode", [contract, "latest"]),
recoveryCall(contract, selectors.creator),
recoveryCall(contract, selectors.factory),
recoveryCall(contract, selectors.settlementToken),
recoveryCall(contract, selectors.status),
recoveryCall(contract, selectors.fundedAmount),
recoveryCall(contract, selectors.solver),
recoveryCall(contract, selectors.activeClaimBond),
recoveryCall(contract, `${selectors.contributions}${addressWord(account)}`),
recoveryCall(LEGACY_RECOVERY.usdc, `${selectors.balanceOf}${addressWord(contract)}`),
]);
const value = {
contract,
code: String(code).toLowerCase(),
creator: recoveryAddress(creator),
factory: recoveryAddress(factory),
token: recoveryAddress(token),
status: recoveryUint(status),
funded: recoveryUint(funded),
solver: recoveryAddress(solver),
bond: recoveryUint(bond),
contribution: recoveryUint(contribution),
balance: recoveryUint(balance),
};
if (value.code !== expectedCloneRuntime()) throw new Error(`${contract} clone bytecode does not match.`);
if (value.creator !== LEGACY_RECOVERY.creator || value.creator !== account.toLowerCase()) {
throw new Error(`${contract} is not owned by the connected creator wallet.`);
}
if (value.factory !== LEGACY_RECOVERY.factory) throw new Error(`${contract} factory does not match.`);
if (value.token !== LEGACY_RECOVERY.usdc) throw new Error(`${contract} token is not native Base USDC.`);
if (value.solver !== "0x0000000000000000000000000000000000000000" || value.bond !== 0n) {
throw new Error(`${contract} has an active solver or bond; recovery refused.`);
}
const fullyFunded = value.funded === LEGACY_RECOVERY.amount
&& value.contribution === LEGACY_RECOVERY.amount
&& value.balance === LEGACY_RECOVERY.amount;
const refundPending = value.status === 5n && fullyFunded;
const ready = value.status === 1n && fullyFunded;
const recovered = value.status === 5n
&& value.funded === 0n
&& value.contribution === 0n
&& value.balance === 0n;
if (!ready && !refundPending && !recovered) {
throw new Error(`${contract} is not in a pinned recoverable state.`);
}
return { ...value, ready, refundPending, recovered };
}
function showLegacyRecoveryState(states) {
for (const stateValue of states) {
const row = document.querySelector(`[data-recovery-contract="${stateValue.contract}"]`);
if (!row) continue;
const target = row.querySelector("output");
if (stateValue.recovered) {
row.dataset.state = "recovered";
target.textContent = "Recovered - 0 USDC locked";
} else if (stateValue.refundPending) {
row.dataset.state = "ready";
target.textContent = "Cancelled - refund ready";
} else {
row.dataset.state = "ready";
target.textContent = "1 USDC - ready to recover";
}
}
}
async function inspectLegacyRecovery(account) {
const states = [];
for (const contract of LEGACY_RECOVERY.contracts) {
states.push(await readLegacyRecoveryState(contract, account));
}
showLegacyRecoveryState(states);
return states;
}
async function waitLegacyRecovery(account, timeoutMs = 180_000) {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const states = await inspectLegacyRecovery(account);
if (states.every((item) => item.recovered)) return states;
await sleep(2_000);
}
throw new Error("Recovery transactions were submitted but final zero-balance state is still pending. Retry to inspect the remaining calls.");
}
async function recoverLegacyBounties(event) {
event.preventDefault();
const form = event.currentTarget;
const result = byId("legacy-recovery-output");
try {
const protocol = requireActiveProtocol(await loadProtocol());
const account = await connectWallet(form);
await acceptLegalAction(form, "recover_funds", account);
if (account.toLowerCase() !== LEGACY_RECOVERY.creator) {
throw new Error(`Connect creator wallet ${LEGACY_RECOVERY.creator}.`);
}
const states = await inspectLegacyRecovery(account);
if (states.every((item) => item.recovered)) {
output(result, "All three contracts are already cancelled, refunded, and at zero USDC.", "success");
return;
}
const calls = [];
for (const item of states) {
if (item.ready) calls.push({ to: item.contract, data: LEGACY_RECOVERY.selectors.cancel });
if (item.ready || item.refundPending) {
calls.push({ to: item.contract, data: LEGACY_RECOVERY.selectors.withdrawRefund });
}
}
if (!calls.length) throw new Error("No recovery calls remain.");
output(result, `Requesting ${calls.length} pinned recovery calls from the connected wallet.`, "pending");
const sent = await sendWalletCalls(calls, account, protocol);
output(result, sent.kind === "bundle" ? "Recovery batch submitted. Verifying Base state..." : "Recovery transactions confirmed. Verifying Base state...", "pending");
await waitLegacyRecovery(account);
const references = sent.kind === "transactions"
? sent.hashes.map((hash) => `${protocol.explorer_url}/tx/${hash}`)
: [`Wallet batch: ${typeof sent.id === "string" ? sent.id : JSON.stringify(sent.id)}`];
output(result, [
"Recovered exactly 3.000000 USDC.",
"All three contracts are cancelled with zero funded amount, zero creator contribution, and zero USDC balance.",
...references,
], "success");
} catch (error) {
output(result, error.message || String(error), "error");
}
}
async function pollEvents(api, bountyId, expectedKinds, timeoutMs = 90_000) {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const events = await requestJson(
`${api}/v1/base/autonomous-bounties/events?network=base-mainnet&bounty_id=${encodeURIComponent(bountyId)}`,
);
if (expectedKinds.every((kind) => events.some((event) => event.kind === kind))) return events;
await sleep(2_500);
}
return null;
}
async function canonicalBountyByContract(api, bountyContract) {
const items = await requestJson(
`${api}/v1/base/autonomous-bounties/feed?network=base-mainnet&claimable_only=false`,
);
const item = items.find((candidate) =>
candidate.bounty_contract.toLowerCase() === bountyContract.toLowerCase());
if (!item) throw new Error("This contract is not indexed from the canonical factory.");
if (!item.terms_valid) {
throw new Error(`The indexed terms do not match this contract: ${item.validation_errors.join("; ")}`);
}
return item;
}
function validateLifecyclePlan(plan, bountyContract, account, expected) {
if (!plan
|| String(plan.from || "").toLowerCase() !== account.toLowerCase()
|| String(plan.to || "").toLowerCase() !== bountyContract.toLowerCase()
|| String(plan.value_wei) !== "0"
|| plan.function !== expected.function
|| String(plan.data || "").toLowerCase() !== expected.data) {
throw new Error("The hosted transaction plan does not match the exact requested bounty action.");
}
return plan;
}
async function pollBountyStatus(api, bountyContract, expectedStatus, timeoutMs = 90_000) {
const started = Date.now();
while (Date.now() - started < timeoutMs) {
const item = await canonicalBountyByContract(api, bountyContract);
if (item.status === expectedStatus) return item;
await sleep(2_500);
}
return null;