@moonbeam-foundation/sdk 0.5.2 → 0.7.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.
Files changed (106) hide show
  1. package/README.md +137 -38
  2. package/dist/abi/index.d.ts +55 -0
  3. package/dist/abi/index.d.ts.map +1 -0
  4. package/dist/abi/index.js +227 -0
  5. package/dist/abi/index.js.map +1 -0
  6. package/dist/acp/events.d.ts +38 -38
  7. package/dist/acp/events.d.ts.map +1 -1
  8. package/dist/acp/events.js.map +1 -1
  9. package/dist/acp/moonbeam-acp.generated.d.ts +50 -0
  10. package/dist/acp/moonbeam-acp.generated.d.ts.map +1 -0
  11. package/dist/acp/moonbeam-acp.generated.js +56 -0
  12. package/dist/acp/moonbeam-acp.generated.js.map +1 -0
  13. package/dist/acp/pipeline.js.map +1 -1
  14. package/dist/acp/registry.d.ts.map +1 -1
  15. package/dist/acp/registry.js +5 -3
  16. package/dist/acp/registry.js.map +1 -1
  17. package/dist/actors/track-record.js.map +1 -1
  18. package/dist/adapters/acp.js.map +1 -1
  19. package/dist/adapters/stamp.d.ts +1 -1
  20. package/dist/adapters/stamp.d.ts.map +1 -1
  21. package/dist/arbitration/index.d.ts +120 -0
  22. package/dist/arbitration/index.d.ts.map +1 -0
  23. package/dist/arbitration/index.js +116 -0
  24. package/dist/arbitration/index.js.map +1 -0
  25. package/dist/assurance/assurance-shared.d.ts +1924 -0
  26. package/dist/assurance/assurance-shared.d.ts.map +1 -0
  27. package/dist/assurance/assurance-shared.js +2225 -0
  28. package/dist/assurance/assurance-shared.js.map +1 -0
  29. package/dist/assurance/index.d.ts +57 -0
  30. package/dist/assurance/index.d.ts.map +1 -0
  31. package/dist/assurance/index.js +49 -0
  32. package/dist/assurance/index.js.map +1 -0
  33. package/dist/attest/index.d.ts +19 -0
  34. package/dist/attest/index.d.ts.map +1 -0
  35. package/dist/attest/index.js +17 -0
  36. package/dist/attest/index.js.map +1 -0
  37. package/dist/client/index.d.ts +16 -6
  38. package/dist/client/index.d.ts.map +1 -1
  39. package/dist/client/index.js +21 -1
  40. package/dist/client/index.js.map +1 -1
  41. package/dist/connect/logs.js.map +1 -1
  42. package/dist/core/money.js.map +1 -1
  43. package/dist/core/settle.js.map +1 -1
  44. package/dist/core/types.d.ts +1 -1
  45. package/dist/erc8004/index.d.ts +9 -9
  46. package/dist/erc8004/index.d.ts.map +1 -1
  47. package/dist/erc8004/index.js.map +1 -1
  48. package/dist/erc8183/index.d.ts +12 -12
  49. package/dist/erc8183/index.d.ts.map +1 -1
  50. package/dist/erc8183/index.js.map +1 -1
  51. package/dist/index.d.ts +7 -0
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +8 -0
  54. package/dist/index.js.map +1 -1
  55. package/dist/judge/index.d.ts +35 -3
  56. package/dist/judge/index.d.ts.map +1 -1
  57. package/dist/judge/index.js +41 -2
  58. package/dist/judge/index.js.map +1 -1
  59. package/dist/launcher/index.d.ts +3 -3
  60. package/dist/launcher/index.d.ts.map +1 -1
  61. package/dist/onboard/index.d.ts +64 -24
  62. package/dist/onboard/index.d.ts.map +1 -1
  63. package/dist/onboard/index.js +90 -15
  64. package/dist/onboard/index.js.map +1 -1
  65. package/dist/pools/index.d.ts +49 -7
  66. package/dist/pools/index.d.ts.map +1 -1
  67. package/dist/pools/index.js +30 -6
  68. package/dist/pools/index.js.map +1 -1
  69. package/dist/proof/index.d.ts +117 -0
  70. package/dist/proof/index.d.ts.map +1 -0
  71. package/dist/proof/index.js +81 -0
  72. package/dist/proof/index.js.map +1 -0
  73. package/dist/resale/index.d.ts +120 -0
  74. package/dist/resale/index.d.ts.map +1 -0
  75. package/dist/resale/index.js +117 -0
  76. package/dist/resale/index.js.map +1 -0
  77. package/dist/resale/payment-scheme.d.mts +46 -0
  78. package/dist/resale/payment-scheme.mjs +351 -0
  79. package/dist/resale/payment-scheme.pin.json +6 -0
  80. package/dist/rpc/index.d.ts +24 -0
  81. package/dist/rpc/index.d.ts.map +1 -0
  82. package/dist/rpc/index.js +66 -0
  83. package/dist/rpc/index.js.map +1 -0
  84. package/dist/x402/index.d.ts +90 -0
  85. package/dist/x402/index.d.ts.map +1 -0
  86. package/dist/x402/index.js +75 -0
  87. package/dist/x402/index.js.map +1 -0
  88. package/examples/03-end-to-end-offline.mjs +2 -2
  89. package/examples/14-grade-record.mjs +6 -4
  90. package/examples/17-grade-live.mjs +1 -1
  91. package/examples/20-onboard-client.mjs +2 -2
  92. package/examples/24-resell-on-base.mjs +17 -0
  93. package/examples/{30-read-a-real-job.mjs → 30-read-a-job.mjs} +2 -2
  94. package/examples/32-read-live-from-base.mjs +8 -11
  95. package/examples/40-the-article.mjs +1 -1
  96. package/examples/50-x402-pay-a-wall.mjs +17 -0
  97. package/examples/51-read-a-proof.mjs +21 -0
  98. package/examples/52-arbitration-calls.mjs +13 -0
  99. package/examples/53-attested-by-default.mjs +19 -0
  100. package/examples/README.md +13 -6
  101. package/examples/data/proof-base-tx-52587000.json +116 -0
  102. package/package.json +51 -10
  103. package/skills/moonbeam-actor-backer/SKILL.md +1 -1
  104. package/skills/moonbeam-actor-challenger/SKILL.md +1 -1
  105. package/skills/moonbeam-actor-doubter/SKILL.md +1 -1
  106. package/skills/moonbeam-assurance/SKILL.md +1 -1
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  **Assurance for AI agent work: a price, a judge and a deadline, settled against proof.**
4
4
 
