@moonbeam-foundation/sdk 0.11.0 → 0.13.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 (110) hide show
  1. package/README.md +79 -70
  2. package/bin/moonbeam.mjs +18 -1
  3. package/dist/actors/track-record.d.ts +1 -1
  4. package/dist/actors/track-record.js +1 -1
  5. package/dist/arbitration/index.d.ts +10 -4
  6. package/dist/arbitration/index.d.ts.map +1 -1
  7. package/dist/arbitration/index.js +14 -2
  8. package/dist/arbitration/index.js.map +1 -1
  9. package/dist/assurance/assurance-shared.d.ts +85 -132
  10. package/dist/assurance/assurance-shared.js +46 -90
  11. package/dist/cover/index.d.ts +3 -3
  12. package/dist/cover/index.d.ts.map +1 -1
  13. package/dist/devnet/index.d.ts +3 -3
  14. package/dist/devnet/index.d.ts.map +1 -1
  15. package/dist/devnet/index.js +4 -4
  16. package/dist/devnet/index.js.map +1 -1
  17. package/dist/devnet/profile.d.ts +1 -1
  18. package/dist/devnet/profile.d.ts.map +1 -1
  19. package/dist/erc8183/index.d.ts +1 -1
  20. package/dist/errors/index.d.ts +5 -5
  21. package/dist/errors/index.d.ts.map +1 -1
  22. package/dist/errors/index.js +3 -3
  23. package/dist/jobs/index.d.ts +4 -4
  24. package/dist/jobs/index.d.ts.map +1 -1
  25. package/dist/jobs/index.js +1 -1
  26. package/dist/jobs/index.js.map +1 -1
  27. package/dist/market/cohorts.d.ts +106 -0
  28. package/dist/market/cohorts.d.ts.map +1 -0
  29. package/dist/market/cohorts.js +70 -0
  30. package/dist/market/cohorts.js.map +1 -0
  31. package/dist/market/http.d.ts +13 -0
  32. package/dist/market/http.d.ts.map +1 -0
  33. package/dist/market/http.js +29 -0
  34. package/dist/market/http.js.map +1 -0
  35. package/dist/market/index.d.ts +43 -20
  36. package/dist/market/index.d.ts.map +1 -1
  37. package/dist/market/index.js +19 -36
  38. package/dist/market/index.js.map +1 -1
  39. package/dist/market/journey.d.ts +174 -0
  40. package/dist/market/journey.d.ts.map +1 -0
  41. package/dist/market/journey.js +179 -0
  42. package/dist/market/journey.js.map +1 -0
  43. package/dist/market/listed.d.ts +228 -0
  44. package/dist/market/listed.d.ts.map +1 -0
  45. package/dist/market/listed.js +168 -0
  46. package/dist/market/listed.js.map +1 -0
  47. package/dist/market/sale-stops.d.ts +29 -0
  48. package/dist/market/sale-stops.d.ts.map +1 -0
  49. package/dist/market/sale-stops.js +29 -0
  50. package/dist/market/sale-stops.js.map +1 -0
  51. package/dist/market/sale.d.ts +98 -0
  52. package/dist/market/sale.d.ts.map +1 -0
  53. package/dist/market/sale.js +64 -0
  54. package/dist/market/sale.js.map +1 -0
  55. package/dist/market/venues-data.d.ts +3 -0
  56. package/dist/market/venues-data.d.ts.map +1 -0
  57. package/dist/market/venues-data.js +1035 -0
  58. package/dist/market/venues-data.js.map +1 -0
  59. package/dist/market/venues.d.ts +143 -0
  60. package/dist/market/venues.d.ts.map +1 -0
  61. package/dist/market/venues.js +123 -0
  62. package/dist/market/venues.js.map +1 -0
  63. package/dist/onboard/index.d.ts +214 -33
  64. package/dist/onboard/index.d.ts.map +1 -1
  65. package/dist/onboard/index.js +340 -31
  66. package/dist/onboard/index.js.map +1 -1
  67. package/dist/onboard/send.d.ts +43 -0
  68. package/dist/onboard/send.d.ts.map +1 -0
  69. package/dist/onboard/send.js +65 -0
  70. package/dist/onboard/send.js.map +1 -0
  71. package/dist/pools/index.d.ts +18 -7
  72. package/dist/pools/index.d.ts.map +1 -1
  73. package/dist/pools/index.js +31 -9
  74. package/dist/pools/index.js.map +1 -1
  75. package/dist/proof/index.d.ts +5 -5
  76. package/dist/proof/index.d.ts.map +1 -1
  77. package/dist/proof/index.js +1 -1
  78. package/dist/resale/index.d.ts +13 -13
  79. package/dist/resale/index.d.ts.map +1 -1
  80. package/dist/resale/index.js +17 -17
  81. package/dist/resale/index.js.map +1 -1
  82. package/dist/resale/payment-scheme.d.mts +2 -5
  83. package/dist/resale/payment-scheme.mjs +16 -116
  84. package/dist/resale/payment-scheme.pin.json +1 -2
  85. package/dist/resale/settle-rule.d.ts +3 -3
  86. package/dist/resale/settle-rule.d.ts.map +1 -1
  87. package/dist/resale/settle-rule.js +3 -3
  88. package/dist/resale/settle-rule.js.map +1 -1
  89. package/dist/rpc/index.js +1 -1
  90. package/dist/workflows/index.js +1 -1
  91. package/dist/workflows/steps.d.ts +4 -4
  92. package/dist/workflows/steps.d.ts.map +1 -1
  93. package/dist/workflows/steps.js +4 -4
  94. package/dist/workflows/steps.js.map +1 -1
  95. package/dist/workflows/types.d.ts +1 -1
  96. package/dist/x402/index.d.ts +2 -2
  97. package/dist/x402/index.d.ts.map +1 -1
  98. package/dist/x402/index.js +2 -2
  99. package/dist/x402/index.js.map +1 -1
  100. package/docs/REFERENCE.md +52 -19
  101. package/docs/VENUES.md +209 -0
  102. package/docs/WORKFLOWS.md +3 -3
  103. package/examples/24-resell-on-base.mjs +1 -1
  104. package/examples/51-read-a-proof.mjs +2 -2
  105. package/examples/70-every-venue.mjs +19 -0
  106. package/examples/README.md +2 -1
  107. package/examples/data/cross-list.recorded.json +1 -1
  108. package/package.json +7 -3
  109. package/dist/assurance/assurance-shared.d.ts.map +0 -1
  110. package/dist/assurance/assurance-shared.js.map +0 -1
