@probecli/cli 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/probe.mjs ADDED
@@ -0,0 +1,2448 @@
1
+ // probe CLI, bundled from protocol/src/cli. Source: https://github.com/probecli/probe
2
+
3
+ // src/cli/main.ts
4
+ import { existsSync as existsSync4, mkdirSync as mkdirSync4, readFileSync as readFileSync5, writeFileSync as writeFileSync4 } from "node:fs";
5
+ import { join as join4, resolve as resolve3 } from "node:path";
6
+ import { parseArgs as parseArgs2 } from "node:util";
7
+ import { parseUnits, toHex as toHex5 } from "viem";
8
+ import { privateKeyToAccount as privateKeyToAccount5 } from "viem/accounts";
9
+
10
+ // src/shared/chain.ts
11
+ import {
12
+ BaseError,
13
+ ContractFunctionRevertedError,
14
+ createPublicClient,
15
+ createWalletClient,
16
+ defineChain,
17
+ erc20Abi,
18
+ http
19
+ } from "viem";
20
+ import { privateKeyToAccount } from "viem/accounts";
21
+
22
+ // src/shared/artifacts.ts
23
+ var probeJobsAbi = [
24
+ {
25
+ "type": "constructor",
26
+ "inputs": [
27
+ {
28
+ "name": "initialOwner",
29
+ "type": "address",
30
+ "internalType": "address"
31
+ }
32
+ ],
33
+ "stateMutability": "nonpayable"
34
+ },
35
+ {
36
+ "type": "function",
37
+ "name": "acceptOwnership",
38
+ "inputs": [],
39
+ "outputs": [],
40
+ "stateMutability": "nonpayable"
41
+ },
42
+ {
43
+ "type": "function",
44
+ "name": "approvedVerifier",
45
+ "inputs": [
46
+ {
47
+ "name": "",
48
+ "type": "address",
49
+ "internalType": "address"
50
+ }
51
+ ],
52
+ "outputs": [
53
+ {
54
+ "name": "",
55
+ "type": "bool",
56
+ "internalType": "bool"
57
+ }
58
+ ],
59
+ "stateMutability": "view"
60
+ },
61
+ {
62
+ "type": "function",
63
+ "name": "close",
64
+ "inputs": [
65
+ {
66
+ "name": "jobId",
67
+ "type": "uint256",
68
+ "internalType": "uint256"
69
+ }
70
+ ],
71
+ "outputs": [],
72
+ "stateMutability": "nonpayable"
73
+ },
74
+ {
75
+ "type": "function",
76
+ "name": "createJob",
77
+ "inputs": [
78
+ {
79
+ "name": "p",
80
+ "type": "tuple",
81
+ "internalType": "struct ProbeJobs.CreateParams",
82
+ "components": [
83
+ {
84
+ "name": "verifier",
85
+ "type": "address",
86
+ "internalType": "address"
87
+ },
88
+ {
89
+ "name": "rewardToken",
90
+ "type": "address",
91
+ "internalType": "address"
92
+ },
93
+ {
94
+ "name": "eligibilityToken",
95
+ "type": "address",
96
+ "internalType": "address"
97
+ },
98
+ {
99
+ "name": "minHolding",
100
+ "type": "uint256",
101
+ "internalType": "uint256"
102
+ },
103
+ {
104
+ "name": "rewardPerAccepted",
105
+ "type": "uint256",
106
+ "internalType": "uint256"
107
+ },
108
+ {
109
+ "name": "budget",
110
+ "type": "uint256",
111
+ "internalType": "uint256"
112
+ },
113
+ {
114
+ "name": "deadline",
115
+ "type": "uint64",
116
+ "internalType": "uint64"
117
+ },
118
+ {
119
+ "name": "specHash",
120
+ "type": "bytes32",
121
+ "internalType": "bytes32"
122
+ },
123
+ {
124
+ "name": "reportKey",
125
+ "type": "bytes32",
126
+ "internalType": "bytes32"
127
+ }
128
+ ]
129
+ }
130
+ ],
131
+ "outputs": [
132
+ {
133
+ "name": "jobId",
134
+ "type": "uint256",
135
+ "internalType": "uint256"
136
+ }
137
+ ],
138
+ "stateMutability": "payable"
139
+ },
140
+ {
141
+ "type": "function",
142
+ "name": "fingerprintPaid",
143
+ "inputs": [
144
+ {
145
+ "name": "",
146
+ "type": "uint256",
147
+ "internalType": "uint256"
148
+ },
149
+ {
150
+ "name": "",
151
+ "type": "bytes32",
152
+ "internalType": "bytes32"
153
+ }
154
+ ],
155
+ "outputs": [
156
+ {
157
+ "name": "",
158
+ "type": "bool",
159
+ "internalType": "bool"
160
+ }
161
+ ],
162
+ "stateMutability": "view"
163
+ },
164
+ {
165
+ "type": "function",
166
+ "name": "fund",
167
+ "inputs": [
168
+ {
169
+ "name": "jobId",
170
+ "type": "uint256",
171
+ "internalType": "uint256"
172
+ },
173
+ {
174
+ "name": "amount",
175
+ "type": "uint256",
176
+ "internalType": "uint256"
177
+ }
178
+ ],
179
+ "outputs": [],
180
+ "stateMutability": "payable"
181
+ },
182
+ {
183
+ "type": "function",
184
+ "name": "getJob",
185
+ "inputs": [
186
+ {
187
+ "name": "jobId",
188
+ "type": "uint256",
189
+ "internalType": "uint256"
190
+ }
191
+ ],
192
+ "outputs": [
193
+ {
194
+ "name": "",
195
+ "type": "tuple",
196
+ "internalType": "struct ProbeJobs.Job",
197
+ "components": [
198
+ {
199
+ "name": "sponsor",
200
+ "type": "address",
201
+ "internalType": "address"
202
+ },
203
+ {
204
+ "name": "verifier",
205
+ "type": "address",
206
+ "internalType": "address"
207
+ },
208
+ {
209
+ "name": "rewardToken",
210
+ "type": "address",
211
+ "internalType": "address"
212
+ },
213
+ {
214
+ "name": "eligibilityToken",
215
+ "type": "address",
216
+ "internalType": "address"
217
+ },
218
+ {
219
+ "name": "minHolding",
220
+ "type": "uint256",
221
+ "internalType": "uint256"
222
+ },
223
+ {
224
+ "name": "rewardPerAccepted",
225
+ "type": "uint256",
226
+ "internalType": "uint256"
227
+ },
228
+ {
229
+ "name": "budget",
230
+ "type": "uint256",
231
+ "internalType": "uint256"
232
+ },
233
+ {
234
+ "name": "funded",
235
+ "type": "uint256",
236
+ "internalType": "uint256"
237
+ },
238
+ {
239
+ "name": "deadline",
240
+ "type": "uint64",
241
+ "internalType": "uint64"
242
+ },
243
+ {
244
+ "name": "accepted",
245
+ "type": "uint32",
246
+ "internalType": "uint32"
247
+ },
248
+ {
249
+ "name": "status",
250
+ "type": "uint8",
251
+ "internalType": "enum ProbeJobs.Status"
252
+ },
253
+ {
254
+ "name": "specHash",
255
+ "type": "bytes32",
256
+ "internalType": "bytes32"
257
+ },
258
+ {
259
+ "name": "reportKey",
260
+ "type": "bytes32",
261
+ "internalType": "bytes32"
262
+ }
263
+ ]
264
+ }
265
+ ],
266
+ "stateMutability": "view"
267
+ },
268
+ {
269
+ "type": "function",
270
+ "name": "isEligible",
271
+ "inputs": [
272
+ {
273
+ "name": "jobId",
274
+ "type": "uint256",
275
+ "internalType": "uint256"
276
+ },
277
+ {
278
+ "name": "operator",
279
+ "type": "address",
280
+ "internalType": "address"
281
+ }
282
+ ],
283
+ "outputs": [
284
+ {
285
+ "name": "",
286
+ "type": "bool",
287
+ "internalType": "bool"
288
+ }
289
+ ],
290
+ "stateMutability": "view"
291
+ },
292
+ {
293
+ "type": "function",
294
+ "name": "nextJobId",
295
+ "inputs": [],
296
+ "outputs": [
297
+ {
298
+ "name": "",
299
+ "type": "uint256",
300
+ "internalType": "uint256"
301
+ }
302
+ ],
303
+ "stateMutability": "view"
304
+ },
305
+ {
306
+ "type": "function",
307
+ "name": "owed",
308
+ "inputs": [
309
+ {
310
+ "name": "",
311
+ "type": "address",
312
+ "internalType": "address"
313
+ },
314
+ {
315
+ "name": "",
316
+ "type": "address",
317
+ "internalType": "address"
318
+ }
319
+ ],
320
+ "outputs": [
321
+ {
322
+ "name": "",
323
+ "type": "uint256",
324
+ "internalType": "uint256"
325
+ }
326
+ ],
327
+ "stateMutability": "view"
328
+ },
329
+ {
330
+ "type": "function",
331
+ "name": "owner",
332
+ "inputs": [],
333
+ "outputs": [
334
+ {
335
+ "name": "",
336
+ "type": "address",
337
+ "internalType": "address"
338
+ }
339
+ ],
340
+ "stateMutability": "view"
341
+ },
342
+ {
343
+ "type": "function",
344
+ "name": "pendingOwner",
345
+ "inputs": [],
346
+ "outputs": [
347
+ {
348
+ "name": "",
349
+ "type": "address",
350
+ "internalType": "address"
351
+ }
352
+ ],
353
+ "stateMutability": "view"
354
+ },
355
+ {
356
+ "type": "function",
357
+ "name": "recordAccepted",
358
+ "inputs": [
359
+ {
360
+ "name": "jobId",
361
+ "type": "uint256",
362
+ "internalType": "uint256"
363
+ },
364
+ {
365
+ "name": "operator",
366
+ "type": "address",
367
+ "internalType": "address"
368
+ },
369
+ {
370
+ "name": "fingerprint",
371
+ "type": "bytes32",
372
+ "internalType": "bytes32"
373
+ },
374
+ {
375
+ "name": "resultHash",
376
+ "type": "bytes32",
377
+ "internalType": "bytes32"
378
+ }
379
+ ],
380
+ "outputs": [],
381
+ "stateMutability": "nonpayable"
382
+ },
383
+ {
384
+ "type": "function",
385
+ "name": "renounceOwnership",
386
+ "inputs": [],
387
+ "outputs": [],
388
+ "stateMutability": "nonpayable"
389
+ },
390
+ {
391
+ "type": "function",
392
+ "name": "setVerifier",
393
+ "inputs": [
394
+ {
395
+ "name": "verifier",
396
+ "type": "address",
397
+ "internalType": "address"
398
+ },
399
+ {
400
+ "name": "approved",
401
+ "type": "bool",
402
+ "internalType": "bool"
403
+ }
404
+ ],
405
+ "outputs": [],
406
+ "stateMutability": "nonpayable"
407
+ },
408
+ {
409
+ "type": "function",
410
+ "name": "transferOwnership",
411
+ "inputs": [
412
+ {
413
+ "name": "newOwner",
414
+ "type": "address",
415
+ "internalType": "address"
416
+ }
417
+ ],
418
+ "outputs": [],
419
+ "stateMutability": "nonpayable"
420
+ },
421
+ {
422
+ "type": "function",
423
+ "name": "withdraw",
424
+ "inputs": [
425
+ {
426
+ "name": "token",
427
+ "type": "address",
428
+ "internalType": "address"
429
+ }
430
+ ],
431
+ "outputs": [],
432
+ "stateMutability": "nonpayable"
433
+ },
434
+ {
435
+ "type": "event",
436
+ "name": "JobClosed",
437
+ "inputs": [
438
+ {
439
+ "name": "jobId",
440
+ "type": "uint256",
441
+ "indexed": true,
442
+ "internalType": "uint256"
443
+ },
444
+ {
445
+ "name": "refunded",
446
+ "type": "uint256",
447
+ "indexed": false,
448
+ "internalType": "uint256"
449
+ }
450
+ ],
451
+ "anonymous": false
452
+ },
453
+ {
454
+ "type": "event",
455
+ "name": "JobCreated",
456
+ "inputs": [
457
+ {
458
+ "name": "jobId",
459
+ "type": "uint256",
460
+ "indexed": true,
461
+ "internalType": "uint256"
462
+ },
463
+ {
464
+ "name": "sponsor",
465
+ "type": "address",
466
+ "indexed": true,
467
+ "internalType": "address"
468
+ },
469
+ {
470
+ "name": "verifier",
471
+ "type": "address",
472
+ "indexed": true,
473
+ "internalType": "address"
474
+ },
475
+ {
476
+ "name": "rewardToken",
477
+ "type": "address",
478
+ "indexed": false,
479
+ "internalType": "address"
480
+ },
481
+ {
482
+ "name": "rewardPerAccepted",
483
+ "type": "uint256",
484
+ "indexed": false,
485
+ "internalType": "uint256"
486
+ },
487
+ {
488
+ "name": "budget",
489
+ "type": "uint256",
490
+ "indexed": false,
491
+ "internalType": "uint256"
492
+ },
493
+ {
494
+ "name": "deadline",
495
+ "type": "uint64",
496
+ "indexed": false,
497
+ "internalType": "uint64"
498
+ },
499
+ {
500
+ "name": "specHash",
501
+ "type": "bytes32",
502
+ "indexed": false,
503
+ "internalType": "bytes32"
504
+ }
505
+ ],
506
+ "anonymous": false
507
+ },
508
+ {
509
+ "type": "event",
510
+ "name": "JobFunded",
511
+ "inputs": [
512
+ {
513
+ "name": "jobId",
514
+ "type": "uint256",
515
+ "indexed": true,
516
+ "internalType": "uint256"
517
+ },
518
+ {
519
+ "name": "from",
520
+ "type": "address",
521
+ "indexed": true,
522
+ "internalType": "address"
523
+ },
524
+ {
525
+ "name": "amount",
526
+ "type": "uint256",
527
+ "indexed": false,
528
+ "internalType": "uint256"
529
+ },
530
+ {
531
+ "name": "budget",
532
+ "type": "uint256",
533
+ "indexed": false,
534
+ "internalType": "uint256"
535
+ }
536
+ ],
537
+ "anonymous": false
538
+ },
539
+ {
540
+ "type": "event",
541
+ "name": "OwnershipTransferStarted",
542
+ "inputs": [
543
+ {
544
+ "name": "previousOwner",
545
+ "type": "address",
546
+ "indexed": true,
547
+ "internalType": "address"
548
+ },
549
+ {
550
+ "name": "newOwner",
551
+ "type": "address",
552
+ "indexed": true,
553
+ "internalType": "address"
554
+ }
555
+ ],
556
+ "anonymous": false
557
+ },
558
+ {
559
+ "type": "event",
560
+ "name": "OwnershipTransferred",
561
+ "inputs": [
562
+ {
563
+ "name": "previousOwner",
564
+ "type": "address",
565
+ "indexed": true,
566
+ "internalType": "address"
567
+ },
568
+ {
569
+ "name": "newOwner",
570
+ "type": "address",
571
+ "indexed": true,
572
+ "internalType": "address"
573
+ }
574
+ ],
575
+ "anonymous": false
576
+ },
577
+ {
578
+ "type": "event",
579
+ "name": "ResultAccepted",
580
+ "inputs": [
581
+ {
582
+ "name": "jobId",
583
+ "type": "uint256",
584
+ "indexed": true,
585
+ "internalType": "uint256"
586
+ },
587
+ {
588
+ "name": "operator",
589
+ "type": "address",
590
+ "indexed": true,
591
+ "internalType": "address"
592
+ },
593
+ {
594
+ "name": "fingerprint",
595
+ "type": "bytes32",
596
+ "indexed": true,
597
+ "internalType": "bytes32"
598
+ },
599
+ {
600
+ "name": "resultHash",
601
+ "type": "bytes32",
602
+ "indexed": false,
603
+ "internalType": "bytes32"
604
+ },
605
+ {
606
+ "name": "reward",
607
+ "type": "uint256",
608
+ "indexed": false,
609
+ "internalType": "uint256"
610
+ }
611
+ ],
612
+ "anonymous": false
613
+ },
614
+ {
615
+ "type": "event",
616
+ "name": "VerifierApproved",
617
+ "inputs": [
618
+ {
619
+ "name": "verifier",
620
+ "type": "address",
621
+ "indexed": true,
622
+ "internalType": "address"
623
+ },
624
+ {
625
+ "name": "approved",
626
+ "type": "bool",
627
+ "indexed": false,
628
+ "internalType": "bool"
629
+ }
630
+ ],
631
+ "anonymous": false
632
+ },
633
+ {
634
+ "type": "event",
635
+ "name": "Withdrawn",
636
+ "inputs": [
637
+ {
638
+ "name": "operator",
639
+ "type": "address",
640
+ "indexed": true,
641
+ "internalType": "address"
642
+ },
643
+ {
644
+ "name": "token",
645
+ "type": "address",
646
+ "indexed": true,
647
+ "internalType": "address"
648
+ },
649
+ {
650
+ "name": "amount",
651
+ "type": "uint256",
652
+ "indexed": false,
653
+ "internalType": "uint256"
654
+ }
655
+ ],
656
+ "anonymous": false
657
+ },
658
+ {
659
+ "type": "error",
660
+ "name": "BudgetExhausted",
661
+ "inputs": []
662
+ },
663
+ {
664
+ "type": "error",
665
+ "name": "DeadlineNotReached",
666
+ "inputs": []
667
+ },
668
+ {
669
+ "type": "error",
670
+ "name": "DeadlinePassed",
671
+ "inputs": []
672
+ },
673
+ {
674
+ "type": "error",
675
+ "name": "DuplicateFingerprint",
676
+ "inputs": []
677
+ },
678
+ {
679
+ "type": "error",
680
+ "name": "InvalidParams",
681
+ "inputs": []
682
+ },
683
+ {
684
+ "type": "error",
685
+ "name": "JobNotOpen",
686
+ "inputs": []
687
+ },
688
+ {
689
+ "type": "error",
690
+ "name": "NativeTransferFailed",
691
+ "inputs": []
692
+ },
693
+ {
694
+ "type": "error",
695
+ "name": "NotEligible",
696
+ "inputs": []
697
+ },
698
+ {
699
+ "type": "error",
700
+ "name": "NotSponsor",
701
+ "inputs": []
702
+ },
703
+ {
704
+ "type": "error",
705
+ "name": "NotVerifier",
706
+ "inputs": []
707
+ },
708
+ {
709
+ "type": "error",
710
+ "name": "NothingOwed",
711
+ "inputs": []
712
+ },
713
+ {
714
+ "type": "error",
715
+ "name": "OwnableInvalidOwner",
716
+ "inputs": [
717
+ {
718
+ "name": "owner",
719
+ "type": "address",
720
+ "internalType": "address"
721
+ }
722
+ ]
723
+ },
724
+ {
725
+ "type": "error",
726
+ "name": "OwnableUnauthorizedAccount",
727
+ "inputs": [
728
+ {
729
+ "name": "account",
730
+ "type": "address",
731
+ "internalType": "address"
732
+ }
733
+ ]
734
+ },
735
+ {
736
+ "type": "error",
737
+ "name": "ReentrancyGuardReentrantCall",
738
+ "inputs": []
739
+ },
740
+ {
741
+ "type": "error",
742
+ "name": "SafeERC20FailedOperation",
743
+ "inputs": [
744
+ {
745
+ "name": "token",
746
+ "type": "address",
747
+ "internalType": "address"
748
+ }
749
+ ]
750
+ },
751
+ {
752
+ "type": "error",
753
+ "name": "VerifierNotApproved",
754
+ "inputs": []
755
+ },
756
+ {
757
+ "type": "error",
758
+ "name": "WrongValue",
759
+ "inputs": []
760
+ }
761
+ ];
762
+
763
+ // src/shared/chain.ts
764
+ function chainFor(chainId, rpcUrl) {
765
+ return defineChain({
766
+ id: chainId,
767
+ name: `chain-${chainId}`,
768
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
769
+ rpcUrls: { default: { http: [rpcUrl] } }
770
+ });
771
+ }
772
+ function publicClient(rpcUrl, chainId) {
773
+ return createPublicClient({ chain: chainFor(chainId, rpcUrl), transport: http(rpcUrl) });
774
+ }
775
+ function walletClient(rpcUrl, chainId, privateKey) {
776
+ const account = privateKeyToAccount(privateKey);
777
+ return createWalletClient({ account, chain: chainFor(chainId, rpcUrl), transport: http(rpcUrl) });
778
+ }
779
+ async function readJob(client, contract, jobId) {
780
+ return await client.readContract({ address: contract, abi: probeJobsAbi, functionName: "getJob", args: [jobId] });
781
+ }
782
+ function revertName(err) {
783
+ if (err instanceof BaseError) {
784
+ const reverted = err.walk((e) => e instanceof ContractFunctionRevertedError);
785
+ if (reverted instanceof ContractFunctionRevertedError) return reverted.data?.errorName ?? reverted.reason ?? null;
786
+ }
787
+ return null;
788
+ }
789
+ function formatUnitsShort(value, decimals) {
790
+ const neg = value < 0n;
791
+ const v = neg ? -value : value;
792
+ const base = 10n ** BigInt(decimals);
793
+ const whole = v / base;
794
+ const frac = (v % base).toString().padStart(decimals, "0").replace(/0+$/, "").slice(0, 6);
795
+ return `${neg ? "-" : ""}${whole.toLocaleString("en-US")}${frac ? `.${frac}` : ""}`;
796
+ }
797
+ var ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
798
+
799
+ // src/shared/rules.ts
800
+ var MAX_BYTES = 64 * 1024;
801
+ var BANNED = [
802
+ { re: /\bvm\s*\.\s*unixTime\b/, reason: "reads wall-clock time, not block time" },
803
+ { re: /\bvm\s*\.\s*(ffi|tryFfi)\b/, reason: "runs shell commands (ffi)" },
804
+ { re: /\bvm\s*\.\s*(env\w*|setEnv)\b/, reason: "reads environment variables" },
805
+ { re: /\bvm\s*\.\s*(readFile\w*|writeFile\w*|readDir|readLine|removeFile|fsMetadata|exists|isFile|isDir|projectRoot|copyFile|writeJson|writeToml|closeFile)\b/, reason: "touches the file system" },
806
+ { re: /\bvm\s*\.\s*(rpc\w*|createFork|createSelectFork|selectFork|rollFork|makePersistent|activeFork|transact)\b/, reason: "makes network calls or switches the fork" },
807
+ { re: /\bvm\s*\.\s*(random\w*|setArbitraryStorage)\b/, reason: "uses randomness without a recorded seed" },
808
+ { re: /\bvm\s*\.\s*(etch|store|mockCall\w*|mockFunction|clearMockedCalls|setCode|loadAllocs|cloneAccount)\b/, reason: "rewrites contract code or storage instead of testing it" },
809
+ { re: /\bvm\s*\.\s*(sleep|prompt\w*|breakpoint)\b/, reason: "waits on or asks the operator's machine" },
810
+ { re: /\bdeployCodeTo\b/, reason: "rewrites contract code instead of testing it" },
811
+ { re: /\bassembly\b/, reason: "uses inline assembly, which is not allowed in cases" },
812
+ { re: /7109709ecfa91a80626ff3989d68f67f5b1dd12d/i, reason: "calls the cheatcode address directly" },
813
+ { re: /\bselfdestruct\b|\bdelegatecall\b/, reason: "uses selfdestruct or delegatecall" }
814
+ ];
815
+ var ASSERTION_RE = /\b(assert\w*\s*\(|vm\s*\.\s*expectRevert\b|vm\s*\.\s*expectEmit\b)/;
816
+ function stripComments(src) {
817
+ return src.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/\/\/[^\n]*/g, " ");
818
+ }
819
+ function checkCase(source, spec) {
820
+ if (Buffer.byteLength(source, "utf8") > MAX_BYTES) return { ok: false, reason: "case is larger than 64 KB" };
821
+ const code = stripComments(source);
822
+ for (const rule of BANNED) if (rule.re.test(code)) return { ok: false, reason: rule.reason };
823
+ const imports = [...code.matchAll(/\bimport\b[^;]*?["']([^"']+)["']/g)].map((m) => m[1]);
824
+ for (const path of imports) {
825
+ const allowed = path === spec.fixture.import || spec.allowedImports.some((p) => path.startsWith(p));
826
+ if (!allowed) return { ok: false, reason: `imports ${path}, which is outside the job fixture` };
827
+ }
828
+ if (!imports.includes(spec.fixture.import)) {
829
+ return { ok: false, reason: `does not import the job fixture (${spec.fixture.import})` };
830
+ }
831
+ const contracts = [...code.matchAll(/\b(?:abstract\s+)?contract\s+([A-Za-z_]\w*)\s+is\s+([^{]+)\{/g)];
832
+ const concrete = contracts.filter((m) => !/\babstract\b/.test(m[0]));
833
+ if (concrete.length !== 1) return { ok: false, reason: "must define exactly one test contract" };
834
+ const [, contractName, bases] = concrete[0];
835
+ if (!bases.split(",").map((b) => b.trim()).includes(spec.fixture.base)) {
836
+ return { ok: false, reason: `test contract must inherit ${spec.fixture.base}, the job snapshot` };
837
+ }
838
+ if (/\bfunction\s+setUp\s*\(/.test(code) && !/super\s*\.\s*setUp\s*\(/.test(code)) {
839
+ return { ok: false, reason: "overrides setUp without calling super.setUp(), so it skips the snapshot" };
840
+ }
841
+ const tests = [...code.matchAll(/\bfunction\s+(test\w*)\s*\(/g)];
842
+ if (tests.length === 0) return { ok: false, reason: "has no test functions" };
843
+ if (tests.length > 8) return { ok: false, reason: "has more than 8 test functions; submit them as separate cases" };
844
+ const parameterised = [...code.matchAll(/\bfunction\s+test\w*\s*\(([^)]*)\)/g)].some((m) => m[1].trim().length > 0);
845
+ if (parameterised || /\bfunction\s+invariant\w*\s*\(/.test(code)) {
846
+ return { ok: false, reason: "uses fuzz or invariant tests; cases must be fixed scenarios" };
847
+ }
848
+ if (!ASSERTION_RE.test(code)) return { ok: false, reason: "does not assert any outcome" };
849
+ const asserts = [...code.matchAll(/\bassert(\w*)\s*\(([^;]*)\)\s*;/g)];
850
+ const meaningful = asserts.filter(([, kind, args]) => {
851
+ const parts = args.split(",").map((p) => p.trim());
852
+ if (/^(True)?$/.test(kind) && /^(true|!false|1\s*==\s*1)$/.test(parts[0])) return false;
853
+ if (/^(False)$/.test(kind) && /^(false|!true)$/.test(parts[0])) return false;
854
+ if (/^(Eq|ApproxEqAbs|ApproxEqRel|Le|Ge)$/.test(kind) && parts.length >= 2 && parts[0] === parts[1]) return false;
855
+ if (/^(True)?$/.test(kind) && /^(\w[\w.]*)\s*(==|>=|<=)\s*\1$/.test(parts[0])) return false;
856
+ return true;
857
+ });
858
+ if (asserts.length && meaningful.length === 0 && !/\bvm\s*\.\s*expect(Revert|Emit)\b/.test(code)) {
859
+ return { ok: false, reason: "only asserts constants, so it cannot fail" };
860
+ }
861
+ return { ok: true, contractName, testCount: tests.length };
862
+ }
863
+ function contractNameOf(source) {
864
+ return stripComments(source).match(/\bcontract\s+([A-Za-z_]\w*)\s+is\b/)?.[1] ?? null;
865
+ }
866
+ function caseTitle(source, fallback) {
867
+ const m = source.match(/((?:\s*\/\/\/[^\n]*\n)+)\s*contract\s/);
868
+ if (m) {
869
+ const first = m[1].split("\n").map((l) => l.replace(/^\s*\/\/\/\s?/, "").trim()).find(Boolean);
870
+ if (first) return first.replace(/\.$/, "").slice(0, 140);
871
+ }
872
+ return fallback.replace(/([a-z])([A-Z])/g, "$1 $2");
873
+ }
874
+
875
+ // src/shared/forge.ts
876
+ import { execFile } from "node:child_process";
877
+ import { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
878
+ import { homedir } from "node:os";
879
+ import { isAbsolute, join, resolve } from "node:path";
880
+ import { keccak256, toHex } from "viem";
881
+ function forgeBin() {
882
+ if (process.env.FORGE_BIN) return process.env.FORGE_BIN;
883
+ const fallback = join(homedir(), ".foundry", "bin", "forge");
884
+ return existsSync(fallback) ? fallback : "forge";
885
+ }
886
+ function run(cmd2, args, opts) {
887
+ return new Promise((resolvePromise) => {
888
+ execFile(
889
+ cmd2,
890
+ args,
891
+ {
892
+ cwd: opts.cwd,
893
+ timeout: opts.timeoutMs ?? 18e4,
894
+ maxBuffer: 64 * 1024 * 1024,
895
+ // Cases never see the caller's secrets, and the sandbox settings below
896
+ // override anything a job's foundry.toml asks for.
897
+ env: opts.env ?? {
898
+ PATH: process.env.PATH ?? "",
899
+ HOME: process.env.HOME ?? "",
900
+ NO_COLOR: "1",
901
+ FOUNDRY_DISABLE_NIGHTLY_WARNING: "1",
902
+ FOUNDRY_FFI: "false",
903
+ FOUNDRY_FS_PERMISSIONS: "[]",
904
+ FOUNDRY_ETH_RPC_URL: "",
905
+ FOUNDRY_FORK_URL: ""
906
+ }
907
+ },
908
+ (err, stdout, stderr) => {
909
+ const e = err;
910
+ resolvePromise({
911
+ code: e ? typeof e.code === "number" ? e.code : 1 : 0,
912
+ stdout: String(stdout),
913
+ stderr: String(stderr),
914
+ timedOut: Boolean(e?.killed)
915
+ });
916
+ }
917
+ );
918
+ });
919
+ }
920
+ async function forgeInstalled() {
921
+ const r = await run(forgeBin(), ["--version"], { cwd: process.cwd(), timeoutMs: 3e4 });
922
+ return r.code === 0;
923
+ }
924
+ async function buildWorkspace(ws) {
925
+ let r = await run(forgeBin(), ["build", "--offline"], { cwd: ws, timeoutMs: 6e5 });
926
+ if (r.code !== 0 && /missing solc|offline mode/i.test(r.stderr + r.stdout)) {
927
+ r = await run(forgeBin(), ["build"], { cwd: ws, timeoutMs: 6e5 });
928
+ }
929
+ if (r.code === 0) return { ok: true };
930
+ const out = stripAnsi(r.stderr || r.stdout);
931
+ const error = out.split("\n").find((l) => /^error|Error:/i.test(l.trim()))?.trim() ?? out.trim().split("\n").slice(-1)[0] ?? "forge build failed";
932
+ return { ok: false, error };
933
+ }
934
+ var stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, "");
935
+ function prepareWorkspace(srcDir, destDir) {
936
+ const src = resolve(srcDir);
937
+ if (!existsSync(join(src, "foundry.toml"))) throw new Error(`No foundry.toml in ${src}`);
938
+ rmSync(destDir, { recursive: true, force: true });
939
+ mkdirSync(destDir, { recursive: true });
940
+ cpSync(src, destDir, {
941
+ recursive: true,
942
+ filter: (p) => !/[/\\](out|cache|broadcast)([/\\]|$)/.test(p.slice(src.length)) && !/[/\\]test[/\\]cases[/\\]/.test(p.slice(src.length) + "/")
943
+ });
944
+ const tomlPath = join(destDir, "foundry.toml");
945
+ const toml = readFileSync(tomlPath, "utf8").replace(/(["=])(\.\.?\/[^"\s]*)/g, (_m, pre, rel) => {
946
+ const abs = resolve(src, rel);
947
+ return `${pre}${abs}${rel.endsWith("/") && !abs.endsWith("/") ? "/" : ""}`;
948
+ });
949
+ const sandboxed = toml.split("\n").filter((l) => !/^\s*(ffi|fs_permissions|eth_rpc_url|fork_url|fork_block_number|rpc_endpoints)\s*=/.test(l)).join("\n").replace(/(\[profile\.default\][^\n]*\n)/, "$1ffi = false\nfs_permissions = []\n");
950
+ if (!/ffi = false/.test(sandboxed)) throw new Error("foundry.toml has no [profile.default] section");
951
+ writeFileSync(tomlPath, sandboxed);
952
+ mkdirSync(join(destDir, "test", "cases"), { recursive: true });
953
+ return destDir;
954
+ }
955
+ function resolveWorkspacePath(repoRoot, path) {
956
+ return isAbsolute(path) ? path : resolve(repoRoot, path);
957
+ }
958
+ async function forgeTest(workspace, casePath, seed) {
959
+ const res = await run(forgeBin(), ["test", "--match-path", casePath, "--json", "--fuzz-seed", String(seed), "--offline"], {
960
+ cwd: workspace
961
+ });
962
+ if (res.timedOut) return { passed: false, tests: [], compileError: null, timedOut: true };
963
+ const jsonStart = res.stdout.indexOf("{");
964
+ if (jsonStart === -1) {
965
+ const msg = stripAnsi(res.stderr || res.stdout).trim();
966
+ return { passed: false, tests: [], compileError: msg.slice(0, 4e3) || "forge produced no output", timedOut: false };
967
+ }
968
+ let parsed;
969
+ try {
970
+ parsed = JSON.parse(res.stdout.slice(jsonStart));
971
+ } catch {
972
+ return { passed: false, tests: [], compileError: stripAnsi(res.stdout + res.stderr).slice(0, 4e3), timedOut: false };
973
+ }
974
+ const tests = [];
975
+ for (const suite of Object.values(parsed)) {
976
+ for (const [name, r] of Object.entries(suite.test_results)) {
977
+ tests.push({ name, passed: r.status === "Success", reason: r.reason, gas: r.kind?.Unit?.gas ?? null });
978
+ }
979
+ }
980
+ return { passed: tests.length > 0 && tests.every((t) => t.passed), tests, compileError: null, timedOut: false };
981
+ }
982
+ var shortFp = (fp) => `${fp.slice(2, 6)}\u2026${fp.slice(-4)}`;
983
+
984
+ // src/shared/crypto.ts
985
+ import nacl from "tweetnacl";
986
+ var b64 = (u) => Buffer.from(u).toString("base64");
987
+ var unb64 = (s) => new Uint8Array(Buffer.from(s, "base64"));
988
+ function generateReportKeyPair() {
989
+ const kp = nacl.box.keyPair();
990
+ return { publicKey: b64(kp.publicKey), secretKey: b64(kp.secretKey) };
991
+ }
992
+ function open(report, recipientSecretKey) {
993
+ const out = nacl.box.open(unb64(report.ct), unb64(report.nonce), unb64(report.epk), unb64(recipientSecretKey));
994
+ if (!out) throw new Error("could not decrypt: wrong key or corrupted report");
995
+ return new TextDecoder().decode(out);
996
+ }
997
+
998
+ // src/shared/messages.ts
999
+ import { keccak256 as keccak2562, toHex as toHex2 } from "viem";
1000
+ var sourceHash = (source) => keccak2562(toHex2(source));
1001
+ function submissionMessage(p) {
1002
+ return `PROBE case submission
1003
+ job: ${p.slug}
1004
+ case: ${p.sourceHash}
1005
+ nonce: ${p.nonce}`;
1006
+ }
1007
+ function registrationMessage(p) {
1008
+ return `PROBE job registration
1009
+ job: ${p.slug}
1010
+ spec: ${p.specHash}
1011
+ onchain: ${p.chainId}/${p.contract}/${p.jobId}`;
1012
+ }
1013
+ function reportsMessage(p) {
1014
+ return `PROBE sponsor reports
1015
+ job: ${p.slug}
1016
+ nonce: ${p.nonce}`;
1017
+ }
1018
+
1019
+ // src/shared/spec.ts
1020
+ import { keccak256 as keccak2563, toHex as toHex3 } from "viem";
1021
+ function canonicalJson(value) {
1022
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
1023
+ if (value && typeof value === "object") {
1024
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
1025
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
1026
+ }
1027
+ return JSON.stringify(value);
1028
+ }
1029
+ function specHash(spec) {
1030
+ return keccak2563(toHex3(canonicalJson(spec)));
1031
+ }
1032
+ var SLUG_RE = /^[a-z0-9][a-z0-9-]{2,63}$/;
1033
+ function validateSpec(spec) {
1034
+ const s = spec;
1035
+ const fail2 = (m) => {
1036
+ throw new Error(`Invalid job spec: ${m}`);
1037
+ };
1038
+ if (!s || typeof s !== "object") fail2("not an object");
1039
+ if (!s.slug || !SLUG_RE.test(s.slug)) fail2("slug must be 3-64 lowercase letters, digits or dashes");
1040
+ for (const k of ["title", "summary", "objective", "sponsor", "reportKey"]) {
1041
+ if (typeof s[k] !== "string" || !s[k]) fail2(`${k} is required`);
1042
+ }
1043
+ for (const k of ["inScope", "outOfScope", "acceptanceRules", "targets", "allowedImports"]) {
1044
+ if (!Array.isArray(s[k])) fail2(`${k} must be a list`);
1045
+ }
1046
+ if (!s.targets.length) fail2("targets must name at least one source file");
1047
+ if (!s.workspace || !s.workspace.path && !s.workspace.git) fail2("workspace needs a path or a git url");
1048
+ if (s.workspace?.git && !/^[0-9a-f]{40}$/.test(s.workspace.commit ?? "")) fail2("git workspaces need a full commit hash");
1049
+ if (!s.fixture?.base || !s.fixture?.import) fail2("fixture.base and fixture.import are required");
1050
+ if (!["findings", "coverage", "findings-and-coverage"].includes(s.rewardModel)) fail2("rewardModel is invalid");
1051
+ if (!s.network?.id || !s.network?.name) fail2("network is required");
1052
+ if (!s.hook?.name) fail2("hook.name is required");
1053
+ if (typeof s.snapshot?.block !== "number") fail2("snapshot.block is required");
1054
+ }
1055
+
1056
+ // src/cli/config.ts
1057
+ import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
1058
+ import { homedir as homedir2 } from "node:os";
1059
+ import { dirname, join as join2, resolve as resolve2 } from "node:path";
1060
+ import { fileURLToPath } from "node:url";
1061
+ import { generatePrivateKey, privateKeyToAccount as privateKeyToAccount2 } from "viem/accounts";
1062
+ var PROBE_HOME = resolve2(process.env.PROBE_HOME ?? join2(homedir2(), ".probe"));
1063
+ var CONFIG = join2(PROBE_HOME, "config.json");
1064
+ var here = dirname(fileURLToPath(import.meta.url));
1065
+ var REPO_ROOT = resolve2(process.env.PROBE_REPO_ROOT ?? join2(here, "../../.."));
1066
+ function loadConfig() {
1067
+ const file = existsSync2(CONFIG) ? JSON.parse(readFileSync2(CONFIG, "utf8")) : {};
1068
+ return {
1069
+ verifierUrl: process.env.PROBE_VERIFIER_URL ?? file.verifierUrl ?? "https://verifier.probecli.com",
1070
+ operatorKey: process.env.PROBE_OPERATOR_KEY ?? file.operatorKey,
1071
+ sponsorKey: process.env.PROBE_SPONSOR_KEY ?? file.sponsorKey,
1072
+ sponsorReportKey: file.sponsorReportKey
1073
+ };
1074
+ }
1075
+ function saveConfig(patch) {
1076
+ mkdirSync2(PROBE_HOME, { recursive: true, mode: 448 });
1077
+ const current = existsSync2(CONFIG) ? JSON.parse(readFileSync2(CONFIG, "utf8")) : {};
1078
+ writeFileSync2(CONFIG, JSON.stringify({ ...current, ...patch }, null, 2), { mode: 384 });
1079
+ chmodSync(CONFIG, 384);
1080
+ }
1081
+ function newOperatorKey() {
1082
+ const key = generatePrivateKey();
1083
+ return { key, address: privateKeyToAccount2(key).address };
1084
+ }
1085
+ var configPath = CONFIG;
1086
+
1087
+ // src/cli/client.ts
1088
+ import { privateKeyToAccount as privateKeyToAccount3 } from "viem/accounts";
1089
+
1090
+ // src/cli/ui.ts
1091
+ var tty = process.stdout.isTTY && !process.env.NO_COLOR;
1092
+ var c = (code) => (s) => tty ? `\x1B[${code}m${s}\x1B[0m` : s;
1093
+ var hot = c("38;2;232;63;40");
1094
+ var dim = c("38;2;154;151;142");
1095
+ var bold = c("1");
1096
+ var prompt = () => hot("\u203A\u2022");
1097
+ function field(label, value) {
1098
+ console.log(` ${dim(label.padEnd(8))} ${value}`);
1099
+ }
1100
+ function note(s) {
1101
+ console.log(dim(s));
1102
+ }
1103
+ var FRAMES = "\u280B\u2819\u2839\u2838\u283C\u2834\u2826\u2827\u2807\u280F";
1104
+ async function task(label, fn, done) {
1105
+ let i = 0;
1106
+ const render = (glyph, suffix = "") => {
1107
+ if (tty) process.stdout.write(`\r\x1B[2K${glyph} ${label}${suffix}`);
1108
+ };
1109
+ const timer = tty ? setInterval(() => render(hot(FRAMES[i++ % FRAMES.length])), 80) : null;
1110
+ try {
1111
+ const v = await fn();
1112
+ if (timer) clearInterval(timer);
1113
+ const suffix = done ? ` ${dim(done(v))}` : "";
1114
+ if (tty) render(dim("\u2713"), suffix), process.stdout.write("\n");
1115
+ else console.log(`\u2713 ${label}${suffix}`);
1116
+ return v;
1117
+ } catch (e) {
1118
+ if (timer) clearInterval(timer);
1119
+ if (tty) render(hot("\xD7"), ` ${dim(e.message)}`), process.stdout.write("\n");
1120
+ else console.log(`\xD7 ${label} ${e.message}`);
1121
+ throw e;
1122
+ }
1123
+ }
1124
+ function verdictLine(index, verdict, reason) {
1125
+ const map = {
1126
+ accepted: ["\u2713", hot, "accepted"],
1127
+ duplicate: ["=", (s) => s, "duplicate"],
1128
+ failed: ["\xD7", (s) => s, "failed verification"],
1129
+ ineligible: ["\xD7", (s) => s, "not eligible"]
1130
+ };
1131
+ const [g, color, label] = map[verdict] ?? ["?", (s) => s, verdict];
1132
+ console.log(`${color(g)} ${color(`case ${index} ${label}`)}${dim(`: ${reason}`)}`);
1133
+ }
1134
+ function payout(text) {
1135
+ console.log(`${hot("\u25CF")} ${text}`);
1136
+ }
1137
+ function fail(message) {
1138
+ console.error(`${hot("\xD7")} ${message}`);
1139
+ process.exit(1);
1140
+ }
1141
+
1142
+ // src/cli/client.ts
1143
+ async function api(path, init2) {
1144
+ const cfg = loadConfig();
1145
+ let res;
1146
+ try {
1147
+ res = await fetch(`${cfg.verifierUrl}${path}`, {
1148
+ method: init2?.method ?? "GET",
1149
+ headers: init2?.body ? { "content-type": "application/json" } : void 0,
1150
+ body: init2?.body ? JSON.stringify(init2.body) : void 0
1151
+ });
1152
+ } catch {
1153
+ throw new Error(`cannot reach the verifier at ${cfg.verifierUrl}. Set it with probe init --verifier <url>.`);
1154
+ }
1155
+ const body = await res.json().catch(() => ({}));
1156
+ if (!res.ok) throw new Error(body.error ?? `verifier returned HTTP ${res.status}`);
1157
+ return body;
1158
+ }
1159
+ function operator() {
1160
+ const key = loadConfig().operatorKey;
1161
+ if (!key) fail("No operator key. Run probe init first.");
1162
+ return privateKeyToAccount3(key);
1163
+ }
1164
+ function clientFor(job2) {
1165
+ return publicClient(job2.chain.rpcUrl, job2.chain.chainId);
1166
+ }
1167
+
1168
+ // src/cli/workspace.ts
1169
+ import { existsSync as existsSync3, mkdirSync as mkdirSync3, readdirSync, readFileSync as readFileSync3, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
1170
+ import { join as join3 } from "node:path";
1171
+ var REPO_URL = process.env.PROBE_REPO_URL ?? "https://github.com/probecli/probe";
1172
+ async function publicRepo() {
1173
+ const dir = join3(PROBE_HOME, "repo");
1174
+ if (!existsSync3(join3(dir, ".git"))) {
1175
+ mkdirSync3(PROBE_HOME, { recursive: true });
1176
+ const r = await run("git", ["clone", "--quiet", "--depth", "1", REPO_URL, dir], { cwd: PROBE_HOME, timeoutMs: 6e5, env: process.env });
1177
+ if (r.code !== 0) throw new Error(`could not download job workspaces from ${REPO_URL}: ${r.stderr.trim().split("\n").pop() ?? "git clone failed"}`);
1178
+ } else {
1179
+ const f = await run("git", ["fetch", "--quiet", "--depth", "1", "origin", "main"], { cwd: dir, timeoutMs: 3e5, env: process.env });
1180
+ if (f.code === 0) await run("git", ["reset", "--quiet", "--hard", "FETCH_HEAD"], { cwd: dir, env: process.env });
1181
+ }
1182
+ return dir;
1183
+ }
1184
+ async function localWorkspace(job2) {
1185
+ let src;
1186
+ if (job2.workspace.path) {
1187
+ src = resolveWorkspacePath(REPO_ROOT, job2.workspace.path);
1188
+ if (!existsSync3(join3(src, "foundry.toml"))) {
1189
+ const repo = await publicRepo();
1190
+ src = resolveWorkspacePath(repo, job2.workspace.path);
1191
+ if (!existsSync3(join3(src, "foundry.toml"))) throw new Error(`workspace ${job2.workspace.path} is not in ${REPO_URL}. Set PROBE_REPO_ROOT to a checkout that has it.`);
1192
+ }
1193
+ } else {
1194
+ src = join3(PROBE_HOME, "src", job2.slug);
1195
+ if (!existsSync3(join3(src, ".git"))) {
1196
+ const r = await run("git", ["clone", "--recurse-submodules", job2.workspace.git, src], { cwd: PROBE_HOME, timeoutMs: 6e5, env: process.env });
1197
+ if (r.code !== 0) throw new Error(`git clone failed: ${r.stderr.slice(0, 300)}`);
1198
+ }
1199
+ await run("git", ["checkout", "--quiet", job2.workspace.commit], { cwd: src, env: process.env });
1200
+ await run("git", ["submodule", "update", "--init", "--recursive"], { cwd: src, timeoutMs: 6e5, env: process.env });
1201
+ }
1202
+ return prepareWorkspace(src, join3(PROBE_HOME, "work", job2.slug));
1203
+ }
1204
+ function seedCases(ws, job2) {
1205
+ if (!job2.seedCases) return [];
1206
+ const dir = join3(ws, job2.seedCases);
1207
+ if (!existsSync3(dir)) return [];
1208
+ return readdirSync(dir).filter((f) => f.endsWith(".sol")).sort().map((f) => {
1209
+ const source = readFileSync3(join3(dir, f), "utf8");
1210
+ const name = f.replace(/\.t\.sol$|\.sol$/, "");
1211
+ return { name, title: caseTitle(source, name), source };
1212
+ });
1213
+ }
1214
+ async function runLocal(ws, c2) {
1215
+ const dir = join3(ws, "test/cases");
1216
+ mkdirSync3(dir, { recursive: true });
1217
+ for (const f of readdirSync(dir)) rmSync2(join3(dir, f), { force: true });
1218
+ const rel = `test/cases/${c2.name.replace(/[^A-Za-z0-9_]/g, "")}.t.sol`;
1219
+ writeFileSync3(join3(ws, rel), c2.source);
1220
+ try {
1221
+ return await forgeTest(ws, rel, 1);
1222
+ } finally {
1223
+ rmSync2(join3(ws, rel), { force: true });
1224
+ }
1225
+ }
1226
+
1227
+ // src/cli/cases.ts
1228
+ import { readFileSync as readFileSync4 } from "node:fs";
1229
+ import { basename } from "node:path";
1230
+ function fixtureHelpers(source) {
1231
+ const out = [];
1232
+ const re = /((?:[ \t]*\/\/\/[^\n]*\n)*)[ \t]*function\s+(\w+)\s*\(([^)]*)\)\s*([^{;]*)[{;]/g;
1233
+ for (const m of source.matchAll(re)) {
1234
+ const [, docBlock, name, params, rest2] = m;
1235
+ if (name === "setUp" || /\bprivate\b/.test(rest2)) continue;
1236
+ const returns = rest2.match(/returns\s*\(([^)]*)\)/)?.[1];
1237
+ const signature = `${name}(${params.replace(/\s+/g, " ").trim()})${returns ? ` returns (${returns.replace(/\s+/g, " ").trim()})` : ""}`;
1238
+ const returnNames = new Set((returns ?? "").split(",").map((r) => r.trim().split(/\s+/).at(-1)).filter(Boolean));
1239
+ const doc = docBlock.split("\n").map((l) => {
1240
+ const line = l.replace(/^\s*\/\/\/\s?/, "");
1241
+ const words = line.replace(/^@\w+\s*/, "").trim().split(/\s+/);
1242
+ if (/^@return\b/.test(line)) while (words.length && returnNames.has(words[0])) words.shift();
1243
+ return words.join(" ");
1244
+ }).filter(Boolean).join(" ");
1245
+ out.push({ signature, doc: doc || null });
1246
+ }
1247
+ return out;
1248
+ }
1249
+ function caseName(input) {
1250
+ const name = input.replace(/\.t\.sol$|\.sol$/, "").split(/[^A-Za-z0-9]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join("");
1251
+ if (!name || /^[0-9]/.test(name)) throw new Error(`"${input}" is not a usable case name. Use letters, like FeeSpikeWithdraw.`);
1252
+ return name;
1253
+ }
1254
+ function caseTemplate(job2, name, helpers) {
1255
+ const fn = `test_${name[0].toLowerCase()}${name.slice(1)}`;
1256
+ const helperLines = helpers.length ? [
1257
+ ` // Helpers from ${job2.fixture.base}:`,
1258
+ ...helpers.map((h) => ` // ${h.signature}${h.doc ? ` ${h.doc}` : ""}`),
1259
+ ` //`
1260
+ ] : [];
1261
+ return [
1262
+ "// SPDX-License-Identifier: MIT",
1263
+ "pragma solidity ^0.8.26;",
1264
+ "",
1265
+ `import {${job2.fixture.base}} from "${job2.fixture.import}";`,
1266
+ "",
1267
+ "/// TODO: one line saying what this case shows. It becomes the case title.",
1268
+ `/// Job ${job2.slug}, hook ${job2.hook.name} (${job2.hook.callbacks.join(", ")}).`,
1269
+ `contract ${name} is ${job2.fixture.base} {`,
1270
+ ...helperLines,
1271
+ " // Set up the scenario with the helpers, then assert a concrete balance or fee",
1272
+ " // outcome. No wall clock, randomness, network, files or env reads.",
1273
+ ` function ${fn}() public {`,
1274
+ ` assertTrue(false, "TODO: write this case");`,
1275
+ " }",
1276
+ "}",
1277
+ ""
1278
+ ].join("\n");
1279
+ }
1280
+ function loadCaseFiles(paths) {
1281
+ return paths.map((p) => {
1282
+ const source = readFileSync4(p, "utf8");
1283
+ const name = contractNameOf(source) ?? basename(p).replace(/\.t\.sol$|\.sol$/, "");
1284
+ return { name, title: caseTitle(source, name), source };
1285
+ });
1286
+ }
1287
+
1288
+ // src/cli/format.ts
1289
+ function deadlineText(deadline, nowMs = Date.now()) {
1290
+ const date = new Date(deadline * 1e3).toISOString().slice(0, 10);
1291
+ const left = deadline * 1e3 - nowMs;
1292
+ if (left <= 0) return `passed (${date})`;
1293
+ const hours = Math.max(1, Math.floor(left / 36e5));
1294
+ if (hours < 48) return `in ${hours} hour${hours === 1 ? "" : "s"} (${date})`;
1295
+ return `in ${Math.floor(hours / 24)} days (${date})`;
1296
+ }
1297
+ function resultCounts(subs) {
1298
+ const order = ["accepted", "duplicate", "failed", "ineligible", "pending"];
1299
+ const counts = /* @__PURE__ */ new Map();
1300
+ for (const s of subs) {
1301
+ const key = s.status === "done" && s.verdict ? s.verdict : "pending";
1302
+ counts.set(key, (counts.get(key) ?? 0) + 1);
1303
+ }
1304
+ return order.filter((v) => counts.has(v)).map((verdict) => ({ verdict, count: counts.get(verdict) }));
1305
+ }
1306
+ function printJson(value) {
1307
+ console.log(JSON.stringify(value, null, 2));
1308
+ }
1309
+ function ago(ms, nowMs = Date.now()) {
1310
+ const s = Math.max(0, Math.floor((nowMs - ms) / 1e3));
1311
+ if (s < 60) return "just now";
1312
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
1313
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
1314
+ if (s < 30 * 86400) return `${Math.floor(s / 86400)}d ago`;
1315
+ return new Date(ms).toISOString().slice(0, 10);
1316
+ }
1317
+
1318
+ // src/cli/doctor.ts
1319
+ import { formatEther } from "viem";
1320
+ import { privateKeyToAccount as privateKeyToAccount4 } from "viem/accounts";
1321
+
1322
+ // src/cli/agent.ts
1323
+ import Anthropic from "@anthropic-ai/sdk";
1324
+ var AGENT_MODEL = process.env.PROBE_AGENT_MODEL ?? "claude-opus-5-5";
1325
+ var SCHEMA = {
1326
+ type: "object",
1327
+ properties: {
1328
+ cases: {
1329
+ type: "array",
1330
+ items: {
1331
+ type: "object",
1332
+ properties: {
1333
+ name: { type: "string", description: "Solidity contract name, PascalCase" },
1334
+ title: { type: "string", description: "One-line scenario description" },
1335
+ source: { type: "string", description: "Complete Solidity file" }
1336
+ },
1337
+ required: ["name", "title", "source"],
1338
+ additionalProperties: false
1339
+ }
1340
+ }
1341
+ },
1342
+ required: ["cases"],
1343
+ additionalProperties: false
1344
+ };
1345
+ function system(spec) {
1346
+ return `You write Foundry test cases for a PROBE testing job on a Uniswap v4 hook.
1347
+
1348
+ Each case is one Solidity file that:
1349
+ - imports {${spec.fixture.base}} from "${spec.fixture.import}" and defines exactly one contract that inherits ${spec.fixture.base} (the pinned job snapshot);
1350
+ - has 1 to 3 test functions with no parameters, each asserting a concrete balance, fee or state outcome;
1351
+ - uses only the helpers and state exposed by the fixture, forge-std and the allowed imports (${spec.allowedImports.join(", ")});
1352
+ - never uses vm.unixTime, vm.ffi, vm.env*, file access, forks or rpc, vm.random*, vm.etch, vm.store, vm.mockCall, deployCodeTo, inline assembly, fuzz or invariant tests;
1353
+ - starts with \`// SPDX-License-Identifier: MIT\` and \`pragma solidity ^0.8.26;\`, and puts a one-line /// comment describing the scenario directly above the contract.
1354
+
1355
+ A case that demonstrates a problem should pass when the problem is present (assert the bad outcome).
1356
+ A case for coverage should assert the expected correct behavior.
1357
+ Prefer scenarios that reach code paths the job history has not covered yet. Do not resubmit a scenario that was already accepted or marked duplicate.`;
1358
+ }
1359
+ function context(ctx) {
1360
+ const s = ctx.spec;
1361
+ return [
1362
+ `Job: ${s.title}`,
1363
+ `Objective: ${s.objective}`,
1364
+ `Pays for: ${s.rewardModel}`,
1365
+ `In scope:
1366
+ - ${s.inScope.join("\n- ")}`,
1367
+ `Out of scope:
1368
+ - ${s.outOfScope.join("\n- ")}`,
1369
+ `Acceptance rules:
1370
+ - ${s.acceptanceRules.join("\n- ")}`,
1371
+ `Fixture (${s.fixture.import}):
1372
+ \`\`\`solidity
1373
+ ${ctx.fixtureSource}
1374
+ \`\`\``,
1375
+ ...ctx.targetSources.map((t) => `Target ${t.path}:
1376
+ \`\`\`solidity
1377
+ ${t.source}
1378
+ \`\`\``),
1379
+ ctx.exampleCase ? `Example of a well-formed case:
1380
+ \`\`\`solidity
1381
+ ${ctx.exampleCase}
1382
+ \`\`\`` : "",
1383
+ ctx.history.length ? `Already processed on this job:
1384
+ ${ctx.history.map((h) => `- ${h.title}: ${h.verdict ?? "pending"}${h.reason ? ` (${h.reason})` : ""}`).join("\n")}` : "No results on this job yet."
1385
+ ].filter(Boolean).join("\n\n");
1386
+ }
1387
+ async function ask(client, ctx, instruction) {
1388
+ const stream = client.beta.messages.stream({
1389
+ model: AGENT_MODEL,
1390
+ max_tokens: 64e3,
1391
+ betas: ["server-side-fallback-2026-07-01"],
1392
+ fallbacks: "default",
1393
+ output_config: { effort: "high", format: { type: "json_schema", schema: SCHEMA } },
1394
+ system: system(ctx.spec),
1395
+ messages: [{ role: "user", content: `${context(ctx)}
1396
+
1397
+ ${instruction}` }]
1398
+ });
1399
+ const message = await stream.finalMessage();
1400
+ if (message.stop_reason === "refusal") throw new Error("the agent declined to write cases for this job");
1401
+ if (message.stop_reason === "max_tokens") throw new Error("the agent's answer was cut off; try fewer cases");
1402
+ const text = message.content.flatMap((b) => b.type === "text" ? [b.text] : []).join("");
1403
+ let parsed;
1404
+ try {
1405
+ parsed = JSON.parse(text);
1406
+ } catch {
1407
+ throw new Error("the agent returned malformed output");
1408
+ }
1409
+ return (parsed.cases ?? []).filter((c2) => c2 && typeof c2.source === "string" && typeof c2.name === "string");
1410
+ }
1411
+ function agentAvailable() {
1412
+ return Boolean(process.env.ANTHROPIC_API_KEY || process.env.ANTHROPIC_AUTH_TOKEN || process.env.ANTHROPIC_PROFILE);
1413
+ }
1414
+ async function proposeCases(ctx, count) {
1415
+ const client = new Anthropic();
1416
+ return ask(client, ctx, `Write ${count} new, distinct cases for this job.`);
1417
+ }
1418
+ async function repairCase(ctx, c2, error) {
1419
+ const client = new Anthropic();
1420
+ const fixed = await ask(
1421
+ client,
1422
+ ctx,
1423
+ `This case failed locally. Fix it so it compiles, follows every rule, and passes on the snapshot while still testing the same scenario. Return exactly one case.
1424
+
1425
+ Case ${c2.name}:
1426
+ \`\`\`solidity
1427
+ ${c2.source}
1428
+ \`\`\`
1429
+
1430
+ Error:
1431
+ ${error.slice(0, 6e3)}`
1432
+ );
1433
+ return fixed[0] ?? null;
1434
+ }
1435
+
1436
+ // src/cli/doctor.ts
1437
+ var MIN_NODE = "22.18.0";
1438
+ function atLeast(a, b) {
1439
+ const pa = a.replace(/^v/, "").split(".").map(Number);
1440
+ const pb = b.replace(/^v/, "").split(".").map(Number);
1441
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
1442
+ const x = pa[i] ?? 0;
1443
+ const y = pb[i] ?? 0;
1444
+ if (x !== y) return x > y;
1445
+ }
1446
+ return true;
1447
+ }
1448
+ async function timed(fn) {
1449
+ const t = Date.now();
1450
+ const v = await fn();
1451
+ return [v, Date.now() - t];
1452
+ }
1453
+ async function runChecks() {
1454
+ const checks = [];
1455
+ const cfg = loadConfig();
1456
+ const node = process.versions.node;
1457
+ checks.push(
1458
+ atLeast(node, MIN_NODE) ? { name: "node", level: "ok", detail: `v${node}` } : { name: "node", level: "fail", detail: `v${node}, needs ${MIN_NODE} or later`, fix: "Install Node 22.18+ from nodejs.org or with your version manager." }
1459
+ );
1460
+ const forge = await run(forgeBin(), ["--version"], { cwd: process.cwd(), timeoutMs: 3e4 });
1461
+ checks.push(
1462
+ forge.code === 0 ? { name: "foundry", level: "ok", detail: forge.stdout.split("\n")[0].replace(/^forge\s*(version:?\s*)?/i, "forge ").trim() } : { name: "foundry", level: "fail", detail: "forge not found", fix: "curl -L https://foundry.paradigm.xyz | bash && foundryup" }
1463
+ );
1464
+ const git = await run("git", ["--version"], { cwd: process.cwd(), timeoutMs: 3e4, env: process.env });
1465
+ checks.push(
1466
+ git.code === 0 ? { name: "git", level: "ok", detail: git.stdout.trim().replace(/^git version /, "") } : { name: "git", level: "warn", detail: "not found; needed for jobs whose workspace is a git repository", fix: "Install git." }
1467
+ );
1468
+ let health = null;
1469
+ try {
1470
+ const [h, ms] = await timed(() => api("/health"));
1471
+ health = h;
1472
+ checks.push({ name: "verifier", level: "ok", detail: `${cfg.verifierUrl} answered in ${ms} ms (${h.network ?? `chain ${h.chainId}`})` });
1473
+ } catch (e) {
1474
+ checks.push({ name: "verifier", level: "fail", detail: e.message, fix: "Check your connection, or point at another verifier with probe init --verifier <url>." });
1475
+ }
1476
+ let rpc = null;
1477
+ if (health) {
1478
+ const jobs2 = await api("/jobs").catch(() => []);
1479
+ const j = jobs2.find((x) => x.chain.chainId === health.chainId);
1480
+ if (j) {
1481
+ try {
1482
+ const client = publicClient(j.chain.rpcUrl, j.chain.chainId);
1483
+ const [[chainId, block], ms] = await timed(() => Promise.all([client.getChainId(), client.getBlockNumber()]));
1484
+ if (chainId !== health.chainId) {
1485
+ checks.push({ name: "chain", level: "fail", detail: `RPC reports chain ${chainId}, the verifier uses ${health.chainId}` });
1486
+ } else {
1487
+ rpc = { url: j.chain.rpcUrl, chainId };
1488
+ checks.push({ name: "chain", level: "ok", detail: `block ${block.toLocaleString("en-US")} in ${ms} ms` });
1489
+ }
1490
+ } catch (e) {
1491
+ checks.push({ name: "chain", level: "fail", detail: `cannot reach ${j.chain.rpcUrl}: ${e.message.split("\n")[0]}` });
1492
+ }
1493
+ } else {
1494
+ checks.push({ name: "chain", level: "warn", detail: "no jobs on this verifier yet, so no RPC to check" });
1495
+ }
1496
+ }
1497
+ if (!cfg.operatorKey) {
1498
+ checks.push({ name: "operator", level: "fail", detail: "no operator key", fix: "probe init" });
1499
+ } else {
1500
+ const address = privateKeyToAccount4(cfg.operatorKey).address;
1501
+ if (rpc) {
1502
+ const gas = await publicClient(rpc.url, rpc.chainId).getBalance({ address }).catch(() => null);
1503
+ if (gas === 0n) {
1504
+ checks.push({ name: "operator", level: "warn", detail: `${address}, no gas`, fix: "Rewards are credited without gas, but probe withdraw needs a little native currency at this address." });
1505
+ } else {
1506
+ checks.push({ name: "operator", level: "ok", detail: `${address}${gas !== null ? `, ${formatEther(gas)} for gas` : ""}` });
1507
+ }
1508
+ } else {
1509
+ checks.push({ name: "operator", level: "ok", detail: address });
1510
+ }
1511
+ }
1512
+ checks.push(
1513
+ agentAvailable() ? { name: "agent", level: "ok", detail: `${AGENT_MODEL}, credentials found` } : { name: "agent", level: "warn", detail: "no credentials; probe work uses seed cases and your own (probe case new)", fix: "Set ANTHROPIC_API_KEY to have the agent write cases." }
1514
+ );
1515
+ return checks;
1516
+ }
1517
+ async function doctor() {
1518
+ const checks = await runChecks();
1519
+ const glyph = { ok: dim("\u2713"), warn: dim("!"), fail: hot("\xD7") };
1520
+ for (const c2 of checks) {
1521
+ console.log(`${glyph[c2.level]} ${c2.name.padEnd(9)} ${c2.detail}`);
1522
+ if (c2.fix && c2.level !== "ok") console.log(` ${" ".repeat(9)} ${dim(c2.fix)}`);
1523
+ }
1524
+ const failed = checks.filter((c2) => c2.level === "fail").length;
1525
+ console.log("");
1526
+ console.log(dim(failed ? `${failed} problem${failed === 1 ? "" : "s"} to fix before probe work. Settings: ${configPath}` : `Ready. Settings: ${configPath}`));
1527
+ if (failed) process.exitCode = 1;
1528
+ }
1529
+
1530
+ // src/cli/check.ts
1531
+ import { parseArgs } from "node:util";
1532
+ import { getAddress as getAddress2, isAddress as isAddress2 } from "viem";
1533
+
1534
+ // src/shared/hookcheck.ts
1535
+ import {
1536
+ encodeFunctionData,
1537
+ getAddress,
1538
+ isAddress,
1539
+ keccak256 as keccak2564,
1540
+ parseAbi,
1541
+ toFunctionSelector,
1542
+ toHex as toHex4
1543
+ } from "viem";
1544
+ var CHECK_VERSION = 1;
1545
+ var POOL_MANAGERS = {
1546
+ 4663: { address: "0x8366a39cc670b4001a1121b8f6a443a643e40951", deployBlock: 9070n }
1547
+ };
1548
+ var DEFAULT_RPC = "https://rpc.mainnet.chain.robinhood.com";
1549
+ var sameOutcome = (a, b) => a.checks.map((c2) => `${c2.id}:${c2.status}`).join() === b.checks.map((c2) => `${c2.id}:${c2.status}`).join();
1550
+ var FLAGS = [
1551
+ { bit: 13, name: "beforeInitialize" },
1552
+ { bit: 12, name: "afterInitialize" },
1553
+ { bit: 11, name: "beforeAddLiquidity" },
1554
+ { bit: 10, name: "afterAddLiquidity" },
1555
+ { bit: 9, name: "beforeRemoveLiquidity" },
1556
+ { bit: 8, name: "afterRemoveLiquidity" },
1557
+ { bit: 7, name: "beforeSwap" },
1558
+ { bit: 6, name: "afterSwap" },
1559
+ { bit: 5, name: "beforeDonate" },
1560
+ { bit: 4, name: "afterDonate" },
1561
+ { bit: 3, name: "beforeSwapReturnDelta" },
1562
+ { bit: 2, name: "afterSwapReturnDelta" },
1563
+ { bit: 1, name: "afterAddLiquidityReturnDelta" },
1564
+ { bit: 0, name: "afterRemoveLiquidityReturnDelta" }
1565
+ ];
1566
+ var CALLBACKS = [
1567
+ "beforeInitialize",
1568
+ "afterInitialize",
1569
+ "beforeAddLiquidity",
1570
+ "afterAddLiquidity",
1571
+ "beforeRemoveLiquidity",
1572
+ "afterRemoveLiquidity",
1573
+ "beforeSwap",
1574
+ "afterSwap",
1575
+ "beforeDonate",
1576
+ "afterDonate"
1577
+ ];
1578
+ var DELTA_NEEDS = [
1579
+ ["beforeSwapReturnDelta", "beforeSwap"],
1580
+ ["afterSwapReturnDelta", "afterSwap"],
1581
+ ["afterAddLiquidityReturnDelta", "afterAddLiquidity"],
1582
+ ["afterRemoveLiquidityReturnDelta", "afterRemoveLiquidity"]
1583
+ ];
1584
+ function decodeFlags(hook) {
1585
+ const low = Number(BigInt(hook) & 0x3fffn);
1586
+ return FLAGS.filter((f) => low >> f.bit & 1).map((f) => f.name);
1587
+ }
1588
+ var KEY = "(address currency0, address currency1, uint24 fee, int24 tickSpacing, address hooks)";
1589
+ var LIQ = "(int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt)";
1590
+ var SWAP = "(bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96)";
1591
+ var hooksAbi = parseAbi([
1592
+ `function beforeInitialize(address sender, ${KEY} key, uint160 sqrtPriceX96) returns (bytes4)`,
1593
+ `function afterInitialize(address sender, ${KEY} key, uint160 sqrtPriceX96, int24 tick) returns (bytes4)`,
1594
+ `function beforeAddLiquidity(address sender, ${KEY} key, ${LIQ} params, bytes hookData) returns (bytes4)`,
1595
+ `function afterAddLiquidity(address sender, ${KEY} key, ${LIQ} params, int256 delta, int256 feesAccrued, bytes hookData) returns (bytes4, int256)`,
1596
+ `function beforeRemoveLiquidity(address sender, ${KEY} key, ${LIQ} params, bytes hookData) returns (bytes4)`,
1597
+ `function afterRemoveLiquidity(address sender, ${KEY} key, ${LIQ} params, int256 delta, int256 feesAccrued, bytes hookData) returns (bytes4, int256)`,
1598
+ `function beforeSwap(address sender, ${KEY} key, ${SWAP} params, bytes hookData) returns (bytes4, int256, uint24)`,
1599
+ `function afterSwap(address sender, ${KEY} key, ${SWAP} params, int256 delta, bytes hookData) returns (bytes4, int128)`,
1600
+ `function beforeDonate(address sender, ${KEY} key, uint256 amount0, uint256 amount1, bytes hookData) returns (bytes4)`,
1601
+ `function afterDonate(address sender, ${KEY} key, uint256 amount0, uint256 amount1, bytes hookData) returns (bytes4)`
1602
+ ]);
1603
+ var SELECTORS = Object.fromEntries(
1604
+ CALLBACKS.map((name) => [name, toFunctionSelector(hooksAbi.find((f) => f.name === name))])
1605
+ );
1606
+ var viewAbi = parseAbi([
1607
+ "function poolManager() view returns (address)",
1608
+ "function owner() view returns (address)"
1609
+ ]);
1610
+ function scanBytecode(code) {
1611
+ const all = Buffer.from(code.slice(2), "hex");
1612
+ const metaLen = all.length >= 2 ? all.readUInt16BE(all.length - 2) : 0;
1613
+ const metaStart = all.length - 2 - metaLen;
1614
+ const bytes = metaLen > 0 && metaStart >= 0 && [161, 162, 163].includes(all[metaStart]) ? all.subarray(0, metaStart) : all;
1615
+ const pushed = /* @__PURE__ */ new Set();
1616
+ const ops = /* @__PURE__ */ new Set();
1617
+ for (let i = 0; i < bytes.length; i++) {
1618
+ const op = bytes[i];
1619
+ ops.add(op);
1620
+ if (op >= 96 && op <= 127) {
1621
+ const n = op - 95;
1622
+ if (n === 3 || n === 4) pushed.add(`0x${bytes.subarray(i + 1, i + 1 + n).toString("hex").padStart(8, "0")}`);
1623
+ i += n;
1624
+ }
1625
+ }
1626
+ return { pushed, ops, size: all.length };
1627
+ }
1628
+ var SLOT_IMPL = "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc";
1629
+ var SLOT_ADMIN = "0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103";
1630
+ var SLOT_BEACON = "0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582cfb8b5d50";
1631
+ var slotAddress = (v) => {
1632
+ if (!v || BigInt(v) === 0n) return null;
1633
+ return getAddress(`0x${v.slice(-40)}`);
1634
+ };
1635
+ function minimalProxyTarget(code) {
1636
+ const m = code.toLowerCase().match(/^0x363d3d373d3d3d363d73([0-9a-f]{40})5af43d82803e903d91602b57fd5bf3$/);
1637
+ return m ? getAddress(`0x${m[1]}`) : null;
1638
+ }
1639
+ var INITIALIZE_TOPIC = keccak2564(toHex4("Initialize(bytes32,address,address,uint24,int24,address,uint160,int24)"));
1640
+ function decodeInitialize(log) {
1641
+ const d = log.data.slice(2);
1642
+ const word = (i) => d.slice(i * 64, (i + 1) * 64);
1643
+ const int = (hex, bits) => {
1644
+ const v = BigInt(`0x${hex}`) & (1n << BigInt(bits)) - 1n;
1645
+ return Number(v >= 1n << BigInt(bits - 1) ? v - (1n << BigInt(bits)) : v);
1646
+ };
1647
+ return {
1648
+ id: log.topics[1],
1649
+ currency0: getAddress(`0x${log.topics[2].slice(-40)}`),
1650
+ currency1: getAddress(`0x${log.topics[3].slice(-40)}`),
1651
+ fee: Number(BigInt(`0x${word(0)}`)),
1652
+ tickSpacing: int(word(1), 24),
1653
+ hooks: getAddress(`0x${word(2).slice(-40)}`),
1654
+ block: String(log.blockNumber ?? 0n)
1655
+ };
1656
+ }
1657
+ async function findPools(client, poolManager, hook, opts) {
1658
+ const limit = opts.limit ?? 5;
1659
+ let chunk = opts.chunk ?? 2000000n;
1660
+ const floor = opts.maxBlocks ? opts.toBlock - opts.maxBlocks > opts.fromBlock ? opts.toBlock - opts.maxBlocks : opts.fromBlock : opts.fromBlock;
1661
+ const want = hook.toLowerCase();
1662
+ const pools = [];
1663
+ let hi = opts.toBlock;
1664
+ while (hi >= floor && pools.length < limit) {
1665
+ const lo = hi - chunk + 1n > floor ? hi - chunk + 1n : floor;
1666
+ let logs;
1667
+ try {
1668
+ logs = await client.request({
1669
+ method: "eth_getLogs",
1670
+ params: [{ address: poolManager, topics: [INITIALIZE_TOPIC], fromBlock: toHex4(lo), toBlock: toHex4(hi) }]
1671
+ });
1672
+ } catch (e) {
1673
+ if (chunk > 50000n) {
1674
+ chunk /= 4n;
1675
+ continue;
1676
+ }
1677
+ throw e;
1678
+ }
1679
+ const found = logs.filter((l) => `0x${l.data.slice(2 + 128 + 24, 2 + 192)}` === want).map((l) => decodeInitialize({ ...l, blockNumber: BigInt(l.blockNumber) })).reverse();
1680
+ pools.push(...found);
1681
+ hi = lo - 1n;
1682
+ }
1683
+ return { pools: pools.slice(0, limit), scannedFrom: hi + 1n, complete: hi < opts.fromBlock + 1n || hi + 1n <= opts.fromBlock };
1684
+ }
1685
+ var STRANGER = "0x00000000000000000000000000000000000ba5ed";
1686
+ function sampleArgs(cb, key) {
1687
+ const ts = Math.max(1, Math.abs(key.tickSpacing));
1688
+ const liq = (delta) => ({ tickLower: -ts * 10, tickUpper: ts * 10, liquidityDelta: delta, salt: `0x${"00".repeat(32)}` });
1689
+ const swap = { zeroForOne: true, amountSpecified: -1000000000000000n, sqrtPriceLimitX96: 4295128740n };
1690
+ const s = STRANGER;
1691
+ switch (cb) {
1692
+ case "beforeInitialize":
1693
+ return [s, key, 1n << 96n];
1694
+ case "afterInitialize":
1695
+ return [s, key, 1n << 96n, 0];
1696
+ case "beforeAddLiquidity":
1697
+ return [s, key, liq(10n ** 18n), "0x"];
1698
+ case "afterAddLiquidity":
1699
+ return [s, key, liq(10n ** 18n), 0n, 0n, "0x"];
1700
+ case "beforeRemoveLiquidity":
1701
+ return [s, key, liq(-(10n ** 18n)), "0x"];
1702
+ case "afterRemoveLiquidity":
1703
+ return [s, key, liq(-(10n ** 18n)), 0n, 0n, "0x"];
1704
+ case "beforeSwap":
1705
+ return [s, key, swap, "0x"];
1706
+ case "afterSwap":
1707
+ return [s, key, swap, 0n, "0x"];
1708
+ case "beforeDonate":
1709
+ case "afterDonate":
1710
+ return [s, key, 0n, 0n, "0x"];
1711
+ }
1712
+ }
1713
+ async function tryCall(client, from, to, data, blockNumber) {
1714
+ try {
1715
+ await client.call({ account: from, to, data, blockNumber });
1716
+ return "ok";
1717
+ } catch {
1718
+ return "revert";
1719
+ }
1720
+ }
1721
+ async function sourcifyMatch(chainId, address) {
1722
+ try {
1723
+ const r = await fetch(`https://sourcify.dev/server/v2/contract/${chainId}/${address}`, { signal: AbortSignal.timeout(1e4) });
1724
+ if (r.status === 404) return null;
1725
+ if (!r.ok) return "unreachable";
1726
+ const j = await r.json();
1727
+ return j.match ?? null;
1728
+ } catch {
1729
+ return "unreachable";
1730
+ }
1731
+ }
1732
+ var isEoaCode = (code) => !code || code === "0x" || code.toLowerCase().startsWith("0xef0100");
1733
+ async function checkHook(client, hookInput, opts) {
1734
+ if (!isAddress(hookInput)) throw new Error(`${hookInput} is not an address.`);
1735
+ const hook = getAddress(hookInput);
1736
+ const pm = POOL_MANAGERS[opts.chainId];
1737
+ if (!pm) throw new Error(`No Uniswap v4 PoolManager is known for chain ${opts.chainId}.`);
1738
+ const poolManager = getAddress(pm.address);
1739
+ const block = opts.block ?? await client.getBlockNumber();
1740
+ const checks = [];
1741
+ const at = { blockNumber: block };
1742
+ const code = await client.getCode({ address: hook, ...at }) ?? "0x";
1743
+ if (code === "0x") {
1744
+ checks.push({ id: "code", title: "Contract code at the address", status: "fail", detail: `No contract at ${hook} at block ${block}.` });
1745
+ return finish({ hook, chainId: opts.chainId, poolManager, block, flags: decodeFlags(hook), implementation: null, pools: [], checks });
1746
+ }
1747
+ const [implSlot, adminSlot, beaconSlot] = await Promise.all(
1748
+ [SLOT_IMPL, SLOT_ADMIN, SLOT_BEACON].map((slot) => client.getStorageAt({ address: hook, slot, ...at }))
1749
+ );
1750
+ const minimal = minimalProxyTarget(code);
1751
+ const impl = slotAddress(implSlot) ?? minimal;
1752
+ const admin = slotAddress(adminSlot);
1753
+ const beacon = slotAddress(beaconSlot);
1754
+ const runCode = impl ? await client.getCode({ address: impl, ...at }) ?? "0x" : code;
1755
+ const scan = scanBytecode(runCode);
1756
+ checks.push({
1757
+ id: "code",
1758
+ title: "Contract code at the address",
1759
+ status: "pass",
1760
+ detail: impl ? `Proxy to ${impl}, ${scan.size.toLocaleString("en-US")} bytes of logic.` : `${scan.size.toLocaleString("en-US")} bytes of runtime code.`
1761
+ });
1762
+ const flags = decodeFlags(hook);
1763
+ const enabled = CALLBACKS.filter((c2) => flags.includes(c2));
1764
+ const badDelta = DELTA_NEEDS.filter(([d, base]) => flags.includes(d) && !flags.includes(base)).map(([d, base]) => `${d} without ${base}`);
1765
+ checks.push(
1766
+ badDelta.length ? { id: "flags", title: "Permission flags are valid", status: "fail", detail: `The PoolManager rejects this address: ${badDelta.join(", ")}.` } : flags.length === 0 ? { id: "flags", title: "Permission flags are valid", status: "warn", detail: "No callback flags are set. Pools can only use this address with a dynamic fee." } : { id: "flags", title: "Permission flags are valid", status: "pass", detail: `${flags.length} flag${flags.length === 1 ? "" : "s"} set: ${flags.join(", ")}.` }
1767
+ );
1768
+ const missing = enabled.filter((c2) => !scan.pushed.has(SELECTORS[c2]));
1769
+ checks.push(
1770
+ missing.length ? {
1771
+ id: "callbacks",
1772
+ title: "Every enabled callback is implemented",
1773
+ status: "fail",
1774
+ detail: `Flag set but no ${missing.join(", ")} function in the code. Pool actions that call it would revert.`,
1775
+ evidence: { missing }
1776
+ } : {
1777
+ id: "callbacks",
1778
+ title: "Every enabled callback is implemented",
1779
+ status: "pass",
1780
+ detail: `${enabled.length} of ${enabled.length} enabled callbacks found in the code.`
1781
+ }
1782
+ );
1783
+ const boundTo = await client.readContract({ address: hook, abi: viewAbi, functionName: "poolManager", ...at }).catch(() => null);
1784
+ checks.push(
1785
+ boundTo === null ? { id: "pool-manager", title: "Bound to the canonical PoolManager", status: "warn", detail: "The hook has no poolManager() getter, so its binding cannot be read." } : getAddress(boundTo) === poolManager ? { id: "pool-manager", title: "Bound to the canonical PoolManager", status: "pass", detail: `poolManager() returns ${poolManager}.` } : { id: "pool-manager", title: "Bound to the canonical PoolManager", status: "fail", detail: `poolManager() returns ${getAddress(boundTo)}, not the canonical ${poolManager}.` }
1786
+ );
1787
+ let pools = opts.pools ?? [];
1788
+ if (!opts.pools) {
1789
+ pools = (await findPools(client, poolManager, hook, { toBlock: block, fromBlock: pm.deployBlock, limit: 5, maxBlocks: opts.poolScanBlocks ?? 6000000n }).catch(() => ({
1790
+ pools: []
1791
+ }))).pools;
1792
+ }
1793
+ const key = pools[0] ?? {
1794
+ currency0: "0x0000000000000000000000000000000000000000",
1795
+ currency1: "0x0000000000000000000000000000000000000001",
1796
+ fee: 3e3,
1797
+ tickSpacing: 60,
1798
+ hooks: hook
1799
+ };
1800
+ if (enabled.length === 0) {
1801
+ checks.push({ id: "caller", title: "Callbacks refuse other callers", status: "info", detail: "No callbacks are enabled." });
1802
+ } else {
1803
+ const rows = await Promise.all(
1804
+ enabled.map(async (cb) => {
1805
+ const data = encodeFunctionData({ abi: hooksAbi, functionName: cb, args: sampleArgs(cb, key) });
1806
+ const [stranger, manager] = await Promise.all([tryCall(client, STRANGER, hook, data, block), tryCall(client, poolManager, hook, data, block)]);
1807
+ return { callback: cb, stranger, manager };
1808
+ })
1809
+ );
1810
+ const open2 = rows.filter((r) => r.stranger === "ok");
1811
+ const confirmed = rows.filter((r) => r.stranger === "revert" && r.manager === "ok").length;
1812
+ checks.push(
1813
+ open2.length ? {
1814
+ id: "caller",
1815
+ title: "Callbacks refuse other callers",
1816
+ status: "fail",
1817
+ detail: `${open2.map((r) => r.callback).join(", ")} ${open2.length === 1 ? "runs" : "run"} when called by an address that is not the PoolManager.`,
1818
+ evidence: { calls: rows, poolKey: key }
1819
+ } : {
1820
+ id: "caller",
1821
+ title: "Callbacks refuse other callers",
1822
+ status: "pass",
1823
+ detail: `All ${rows.length} enabled callbacks revert for an outside caller${confirmed ? `; ${confirmed} ran normally when the PoolManager called with the same arguments` : ""}.`,
1824
+ evidence: { calls: rows, poolKey: key }
1825
+ }
1826
+ );
1827
+ }
1828
+ if (impl || beacon) {
1829
+ const who = admin ?? (beacon ? `beacon ${beacon}` : null);
1830
+ checks.push({
1831
+ id: "upgrade",
1832
+ title: "Code cannot be replaced",
1833
+ status: "warn",
1834
+ detail: `Upgradeable proxy${minimal ? " (minimal clone, fixed target)" : ""}. ${who ? `Controlled by ${who}.` : "Upgrade control is in the logic contract."} The hook's behaviour can change after this check.`,
1835
+ evidence: { implementation: impl, admin, beacon }
1836
+ });
1837
+ } else {
1838
+ checks.push({ id: "upgrade", title: "Code cannot be replaced", status: "pass", detail: "Not a proxy. The code at this address cannot change." });
1839
+ }
1840
+ const owner = await client.readContract({ address: hook, abi: viewAbi, functionName: "owner", ...at }).catch(() => null);
1841
+ if (owner === null) {
1842
+ checks.push({ id: "owner", title: "No single key controls the hook", status: "pass", detail: "No owner() function." });
1843
+ } else if (BigInt(owner) === 0n) {
1844
+ checks.push({ id: "owner", title: "No single key controls the hook", status: "pass", detail: "Ownership has been renounced." });
1845
+ } else {
1846
+ const ownerCode = await client.getCode({ address: owner, ...at });
1847
+ checks.push(
1848
+ isEoaCode(ownerCode) ? { id: "owner", title: "No single key controls the hook", status: "warn", detail: `Owned by ${owner}, a single key. Whatever owner-only functions the hook has, one signer can call them.` } : { id: "owner", title: "No single key controls the hook", status: "info", detail: `Owned by the contract ${owner}, often a multisig or timelock. Check who controls it.` }
1849
+ );
1850
+ }
1851
+ const risky = [scan.ops.has(255) ? "SELFDESTRUCT" : null, scan.ops.has(244) ? "DELEGATECALL" : null].filter(Boolean);
1852
+ checks.push(
1853
+ risky.length ? {
1854
+ id: "opcodes",
1855
+ title: "No self-destruct or delegatecall",
1856
+ status: "warn",
1857
+ detail: `The code contains ${risky.join(" and ")}. ${risky.includes("DELEGATECALL") ? "It can run code from another contract in its own storage." : ""}`.trim()
1858
+ } : { id: "opcodes", title: "No self-destruct or delegatecall", status: "pass", detail: "Neither opcode appears in the code." }
1859
+ );
1860
+ if (!opts.skipSource) {
1861
+ const m = await sourcifyMatch(opts.chainId, impl ?? hook);
1862
+ checks.push(
1863
+ m === "unreachable" ? { id: "source", title: "Source code is verified", status: "info", detail: "Sourcify could not be reached." } : m ? { id: "source", title: "Source code is verified", status: "pass", detail: `Sourcify ${m === "exact_match" ? "exact match" : "match"}${impl ? " for the implementation" : ""}.` } : { id: "source", title: "Source code is verified", status: "warn", detail: "No Sourcify match. Nobody can read what this code does without decompiling it." }
1864
+ );
1865
+ }
1866
+ return finish({ hook, chainId: opts.chainId, poolManager, block, flags, implementation: impl, pools, checks });
1867
+ }
1868
+ function finish(r) {
1869
+ const scored = r.checks.filter((c2) => c2.status !== "info");
1870
+ return {
1871
+ ...r,
1872
+ version: CHECK_VERSION,
1873
+ block: r.block.toString(),
1874
+ checkedAt: Date.now(),
1875
+ summary: {
1876
+ passed: scored.filter((c2) => c2.status === "pass").length,
1877
+ total: scored.length,
1878
+ warnings: scored.filter((c2) => c2.status === "warn").length,
1879
+ failed: scored.filter((c2) => c2.status === "fail").length
1880
+ }
1881
+ };
1882
+ }
1883
+
1884
+ // src/cli/check.ts
1885
+ var SITE = process.env.PROBE_SITE_URL ?? "https://probecli.com";
1886
+ var GLYPH = {
1887
+ pass: () => dim("\u2713"),
1888
+ warn: () => "!",
1889
+ fail: () => hot("\xD7"),
1890
+ info: () => dim("\xB7")
1891
+ };
1892
+ function printReport(r) {
1893
+ console.log("");
1894
+ for (const c2 of r.checks) {
1895
+ console.log(`${GLYPH[c2.status]("")} ${c2.status === "fail" ? hot(c2.title) : c2.title}`);
1896
+ console.log(` ${dim(c2.detail)}`);
1897
+ }
1898
+ console.log("");
1899
+ const s = r.summary;
1900
+ const line = `${s.passed} of ${s.total} checks passed${s.failed ? `, ${s.failed} failed` : ""}${s.warnings ? `, ${s.warnings} warning${s.warnings === 1 ? "" : "s"}` : ""}`;
1901
+ console.log(`${s.failed ? hot("\xD7") : dim("\u2713")} ${bold(line)} ${dim(`at block ${Number(r.block).toLocaleString("en-US")}`)}`);
1902
+ if (r.checks.length === 1) return;
1903
+ if (r.pools.length) console.log(dim(` Live calls used pool ${r.pools[0].id.slice(0, 10)}\u2026, one of the pools that use this hook.`));
1904
+ else console.log(dim(" No pool using this hook was found in the recent blocks scanned; live calls used a sample pool key."));
1905
+ console.log(dim(" A passing check is evidence about one property at one block, not an audit."));
1906
+ }
1907
+ async function check(args) {
1908
+ const { values, positionals } = parseArgs({
1909
+ args,
1910
+ allowPositionals: true,
1911
+ options: {
1912
+ rpc: { type: "string" },
1913
+ block: { type: "string" },
1914
+ json: { type: "boolean", default: false },
1915
+ publish: { type: "boolean", default: false }
1916
+ }
1917
+ });
1918
+ const hook = positionals[0];
1919
+ if (!hook || !isAddress2(hook)) fail("Usage: probe check <hook address> [--rpc <url>] [--block <n>] [--json] [--publish]");
1920
+ const rpc = values.rpc ?? process.env.PROBE_RPC_URL ?? DEFAULT_RPC;
1921
+ const probeClient = publicClient(rpc, 1);
1922
+ const chainId = await probeClient.getChainId().catch(() => fail(`Cannot reach the RPC at ${rpc}. Pass another with --rpc <url>.`));
1923
+ const client = publicClient(rpc, chainId);
1924
+ const block = values.block ? BigInt(values.block) : await client.getBlockNumber();
1925
+ if (values.json && !values.publish) {
1926
+ const report2 = await checkHook(client, hook, { chainId, block });
1927
+ printJson(report2);
1928
+ if (report2.summary.failed) process.exitCode = 1;
1929
+ return;
1930
+ }
1931
+ console.log(`${bold("probe check")} ${getAddress2(hook)} ${dim(`chain ${chainId}, block ${block.toLocaleString("en-US")}`)}`);
1932
+ const report = await task("Running the standard hook checks", () => checkHook(client, hook, { chainId, block }), (r) => `${r.checks.length} checks`);
1933
+ printReport(report);
1934
+ if (values.publish) {
1935
+ const published = await task(
1936
+ "Asking the verifier to reproduce and sign the result",
1937
+ () => api("/checks", { method: "POST", body: { hook, block: block.toString() } }),
1938
+ (p) => `signed by ${p.signer.slice(0, 6)}\u2026${p.signer.slice(-4)}`
1939
+ );
1940
+ const same = sameOutcome(published.report, report);
1941
+ console.log(same ? dim(" The verifier's run matched yours check for check.") : hot(" The verifier's result differs from your run. Its signed copy is the one published."));
1942
+ console.log(` ${SITE}/hooks/${getAddress2(hook)}`);
1943
+ if (values.json) printJson(published);
1944
+ } else {
1945
+ console.log(dim(` Publish this with a verifier signature: probe check ${getAddress2(hook)} --publish`));
1946
+ }
1947
+ if (report.summary.failed) process.exitCode = 1;
1948
+ }
1949
+
1950
+ // src/cli/version.ts
1951
+ var VERSION = true ? "0.4.0" : JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
1952
+
1953
+ // src/cli/main.ts
1954
+ var HELP = `${bold("probe")}: test Uniswap v4 hooks, get paid for verified work.
1955
+
1956
+ Operator
1957
+ probe init [--verifier <url>] Create an operator key and save settings
1958
+ probe whoami Show your operator address and verifier
1959
+ probe doctor Check Node, Foundry, the verifier, the chain and your key
1960
+ probe jobs [--json] List jobs on the verifier
1961
+ probe job <job> [--json] Show a job's scope, rules, budget and results
1962
+ probe work <job> [options] Run a job and submit what passes
1963
+ --agent / --no-agent Use the AI agent (default: when credentials exist)
1964
+ --cases <n> Number of cases to ask the agent for (default 3)
1965
+ --dry-run Run locally, submit nothing
1966
+ --case <file> Run your own case file instead (repeat for more)
1967
+ --submit-all Also submit cases that break a rule (the verifier will reject them)
1968
+ probe case new <job> <Name> Write a new case for a job, with the fixture's helpers listed
1969
+ probe case check <job> <file...> Check cases against the job's rules and run them locally
1970
+ probe status <submission-id> Show a submission's verdict
1971
+ probe submissions [job] [--all] Your submissions and verdicts, newest first (--all: everyone's)
1972
+ probe balance <job> Show what you are owed on a job's reward token
1973
+ probe withdraw <job> Withdraw what you are owed
1974
+
1975
+ Hooks
1976
+ probe check <hook> [options] Run the standard safety checks on a deployed hook
1977
+ --block <n> Check at this block (default: latest)
1978
+ --rpc <url> Chain RPC (default: Robinhood Chain mainnet)
1979
+ --publish Have the verifier reproduce, sign and publish the result
1980
+ --json Print the report as JSON
1981
+
1982
+ Sponsor
1983
+ probe sponsor keygen Create your report-decryption key pair
1984
+ probe sponsor create --spec <file> --token <addr> --reward <amount> --budget <amount> [--days 14]
1985
+ [--eligibility-token <addr> --min-holding <amount>]
1986
+ probe sponsor reports <job> Download and decrypt private failure reports
1987
+
1988
+ Other
1989
+ probe --version Print the CLI version
1990
+
1991
+ Environment: PROBE_VERIFIER_URL, PROBE_RPC_URL, PROBE_OPERATOR_KEY, PROBE_SPONSOR_KEY, ANTHROPIC_API_KEY, PROBE_HOME
1992
+ `;
1993
+ var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
1994
+ async function init(args) {
1995
+ const { values } = parseArgs2({ args, options: { verifier: { type: "string" }, force: { type: "boolean" } } });
1996
+ const cfg = loadConfig();
1997
+ if (values.verifier) saveConfig({ verifierUrl: values.verifier.replace(/\/$/, "") });
1998
+ if (cfg.operatorKey && !values.force) {
1999
+ console.log(`${prompt()} Operator ${privateKeyToAccount5(cfg.operatorKey).address} already set up (${configPath}).`);
2000
+ } else {
2001
+ const { key, address } = newOperatorKey();
2002
+ saveConfig({ operatorKey: key });
2003
+ console.log(`${prompt()} Created operator ${bold(address)}`);
2004
+ note(` Key saved to ${configPath} (readable only by you). Back it up: rewards are paid to this address.`);
2005
+ }
2006
+ console.log(` ${dim("verifier")} ${loadConfig().verifierUrl}`);
2007
+ }
2008
+ async function whoami() {
2009
+ const cfg = loadConfig();
2010
+ console.log(`${dim("operator")} ${cfg.operatorKey ? privateKeyToAccount5(cfg.operatorKey).address : "not set (probe init)"}`);
2011
+ console.log(`${dim("sponsor ")} ${cfg.sponsorKey ? privateKeyToAccount5(cfg.sponsorKey).address : "not set"}`);
2012
+ console.log(`${dim("verifier")} ${cfg.verifierUrl}`);
2013
+ console.log(`${dim("agent ")} ${agentAvailable() ? `${AGENT_MODEL} (credentials found)` : "no credentials; seed cases only"}`);
2014
+ }
2015
+ async function jobs(args) {
2016
+ const { values } = parseArgs2({ args, options: { json: { type: "boolean" } } });
2017
+ const list = await api("/jobs");
2018
+ if (values.json) return printJson(list);
2019
+ if (!list.length) return note("No jobs registered on this verifier yet.");
2020
+ for (const j of list) {
2021
+ const d = j.chain.rewardDecimals;
2022
+ console.log(
2023
+ `${j.state.status === "open" ? hot("\u25CF") : dim("\u25CB")} ${bold(j.slug)} ${j.title}
2024
+ ${dim(
2025
+ `${formatUnitsShort(BigInt(j.state.rewardPerAccepted), d)} ${j.chain.rewardSymbol} per accepted case, ${formatUnitsShort(BigInt(j.state.budget), d)} ${j.chain.rewardSymbol} left, ${j.state.accepted} accepted, ${j.state.status}`
2026
+ )}`
2027
+ );
2028
+ }
2029
+ }
2030
+ async function work(args) {
2031
+ const { values, positionals } = parseArgs2({
2032
+ args,
2033
+ allowPositionals: true,
2034
+ options: {
2035
+ agent: { type: "boolean" },
2036
+ "no-agent": { type: "boolean" },
2037
+ cases: { type: "string", default: "3" },
2038
+ "dry-run": { type: "boolean" },
2039
+ "submit-all": { type: "boolean" },
2040
+ case: { type: "string", multiple: true }
2041
+ }
2042
+ });
2043
+ const slug = positionals[0];
2044
+ if (!slug) fail("Usage: probe work <job>");
2045
+ const own = values.case ?? [];
2046
+ for (const f of own) if (!existsSync4(f)) fail(`No case file at ${f}.`);
2047
+ const account = values["dry-run"] ? null : operator();
2048
+ console.log(`${prompt()} probe work ${slug}`);
2049
+ const job2 = await api(`/jobs/${slug}`);
2050
+ const d = job2.chain.rewardDecimals;
2051
+ const sym = job2.chain.rewardSymbol;
2052
+ field("job", job2.title);
2053
+ field("chain", `${job2.network.name} (chain ${job2.chain.chainId}), job #${job2.chain.jobId}, snapshot #${job2.snapshot.block.toLocaleString("en-US")}`);
2054
+ field("hook", `${job2.hook.name} (${job2.hook.callbacks.join(", ")})`);
2055
+ field("reward", `${formatUnitsShort(BigInt(job2.state.rewardPerAccepted), d)} ${sym} per accepted case, ${formatUnitsShort(BigInt(job2.state.budget), d)} ${sym} left`);
2056
+ if (account) field("operator", account.address);
2057
+ if (job2.state.status !== "open") fail("This job is closed.");
2058
+ console.log("");
2059
+ const ws = await prepare(job2);
2060
+ const useAgent = own.length ? false : values["no-agent"] ? false : values.agent ? true : agentAvailable();
2061
+ let cases;
2062
+ let ctx = null;
2063
+ if (useAgent) {
2064
+ const history = await api(`/jobs/${slug}/submissions`).catch(() => []);
2065
+ ctx = {
2066
+ spec: job2,
2067
+ fixtureSource: readFileSync5(join4(ws, "test", job2.fixture.import.replace(/^\.\.\//, "")), "utf8"),
2068
+ targetSources: job2.targets.map((p) => ({ path: p, source: readFileSync5(join4(ws, p), "utf8") })),
2069
+ exampleCase: seedCases(ws, job2)[0]?.source,
2070
+ history: history.map((h) => ({ title: h.title, verdict: h.verdict, reason: h.reason }))
2071
+ };
2072
+ const n = Math.max(1, Math.min(8, Number(values.cases) || 3));
2073
+ cases = await task(`Agent proposing cases for ${job2.hook.callbacks.at(-1)} ${dim(`(${AGENT_MODEL})`)}`, () => proposeCases(ctx, n), (v) => `${v.length} cases`);
2074
+ } else if (own.length) {
2075
+ cases = loadCaseFiles(own);
2076
+ note(` Running ${cases.length} case${cases.length === 1 ? "" : "s"} from your files.`);
2077
+ } else {
2078
+ cases = seedCases(ws, job2);
2079
+ note(` No AI agent configured (set ANTHROPIC_API_KEY or run ant auth login). Using ${cases.length} seed cases from the job.`);
2080
+ note(` Seed cases may already be paid. Write your own with: probe case new ${slug} <Name>`);
2081
+ }
2082
+ if (!cases.length) fail("No cases to run.");
2083
+ const toSubmit = [];
2084
+ for (let i = 0; i < cases.length; i++) {
2085
+ let c2 = cases[i];
2086
+ let rules = checkCase(c2.source, job2);
2087
+ let local = rules.ok ? await runLocal(ws, c2) : null;
2088
+ if (ctx && (!rules.ok || !local?.passed)) {
2089
+ const error = !rules.ok ? `Rule violation: ${rules.reason}` : local.compileError ?? local.tests.filter((t) => !t.passed).map((t) => `${t.name}: ${t.reason}`).join("\n");
2090
+ const fixed = await repairCase(ctx, c2, error).catch(() => null);
2091
+ if (fixed) {
2092
+ c2 = fixed;
2093
+ rules = checkCase(c2.source, job2);
2094
+ local = rules.ok ? await runLocal(ws, c2) : null;
2095
+ }
2096
+ }
2097
+ const label = `${dim(`case ${i + 1}/${cases.length}`)} ${c2.title}`;
2098
+ if (local?.passed && rules.ok) {
2099
+ console.log(`${dim("\xB7")} ${label} ${dim("passed locally")}`);
2100
+ toSubmit.push(c2);
2101
+ } else if (!rules.ok) {
2102
+ const ran = await runLocal(ws, c2).catch(() => null);
2103
+ console.log(`${dim("\xB7")} ${label} ${dim(`${ran?.passed ? "passed locally, " : ""}breaks a rule: ${rules.reason}`)}`);
2104
+ if (values["submit-all"] && ran?.passed) toSubmit.push(c2);
2105
+ } else {
2106
+ console.log(`${dim("\xB7")} ${label} ${dim(`failed locally: ${localFailure(local)}`)}`);
2107
+ }
2108
+ }
2109
+ if (values["dry-run"]) return note("\nDry run: nothing submitted.");
2110
+ if (!toSubmit.length) return note("\nNothing to submit.");
2111
+ console.log("");
2112
+ const submissions2 = await task(`Submitting ${toSubmit.length} case${toSubmit.length === 1 ? "" : "s"} to the verifier`, async () => {
2113
+ const out = [];
2114
+ for (const c2 of toSubmit) {
2115
+ const nonce = Date.now() + out.length;
2116
+ const signature = await account.signMessage({ message: submissionMessage({ slug, sourceHash: sourceHash(c2.source), nonce }) });
2117
+ const sub = await api("/submissions", { method: "POST", body: { slug, source: c2.source, operator: account.address, nonce, signature } });
2118
+ out.push({ c: c2, sub });
2119
+ }
2120
+ return out;
2121
+ }, () => "sent");
2122
+ const final = await task(`Verifier replaying ${submissions2.length} case${submissions2.length === 1 ? "" : "s"} on ${job2.snapshot.id}`, async () => {
2123
+ const deadline = Date.now() + 15 * 6e4;
2124
+ while (Date.now() < deadline) {
2125
+ const latest = await Promise.all(submissions2.map((s) => api(`/submissions/${s.sub.id}`)));
2126
+ if (latest.every((s) => s.status === "done")) return latest;
2127
+ await sleep(1500);
2128
+ }
2129
+ throw new Error("still running after 15 minutes; check later with probe status");
2130
+ }, () => "done");
2131
+ final.forEach((s, i) => verdictLine(i + 1, s.verdict ?? "failed", s.reason ?? ""));
2132
+ const accepted = final.filter((s) => s.verdict === "accepted");
2133
+ console.log("");
2134
+ if (accepted.length) {
2135
+ const owed = await clientFor(job2).readContract({ address: job2.chain.contract, abi: probeJobsAbi, functionName: "owed", args: [job2.chain.rewardToken, account.address] });
2136
+ payout(`Payout step reached: ${accepted.map((a) => a.reward).join(" + ")} credited on-chain. You are owed ${formatUnitsShort(owed, d)} ${sym}.`);
2137
+ note(` Claim it with: probe withdraw ${slug}`);
2138
+ for (const a of accepted) if (a.txHash) note(` tx ${a.txHash}`);
2139
+ } else {
2140
+ note("No case was accepted this run. Read the verdicts above, then try a different path.");
2141
+ }
2142
+ }
2143
+ async function job(args) {
2144
+ const { values, positionals } = parseArgs2({ args, allowPositionals: true, options: { json: { type: "boolean" } } });
2145
+ const slug = positionals[0];
2146
+ if (!slug) fail("Usage: probe job <job> [--json]");
2147
+ const [j, subs] = await Promise.all([
2148
+ api(`/jobs/${slug}`),
2149
+ api(`/jobs/${slug}/submissions`).catch(() => [])
2150
+ ]);
2151
+ if (values.json) return printJson({ ...j, submissions: subs });
2152
+ const d = j.chain.rewardDecimals;
2153
+ const sym = j.chain.rewardSymbol;
2154
+ const amount = (v) => `${formatUnitsShort(BigInt(v), d)} ${sym}`;
2155
+ const explorer = j.chain.explorerUrl?.replace(/\/$/, "");
2156
+ console.log(`${j.state.status === "open" ? hot("\u25CF") : dim("\u25CB")} ${bold(j.title)} ${dim(`(${j.state.status})`)}`);
2157
+ console.log(` ${j.summary}
2158
+ `);
2159
+ field("chain", `${j.network.name} (chain ${j.chain.chainId}), job #${j.chain.jobId}`);
2160
+ field("contract", explorer ? `${j.chain.contract} ${dim(`${explorer}/address/${j.chain.contract}`)}` : j.chain.contract);
2161
+ field("hook", `${j.hook.name} (${j.hook.callbacks.join(", ")})`);
2162
+ field("snapshot", `${j.snapshot.id}, block ${j.snapshot.block.toLocaleString("en-US")}`);
2163
+ field("pays for", j.rewardModel.replace(/-/g, " "));
2164
+ field("reward", `${amount(j.state.rewardPerAccepted)} per accepted case`);
2165
+ field("budget", `${amount(j.state.budget)} left of ${amount(j.state.funded)} funded, ${j.state.accepted} accepted`);
2166
+ field("deadline", deadlineText(j.state.deadline));
2167
+ if (BigInt(j.state.minHolding) > 0n) field("eligible", `hold at least ${j.state.minHolding} of ${j.state.eligibilityToken}`);
2168
+ field("sponsor", `${j.sponsor} ${dim(j.state.sponsor)}`);
2169
+ console.log(`
2170
+ ${bold("Objective")}
2171
+ ${j.objective}`);
2172
+ console.log(`
2173
+ ${bold("In scope")}`);
2174
+ for (const x of j.inScope) console.log(` ${dim("\xB7")} ${x}`);
2175
+ console.log(`
2176
+ ${bold("Out of scope")}`);
2177
+ for (const x of j.outOfScope) console.log(` ${dim("\xB7")} ${x}`);
2178
+ console.log(`
2179
+ ${bold("Acceptance rules")}`);
2180
+ j.acceptanceRules.forEach((r, i) => console.log(` ${dim(`${i + 1}.`)} ${r}`));
2181
+ console.log(`
2182
+ ${bold("Results")}`);
2183
+ const counts = resultCounts(subs);
2184
+ if (!counts.length) console.log(` ${dim("No submissions yet.")}`);
2185
+ else console.log(` ${counts.map((c2) => `${c2.count} ${c2.verdict}`).join(", ")}`);
2186
+ for (const s of subs.filter((s2) => s2.verdict === "accepted")) {
2187
+ console.log(` ${hot("\u2713")} ${s.title} ${dim(`${s.reward ?? ""}${s.txHash && explorer ? ` ${explorer}/tx/${s.txHash}` : ""}`)}`);
2188
+ }
2189
+ if (j.state.status === "open") note(`
2190
+ Run it: probe work ${slug} Write your own case: probe case new ${slug} <Name>`);
2191
+ }
2192
+ async function prepare(job2) {
2193
+ if (!await forgeInstalled()) {
2194
+ fail("Foundry is not installed. Install it with: curl -L https://foundry.paradigm.xyz | bash && foundryup, then run this again.");
2195
+ }
2196
+ const ws = await task(`Preparing workspace ${dim(job2.snapshot.id)}`, () => localWorkspace(job2), () => "ok");
2197
+ await task("Compiling the snapshot", async () => {
2198
+ const b = await buildWorkspace(ws);
2199
+ if (!b.ok) throw new Error(`the job workspace does not compile: ${b.error}`);
2200
+ }, () => "ok");
2201
+ return ws;
2202
+ }
2203
+ function localFailure(local) {
2204
+ if (!local) return "did not run";
2205
+ if (local.timedOut) return "timed out";
2206
+ if (local.compileError) return `does not compile: ${local.compileError.split("\n").find((l) => /error/i.test(l))?.trim() ?? "see forge output"}`;
2207
+ const failed = local.tests.filter((t) => !t.passed);
2208
+ return failed.map((t) => `${t.name}${t.reason ? ` (${t.reason})` : ""}`).join(", ") || "no tests ran";
2209
+ }
2210
+ async function caseNew(args) {
2211
+ const { values, positionals } = parseArgs2({ args, allowPositionals: true, options: { out: { type: "string", default: "." } } });
2212
+ const [slug, raw] = positionals;
2213
+ if (!slug || !raw) fail("Usage: probe case new <job> <Name> [--out <dir>]");
2214
+ const name = caseName(raw);
2215
+ const file = resolve3(values.out, `${name}.t.sol`);
2216
+ if (existsSync4(file)) fail(`${file} already exists.`);
2217
+ const job2 = await api(`/jobs/${slug}`);
2218
+ const ws = await task(`Preparing workspace ${dim(job2.snapshot.id)}`, () => localWorkspace(job2), () => "ok");
2219
+ const fixture = resolve3(ws, "test/cases", job2.fixture.import);
2220
+ const helpers = existsSync4(fixture) ? fixtureHelpers(readFileSync5(fixture, "utf8")) : [];
2221
+ mkdirSync4(values.out, { recursive: true });
2222
+ writeFileSync4(file, caseTemplate(job2, name, helpers));
2223
+ console.log(`${prompt()} Wrote ${bold(file)}`);
2224
+ note(` It inherits ${job2.fixture.base}, the job snapshot. Fixture source: ${fixture}`);
2225
+ note(` Replace the TODOs, then:`);
2226
+ note(` probe case check ${slug} ${file}`);
2227
+ note(` probe work ${slug} --case ${file}`);
2228
+ }
2229
+ async function caseCheck(args) {
2230
+ const [slug, ...files] = args;
2231
+ if (!slug || !files.length) fail("Usage: probe case check <job> <file...>");
2232
+ for (const f of files) if (!existsSync4(f)) fail(`No case file at ${f}.`);
2233
+ const job2 = await api(`/jobs/${slug}`);
2234
+ const ws = await prepare(job2);
2235
+ let ok = 0;
2236
+ for (const c2 of loadCaseFiles(files)) {
2237
+ const rules = checkCase(c2.source, job2);
2238
+ if (!rules.ok) {
2239
+ console.log(`${hot("\xD7")} ${c2.title} ${dim(`breaks a rule: ${rules.reason}`)}`);
2240
+ continue;
2241
+ }
2242
+ const local = await runLocal(ws, c2);
2243
+ if (local.passed) {
2244
+ ok++;
2245
+ console.log(`${dim("\u2713")} ${c2.title} ${dim(`follows the rules and passes locally (${rules.testCount} test${rules.testCount === 1 ? "" : "s"})`)}`);
2246
+ } else {
2247
+ console.log(`${hot("\xD7")} ${c2.title} ${dim(`follows the rules, fails locally: ${localFailure(local)}`)}`);
2248
+ }
2249
+ }
2250
+ console.log("");
2251
+ if (ok === files.length) note(`Ready to submit: probe work ${slug} ${files.map((f) => `--case ${f}`).join(" ")}`);
2252
+ else process.exitCode = 1;
2253
+ }
2254
+ async function submissions(args) {
2255
+ const { values, positionals } = parseArgs2({ args, allowPositionals: true, options: { all: { type: "boolean" }, json: { type: "boolean" } } });
2256
+ const key = loadConfig().operatorKey;
2257
+ if (!values.all && !key) fail("No operator key, so no submissions of yours. Run probe init, or pass --all to see everyone's.");
2258
+ const me = key && !values.all ? privateKeyToAccount5(key).address.toLowerCase() : null;
2259
+ const slugs = positionals[0] ? [positionals[0]] : (await api("/jobs")).map((j) => j.slug);
2260
+ const all = (await Promise.all(slugs.map((s) => api(`/jobs/${s}/submissions`)))).flat();
2261
+ const list = all.filter((s) => !me || s.operator.toLowerCase() === me).sort((a, b) => b.createdAt - a.createdAt);
2262
+ if (values.json) return printJson(list);
2263
+ if (!list.length) return note(me ? `No submissions from ${me} yet.` : "No submissions yet.");
2264
+ const glyph = { accepted: hot("\u2713"), duplicate: "=", failed: "\xD7", ineligible: "\xD7" };
2265
+ for (const s of list) {
2266
+ const verdict = s.status === "done" ? s.verdict ?? "failed" : s.status;
2267
+ console.log(`${glyph[verdict] ?? dim("\u2026")} ${s.title} ${dim(`${verdict}, ${ago(s.createdAt)}`)}`);
2268
+ const meta = [s.slug, me ? null : s.operator, s.fingerprint ? `fingerprint ${shortFp(s.fingerprint)}` : null, s.reward, s.id].filter(Boolean).join(" ");
2269
+ console.log(` ${dim(meta)}`);
2270
+ if (s.reason && s.verdict !== "accepted") console.log(` ${dim(s.reason)}`);
2271
+ }
2272
+ const counts = resultCounts(list);
2273
+ note(`
2274
+ ${list.length} submission${list.length === 1 ? "" : "s"}: ${counts.map((c2) => `${c2.count} ${c2.verdict}`).join(", ")}`);
2275
+ }
2276
+ async function status(args) {
2277
+ const id = args[0];
2278
+ if (!id) fail("Usage: probe status <submission-id>");
2279
+ const s = await api(`/submissions/${id}`);
2280
+ console.log(`${bold(s.title)} ${dim(`(${s.slug})`)}`);
2281
+ if (s.status !== "done") return note(` ${s.status}`);
2282
+ verdictLine(1, s.verdict ?? "failed", s.reason ?? "");
2283
+ if (s.fingerprint) note(` fingerprint ${shortFp(s.fingerprint)}`);
2284
+ if (s.txHash) note(` tx ${s.txHash}`);
2285
+ }
2286
+ async function balance(args) {
2287
+ const slug = args[0];
2288
+ if (!slug) fail("Usage: probe balance <job>");
2289
+ const job2 = await api(`/jobs/${slug}`);
2290
+ const account = operator();
2291
+ const owed = await clientFor(job2).readContract({ address: job2.chain.contract, abi: probeJobsAbi, functionName: "owed", args: [job2.chain.rewardToken, account.address] });
2292
+ console.log(`${formatUnitsShort(owed, job2.chain.rewardDecimals)} ${job2.chain.rewardSymbol} owed to ${account.address}`);
2293
+ }
2294
+ async function withdraw(args) {
2295
+ const slug = args[0];
2296
+ if (!slug) fail("Usage: probe withdraw <job>");
2297
+ const job2 = await api(`/jobs/${slug}`);
2298
+ const cfg = loadConfig();
2299
+ const account = operator();
2300
+ const client = clientFor(job2);
2301
+ const owed = await client.readContract({ address: job2.chain.contract, abi: probeJobsAbi, functionName: "owed", args: [job2.chain.rewardToken, account.address] });
2302
+ if (owed === 0n) return note("Nothing to withdraw.");
2303
+ const wallet = walletClient(job2.chain.rpcUrl, job2.chain.chainId, cfg.operatorKey);
2304
+ await task(`Withdrawing ${formatUnitsShort(owed, job2.chain.rewardDecimals)} ${job2.chain.rewardSymbol}`, async () => {
2305
+ try {
2306
+ const hash = await wallet.writeContract({ address: job2.chain.contract, abi: probeJobsAbi, functionName: "withdraw", args: [job2.chain.rewardToken] });
2307
+ const r = await client.waitForTransactionReceipt({ hash });
2308
+ if (r.status !== "success") throw new Error("transaction reverted");
2309
+ return hash;
2310
+ } catch (e) {
2311
+ const name = revertName(e);
2312
+ if (/insufficient funds/i.test(String(e))) throw new Error(`${account.address} needs a little native currency for gas`);
2313
+ throw new Error(name ?? e.message.split("\n")[0]);
2314
+ }
2315
+ }, (h) => `tx ${h}`);
2316
+ }
2317
+ function sponsorAccount() {
2318
+ const key = loadConfig().sponsorKey;
2319
+ if (!key) fail("No sponsor key. Set PROBE_SPONSOR_KEY to the funding wallet's private key.");
2320
+ return { key, account: privateKeyToAccount5(key) };
2321
+ }
2322
+ async function sponsorKeygen() {
2323
+ const cfg = loadConfig();
2324
+ if (cfg.sponsorReportKey) {
2325
+ console.log(`${prompt()} Report key already exists: ${cfg.sponsorReportKey.publicKey}`);
2326
+ return;
2327
+ }
2328
+ const kp = generateReportKeyPair();
2329
+ saveConfig({ sponsorReportKey: kp });
2330
+ console.log(`${prompt()} Report public key: ${bold(kp.publicKey)}`);
2331
+ note(` Put it in your job spec as "reportKey". The secret key is in ${configPath}. Only it can open your reports.`);
2332
+ }
2333
+ async function sponsorCreate(args) {
2334
+ const { values } = parseArgs2({
2335
+ args,
2336
+ options: {
2337
+ spec: { type: "string" },
2338
+ token: { type: "string" },
2339
+ reward: { type: "string" },
2340
+ budget: { type: "string" },
2341
+ days: { type: "string", default: "14" },
2342
+ "eligibility-token": { type: "string" },
2343
+ "min-holding": { type: "string", default: "0" }
2344
+ }
2345
+ });
2346
+ if (!values.spec || !values.token || !values.reward || !values.budget) fail("Usage: probe sponsor create --spec <file> --token <addr> --reward <amount> --budget <amount>");
2347
+ const spec = JSON.parse(readFileSync5(resolve3(values.spec), "utf8"));
2348
+ const cfg = loadConfig();
2349
+ if (!spec.reportKey && cfg.sponsorReportKey) spec.reportKey = cfg.sponsorReportKey.publicKey;
2350
+ validateSpec(spec);
2351
+ const { key, account } = sponsorAccount();
2352
+ const health = await api("/health");
2353
+ const rpcUrl = process.env.RPC_URL;
2354
+ if (!rpcUrl) fail("Set RPC_URL to the chain's RPC endpoint to send the funding transaction.");
2355
+ const client = publicClient(rpcUrl, health.chainId);
2356
+ const wallet = walletClient(rpcUrl, health.chainId, key);
2357
+ const token = values.token;
2358
+ const decimals = token === ZERO_ADDRESS ? 18 : await client.readContract({ address: token, abi: erc20Abi, functionName: "decimals" });
2359
+ const reward = parseUnits(values.reward, decimals);
2360
+ const budget = parseUnits(values.budget, decimals);
2361
+ const eligibilityToken = values["eligibility-token"] ?? ZERO_ADDRESS;
2362
+ const minHolding = eligibilityToken === ZERO_ADDRESS ? 0n : parseUnits(values["min-holding"], await client.readContract({ address: eligibilityToken, abi: erc20Abi, functionName: "decimals" }));
2363
+ const hash = specHash(spec);
2364
+ const reportKey = toHex5(new Uint8Array(Buffer.from(spec.reportKey, "base64")));
2365
+ console.log(`${prompt()} Creating job ${bold(spec.slug)} as ${account.address}`);
2366
+ if (token !== ZERO_ADDRESS) {
2367
+ await task("Approving the budget", async () => {
2368
+ const tx = await wallet.writeContract({ address: token, abi: erc20Abi, functionName: "approve", args: [health.contract, budget] });
2369
+ await client.waitForTransactionReceipt({ hash: tx });
2370
+ }, () => "ok");
2371
+ }
2372
+ const jobId = await task("Funding the job on-chain", async () => {
2373
+ const { request, result } = await client.simulateContract({
2374
+ account,
2375
+ address: health.contract,
2376
+ abi: probeJobsAbi,
2377
+ functionName: "createJob",
2378
+ value: token === ZERO_ADDRESS ? budget : 0n,
2379
+ args: [{ verifier: health.verifier, rewardToken: token, eligibilityToken, minHolding, rewardPerAccepted: reward, budget, deadline: BigInt(Math.floor(Date.now() / 1e3) + Number(values.days) * 86400), specHash: hash, reportKey }]
2380
+ });
2381
+ const tx = await wallet.writeContract(request);
2382
+ const r = await client.waitForTransactionReceipt({ hash: tx });
2383
+ if (r.status !== "success") throw new Error("createJob reverted");
2384
+ return result.toString();
2385
+ }, (id) => `job #${id}`);
2386
+ await task("Registering the spec with the verifier", async () => {
2387
+ const signature = await account.signMessage({ message: registrationMessage({ slug: spec.slug, specHash: hash, jobId, contract: health.contract, chainId: health.chainId }) });
2388
+ await api("/jobs", { method: "POST", body: { spec, jobId, signature } });
2389
+ }, () => "ready");
2390
+ const onchain = await readJob(client, health.contract, BigInt(jobId));
2391
+ payout(`Job ${spec.slug} is open with ${formatUnitsShort(onchain.budget, decimals)} funded. Operators can run: probe work ${spec.slug}`);
2392
+ }
2393
+ async function sponsorReports(args) {
2394
+ const slug = args[0];
2395
+ if (!slug) fail("Usage: probe sponsor reports <job>");
2396
+ const { account } = sponsorAccount();
2397
+ const secret = loadConfig().sponsorReportKey?.secretKey;
2398
+ if (!secret) fail("No report key on this machine. Reports can only be opened with the key from probe sponsor keygen.");
2399
+ const nonce = Date.now();
2400
+ const signature = await account.signMessage({ message: reportsMessage({ slug, nonce }) });
2401
+ const reports = await api(`/jobs/${slug}/reports?nonce=${nonce}&signature=${signature}`);
2402
+ if (!reports.length) return note("No private reports yet.");
2403
+ const dir = join4(PROBE_HOME, "reports", slug);
2404
+ mkdirSync4(dir, { recursive: true });
2405
+ for (const r of reports) {
2406
+ const body = JSON.parse(open(r.sealed, secret));
2407
+ const file = join4(dir, `${r.id}.json`);
2408
+ writeFileSync4(file, JSON.stringify(body, null, 2), { mode: 384 });
2409
+ console.log(`${hot("\u25CF")} ${body.case} ${dim(`fingerprint ${shortFp(body.fingerprint)}, operator ${body.operator}`)}
2410
+ ${dim(file)}`);
2411
+ }
2412
+ }
2413
+ var [cmd, ...rest] = process.argv.slice(2);
2414
+ var commands = {
2415
+ init,
2416
+ whoami,
2417
+ doctor,
2418
+ check,
2419
+ jobs,
2420
+ job,
2421
+ work,
2422
+ status,
2423
+ submissions,
2424
+ balance,
2425
+ withdraw,
2426
+ case: async (a) => {
2427
+ const [sub, ...r] = a;
2428
+ if (sub === "new") return caseNew(r);
2429
+ if (sub === "check") return caseCheck(r);
2430
+ fail("Usage: probe case new <job> <Name> | probe case check <job> <file...>");
2431
+ },
2432
+ sponsor: async (a) => {
2433
+ const [sub, ...r] = a;
2434
+ if (sub === "keygen") return sponsorKeygen();
2435
+ if (sub === "create") return sponsorCreate(r);
2436
+ if (sub === "reports") return sponsorReports(r);
2437
+ fail("Usage: probe sponsor keygen | create | reports");
2438
+ }
2439
+ };
2440
+ if (cmd === "--version" || cmd === "-v" || cmd === "version") {
2441
+ console.log(`probe ${VERSION}`);
2442
+ } else if (!cmd || cmd === "help" || cmd === "--help" || cmd === "-h") {
2443
+ console.log(HELP);
2444
+ } else if (!commands[cmd]) {
2445
+ fail(`Unknown command ${cmd}. Run probe help.`);
2446
+ } else {
2447
+ commands[cmd](rest).catch((e) => fail(e instanceof Error ? e.message : String(e)));
2448
+ }