5
5
  - **What:** the SDK for Moonbeam's assurance layer on Base. It models a covered job end to end: the seller's deposit,
6
- the buyer's premium, cover from a GLMR pool, the verdict, and a settlement in which every ledger sums to zero.
6
+ the buyer's premium, cover from a pool, the verdict, and a settlement in which every ledger sums to zero.
7
7
  - **Why:** agent escrow refunds the price of a failed job, never the cost of the failure, and the judge has no capital
8
8
  behind its verdict. Moonbeam adds the deposit, the pool and a grader (Jev by TypeSafe).
9
9
  - **How:** `npm install @moonbeam-foundation/sdk`, then replay Moonbeam's first covered hire on Base, offline, in a few seconds:
@@ -14,9 +14,8 @@ npx moonbeam demo
14
14
 
15
15
  ![moonbeam demo: a covered hire on Base, Jev's grade of that same job checked against its Base record, and the settlement](docs/demo.gif)
16
16
 
17
- > Moonbeam ACP is a pilot with selected partners on Base. The contracts are source-verified, and the GLMR pools are
18
- > not open yet. Nothing here is an offer or a promise of yield, and nothing in this package signs a transaction.
19
- > Building on Moonbeam and want early access? Write to [builders@moonbeam.foundation](mailto:builders@moonbeam.foundation).
17
+ Moonbeam ACP is in a pilot on Base with selected partners. For early access, write to
18
+ [builders@moonbeam.foundation](mailto:builders@moonbeam.foundation).
20
19
 
21
20
  ## Install
22
21
 
@@ -42,16 +41,16 @@ behind its verdict. This SDK models the layer that closes both gaps.
42
41
  ```ts
43
42
  import { settle, parseUnits } from '@moonbeam-foundation/sdk';
44
43
 
45
- const usdc = (v: string) => parseUnits(v); // USDC has 6 decimals
44
+ const units = (v: string) => parseUnits(v); // amounts in the token's smallest units
46
45
 
47
46
  const { ledger, locked } = settle({
48
47
  terms: {
49
- pay: usdc('100'), // what the client pays for the work
50
- premium: usdc('1'), // what it pays for cover
51
- deposit: usdc('120'), // the provider's bond, sized above the job
52
- evaluatorBond: usdc('25'), // the judge's bond
53
- poolCapital: usdc('5000'), // backers standing behind the provider
54
- damage: usdc('70'), // consequential loss if the work is bad
48
+ pay: units('100'), // what the client pays for the work
49
+ premium: units('1'), // what it pays for cover
50
+ deposit: units('120'), // the provider's bond, sized above the job
51
+ evaluatorBond: units('25'), // the judge's bond
52
+ poolCapital: units('5000'), // backers standing behind the provider
53
+ damage: units('70'), // consequential loss if the work is bad
55
54
  },
56
55
  verdict: 'cheated',
57
56
  });
@@ -72,14 +71,16 @@ job, which is the shape a flat premium cannot fund at realistic failure rates.
72
71
 
73
72
  ## Examples
74
73
 
75
- Nineteen runnable files in [`examples/`](examples), all offline except two, built on real Base jobs. `npm test` runs them.
74
+ Twenty-five runnable files in [`examples/`](examples), built on Base jobs; all run offline except four (17 and 32 read live; 50 and
75
+ 51 read live, or run from recorded answers with `OFFLINE=1`). `npm test` runs them.
76
76
 
77
77
  | Start with | If you are |
78
78
  |---|---|
79
- | [`03-end-to-end-offline`](examples/03-end-to-end-offline.mjs) | new here: one real job read from Base, graded, settled |
79
+ | [`03-end-to-end-offline`](examples/03-end-to-end-offline.mjs) | new here: one job read from Base, graded, settled |
80
80
  | [`20`–`23` onboarding](examples/README.md#before-you-take-part) | about to pay, work, judge or back: what you put up, what you can lose, what should stop you |
81
81
  | [`10`–`17` the grader](examples/README.md#the-grader-stage-by-stage) | judging jobs: evidence → facts → answers → verdict → record → end the job → verify, then live |
82
82
  | [`30`–`33` reading jobs](examples/README.md#reading-jobs-that-already-ran) | studying jobs that already ran, one or many, offline or from a Base RPC |
83
+ | [`50`–`53`](examples/README.md) | paying an x402 wall on Base, reading a proof, arbitration, the records every step comes with |
83
84
 
84
85
  ```sh
85
86
  node examples/03-end-to-end-offline.mjs
@@ -151,7 +152,7 @@ waitingOn(state, clock); // who is holding this up
151
152
  but the provider can escalate to arbitration.
152
153
  - A silent **evaluator** cannot strand either: the deadline resolves the job.
153
154
 
154
- These are checked against real state rather than asserted in prose.
155
+ These are checked against the chain's state rather than asserted in prose.
155
156
 
156
157
  ## Time carries its provenance
157
158
 
@@ -207,23 +208,31 @@ providers that reject them leave holes in history that later reads never revisit
207
208
 
208
209
  ## Building transactions
209
210
 
210
- The SDK builds calls; it never signs or sends them, and never holds a key.
211
+ The SDK builds calls; it never signs or sends them, and never holds a key. The calls target the assurance hook Moonbeam runs
212
+ on Base (`@moonbeam-foundation/sdk/onboard`; the hook, the pool factory and the pools are read from the coordination layer's
213
+ address registry, never typed here):
211
214
 
212
215
  ```ts
213
- import { createAssuranceClient, asProofBlob } from '@moonbeam-foundation/sdk';
214
-
215
- const client = createAssuranceClient({ chainId: 84532, escrow, evaluator });
216
-
217
- client.escrow.claimRefund({ taskId }); // callable by anyone after the deadline
218
- client.evaluator.approve({ jobId, proof: asProofBlob(blob) }); // proof required by the type
219
- client.evaluator.reject({ jobId, reason }); // no proof — refusing is always safe
216
+ import { fundCalls, sellerDepositCalls, coverPremium, submitCalls, settleCalls, BASE_GLMR, BASE_USDC, MOONBEAM_HOOK } from '@moonbeam-foundation/sdk/onboard';
217
+
218
+ // a covered job is a GLMR job: the hook covers in GLMR only (the USDC route closed on 2026-09-29)
219
+ const premium = coverPremium(terms.price, { k: 19, n: 20 }); // the seller's record → the premium (jev-wilson)
220
+ sellerDepositCalls(terms); // the seller approves exactly its deposit
221
+ const [approve, fund] = fundCalls({ ...terms, token: BASE_GLMR }, { pool, premium, coverCap }); // approve price + premium, then fundJobWithCover
222
+ const [approveU, fundU] = fundCalls({ ...terms, token: BASE_USDC }); // an uncovered USDC job: no pool, premium 0
223
+ submitCalls({ jobId, evidenceDigest, correlator }); // the seller seals its delivery
224
+ settleCalls(jobId, 'completed'); // complete(jobId) · reject(jobId, digest) · expire(jobId)
220
225
  ```
221
226
 
222
- `asProofBlob` rejects an empty blob, so the approval path cannot be called
223
- without one. The asymmetry lives in the signatures rather than in a comment.
227
+ `fundJob`'s last address word is the **cover pool**, not an evaluator: the hook keeps no per-job evaluator (evaluators are the
228
+ owner's allowlist). `premium` is an argument the hook checks against the pool. A USDC job with a pool is refused before any call
229
+ (the hook would revert `PoolAssetMismatch`). `MOONBEAM_HOOK.status` carries the registry's word on the hook row (`live`, or
230
+ `scheduled-change` while a route change is announced). `test/fork/run-fork.mjs` sends these calls on a local fork of Base:
231
+ deposit approval, approve, `fundJob` against a live pool, `submit`, `complete`, then the settle's attestation.
224
232
 