@@ -8,7 +8,7 @@
8
8
  * nothing fetches unless it is handed a transport.
9
9
  *
10
10
  * The transport is a fetch and a base URL. On a Moonbeam surface the base is
11
- * the site's own same-origin proxy, which scrubs the coordination layer's
11
+ * the site's own same-origin proxy, which scrubs the API's
12
12
  * name and hosts before anything reaches the page; the module never renders
13
13
  * an upstream URL and never needs to know one.
14
14
  *
@@ -54,10 +54,10 @@ export const QUOTA_MAX_BLOCKS = 20;
54
54
  /** the seller's record is calibrated at n ≥ 5 and a Wilson width ≤ 0.35 */
55
55
  export const RECORD_MIN_N = 5;
56
56
  export const RECORD_MAX_WIDTH = 0.35;
57
- /** the hook's grading window after submission, in seconds (what the layer's calls carry) */
57
+ /** the hook's grading window after submission, in seconds (what Moonbeam's calls carry) */
58
58
  export const DEFAULT_GRADE_WINDOW = 604_800;
59
59
  export const DEFAULT_QUESTION = 'Was the work delivered as specified?';
60
- /** The guard as this surface applies it. `anchor` names the decision log the layer writes to today. */
60
+ /** The guard as this surface applies it. `anchor` names the decision log Moonbeam writes to today. */
61
61
  export const DEFAULT_GUARD = Object.freeze({
62
62
  bar: 0.8,
63
63
  mode: 'calibrated',
@@ -67,8 +67,8 @@ export const DEFAULT_GUARD = Object.freeze({
67
67
  anchor: { chain: 8453, log: JEV_DECISION_LOG.address },
68
68
  });
69
69
  /**
70
- * The judge's quota as the layer states it today (GET /v1/judge/credits, keyless: the free grades per address, the grades a
71
- * block buys, the burst cap, the price of a block), with the typed values as the fallback when the read fails. The layer's
70
+ * The judge's quota as Moonbeam states it today (GET /v1/judge/credits, keyless: the free grades per address, the grades a
71
+ * block buys, the burst cap, the price of a block), with the typed values as the fallback when the read fails. Moonbeam's
72
72
  * numbers win: the constants above are what they were on 2026-09-24 and may drift from what it charges.
73
73
  */
74
74
  export async function quotaOf(t) {
@@ -300,13 +300,32 @@ export const SIGNATURES = Object.freeze({
300
300
  complete: 'complete(bytes32)',
301
301
  reject: 'reject(bytes32,bytes32)',
302
302
  expire: 'expire(bytes32)',
303
+ // V3.1 (an append-only upgrade of the hook; until it executes, these revert on the live V3 hook)
304
+ approveFunder: 'approveFunder(address,bool)',
305
+ claimAutoComplete: 'claimAutoComplete(bytes32)',
306
+ claim: 'claim(address)',
303
307
  });
304
308
  // ── Identifiers the calls need ────────────────────────────────────────────────
305
- /** The bytes32 job id for a set of terms: keccak over the canonical terms, so the same terms always name the same job and anyone can recompute it. */
306
- export function jobIdOf(t) {
307
- const canonical = JSON.stringify({ chainId: t.chainId, buyer: t.buyer.toLowerCase(), seller: t.seller.toLowerCase(), token: t.token.toLowerCase(), price: t.price.toString(), deadline: t.deadline, task: t.task });
309
+ /**
310
+ * The bytes32 job id for a set of terms: keccak over the canonical terms. Without a salt the same terms always name the same
311
+ * job and anyone who knows the terms can recompute it, which also lets anyone fund that id first: the hook refuses a second
312
+ * funding of an id (JobExists), so the intended funding fails. With a salt (32 random bytes, `newJobSalt()`, kept private
313
+ * until the funding lands) the id cannot be derived from the terms. `planFunding` salts every id it plans.
314
+ */
315
+ export function jobIdOf(t, salt) {
316
+ if (salt !== undefined && !isHex32(salt))
317
+ throw new Error('a job id salt is 32 bytes');
318
+ const terms = { chainId: t.chainId, buyer: t.buyer.toLowerCase(), seller: t.seller.toLowerCase(), token: t.token.toLowerCase(), price: t.price.toString(), deadline: t.deadline, task: t.task };
319
+ const canonical = JSON.stringify(salt === undefined ? terms : { ...terms, salt: salt.toLowerCase() });
308
320
  return keccakHex(utf8(canonical));
309
321
  }
322
+ /** 32 random bytes from the platform's CSPRNG (Web Crypto), for `jobIdOf(terms, salt)`. Throws where none exists. */
323
+ export function newJobSalt() {
324
+ const c = globalThis.crypto;
325
+ if (!c?.getRandomValues)
326
+ throw new Error('no Web Crypto getRandomValues here: pass your own 32 random bytes as the salt');
327
+ return bytesToHex(c.getRandomValues(new Uint8Array(32)));
328
+ }
310
329
  /** correlator = keccak(domain ‖ nonce ‖ payTo ‖ uint64 chainId): binds off-chain work to the job it is paid under. */
311
330
  export function correlatorOf(a) {
312
331
  if (!isHex32(a.nonce))
@@ -318,19 +337,31 @@ export function correlatorOf(a) {
318
337
  const ZERO = '0x0000000000000000000000000000000000000000';
319
338
  // ── Unsigned calls (pure) ─────────────────────────────────────────────────────
320
339
  const call = (to, data, step, signer, effect, chainId = 8453) => ({ chainId, to, data: data, value: '0x0', step, signer, effect });
340
+ /** The furthest deadline a funding may carry, counted from the chain's time at funding: 365 days. The V3.1 hook refuses a
341
+ * later one (DeadlineTooFar); the live V3 hook accepts any, and this SDK refuses it on both, since a pool's reservation and
342
+ * the seller's deposit are held until the deadline. */
343
+ export const MAX_DEADLINE_S = 365 * 86_400;
344
+ /** The bounds V3.1 clamps a job's review window (its `challengeWindow`) to, in seconds: 1 hour to 30 days. */
345
+ export const REVIEW_WINDOW_S = Object.freeze({ min: 3_600, max: 30 * 86_400 });
321
346
  /**
322
347
  * The calls the buyer signs to fund a job on Base, in order: an exact-amount token approve to the hook (the price plus the
323
- * premium, when a pool covers the job), then fundJob — or fundJobWithCover when a cover cap is named. The seller must already
324
- * have approved the hook for exactly its deposit for this job (never a standing allowance: the live contract pulls the deposit
325
- * from whichever seller the funder names). Refuses terms whose deposit is below the rule.
348
+ * premium, when a pool covers the job), then fundJob — or fundJobWithCover when a cover cap is named. Refuses terms whose
349
+ * deposit is below the rule.
326
350
  *
327
- * The hook's signature (AssuranceHook.sol, fundJob and fundJobWithCover):
351
+ * The seller must already have approved the hook for exactly its deposit (`sellerDepositCalls`). On the live V3 hook that
352
+ * allowance is not bound to one buyer or one job: the contract pulls the deposit from whichever seller the funder names. On
353
+ * V3.1 the hook pulls it only when the caller is the seller or a funder the seller approved (`approveFunder`), so the seller
354
+ * signs both before the buyer funds; `planFunding` reads which rules apply and what is missing.
355
+ *
356
+ * The hook's signature (AssuranceHook.sol, fundJob and fundJobWithCover, the same on V3 and V3.1):
328
357
  * fundJob(bytes32 jobId, address seller, address token, uint256 price, uint256 premium, uint256 deposit, uint64 deadline, uint64 challengeWindow, address pool)
329
358
  * fundJobWithCover(…the same…, address pool, uint256 coverCap)
330
359
  * The LAST address word is the COVER POOL, not an evaluator: the hook keeps no per-job evaluator (evaluators are the owner's
331
- * allowlist, setEvaluator). `premium` is an ARGUMENT the hook checks against the pool (CoverNotPaidFor when a pool is set and the
332
- * premium is below what it asks); it is not read from the pool. A covered job (pool ≠ 0) is a GLMR job: the hook's USDC route closed
333
- * on 2026-09-29, and a USDC job with a GLMR pool reverts PoolAssetMismatch. Uncovered jobs (pool = 0, premium = 0) may be USDC.
360
+ * allowlist, setEvaluator). `premium` is an ARGUMENT: the hook refuses a premium of 0 when a pool is named (CoverNotPaidFor)
361
+ * and a cover cap above maxCoverFor(price) (CoverCapTooHigh); it does not compare the premium with any rate of the pool. A
362
+ * named pool must be the factory's pool for the seller (`registeredPool`, read from PoolFactory.poolOf): V3.1 refuses any
363
+ * other (PoolNotRegistered), and this SDK refuses it on both. A covered job (pool ≠ 0) is a GLMR job: the hook's USDC route
364
+ * closed on 2026-09-29, and a USDC job with a GLMR pool reverts PoolAssetMismatch. Uncovered jobs (pool = 0, premium = 0) may be USDC.
334
365
  */
335
366
  export function fundCalls(terms, opts = {}) {
336
367
  if (opts.evaluator !== undefined) {
@@ -343,10 +374,24 @@ export function fundCalls(terms, opts = {}) {
343
374
  throw new RangeError('price must be positive');
344
375
  if (!Number.isInteger(terms.deadline) || terms.deadline <= 0)
345
376
  throw new RangeError('deadline must be unix seconds');
346
- const jobId = opts.jobId ?? jobIdOf(terms);
377
+ if (opts.now !== undefined) {
378
+ if (terms.deadline <= opts.now)
379
+ throw new RangeError(`the deadline ${terms.deadline} has passed (chain time ${opts.now})`);
380
+ if (terms.deadline > opts.now + MAX_DEADLINE_S)
381
+ throw new RangeError(`the deadline is more than 365 days away (at most ${opts.now + MAX_DEADLINE_S})`);
382
+ }
383
+ if (opts.jobId !== undefined && opts.salt !== undefined)
384
+ throw new TypeError('fundCalls: pass a jobId or a salt, not both');
385
+ const jobId = opts.jobId ?? jobIdOf(terms, opts.salt);
386
+ if (!isHex32(jobId))
387
+ throw new Error('jobId must be bytes32');
347
388
  const pool = opts.pool ?? ZERO;
348
389
  const premium = opts.premium ?? 0n;
349
390
  const gradeWindow = opts.gradeWindow ?? DEFAULT_GRADE_WINDOW;
391
+ const v31 = opts.rules === 'v3.1';
392
+ if (v31 && (!Number.isInteger(gradeWindow) || gradeWindow < REVIEW_WINDOW_S.min || gradeWindow > REVIEW_WINDOW_S.max)) {
393
+ throw new RangeError(`the review window is ${REVIEW_WINDOW_S.min} to ${REVIEW_WINDOW_S.max} seconds on this hook (the hook would clamp ${gradeWindow})`);
394
+ }
350
395
  if (premium < 0n || (opts.coverCap !== undefined && opts.coverCap < 0n))
351
396
  throw new RangeError('premium and coverCap are non-negative');
352
397
  if (pool === ZERO && premium !== 0n)
@@ -354,43 +399,101 @@ export function fundCalls(terms, opts = {}) {
354
399
  if (pool !== ZERO && terms.token.toLowerCase() !== BASE_GLMR.toLowerCase()) {
355
400
  throw new RangeError(`a covered job is a GLMR job: the hook covers in GLMR only (${BASE_GLMR}); fund an uncovered job (no pool) in ${terms.token}, or price the job in GLMR`);
356
401
  }
402
+ if (pool !== ZERO && premium === 0n)
403
+ throw new RangeError('a covered job pays a premium: the hook refuses a pool with premium 0 (CoverNotPaidFor)');
404
+ if (pool !== ZERO) {
405
+ if (opts.registeredPool === undefined)
406
+ throw new TypeError('fundCalls: a named pool is checked against PoolFactory.poolOf(seller, GLMR); read it (readHook / planFunding) and pass { registeredPool }');
407
+ if (!opts.registeredPool || opts.registeredPool.toLowerCase() !== pool.toLowerCase()) {
408
+ throw new RangeError(`pool ${pool} is not the factory's pool for seller ${terms.seller} (the factory names ${opts.registeredPool ?? 'none'})`);
409
+ }
410
+ }
357
411
  if (pool !== ZERO && opts.coverCap !== undefined && opts.coverCap > terms.price)
358
412
  throw new RangeError('the cover cap is at most the price (the hook caps cover at the price)');
359
413
  const approved = terms.price + premium;
360
414
  const approve = call(terms.token, selector(SIGNATURES.approve) + addrWord(BASE_ASSURANCE_HOOK) + word(approved), 'approve', 'buyer', `Lets the hook move exactly ${approved} of the token from you for this job${premium > 0n ? ` (${terms.price} price + ${premium} premium)` : ''}. Nothing moves until the job is funded. Exact amount, never a standing allowance.`);
361
415
  const common = b32Word(jobId) + addrWord(terms.seller) + addrWord(terms.token) + word(terms.price) + word(premium) + word(terms.deposit) + word(terms.deadline) + word(gradeWindow) + addrWord(pool);
362
416
  const withCover = pool !== ZERO && opts.coverCap !== undefined;
363
- const fund = call(BASE_ASSURANCE_HOOK, withCover ? selector(SIGNATURES.fundJobWithCover) + common + word(opts.coverCap) : selector(SIGNATURES.fundJob) + common, withCover ? 'fundJobWithCover' : 'fundJob', 'buyer', `Locks ${terms.price} in escrow from you and ${terms.deposit} from the seller, creating ${pool === ZERO ? 'uncovered' : 'covered'} job ${jobId.slice(0, 10)}…; deadline ${terms.deadline}. ${pool === ZERO ? 'No pool covers it; you complete or reject it yourself, or an evaluator the hook registered does.' : `Pool ${pool.slice(0, 10)}… covers it${withCover ? ` up to ${opts.coverCap}` : ' up to the price'} for a premium of ${premium}.`}`);
417
+ const ending = v31
418
+ ? `The seller must have approved you as a funder first, or the hook refuses the funding. Once the seller delivers you have ${gradeWindow} seconds to complete it; you have no reject, a hook evaluator may reject inside that window, and after it anyone may complete it (claimAutoComplete). Not delivered by the deadline, anyone may unwind it.`
419
+ : `${pool === ZERO ? 'No pool covers it; you complete or reject it yourself, or an evaluator the hook registered does.' : 'You complete or reject it yourself, or an evaluator the hook registered does.'} Past the deadline anyone may unwind it.`;
420
+ const fund = call(BASE_ASSURANCE_HOOK, withCover ? selector(SIGNATURES.fundJobWithCover) + common + word(opts.coverCap) : selector(SIGNATURES.fundJob) + common, withCover ? 'fundJobWithCover' : 'fundJob', 'buyer', `Locks ${terms.price} in escrow from you and ${terms.deposit} from the seller, creating ${pool === ZERO ? 'uncovered' : 'covered'} job ${jobId.slice(0, 10)}…; deadline ${terms.deadline}. ${pool === ZERO ? '' : `Pool ${pool.slice(0, 10)}… covers it${withCover ? ` up to ${opts.coverCap}` : ' up to the price'} for a premium of ${premium}. `}${ending}`);
364
421
  return [approve, fund];
365
422
  }
366
423
  /** The seller's call: submit(jobId, evidenceDigest) seals the digest on the hook. It does not release payment. */
367
424
  export function submitCalls(d) {
368
425
  return [call(BASE_ASSURANCE_HOOK, selector(SIGNATURES.submit) + b32Word(d.jobId) + b32Word(d.evidenceDigest), 'submit', 'seller', `Records that you delivered job ${d.jobId.slice(0, 10)}…, sealing evidence ${d.evidenceDigest.slice(0, 10)}… bound by correlator ${d.correlator.slice(0, 10)}…. It does not release payment.`)];
369
426
  }
427
+ export const JOB_STATES = ['None', 'Funded', 'Submitted', 'Completed', 'Expired', 'Rejected', 'Cheated'];
370
428
  /**
371
429
  * The call that settles a job under one of the four endings.
372
430
  * completed → complete(jobId), the buyer or a registered evaluator
373
- * rejected → reject(jobId, verdictDigest), the buyer or a registered evaluator; the digest is required
374
- * expired → expire(jobId), anyone, once the deadline has passed
431
+ * rejected → reject(jobId, verdictDigest); the digest is required, and so are the job's rules (`job`, from readHook):
432
+ * a job under V3 rules: the buyer or a registered evaluator, while it is Submitted;
433
+ * a job under V3.1 rules: the buyer has no reject. Only a hook evaluator rejects, inside the review window
434
+ * (`as: 'evaluator'`); otherwise the buyer completes, or the window passes and anyone calls claimAutoComplete
435
+ * expired → expire(jobId), anyone, once the deadline has passed; on a V3.1 job only while it is not yet delivered
375
436
  * cheat → refused here: an adjudicated cheat is posted through the judge adapter by a registered evaluator, and no adapter is deployed on Base
376
437
  */
377
- export function settleCalls(jobId, ending, verdictDigest) {
438
+ export function settleCalls(jobId, ending, verdictDigest, opts = {}) {
378
439
  if (!isHex32(jobId))
379
440
  throw new Error('jobId must be bytes32');
441
+ const job = opts.job;
442
+ if (job && job.jobId.toLowerCase() !== jobId.toLowerCase())
443
+ throw new Error(`the rules read are for job ${job.jobId}, not ${jobId}`);
380
444
  switch (ending) {
381
445
  case 'completed':
382
- return [call(BASE_ASSURANCE_HOOK, selector(SIGNATURES.complete) + b32Word(jobId), 'complete', 'buyer', ENDING_MONEY.completed + ' This is final.')];
383
- case 'rejected':
446
+ if (job && job.state !== 'Submitted')
447
+ throw new RangeError(`only a delivered (Submitted) job can be completed; this one is ${job.state}`);
448
+ return [call(BASE_ASSURANCE_HOOK, selector(SIGNATURES.complete) + b32Word(jobId), 'complete', opts.as ?? 'buyer', ENDING_MONEY.completed + ' This is final.')];
449
+ case 'rejected': {
384
450
  if (!verdictDigest || !isHex32(verdictDigest))
385
451
  throw new Error('a rejection carries the verdict digest it rests on');
386
- return [call(BASE_ASSURANCE_HOOK, selector(SIGNATURES.reject) + b32Word(jobId) + b32Word(verdictDigest), 'reject', 'buyer', ENDING_MONEY.rejected)];
452
+ if (!job)
453
+ throw new TypeError('settleCalls: a rejection depends on the job’s rules (a job funded under V3.1 has no buyer reject); read them with readHook({ jobId }) and pass { job }');
454
+ if (job.state !== 'Submitted')
455
+ throw new RangeError(`only a delivered (Submitted) job can be rejected; this one is ${job.state}`);
456
+ const data = selector(SIGNATURES.reject) + b32Word(jobId) + b32Word(verdictDigest);
457
+ if (job.rules === 'v3')
458
+ return [call(BASE_ASSURANCE_HOOK, data, 'reject', opts.as ?? 'buyer', ENDING_MONEY.rejected)];
459
+ if (opts.as !== 'evaluator') {
460
+ throw new RangeError('this job runs the V3.1 rules: the buyer has no reject. Complete it, or let the review window pass and anyone completes it (claimAutoComplete); only a hook evaluator may reject, inside the window');
461
+ }
462
+ if (opts.now !== undefined && job.autoCompleteAt !== null && opts.now >= job.autoCompleteAt)
463
+ throw new RangeError(`the review window closed at ${job.autoCompleteAt}: the job can only be completed now`);
464
+ return [call(BASE_ASSURANCE_HOOK, data, 'reject', 'evaluator', `${ENDING_MONEY.rejected} Only a hook evaluator can send it, and only before ${job.autoCompleteAt ?? 'the end of the review window'}.`)];
465
+ }
387
466
  case 'expired':
467
+ if (job && job.rules === 'v3.1' && job.state === 'Submitted')
468
+ throw new RangeError('a delivered job under the V3.1 rules does not expire: after its review window anyone completes it (claimAutoComplete)');
469
+ if (job && job.state !== 'Funded' && job.state !== 'Submitted')
470
+ throw new RangeError(`this job has ended (${job.state})`);
471
+ if (job && opts.now !== undefined && opts.now <= job.deadline)
472
+ throw new RangeError(`the deadline ${job.deadline} has not passed`);
388
473
  return [call(BASE_ASSURANCE_HOOK, selector(SIGNATURES.expire) + b32Word(jobId), 'expire', 'anyone', ENDING_MONEY.expired)];
389
474
  case 'cheat':
390
475
  throw new Error('an adjudicated cheat is posted through the judge adapter by a registered evaluator; no adapter is deployed on Base, so this module cannot build it');
391
476
  }
392
477
  }
393
- /** A refusal from the layer (either shape: see ./errors). An OnboardError is a CoordError: status, code, type, param, nextStep, body. */
478
+ /** V3.1: the review window of a delivered job has passed with no decision; anyone may send claimAutoComplete(jobId), which pays
479
+ * exactly as a completion. Refused for a job under the V3 rules (it has no window), for a job that is not delivered, and, with
480
+ * `now` (chain time), before the window ends. */
481
+ export function autoCompleteCalls(job, now) {
482
+ if (!isHex32(job.jobId))
483
+ throw new Error('jobId must be bytes32');
484
+ if (job.rules !== 'v3.1')
485
+ throw new RangeError('this job runs the V3 rules: it has no review window, so there is no auto-completion (the buyer completes, or past the deadline anyone unwinds it)');
486
+ if (job.state !== 'Submitted' || job.autoCompleteAt === null)
487
+ throw new RangeError(`only a delivered job completes on its own; this one is ${job.state}`);
488
+ if (now !== undefined && now < job.autoCompleteAt)
489
+ throw new RangeError(`the review window is open until ${job.autoCompleteAt}`);
490
+ return [call(BASE_ASSURANCE_HOOK, selector(SIGNATURES.claimAutoComplete) + b32Word(job.jobId), 'claimAutoComplete', 'anyone', `${ENDING_MONEY.completed} The review window has passed with no decision, so the delivery stands. Anyone may send it. This is final.`)];
491
+ }
492
+ /** V3.1: withdraw what an ending credited to you in `token` because its transfer to you failed (`claimable(token, you)`, from readHook). */
493
+ export function claimCalls(token) {
494
+ return [call(BASE_ASSURANCE_HOOK, selector(SIGNATURES.claim) + addrWord(token), 'claim', 'anyone', `Pays you what a job's ending credited to you in ${token} when the transfer to you failed. Only the credited account receives it.`)];
495
+ }
496
+ /** A refusal from Moonbeam (either shape: see ./errors). An OnboardError is a CoordError: status, code, type, param, nextStep, body. */
394
497
  export class OnboardError extends CoordError {
395
498
  constructor(status, message, body) { super(refusalOf(body ?? null, status, message)); this.name = 'OnboardError'; }
396
499
  }
@@ -424,7 +527,7 @@ const protocolOf = (kind, wireProtocol) => {
424
527
  return 'unknown';
425
528
  };
426
529
  const wireOf = (w) => (w === 'ready' || w === 'x402' || w === 'silent' || w === 'unreachable' ? w : 'unprobed');
427
- /** A registry row as the layer returns it, folded into a candidate. Exported so the fold is testable without a transport. */
530
+ /** A registry row as Moonbeam returns it, folded into a candidate. Exported so the fold is testable without a transport. */
428
531
  export function candidateFromRegistry(r, seenAt) {
429
532
  if (Number(r.chainId) !== 8453 || !isAddress(r.owner))
430
533
  return null;
@@ -494,7 +597,7 @@ export async function quote(t, c, ask) {
494
597
  const q = await post(t, '/assurance/quote', { chainId: 8453, seller: c.address, price: ask.price.toString() });
495
598
  return termsFromQuote(c, ask, q);
496
599
  }
497
- /** The fold behind `quote`, exported for tests. The deposit is the larger of the rule and what the layer requires. */
600
+ /** The fold behind `quote`, exported for tests. The deposit is the larger of the rule and what Moonbeam requires. */
498
601
  export function termsFromQuote(c, ask, q) {
499
602
  const required = q.terms?.depositRequired && /^\d+$/.test(q.terms.depositRequired) ? BigInt(q.terms.depositRequired) : 0n;
500
603
  const rule = depositFor(ask.price);
@@ -508,7 +611,7 @@ export async function judge(t, jobId, evidence, guard = {}) {
508
611
  const r = await post(t, '/judge/ref', { state: evidence.state, question: g.question, options: g.options, chainId: 8453, jobId, subject: jobId, source: 'moonbeam-onboard' });
509
612
  return decisionFromRef(r, g.bar);
510
613
  }
511
- /** The fold behind `judge`, exported for tests: the layer's reply to a JevDecision, ending decided against the bar. */
614
+ /** The fold behind `judge`, exported for tests: Moonbeam's reply to a JevDecision, ending decided against the bar. */
512
615
  export function decisionFromRef(r, bar = JEV_BAR) {
513
616
  const a = r.answer ?? r;
514
617
  const value = isJevOption(a.value) ? a.value : 'cannot_determine';
@@ -562,17 +665,223 @@ export * as readiness from '../onboarding/index.js';
562
665
  // ── the premium and the seller's deposit approval (0.7.0) ──────────────────────────────────────────────────────────────
563
666
  import { premiumAmount, wilsonUpperFailure } from '@taifoon/jev-wilson';
564
667
  /** The premium of a covered job, in the job's token units: price × the upper Wilson bound on the seller's failure rate
565
- * (k correct of n), floored exactly as the layer's pool quote computes it (jev-wilson). Pass it to fundCalls({ premium }). */
668
+ * (k correct of n), floored exactly as Moonbeam's pool quote computes it (jev-wilson). Pass it to fundCalls({ premium }). */
566
669
  export function coverPremium(price, record) {
567
670
  if (!(Number.isInteger(record.k) && Number.isInteger(record.n) && record.n >= 0 && record.k >= 0 && record.k <= record.n))
568
671
  throw new RangeError('a record is k correct of n settled, 0 ≤ k ≤ n');
569
672
  return premiumAmount(price, wilsonUpperFailure(record.k, record.n));
570
673
  }
571
- /** The seller's call before funding: approve the hook for exactly its deposit (the hook pulls it at fundJob). */
572
- export function sellerDepositCalls(terms) {
674
+ /**
675
+ * The seller's calls before funding, in order. On both hooks: approve the hook for exactly its deposit (the hook pulls it at
676
+ * fundJob). The rules decide what that allowance means, so pass them as read (`readHook`, or let `planFunding` do it):
677
+ * v3 (the live hook) the allowance is not bound to one buyer or one job: any funder may name this seller and spend it on
678
+ * terms of its own until it is spent, so the seller approves only when its buyer is about to fund, and revokes
679
+ * (approve 0) if the funding does not come.
680
+ * v3.1 the hook pulls the deposit only for the seller itself or a funder the seller approved, so the seller also signs
681
+ * approveFunder(funder, true) for its buyer (`funder`). The approval names the funder, not the terms, and stays until
682
+ * the seller revokes it (`revokeFunderCalls`): revoke it after the funding unless the seller wants that buyer to open
683
+ * more jobs. `funderApproved: true` (read) leaves the call out.
684
+ * Without `rules` the live hook's (v3) calls are built.
685
+ */
686
+ export function sellerDepositCalls(terms, opts = {}) {
573
687
  const d = checkDeposit(terms.price, terms.deposit);
574
688
  if (!d.ok)
575
689
  throw new RangeError(d.reason);
576
- return [call(terms.token, selector(SIGNATURES.approve) + addrWord(BASE_ASSURANCE_HOOK) + word(terms.deposit), 'approve-deposit', 'seller', `Lets the hook take exactly your ${terms.deposit} deposit when the job is funded; it comes back with the price when the job completes. Exact amount, never a standing allowance.`)];
690
+ const data = selector(SIGNATURES.approve) + addrWord(BASE_ASSURANCE_HOOK) + word(terms.deposit);
691
+ if (opts.rules !== 'v3.1') {
692
+ return [call(terms.token, data, 'approve-deposit', 'seller', `Lets the hook take exactly your ${terms.deposit} deposit at funding; it comes back with the price when the job completes. The hook does not tie this allowance to your buyer: until it is spent, anyone funding a job that names you can use it. Approve only when your buyer is about to fund, and set it back to 0 if the funding does not come.`)];
693
+ }
694
+ if (!opts.funder || !isAddress(opts.funder))
695
+ throw new RangeError('on this hook the seller approves its buyer as a funder: pass { funder } (the address that sends the funding)');
696
+ const out = [call(terms.token, data, 'approve-deposit', 'seller', `Lets the hook take exactly your ${terms.deposit} deposit at funding; it comes back with the price when the job completes. The hook takes it only for a job you or a funder you approved opens. Exact amount, never a standing allowance.`)];
697
+ if (opts.funderApproved !== true)
698
+ out.push(...approveFunderCalls(opts.funder));
699
+ return out;
577
700
  }
701
+ /** V3.1: approveFunder(funder, true). The funder may open jobs that pull your deposit (up to your allowance to the hook, each
702
+ * with a deadline at most 365 days out) until you revoke it. */
703
+ export function approveFunderCalls(funder) {
704
+ return [call(BASE_ASSURANCE_HOOK, selector(SIGNATURES.approveFunder) + addrWord(funder) + word(1n), 'approve-funder', 'seller', `Lets ${funder} open jobs that pull your deposit, up to what you approved the hook for. It names the funder, not the terms, and stays until you revoke it (approveFunder(${funder.slice(0, 10)}…, false)).`)];
705
+ }
706
+ /** V3.1: approveFunder(funder, false). Stops the funder opening new jobs against your deposit; jobs it already funded are unchanged. */
707
+ export function revokeFunderCalls(funder) {
708
+ return [call(BASE_ASSURANCE_HOOK, selector(SIGNATURES.approveFunder) + addrWord(funder) + word(0n), 'revoke-funder', 'seller', `Stops ${funder} opening new jobs that pull your deposit. Jobs it already funded are not changed.`)];
709
+ }
710
+ // ── The hook's rules, by read (the live V3 hook and its V3.1 upgrade) ─────────────────────────────────────────────────────
711
+ // Which rules apply is read from the chain, never assumed: V3.1 answers poolFactory() and MAX_DEADLINE(); V3 has neither (and
712
+ // no fallback), so both calls revert there. Every fact below comes from ONE eth_call: Multicall3.aggregate3 with allowFailure.
713
+ /** Multicall3, the same address on Base and most EVM chains. */
714
+ export const MULTICALL3 = '0xcA11bde05977b3631167028862bE2a173976CA11';
715
+ /** The views read, by signature. */
716
+ export const HOOK_READS = Object.freeze({
717
+ poolFactory: 'poolFactory()',
718
+ maxDeadline: 'MAX_DEADLINE()',
719
+ reviewOf: 'reviewOf(bytes32)',
720
+ jobs: 'jobs(bytes32)',
721
+ funderApproved: 'funderApproved(address,address)',
722
+ claimable: 'claimable(address,address)',
723
+ poolOf: 'poolOf(address,address)',
724
+ allowance: 'allowance(address,address)',
725
+ blockTimestamp: 'getCurrentBlockTimestamp()',
726
+ aggregate3: 'aggregate3((address,bool,bytes)[])',
727
+ });
728
+ const padHex = (h) => h.padEnd(Math.ceil(h.length / 64) * 64, '0');
729
+ /** aggregate3 calldata for calls that may each fail (allowFailure = true) */
730
+ export function encodeAggregate3(calls) {
731
+ const elems = calls.map((c) => { const d = c.data.replace(/^0x/, ''); return addrWord(c.target) + word(1n) + word(96n) + word(BigInt(d.length / 2)) + padHex(d); });
732
+ let offsets = '';
733
+ let at = calls.length * 32;
734
+ for (const e of elems) {
735
+ offsets += word(BigInt(at));
736
+ at += e.length / 2;
737
+ }
738
+ return (selector(HOOK_READS.aggregate3) + word(32n) + word(BigInt(calls.length)) + offsets + elems.join(''));
739
+ }
740
+ /** aggregate3's return: (bool success, bytes returnData)[] */
741
+ export function decodeAggregate3(ret) {
742
+ const h = ret.replace(/^0x/, '');
743
+ const num = (byte) => { const w = h.slice(byte * 2, byte * 2 + 64); if (w.length < 64)
744
+ throw new Error('aggregate3: the answer is too short'); const v = BigInt(`0x${w}`); if (v > BigInt(h.length))
745
+ throw new Error('aggregate3: an offset points outside the answer'); return Number(v); };
746
+ const arr = num(0);
747
+ const n = num(arr);
748
+ const base = arr + 32;
749
+ const out = [];
750
+ for (let i = 0; i < n; i++) {
751
+ const e = base + num(base + i * 32);
752
+ const success = BigInt(`0x${h.slice(e * 2, e * 2 + 64)}`) !== 0n;
753
+ const bo = e + num(e + 32);
754
+ const len = num(bo);
755
+ if ((bo + 32 + len) * 2 > h.length)
756
+ throw new Error('aggregate3: return data runs past the answer');
757
+ out.push({ success, data: `0x${h.slice((bo + 32) * 2, (bo + 32 + len) * 2)}` });
758
+ }
759
+ return out;
760
+ }
761
+ const wordAt = (data, i) => { const w = data.slice(2 + i * 64, 2 + i * 64 + 64); return w.length === 64 ? BigInt(`0x${w}`) : null; };
762
+ const addrOf = (v) => `0x${v.toString(16).padStart(40, '0')}`;
763
+ /**
764
+ * Read which rules the hook runs and the facts a call needs, in one eth_call (Multicall3.aggregate3):
765
+ * always poolFactory(), MAX_DEADLINE() (both revert on V3) and the chain's time
766
+ * seller PoolFactory.poolOf(seller, asset ?? GLMR); with `funder`, funderApproved(seller, funder); with `token`, the
767
+ * seller's allowance of that token to the hook
768
+ * jobId jobs(jobId) and reviewOf(jobId): the job's state, deadline and (V3.1) review window
769
+ * account with `token`, claimable(token, account) (V3.1)
770
+ * Throws when the read fails (no answer is never read as V3), when the hook answers as neither V3 nor V3.1, and when a V3.1 hook
771
+ * names a pool factory other than the one this SDK ships (or `factory`).
772
+ */
773
+ export async function readHook(r, q = {}) {
774
+ const hook = q.hook ?? BASE_ASSURANCE_HOOK;
775
+ const factory = q.factory ?? BASE_POOL_FACTORY;
776
+ for (const [k, v] of Object.entries({ hook, factory, seller: q.seller, asset: q.asset, funder: q.funder, token: q.token, account: q.account }))
777
+ if (v !== undefined && !isAddress(v))
778
+ throw new Error(`readHook: ${k} is not an address: ${v}`);
779
+ if (q.jobId !== undefined && !isHex32(q.jobId))
780
+ throw new Error('readHook: jobId must be bytes32');
781
+ const calls = [
782
+ { key: 'poolFactory', target: hook, data: selector(HOOK_READS.poolFactory) },
783
+ { key: 'maxDeadline', target: hook, data: selector(HOOK_READS.maxDeadline) },
784
+ { key: 'time', target: MULTICALL3, data: selector(HOOK_READS.blockTimestamp) },
785
+ ];
786
+ if (q.seller) {
787
+ calls.push({ key: 'poolOf', target: factory, data: (selector(HOOK_READS.poolOf) + addrWord(q.seller) + addrWord(q.asset ?? BASE_GLMR)) });
788
+ if (q.funder)
789
+ calls.push({ key: 'funderApproved', target: hook, data: (selector(HOOK_READS.funderApproved) + addrWord(q.seller) + addrWord(q.funder)) });
790
+ if (q.token)
791
+ calls.push({ key: 'allowance', target: q.token, data: (selector(HOOK_READS.allowance) + addrWord(q.seller) + addrWord(hook)) });
792
+ }
793
+ if (q.jobId) {
794
+ calls.push({ key: 'jobs', target: hook, data: (selector(HOOK_READS.jobs) + b32Word(q.jobId)) });
795
+ calls.push({ key: 'reviewOf', target: hook, data: (selector(HOOK_READS.reviewOf) + b32Word(q.jobId)) });
796
+ }
797
+ if (q.account && q.token)
798
+ calls.push({ key: 'claimable', target: hook, data: (selector(HOOK_READS.claimable) + addrWord(q.token) + addrWord(q.account)) });
799
+ const ret = await r.call('eth_call', [{ to: MULTICALL3, data: encodeAggregate3(calls) }, q.block ?? 'latest']);
800
+ if (typeof ret !== 'string' || !/^0x[0-9a-fA-F]*$/.test(ret) || ret.length < 130)
801
+ throw new Error('readHook: the read returned no answer');
802
+ const res = decodeAggregate3(ret);
803
+ if (res.length !== calls.length)
804
+ throw new Error(`readHook: ${calls.length} reads sent, ${res.length} answered`);
805
+ const got = (k) => { const i = calls.findIndex((c) => c.key === k); const x = i >= 0 ? res[i] : null; return x && x.success && x.data.length >= 66 ? x.data : null; };
806
+ const pf = got('poolFactory');
807
+ const md = got('maxDeadline');
808
+ const t = got('time');
809
+ if (!t)
810
+ throw new Error('readHook: the chain time did not read (is Multicall3 deployed here?)');
811
+ if ((pf === null) !== (md === null))
812
+ throw new Error('readHook: the hook answers neither as V3 (no poolFactory, no MAX_DEADLINE) nor as V3.1 (both)');
813
+ const rules = pf ? 'v3.1' : 'v3';
814
+ let poolFactory = factory;
815
+ if (pf) {
816
+ const named = addrOf(wordAt(pf, 0));
817
+ if (named === ZERO)
818
+ throw new Error('readHook: the hook runs V3.1 but names no pool factory (initializeV31 never ran): every covered funding would revert');
819
+ if (named.toLowerCase() !== factory.toLowerCase())
820
+ throw new Error(`readHook: the hook takes pools from factory ${named}, not ${factory}; pass { factory } once that factory is known`);
821
+ poolFactory = named;
822
+ }
823
+ const facts = { hook, rules, poolFactory, maxDeadline: md ? Number(wordAt(md, 0)) : null, blockTime: Number(wordAt(t, 0)) };
824
+ if (q.seller) {
825
+ const p = got('poolOf');
826
+ if (p === null)
827
+ throw new Error(`readHook: PoolFactory.poolOf did not read on ${factory}`);
828
+ const pa = addrOf(wordAt(p, 0));
829
+ facts.registeredPool = pa === ZERO ? null : pa;
830
+ if (q.funder) {
831
+ const f = got('funderApproved');
832
+ facts.funderApproved = rules === 'v3.1' ? (f ? wordAt(f, 0) !== 0n : (() => { throw new Error('readHook: funderApproved did not read on a V3.1 hook'); })()) : null;
833
+ }
834
+ if (q.token) {
835
+ const a = got('allowance');
836
+ facts.depositAllowance = a ? wordAt(a, 0) : null;
837
+ }
838
+ }
839
+ if (q.jobId) {
840
+ const j = got('jobs');
841
+ if (j === null || j.length < 2 + 10 * 64)
842
+ throw new Error('readHook: jobs(jobId) did not read');
843
+ const stateN = Number(wordAt(j, 9));
844
+ const state = JOB_STATES[stateN];
845
+ if (!state)
846
+ throw new Error(`readHook: unknown job state ${stateN}`);
847
+ const rv = rules === 'v3.1' ? got('reviewOf') : null;
848
+ if (rules === 'v3.1' && rv === null)
849
+ throw new Error('readHook: reviewOf did not read on a V3.1 hook');
850
+ const window = rv ? Number(wordAt(rv, 0)) : 0;
851
+ const submittedAt = rv ? Number(wordAt(rv, 1) ?? 0n) : 0;
852
+ const v31Job = rules === 'v3.1' && window !== 0;
853
+ facts.job = { jobId: q.jobId, rules: v31Job ? 'v3.1' : 'v3', state, window: v31Job ? window : 0, submittedAt: v31Job ? submittedAt : 0,
854
+ autoCompleteAt: v31Job && submittedAt > 0 ? submittedAt + window : null, deadline: Number(wordAt(j, 6)) };
855
+ }
856
+ if (q.account && q.token) {
857
+ const c = got('claimable');
858
+ facts.claimable = rules === 'v3.1' ? (c ? wordAt(c, 0) : null) : null;
859
+ }
860
+ return facts;
861
+ }
862
+ /**
863
+ * Plan one funding from the chain's own answer: read the rules, the factory's pool for the seller, whether the seller approved
864
+ * this buyer as a funder, the seller's outstanding allowance and the chain's time (one eth_call), then build the seller's and
865
+ * the buyer's calls for exactly those rules. The job id is salted with fresh random bytes unless a jobId is passed: an id
866
+ * nobody can derive from the terms cannot be funded first by someone else. On a JobExists refusal, plan again (a new salt).
867
+ */
868
+ export async function planFunding(r, terms, opts = {}) {
869
+ if (!isAddress(terms.buyer) || terms.buyer.toLowerCase() === ZERO)
870
+ throw new RangeError('planFunding: the terms name no buyer (the address that sends the funding)');
871
+ const facts = await readHook(r, { seller: terms.seller, asset: BASE_GLMR, funder: terms.buyer, token: terms.token });
872
+ const salt = opts.jobId !== undefined ? null : (opts.salt ?? newJobSalt());
873
+ const buyer = fundCalls(terms, { ...opts, ...(salt ? { salt } : {}), ...(opts.pool ? { registeredPool: facts.registeredPool ?? null } : {}), rules: facts.rules, now: facts.blockTime });
874
+ const jobId = opts.jobId ?? jobIdOf(terms, salt ?? undefined);
875
+ const self = terms.buyer.toLowerCase() === terms.seller.toLowerCase();
876
+ const seller = sellerDepositCalls(terms, { rules: facts.rules, funder: terms.buyer, funderApproved: self || facts.funderApproved === true });
877
+ const notes = [];
878
+ if (facts.rules === 'v3')
879
+ notes.push('The hook runs the V3 rules: the seller’s allowance can be spent by any funder that names it, so the seller approves in the block before the funding, or revokes it.');
880
+ else
881
+ notes.push(facts.funderApproved || self ? 'The seller has already approved this buyer as a funder.' : 'The seller approves this buyer as a funder (approveFunder) before the buyer funds; it may revoke it after.');
882
+ if (facts.depositAllowance && facts.depositAllowance > 0n)
883
+ notes.push(`The seller already allows the hook ${facts.depositAllowance} of the token; its approve-deposit sets that to exactly ${terms.deposit}.`);
884
+ return { rules: facts.rules, jobId, salt, seller, buyer, facts, notes };
885
+ }
886
+ export { sendCalls, assertCallChain, ChainMismatchError } from './send.js';
578
887
  //# sourceMappingURL=index.js.map