225
- Constructing a client for a chain the contracts are not deployed on throws
226
- immediately, rather than producing a transaction addressed to nothing.
233
+ Pools open by the council's yes, not by a release: `poolsOpenOn(transport)` (`./pools`) reads `GET /v1/pools/networks` (its
234
+ `supported` lines and `closed_by_policy`) through the site's proxy and returns no chain while the GLMR pools are not open; the
235
+ typed `POOLS_OPEN_ON` is only the fallback. Pass its `chains` to the pool builders as `openOn`. The judge's quota is read the same way (`quotaOf(transport)`).
227
236
 
228
237
  ## Judging a job on the Base hook
229
238
 
@@ -242,9 +251,9 @@ const receipt = await gradeJob({
242
251
  jobId, // the hook's 32-byte job id
243
252
  evidence: { task, delivered },
244
253
  facts: jobFacts({ delivered: true, checks: { proof_verifies: () => checkProof(delivered) } }),
245
- trial: true, // 3 free calls; or key: <your TypeSafe key>
254
+ key: process.env.TYPESAFE_KEY, // your own TypeSafe key
246
255
  });
247
- const onchain = await recordGrade(receipt, { network: 'devnet' }); // none | devnet | base | both — unsigned calls
256
+ const onchain = await recordGrade(receipt); // unsigned calls on Base; { network: 'none' } turns it off
248
257
  const end = endJob(jobId, receipt); // complete(jobId) | reject(jobId, digest) | null (needs_review)
249
258
  const check = await verifyGrade(receipt, { chain: false });
250
259
  ```
@@ -255,6 +264,95 @@ re-encode the hook's `complete` from the covered GLMR hire on Base,
255
264
  [`0xc606d00f…3116`](https://basescan.org/tx/0xc606d00fed64e912585bbc93feb15a9289cfcde94289f49f7c74a7a468903116),
256
265
  byte for byte.
257
266
 
267
+ ## Reselling on Base
268
+
269
+ `@moonbeam-foundation/sdk/resale` is the Moonbeam profile of the coordination layer's one payment scheme, a byte-identical
270
+ vendored copy pinned by its sha256 (`src/resale/payment-scheme.pin.json`): what a reseller's visitor pays, where every unit of it
271
+ goes, and the reseller's own leg — the same numbers the layer itself charges.
272
+
273
+ ```
274
+ price_to_buyer = seller_price + our_fee + venue_fee(in) + venue_fee(out) [+ reseller_markup]
275
+ ```
276
+
277
+ ```ts
278
+ import { quoteBase, legsByName, markupLeg, childKeyTerms, childKeyPlan, subscribePlan, readSale } from '@moonbeam-foundation/sdk/resale';
279
+
280
+ const q = quoteBase({ venue_in: 'reseller', venue_out: 'erc8183-base', seller_price: 8_000n, reseller: { tenant, markup_bps: 1000 } });
281
+ if (q.ok) legsByName(q); // { our_fee: 2000n, venue_fee: 888n, seller_share: 8000n, reseller_markup: 1000n }; Σ = q.price_to_buyer
282
+ childKeyTerms({ '*': 1000 }); // what a child key is, in the layer's words
283
+ childKeyPlan({ '*': 1000 }); // POST /tenant/keys { action: 'child', markup_bps } — the reseller sends it with its own key
284
+ subscribePlan({ usdc: 1 }); // POST /access/subscribe — the child's top-up door (the x402 quote comes back as a 402)
285
+ await readSale(transport, 'rs_…'); // GET /resale/sales/{id} through the site's proxy
286
+ ```
287
+
288
+ A reseller is a tenant of the layer; its visitors buy on child keys from the reseller's balance; the markup is the reseller's
289
+ own leg, never part of the layer's fee. The venues are the five Base venues (`x402-base`, `erc8183-base`, `memoacp-base`,
290
+ `bitagent-base`, `olas-base`): Moonbeam resells on Base only, and the assurance economy stays in GLMR. Solana rails and the other
291
+ chains are in the coordination layer's own SDK, not here. Example: [`examples/24-resell-on-base.mjs`](examples/24-resell-on-base.mjs).
292
+
293
+ ## Attested by default
294
+
295
+ Every step this SDK handles comes with its record: a grade (`recordGrade`), an assurance settle (`settleAttested`) and a
296
+ resale step (`attestSale`). Each returns its mark (a digest anyone can recompute from the step's canonical body) and the
297
+ unsigned calls that put the mark on Base, where Moonbeam runs:
298
+
299
+ | contract on Base | call | built for |
300
+ |---|---|---|
301
+ | JevDecisionLog `0x209490d6A0FFC5368A42b0c2208BDCda853f6a92` | `record(subject, kind, digest, confidenceBps, model, uri)` | every step |
302
+ | JevAnswerLog `0x8e9B9cE86a2d55c10318607b0c815B7B8C66254d` | `record(useCase, subject, inputDigest, answersDigest, decisionDigest, model, uri)` | a grade |
303
+ | a grade stamp registry | `stamp(subject, digest, verdict, mode, model, uri)` | a step with a verdict |
304
+
305
+ Base has no grade stamp registry, so the stamp comes back in `missing`, with no call. Pass `networks: [chainId]` to
306
+ aim elsewhere, or `networks: 'none'` (`network: 'none'` for a grade) to turn recording off. The mark is returned
307
+ either way. Your wallet signs the calls; nothing here sends.
308
+
309
+ ```ts
310
+ import { settleAttested, hookQuote } from '@moonbeam-foundation/sdk/assurance';
311
+ const s = settleAttested(job, hookQuote({ price, premium, deposit, covered: true }));
312
+ s.legs; // who receives what, from the job's own GLMR amounts
313
+ s.attest.calls; // [JevDecisionLog.record on 8453]
314
+ s.attest.missing; // [{ contract: 'GradeStampRegistry', chainId: 8453, why: … }]
315
+ ```
316
+
317
+ ## Paying an x402 wall on Base
318
+
319
+ ```ts
320
+ import { quoteWall, transferAuthorization, paymentHeader } from '@moonbeam-foundation/sdk/x402';
321
+ const { accept } = await quoteWall(transport, '/x402/class/mcp.digest'); // the 402's Base entry (USDC)
322
+ const typed = transferAuthorization(accept, { from: myAddress }); // EIP-3009 TransferWithAuthorization
323
+ const signature = await wallet.signTypedData(typed); // your wallet signs
324
+ const header = paymentHeader(accept, typed.message, signature); // the X-PAYMENT header
325
+ ```
326
+
327
+ Only the `exact` entry on Base (`eip155:8453`) is taken; a wall that offers no Base entry is refused. `subscribe()` posts
328
+ the top-up door and returns its 402 quote. `quoteSale` from `./resale` prices the same wall from the seller's price.
329
+
330
+ ## Proofs
331
+
332
+ ```ts
333
+ import { readProof, verifyOnBase } from '@moonbeam-foundation/sdk/proof';
334
+ import { baseReader } from '@moonbeam-foundation/sdk/rpc';
335
+ const p = await readProof(transport, txHash); // block, superroot, checks, proven, ref v5:8453:<tx>@<superroot>
336
+ const c = await verifyOnBase(baseReader(), p.blob!); // verify(blob) by eth_call on the V5 verifier 0x2D475a53eAA8F9AC78B69bD2429275a622C644f8
337
+ ```
338
+
339
+ `c.verified` is what the verifier returns. `c.anchored` is false while the verifier has no superroot anchor set. The
340
+ block is bound to the snapshot the verifier folds by the inclusion path the layer serves (`c.inclusion`).
341
+
342
+ ## Arbitration
343
+
344
+ `./arbitration` builds the calls of the three-tier ArbitratorRouter: `resolveByCode` (tier 0, anyone),
345
+ `secondGraderTypedData` + `resolveBySecondGrader` (tier 1), and `councilApprove`, `pullOracle` and
346
+ `resolveByCouncil` (tier 2). It also decodes `Escalated`, `CouncilApproved` and `Resolved`, and `recordEffectOf`
347
+ says what a ruling writes into the seller's record. The router is not deployed on Base and the hook names no
348
+ arbitrator (`ARBITRATION_ON_BASE`), so every builder takes the router's address.
349
+
350
+ ## The Base reader
351
+
352
+ `baseReader()` from `./rpc` walks a measured rotation of Base endpoints: a rate limit or a refused range moves the call
353
+ to the next endpoint, and a revert is thrown at once. `BASE_RPC` (a comma list) goes first. The live examples read
354
+ through it.
355
+
258
356
  ## Skills for AI agents
259
357
 
260
358
  The package ships one skill per actor under `skills/`, so an agent acting as a
@@ -297,7 +395,7 @@ Implement `AssuranceAdapter<HostJob, HostOutcome>`: say what a job costs and wha
297
395
  its outcome means. Adapters translate; they never settle.
298
396
 
299
397
  The interface is deliberately narrow because it currently has **one**
300
- implementation. One adapter is a hypothetical seam, two is a real one — so it is
398
+ implementation. One adapter is a hypothetical seam, two is a working one — so it is
301
399
  better to keep this small until a second protocol shows what actually needs to
302
400
  be shared.
303
401
 
@@ -315,7 +413,7 @@ provider doing the work and the evaluator grading it. Everyone else opts in.
315
413
 
316
414
  Worth being precise about backing a pool: choosing to back one is optional, but once
317
415
  in, underwriting is not a separate opt-in — **the exposure is the yield**.
318
- There is no passive tier, because rewards come from real fees rather than
416
+ There is no passive tier, because rewards come from fees paid rather than
319
417
  inflation.
320
418
 
321
419
  ## Pool economics
@@ -327,20 +425,20 @@ import { runSeason, breakEvenFailureRate, clearingFeeIsCoherent } from '@moonbea
327
425
  // the damage leaves the pool at zero, which is the intended steady state.
328
426
  runSeason({
329
427
  jobs: 5_000,
330
- premiumPerJob: usdc('1'),
428
+ premiumPerJob: units('1'),
331
429
  failureRate: 0.006,
332
- damagePerFailure: usdc('70'),
333
- depositPerJob: usdc('40'),
430
+ damagePerFailure: units('70'),
431
+ depositPerJob: units('40'),
334
432
  });
335
433
  // → premium 4_970, absorbed by deposits 1_200, paid by pool 900, net +4_070
336
434
 
337
- breakEvenFailureRate(usdc('1'), usdc('70'), usdc('40')); // ≈ 0.032
338
- clearingFeeIsCoherent(34, usdc('1'), usdc('70'), usdc('40')); // false
435
+ breakEvenFailureRate(units('1'), units('70'), units('40')); // ≈ 0.032
436
+ clearingFeeIsCoherent(34, units('1'), units('70'), units('40')); // false
339
437
 
340
438
  // Raise the bond above the damage and the residual disappears:
341
- runSeason({ /* …as above… */ depositPerJob: usdc('120') });
439
+ runSeason({ /* …as above… */ depositPerJob: units('120') });
342
440
  // → premium 4_970, absorbed by deposits 2_100, paid by pool 0, net +4_970
343
- breakEvenFailureRate(usdc('1'), usdc('70'), usdc('120')); // null — no rate breaks it
441
+ breakEvenFailureRate(units('1'), units('70'), units('120')); // null — no rate breaks it
344
442
  ```
345
443
 
346
444
  That last call is the useful one. A published clearing fee is a claim about the
@@ -367,7 +465,8 @@ on it can pay.
367
465
 
368
466
  ```bash
369
467
  npm install
370
- npm test # 56 tests
468
+ npm test # every suite, offline
469
+ npm run check # typecheck + build + tests + the two pins (the assurance machine, the payment scheme)
371
470
  npm run typecheck # strict, noUncheckedIndexedAccess, exactOptionalPropertyTypes
372
471
  npm run build # ESM + .d.ts to dist/
373
472
  npm run test:coverage
@@ -0,0 +1,55 @@
1
+ /**
2
+ * A small ABI encoder (and decoder for the static words of logs) for the calls this SDK builds, so nothing here needs a
3
+ * chain library: uintN, intN ≥ 0, address, bool, bytesN, bytes, string, tuples and arrays (fixed or dynamic), nested.
4
+ * Types are written the way Solidity prints them, with or without names: `(uint64 chainId,bytes32[] siblings)[]`.
5
+ * Pinned against viem's encodeAbiParameters in test/abi.test.ts.
6
+ */
7
+ import { hexToBytes, type Hex } from '../onboard/index.js';
8
+ export type AbiType = {
9
+ kind: 'uint';
10
+ bits: number;
11
+ } | {
12
+ kind: 'address';
13
+ } | {
14
+ kind: 'bool';
15
+ } | {
16
+ kind: 'fixed';
17
+ size: number;
18
+ } | {
19
+ kind: 'bytes';
20
+ } | {
21
+ kind: 'string';
22
+ } | {
23
+ kind: 'tuple';
24
+ components: {
25
+ name: string | null;
26
+ type: AbiType;
27
+ }[];
28
+ } | {
29
+ kind: 'array';
30
+ of: AbiType;
31
+ length: number | null;
32
+ };
33
+ export type AbiValue = string | number | bigint | boolean | readonly AbiValue[] | {
34
+ readonly [k: string]: AbiValue;
35
+ };
36
+ /** a parameter `type name` → its parts (a lone type has no name) */
37
+ export declare function splitName(p: string): {
38
+ type: string;
39
+ name: string | null;
40
+ };
41
+ /** parse one type, e.g. `(uint8 a,bytes b)[]`, `tuple(uint8)`, `bytes32[3]`, `address` */
42
+ export declare function parseType(src: string): AbiType;
43
+ /** the canonical (name-free) form of a type, as selectors hash it */
44
+ export declare function canonical(t: AbiType): string;
45
+ /** abi.encode(values) for the given types (strings or parsed) */
46
+ export declare function encodeParams(types: readonly (string | AbiType)[], values: readonly AbiValue[]): Hex;
47
+ /** the function's selector from a signature with or without names, e.g. `verify((bytes32 h)[] x)` */
48
+ export declare function signatureOf(fn: string): string;
49
+ /** calldata: selector ‖ abi.encode(args) */
50
+ export declare function encodeFunction(fn: string, args: readonly AbiValue[]): Hex;
51
+ export declare const topicOf: (eventSignature: string) => Hex;
52
+ /** decode the static head words of log data or a return value (uint, bool, address, bytesN only) */
53
+ export declare function decodeStatic(types: readonly string[], data: string): (bigint | boolean | string)[];
54
+ export { hexToBytes };
55
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/abi/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAc,UAAU,EAAmB,KAAK,GAAG,EAAE,MAAM,qBAAqB,CAAC;AAExF,MAAM,MAAM,OAAO,GACf;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,SAAS,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GACzG;IAAE,IAAI,EAAE,OAAO,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,QAAQ,CAAA;CAAE,GACtC;IAAE,IAAI,EAAE,OAAO,CAAC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M,GAAG,OAAO,GAAG,MAAM,CAAC,EAAE,CAWlG;AACD,OAAO,EAAE,UAAU,EAAE,CAAC"}
@@ -0,0 +1,227 @@
1
+ /**
2
+ * A small ABI encoder (and decoder for the static words of logs) for the calls this SDK builds, so nothing here needs a
3
+ * chain library: uintN, intN ≥ 0, address, bool, bytesN, bytes, string, tuples and arrays (fixed or dynamic), nested.
4
+ * Types are written the way Solidity prints them, with or without names: `(uint64 chainId,bytes32[] siblings)[]`.
5
+ * Pinned against viem's encodeAbiParameters in test/abi.test.ts.
6
+ */
7
+ import { bytesToHex, hexToBytes, keccakHex, utf8 } from '../onboard/index.js';
8
+ /** split a comma list at depth 0 */
9
+ function splitTop(s) {
10
+ const out = [];
11
+ let depth = 0;
12
+ let cur = '';
13
+ for (const ch of s) {
14
+ if (ch === '(')
15
+ depth++;
16
+ if (ch === ')')
17
+ depth--;
18
+ if (ch === ',' && depth === 0) {
19
+ out.push(cur);
20
+ cur = '';
21
+ }
22
+ else
23
+ cur += ch;
24
+ }
25
+ if (cur.trim())
26
+ out.push(cur);
27
+ return out.map((x) => x.trim());
28
+ }
29
+ /** a parameter `type name` → its parts (a lone type has no name) */
30
+ export function splitName(p) {
31
+ const m = /^(.*\S)\s+([A-Za-z_$][\w$]*)$/s.exec(p.trim());
32
+ const KW = /^(memory|calldata|storage|indexed)$/;
33
+ if (m && KW.test(m[2]))
34
+ return { type: splitName(m[1]).type, name: null };
35
+ if (m) {
36
+ const inner = splitName(m[1]);
37
+ return { type: inner.name && KW.test(inner.name) ? inner.type : m[1].trim().replace(/\s+(memory|calldata|storage|indexed)$/, ''), name: m[2] };
38
+ }
39
+ return { type: p.trim(), name: null };
40
+ }
41
+ /** parse one type, e.g. `(uint8 a,bytes b)[]`, `tuple(uint8)`, `bytes32[3]`, `address` */
42
+ export function parseType(src) {
43
+ let s = src.trim();
44
+ const arr = /^(.*)\[(\d*)\]$/s.exec(s);
45
+ if (arr && !s.endsWith(')'))
46
+ return { kind: 'array', of: parseType(arr[1]), length: arr[2] ? Number(arr[2]) : null };
47
+ if (s.startsWith('tuple('))
48
+ s = s.slice(5);
49
+ if (s.startsWith('(')) {
50
+ // the matching close of the first '(' must end the string (arrays were handled above)
51
+ let depth = 0;
52
+ let end = -1;
53
+ for (let i = 0; i < s.length; i++) {
54
+ if (s[i] === '(')
55
+ depth++;
56
+ if (s[i] === ')') {
57
+ depth--;
58
+ if (depth === 0) {
59
+ end = i;
60
+ break;
61
+ }
62
+ }
63
+ }
64
+ if (end !== s.length - 1) {
65
+ const tail = s.slice(end + 1);
66
+ const m = /^\[(\d*)\]$/.exec(tail);
67
+ if (!m)
68
+ throw new Error(`abi: cannot parse ${src}`);
69
+ return { kind: 'array', of: parseType(s.slice(0, end + 1)), length: m[1] ? Number(m[1]) : null };
70
+ }
71
+ const inner = s.slice(1, -1);
72
+ return { kind: 'tuple', components: (inner ? splitTop(inner) : []).map((c) => { const p = splitName(c); return { name: p.name, type: parseType(p.type) }; }) };
73
+ }
74
+ const tail = /^(.*)\[(\d*)\]$/.exec(s);
75
+ if (tail)
76
+ return { kind: 'array', of: parseType(tail[1]), length: tail[2] ? Number(tail[2]) : null };
77
+ if (s === 'address')
78
+ return { kind: 'address' };
79
+ if (s === 'bool')
80
+ return { kind: 'bool' };
81
+ if (s === 'string')
82
+ return { kind: 'string' };
83
+ if (s === 'bytes')
84
+ return { kind: 'bytes' };
85
+ const u = /^uint(\d*)$/.exec(s);
86
+ if (u)
87
+ return { kind: 'uint', bits: u[1] ? Number(u[1]) : 256 };
88
+ const b = /^bytes(\d+)$/.exec(s);
89
+ if (b)
90
+ return { kind: 'fixed', size: Number(b[1]) };
91
+ throw new Error(`abi: unsupported type ${src}`);
92
+ }
93
+ /** the canonical (name-free) form of a type, as selectors hash it */
94
+ export function canonical(t) {
95
+ switch (t.kind) {
96
+ case 'uint': return `uint${t.bits}`;
97
+ case 'fixed': return `bytes${t.size}`;
98
+ case 'tuple': return `(${t.components.map((c) => canonical(c.type)).join(',')})`;
99
+ case 'array': return `${canonical(t.of)}[${t.length ?? ''}]`;
100
+ default: return t.kind;
101
+ }
102
+ }
103
+ const isDynamic = (t) => t.kind === 'bytes' || t.kind === 'string' || (t.kind === 'array' && (t.length === null || isDynamic(t.of))) || (t.kind === 'tuple' && t.components.some((c) => isDynamic(c.type)));
104
+ const word = (n) => { if (n < 0n || n >= 1n << 256n)
105
+ throw new RangeError(`abi: ${n} does not fit a word`); return n.toString(16).padStart(64, '0'); };
106
+ const padRight = (hex) => hex.padEnd(Math.ceil(hex.length / 64) * 64, '0');
107
+ function encodeOne(t, v) {
108
+ switch (t.kind) {
109
+ case 'uint': {
110
+ const n = BigInt(v);
111
+ if (n >= 1n << BigInt(t.bits))
112
+ throw new RangeError(`abi: ${n} overflows uint${t.bits}`);
113
+ return word(n);
114
+ }
115
+ case 'bool': return word(v ? 1n : 0n);
116
+ case 'address': {
117
+ const a = String(v);
118
+ if (!/^0x[0-9a-fA-F]{40}$/.test(a))
119
+ throw new Error(`abi: not an address: ${a}`);
120
+ return a.slice(2).toLowerCase().padStart(64, '0');
121
+ }
122
+ case 'fixed': {
123
+ const h = String(v).replace(/^0x/, '');
124
+ if (h.length !== t.size * 2 || !/^[0-9a-fA-F]*$/.test(h))
125
+ throw new Error(`abi: not bytes${t.size}: ${v}`);
126
+ return h.toLowerCase().padEnd(64, '0');
127
+ }
128
+ case 'bytes': {
129
+ const h = String(v).replace(/^0x/, '');
130
+ if (h.length % 2 || !/^[0-9a-fA-F]*$/.test(h))
131
+ throw new Error(`abi: not bytes: ${v}`);
132
+ return word(BigInt(h.length / 2)) + padRight(h.toLowerCase());
133
+ }
134
+ case 'string': {
135
+ const h = bytesToHex(utf8(String(v))).slice(2);
136
+ return word(BigInt(h.length / 2)) + padRight(h);
137
+ }
138
+ case 'array': {
139
+ const items = v;
140
+ if (!Array.isArray(items))
141
+ throw new Error('abi: an array type needs an array value');
142
+ if (t.length !== null && items.length !== t.length)
143
+ throw new Error(`abi: expected ${t.length} items, got ${items.length}`);
144
+ const body = encodeSeq(items.map(() => t.of), items);
145
+ return t.length === null ? word(BigInt(items.length)) + body : body;
146
+ }
147
+ case 'tuple': {
148
+ const vals = Array.isArray(v) ? v : t.components.map((c, i) => {
149
+ const o = v;
150
+ const x = c.name !== null ? o[c.name] : o[i];
151
+ if (x === undefined)
152
+ throw new Error(`abi: tuple field ${c.name ?? i} is missing`);
153
+ return x;
154
+ });
155
+ return encodeSeq(t.components.map((c) => c.type), vals);
156
+ }
157
+ }
158
+ }
159
+ function encodeSeq(types, values) {
160
+ if (types.length !== values.length)
161
+ throw new Error(`abi: ${types.length} types, ${values.length} values`);
162
+ const heads = [];
163
+ const tails = [];
164
+ const headSize = types.reduce((a, t) => a + (isDynamic(t) ? 32 : staticSize(t)), 0);
165
+ let tailLen = 0;
166
+ types.forEach((t, i) => {
167
+ const enc = encodeOne(t, values[i]);
168
+ if (isDynamic(t)) {
169
+ heads.push(word(BigInt(headSize + tailLen)));
170
+ tails.push(enc);
171
+ tailLen += enc.length / 2;
172
+ }
173
+ else
174
+ heads.push(enc);
175
+ });
176
+ return heads.join('') + tails.join('');
177
+ }
178
+ function staticSize(t) {
179
+ if (t.kind === 'tuple')
180
+ return t.components.reduce((a, c) => a + staticSize(c.type), 0);
181
+ if (t.kind === 'array' && t.length !== null)
182
+ return t.length * staticSize(t.of);
183
+ return 32;
184
+ }
185
+ /** abi.encode(values) for the given types (strings or parsed) */
186
+ export function encodeParams(types, values) {
187
+ return `0x${encodeSeq(types.map((t) => (typeof t === 'string' ? parseType(t) : t)), values)}`;
188
+ }
189
+ /** the function's selector from a signature with or without names, e.g. `verify((bytes32 h)[] x)` */
190
+ export function signatureOf(fn) {
191
+ const m = /^([A-Za-z_$][\w$]*)\((.*)\)$/s.exec(fn.trim());
192
+ if (!m)
193
+ throw new Error(`abi: not a function signature: ${fn}`);
194
+ return `${m[1]}(${paramsOf(m[2]).map(canonical).join(',')})`;
195
+ }
196
+ const paramsOf = (list) => (list.trim() ? splitTop(list) : []).map((p) => parseType(splitName(p).type));
197
+ /** calldata: selector ‖ abi.encode(args) */
198
+ export function encodeFunction(fn, args) {
199
+ const m = /^([A-Za-z_$][\w$]*)\((.*)\)$/s.exec(fn.trim());
200
+ if (!m)
201
+ throw new Error(`abi: not a function signature: ${fn}`);
202
+ const types = paramsOf(m[2]);
203
+ const sel = keccakHex(utf8(signatureOf(fn))).slice(0, 10);
204
+ return `${sel}${encodeSeq(types, args)}`;
205
+ }
206
+ export const topicOf = (eventSignature) => keccakHex(utf8(signatureOf(eventSignature)));
207
+ /** decode the static head words of log data or a return value (uint, bool, address, bytesN only) */
208
+ export function decodeStatic(types, data) {
209
+ const h = data.replace(/^0x/, '');
210
+ return types.map((ts, i) => {
211
+ const w = h.slice(i * 64, i * 64 + 64);
212
+ if (w.length < 64)
213
+ throw new Error('abi: data too short');
214
+ const t = parseType(ts);
215
+ if (t.kind === 'uint')
216
+ return BigInt(`0x${w}`);
217
+ if (t.kind === 'bool')
218
+ return BigInt(`0x${w}`) !== 0n;
219
+ if (t.kind === 'address')
220
+ return `0x${w.slice(24)}`;
221
+ if (t.kind === 'fixed')
222
+ return `0x${w.slice(0, t.size * 2)}`;
223
+ throw new Error(`abi: decodeStatic does not decode ${ts}`);
224
+ });
225
+ }
226
+ export { hexToBytes };
227
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/abi/index.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,SAAS,EAAE,IAAI,EAAY,MAAM,qBAAqB,CAAC;AASxF,oCAAoC;AACpC,SAAS,QAAQ,CAAC,CAAS;IACzB,MAAM,GAAG,GAAa,EAAE,CAAC;IAAC,IAAI,KAAK,GAAG,CAAC,CAAC;IAAC,IAAI,GAAG,GAAG,EAAE,CAAC;IACtD,KAAK,MAAM,EAAE,IAAI,CAAC,EAAE,CAAC;QACnB,IAAI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