@t3foundry/tasra-sdk 0.3.1-next.1 → 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.
Files changed (255) hide show
  1. package/CHANGELOG.md +1067 -28
  2. package/README.md +15 -0
  3. package/dist/app/approvals.d.ts +66 -4
  4. package/dist/app/approvals.js +153 -16
  5. package/dist/app/authorization.d.ts +1 -1
  6. package/dist/app/authorization.js +1 -1
  7. package/dist/app/browser.d.ts +63 -0
  8. package/dist/app/browser.js +242 -0
  9. package/dist/app/client.d.ts +114 -13
  10. package/dist/app/client.js +302 -76
  11. package/dist/app/identity.js +21 -9
  12. package/dist/app/index.d.ts +28 -3
  13. package/dist/app/index.js +16 -1
  14. package/dist/app/memory-store.d.ts +7 -0
  15. package/dist/app/memory-store.js +55 -0
  16. package/dist/app/node.d.ts +34 -6
  17. package/dist/app/node.js +387 -64
  18. package/dist/app/paid-allowance.d.ts +325 -0
  19. package/dist/app/paid-allowance.js +1290 -0
  20. package/dist/app/paid-approval.d.ts +122 -0
  21. package/dist/app/paid-approval.js +379 -0
  22. package/dist/app/paid-journal.d.ts +51 -0
  23. package/dist/app/paid-journal.js +117 -0
  24. package/dist/app/paid-keys.d.ts +12 -0
  25. package/dist/app/paid-keys.js +20 -0
  26. package/dist/app/paid-operation.d.ts +821 -0
  27. package/dist/app/paid-operation.js +1720 -0
  28. package/dist/app/paid-reservation.d.ts +157 -0
  29. package/dist/app/paid-reservation.js +323 -0
  30. package/dist/app/paid-session.d.ts +147 -0
  31. package/dist/app/paid-session.js +578 -0
  32. package/dist/app/payer-queue.d.ts +11 -0
  33. package/dist/app/payer-queue.js +27 -0
  34. package/dist/app/policy-bootstrap.d.ts +342 -0
  35. package/dist/app/policy-bootstrap.js +365 -0
  36. package/dist/app/policy-operation.d.ts +47 -0
  37. package/dist/app/policy-operation.js +101 -0
  38. package/dist/app/ready-slot.d.ts +12 -0
  39. package/dist/app/ready-slot.js +5 -2
  40. package/dist/app/rotation-lock.d.ts +38 -0
  41. package/dist/app/rotation-lock.js +42 -0
  42. package/dist/app/session-decrypt.d.ts +135 -0
  43. package/dist/app/session-decrypt.js +335 -0
  44. package/dist/app/session-grants.d.ts +349 -0
  45. package/dist/app/session-grants.js +811 -0
  46. package/dist/app/signing-intents.d.ts +78 -0
  47. package/dist/app/signing-intents.js +95 -0
  48. package/dist/app/store-commit.d.ts +63 -0
  49. package/dist/app/store-commit.js +126 -0
  50. package/dist/app/store-errors.d.ts +8 -0
  51. package/dist/app/store-errors.js +11 -0
  52. package/dist/app/tasra-client.d.ts +2 -0
  53. package/dist/app/tasra-client.js +1 -1
  54. package/dist/app/wallet.js +4 -1
  55. package/dist/auth/holderProof.d.ts +3 -0
  56. package/dist/auth/holderProof.js +8 -7
  57. package/dist/auth/verifier.d.ts +4 -2
  58. package/dist/auth/verifier.js +5 -2
  59. package/dist/chain/abis/index.d.ts +6178 -4101
  60. package/dist/chain/abis/index.js +3 -0
  61. package/dist/chain/abis/keyRegistry.d.ts +256 -0
  62. package/dist/chain/abis/keyRegistry.js +333 -0
  63. package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
  64. package/dist/chain/abis/prepaidFaultOracle.js +413 -0
  65. package/dist/chain/abis/settlement.d.ts +2203 -703
  66. package/dist/chain/abis/settlement.js +2685 -764
  67. package/dist/chain/allowance.d.ts +358 -0
  68. package/dist/chain/allowance.js +800 -0
  69. package/dist/chain/billing.d.ts +85 -0
  70. package/dist/chain/billing.js +197 -0
  71. package/dist/chain/chainId.d.ts +13 -0
  72. package/dist/chain/chainId.js +26 -0
  73. package/dist/chain/client.d.ts +15 -1
  74. package/dist/chain/client.js +57 -1
  75. package/dist/chain/commitmentRecovery.d.ts +51 -0
  76. package/dist/chain/commitmentRecovery.js +38 -0
  77. package/dist/chain/committeeClient.d.ts +17 -10
  78. package/dist/chain/committeeClient.js +64 -16
  79. package/dist/chain/committeeDraw.d.ts +12 -0
  80. package/dist/chain/committeeDraw.js +56 -0
  81. package/dist/chain/custodyHealth.d.ts +212 -0
  82. package/dist/chain/custodyHealth.js +365 -0
  83. package/dist/chain/deployments.js +2 -0
  84. package/dist/chain/events.js +2 -0
  85. package/dist/chain/headFollower.d.ts +77 -0
  86. package/dist/chain/headFollower.js +219 -0
  87. package/dist/chain/headPrefetch.d.ts +23 -0
  88. package/dist/chain/headPrefetch.js +67 -0
  89. package/dist/chain/index.d.ts +50 -8
  90. package/dist/chain/index.js +28 -3
  91. package/dist/chain/keeperExecution.d.ts +44 -0
  92. package/dist/chain/keeperExecution.js +127 -0
  93. package/dist/chain/keeperRecovery.d.ts +78 -0
  94. package/dist/chain/keeperRecovery.js +91 -0
  95. package/dist/chain/node.d.ts +24 -1
  96. package/dist/chain/node.js +88 -43
  97. package/dist/chain/offchain.d.ts +2 -0
  98. package/dist/chain/paidAgentTransport.d.ts +38 -0
  99. package/dist/chain/paidAgentTransport.js +1 -0
  100. package/dist/chain/paidEpoch.d.ts +66 -0
  101. package/dist/chain/paidEpoch.js +139 -0
  102. package/dist/chain/paidPacing.d.ts +81 -0
  103. package/dist/chain/paidPacing.js +136 -0
  104. package/dist/chain/pinnedReads.d.ts +49 -0
  105. package/dist/chain/pinnedReads.js +218 -0
  106. package/dist/chain/prepaid.d.ts +383 -0
  107. package/dist/chain/prepaid.js +1046 -0
  108. package/dist/chain/prepaidEscape.d.ts +274 -0
  109. package/dist/chain/prepaidEscape.js +432 -0
  110. package/dist/chain/prepaidFault.d.ts +94 -0
  111. package/dist/chain/prepaidFault.js +148 -0
  112. package/dist/chain/receipt.d.ts +24 -0
  113. package/dist/chain/receipt.js +82 -0
  114. package/dist/chain/registeredAgent.d.ts +68 -3
  115. package/dist/chain/registeredAgent.js +143 -42
  116. package/dist/chain/registeredOperation.d.ts +10 -1
  117. package/dist/chain/registeredOperation.js +18 -3
  118. package/dist/chain/registeredPaidAgent.d.ts +254 -0
  119. package/dist/chain/registeredPaidAgent.js +889 -0
  120. package/dist/chain/registeredRelay.d.ts +31 -1
  121. package/dist/chain/registeredRelay.js +164 -43
  122. package/dist/chain/relayVoucher.d.ts +64 -0
  123. package/dist/chain/relayVoucher.js +69 -0
  124. package/dist/chain/reservation.d.ts +239 -0
  125. package/dist/chain/reservation.js +746 -0
  126. package/dist/chain/reshareRoster.d.ts +64 -0
  127. package/dist/chain/reshareRoster.js +85 -0
  128. package/dist/chain/revertReason.d.ts +8 -0
  129. package/dist/chain/revertReason.js +2 -1
  130. package/dist/chain/rotationLock.d.ts +130 -0
  131. package/dist/chain/rotationLock.js +168 -0
  132. package/dist/chain/serviceRequestPolicy.d.ts +47 -0
  133. package/dist/chain/serviceRequestPolicy.js +86 -0
  134. package/dist/chain/services.d.ts +7 -0
  135. package/dist/chain/services.js +44 -4
  136. package/dist/chain/slotClient.js +11 -2
  137. package/dist/chain/slotHandoff.d.ts +81 -0
  138. package/dist/chain/slotHandoff.js +166 -0
  139. package/dist/chain/slotSeed.d.ts +47 -5
  140. package/dist/chain/slotSeed.js +173 -42
  141. package/dist/chain/verifierSnapshot.d.ts +36 -0
  142. package/dist/chain/verifierSnapshot.js +197 -0
  143. package/dist/chain/write.d.ts +111 -21
  144. package/dist/chain/write.js +378 -146
  145. package/dist/committee/blsSharing.d.ts +53 -0
  146. package/dist/committee/blsSharing.js +90 -0
  147. package/dist/committee/client.d.ts +62 -23
  148. package/dist/committee/client.js +288 -72
  149. package/dist/committee/dual-operation.d.ts +165 -0
  150. package/dist/committee/dual-operation.js +229 -0
  151. package/dist/committee/dual-sign.d.ts +26 -1
  152. package/dist/committee/dual-sign.js +85 -7
  153. package/dist/committee/ecdsa.d.ts +38 -0
  154. package/dist/committee/ecdsa.js +87 -15
  155. package/dist/committee/evidence.d.ts +30 -0
  156. package/dist/committee/evidence.js +65 -0
  157. package/dist/committee/execution.d.ts +414 -0
  158. package/dist/committee/execution.js +446 -0
  159. package/dist/committee/extraction.js +33 -26
  160. package/dist/committee/index.d.ts +30 -7
  161. package/dist/committee/index.js +18 -6
  162. package/dist/committee/keeperExecution.d.ts +37 -0
  163. package/dist/committee/keeperExecution.js +141 -0
  164. package/dist/committee/oauth.d.ts +14 -4
  165. package/dist/committee/oauth.js +17 -5
  166. package/dist/committee/payment.d.ts +369 -0
  167. package/dist/committee/payment.js +339 -0
  168. package/dist/committee/recovery.d.ts +136 -0
  169. package/dist/committee/recovery.js +204 -0
  170. package/dist/committee/recoveryJson.d.ts +2 -0
  171. package/dist/committee/recoveryJson.js +87 -0
  172. package/dist/committee/request.d.ts +63 -27
  173. package/dist/committee/request.js +77 -66
  174. package/dist/committee/session-grant.d.ts +320 -0
  175. package/dist/committee/session-grant.js +397 -0
  176. package/dist/committee/status-refresh.d.ts +257 -0
  177. package/dist/committee/status-refresh.js +619 -0
  178. package/dist/committee/token.d.ts +163 -15
  179. package/dist/committee/token.js +247 -10
  180. package/dist/crypto/bn254.d.ts +70 -0
  181. package/dist/crypto/bn254.js +222 -0
  182. package/dist/crypto/ibe.d.ts +32 -0
  183. package/dist/crypto/ibe.js +56 -8
  184. package/dist/crypto/index.d.ts +1 -1
  185. package/dist/crypto/index.js +1 -1
  186. package/dist/crypto/kem.d.ts +31 -0
  187. package/dist/crypto/kem.js +113 -7
  188. package/dist/crypto/recipient.d.ts +75 -0
  189. package/dist/crypto/recipient.js +107 -0
  190. package/dist/decryption/client.d.ts +10 -16
  191. package/dist/decryption/client.js +8 -76
  192. package/dist/decryption/index.d.ts +2 -0
  193. package/dist/decryption/index.js +2 -0
  194. package/dist/decryption/sealed.d.ts +72 -0
  195. package/dist/decryption/sealed.js +147 -0
  196. package/dist/decryption/session.d.ts +115 -0
  197. package/dist/decryption/session.js +358 -0
  198. package/dist/errors.d.ts +406 -1
  199. package/dist/errors.js +400 -5
  200. package/dist/index.d.ts +9 -2
  201. package/dist/index.js +6 -1
  202. package/dist/internal/bounded.d.ts +66 -0
  203. package/dist/internal/bounded.js +126 -0
  204. package/dist/internal/network.d.ts +4 -0
  205. package/dist/internal/network.js +40 -0
  206. package/dist/internal/retryAfter.d.ts +8 -0
  207. package/dist/internal/retryAfter.js +28 -0
  208. package/dist/internal/sleep.d.ts +6 -0
  209. package/dist/internal/sleep.js +15 -0
  210. package/dist/internal/typedData.d.ts +13 -0
  211. package/dist/internal/typedData.js +77 -0
  212. package/dist/internal/viemErrors.d.ts +26 -0
  213. package/dist/internal/viemErrors.js +49 -0
  214. package/dist/oid4vp/binding.d.ts +27 -1
  215. package/dist/oid4vp/binding.js +36 -1
  216. package/dist/oid4vp/jose.d.ts +4 -2
  217. package/dist/oid4vp/jose.js +39 -7
  218. package/dist/oid4vp/request-object.d.ts +61 -4
  219. package/dist/oid4vp/request-object.js +140 -5
  220. package/dist/oid4vp/verifier-agent.d.ts +18 -8
  221. package/dist/oid4vp/verifier-agent.js +48 -6
  222. package/dist/oid4vp/wallet.d.ts +2 -4
  223. package/dist/oid4vp/wallet.js +1 -0
  224. package/dist/retry.d.ts +78 -0
  225. package/dist/retry.js +137 -0
  226. package/dist/signing/frost.d.ts +1 -1
  227. package/dist/verifier-agent/index.d.ts +41 -5
  228. package/dist/verifier-agent/index.js +124 -9
  229. package/dist/verifier-agent/payment.d.ts +7 -0
  230. package/dist/verifier-agent/payment.js +17 -0
  231. package/docs/api.md +8 -2
  232. package/docs/application-api.md +25 -2
  233. package/docs/chain.md +155 -9
  234. package/docs/consumer-migrations.md +61 -0
  235. package/docs/encrypted-notes.md +3 -2
  236. package/docs/encryption.md +4 -2
  237. package/docs/errors.md +14 -1
  238. package/docs/flows.md +2 -2
  239. package/docs/funding.md +902 -0
  240. package/docs/native-approvals.md +63 -0
  241. package/docs/reference/README.md +9 -8
  242. package/docs/reference/app-browser.md +232 -0
  243. package/docs/reference/app-node.md +38 -8
  244. package/docs/reference/app.md +4621 -805
  245. package/docs/reference/chain-node.md +74 -16
  246. package/docs/reference/chain.md +6740 -1592
  247. package/docs/reference/committee.md +5630 -987
  248. package/docs/reference/main.md +1439 -140
  249. package/docs/reference/oid4vp.md +297 -144
  250. package/docs/reference/verifier-agent.md +77 -35
  251. package/docs/signing.md +6 -0
  252. package/examples/encrypted-notes.ts +21 -6
  253. package/examples/getting-started.ts +2 -7
  254. package/examples/live-config.ts +24 -17
  255. package/package.json +17 -5
@@ -0,0 +1,800 @@
1
+ // ADR-0090 D1/D2, client side: reserve a prepaid ALLOWANCE once (one on-chain transaction, an
2
+ // accountant-quorum authorization over a creator-signed `SlotPrepaidAllowanceIntent`), then obtain
3
+ // one accountant-quorum DEBIT VOUCHER per operation instead of a per-operation reservation.
4
+ //
5
+ // The reservation mirrors `reservePaidOperation` (reservation.ts): one quote collected across the
6
+ // responsive members, the same `prepared` / `submitted` / `confirmed` durable checkpoints, exactly
7
+ // one broadcast, the short-interval receipt waiter, and every observation pinned to the quote
8
+ // block. An allowance is fixed-amount: a top-up is a NEW allowance (a new intent nonce).
9
+ //
10
+ // A voucher round sends the same debit request to every accountant in parallel at ONE quote block
11
+ // the caller fixes (journaled before the round, so a retry reuses it), verifies each member's BN254
12
+ // partial against its verifying share, Lagrange-combines `k` of them and verifies the aggregate
13
+ // against `beacon.mpk()` read at that quote block. Nothing here is sent to a keeper.
14
+ //
15
+ // Capability discovery: the network exposes none for allowances (an accountant that has the
16
+ // writer switched off answers 503 "allowance reservations are not enabled"); the SDK path is
17
+ // enabled only by an explicit application option (`PaidOperationConfig.allowances`).
18
+ import { decodeFunctionResult, encodeFunctionData, keccak256, parseTransaction, recoverTransactionAddress, recoverTypedDataAddress, toHex } from 'viem';
19
+ import { settlementAbi } from './abis/settlement.js';
20
+ import { keyRegistryAbi } from './abis/keyRegistry.js';
21
+ import { thresholdRandomBeaconAbi } from './abis/thresholdRandomBeacon.js';
22
+ import { allowanceId, allowanceReserveDigest, assertDebitVoucherWire, assertPaymentIntentWire, debitVoucherDigest, prepaidAllowanceIntentHash, prepaidAllowanceIntentTypedData, prepaidRequestId } from '../committee/payment.js';
23
+ import { accountantEndpoints, PaidReservationQuorumNotPreparedError, PaidReservationUncertainError, untilAborted } from './reservation.js';
24
+ import { headFollowerOf } from './headFollower.js';
25
+ import { pollTransactionReceipt } from './receipt.js';
26
+ import { pinnedCall } from './pinnedReads.js';
27
+ import { chainIdOf } from './chainId.js';
28
+ import { UnderfundedGasPayerError, UnderfundedSlotError } from '../errors.js';
29
+ import { interpolateBn254, verifyBn254 } from '../crypto/bn254.js';
30
+ import { bytesToHex, hexToBytes } from '../crypto/hex.js';
31
+ const HEX32 = /^0x[0-9a-f]{64}$/i;
32
+ const ZERO32 = `0x${'0'.repeat(64)}`;
33
+ const MAX_BODY = 64 * 1024;
34
+ /** Quote freshness the accountants enforce (`MAX_QUOTE_AGE`). */
35
+ export const ALLOWANCE_QUOTE_MAX_AGE_SECS = 30;
36
+ /** `PAYMENT_INTENT_MAX_LIFETIME_SECS`: an allowance lives at most one hour. */
37
+ export const ALLOWANCE_MAX_LIFETIME_SECS = 3600;
38
+ const now = () => Math.floor(Date.now() / 1000);
39
+ const same = (a, b) => a.toLowerCase() === b.toLowerCase();
40
+ /** An accountant was unreachable or answered 5xx/408/429: another member may still answer. */
41
+ class Unavailable extends Error {
42
+ /** The answer recorded nothing (the pre-write 503 or a stale named block): asked again at the seed block. */
43
+ preWrite = false;
44
+ /** The member's RPC has not served the named block yet: asked again at the seed block. */
45
+ notYetVisible = false;
46
+ }
47
+ /** A definite 403/409 to a `prepare`, judged before the accountant records anything: that member's answer (402 is {@link UnderfundedSlotError}). */
48
+ class AllowanceRefusedError extends Error {
49
+ }
50
+ const labelled = (text, label) => {
51
+ const t = text.trimStart();
52
+ return t.startsWith(label) && (t.length === label.length || t[label.length] === ':');
53
+ };
54
+ /** A bounded JSON POST to one accountant; non-2xx answers carry their status and a bounded reason. */
55
+ async function post(url, body, timeoutMs, signal) {
56
+ const deadline = AbortSignal.timeout(timeoutMs);
57
+ let response;
58
+ try {
59
+ response = await fetch(url, { method: 'POST', redirect: 'error', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
60
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline });
61
+ }
62
+ catch (cause) {
63
+ signal?.throwIfAborted();
64
+ throw new Unavailable('accountant transport unavailable', { cause });
65
+ }
66
+ if (!response.body)
67
+ return { status: response.status, text: '' };
68
+ const reader = response.body.getReader(), chunks = [];
69
+ let size = 0;
70
+ try {
71
+ for (;;) {
72
+ const { done, value } = await reader.read().catch((cause) => {
73
+ signal?.throwIfAborted();
74
+ throw new Unavailable('accountant response interrupted', { cause });
75
+ });
76
+ if (done)
77
+ break;
78
+ size += value.length;
79
+ if (size > MAX_BODY)
80
+ throw new Error('accountant response exceeds 64 KiB');
81
+ chunks.push(value);
82
+ }
83
+ }
84
+ finally {
85
+ void reader.cancel().catch(() => { });
86
+ reader.releaseLock();
87
+ }
88
+ const bytes = new Uint8Array(size);
89
+ let offset = 0;
90
+ for (const chunk of chunks) {
91
+ bytes.set(chunk, offset);
92
+ offset += chunk.length;
93
+ }
94
+ const text = new TextDecoder('utf-8', { fatal: false }).decode(bytes);
95
+ if (!response.ok)
96
+ return { status: response.status, text: text.slice(0, 256) };
97
+ return { status: response.status, json: JSON.parse(text), text: '' };
98
+ }
99
+ const transient = (status) => status >= 500 || status === 408 || status === 429;
100
+ function checkIntent(intent, d) {
101
+ prepaidAllowanceIntentHash(intent);
102
+ if (typeof intent.signature !== 'string' || !/^0x[0-9a-f]{130}$/i.test(intent.signature))
103
+ throw new Error('allowance intent signature must be 65 bytes');
104
+ if (intent.chain_id !== d.chainId || !same(intent.settlement, d.settlement) || !same(intent.key_registry, d.keyRegistry))
105
+ throw new Error('allowance intent deployment mismatch');
106
+ }
107
+ function liveIntent(intent) {
108
+ const at = now();
109
+ if (intent.expires_at <= at || intent.expires_at > at + ALLOWANCE_MAX_LIFETIME_SECS)
110
+ throw new Error('allowance intent is expired or exceeds the one-hour lifetime');
111
+ }
112
+ /**
113
+ * The allowance id every reader derives from a creator intent.
114
+ * @param intent - Creator intent (signature not part of the preimage).
115
+ */
116
+ export function prepaidAllowanceId(intent) {
117
+ return allowanceId(intent.chain_id, intent.settlement, intent.slot, prepaidAllowanceIntentHash(intent));
118
+ }
119
+ function parseQuote(value, intent, d, signed) {
120
+ if (!value || typeof value !== 'object' || Array.isArray(value))
121
+ throw new Error('invalid accountant allowance quote');
122
+ const q = value;
123
+ const fields = ['slot', 'allowance_id', 'intent_hash', 'quote_block', 'legacy_nonce', 'amount', 'max_op_cost', 'actions', 'expires_at', 'deadline', 'digest', 'signature', 'mined'];
124
+ if (Object.keys(q).length !== fields.length || fields.some(k => !Object.hasOwn(q, k)))
125
+ throw new Error('invalid accountant allowance quote fields');
126
+ for (const k of ['slot', 'allowance_id', 'intent_hash', 'quote_block', 'digest'])
127
+ if (typeof q[k] !== 'string' || !HEX32.test(q[k]))
128
+ throw new Error('invalid accountant allowance quote hash');
129
+ const intentHash = prepaidAllowanceIntentHash(intent), id = allowanceId(d.chainId, d.settlement, intent.slot, intentHash);
130
+ if (!same(q.slot, intent.slot) || !same(q.intent_hash, intentHash) || !same(q.allowance_id, id)
131
+ || same(q.quote_block, ZERO32) || q.mined !== false || q.amount !== intent.amount || q.max_op_cost !== intent.max_op_cost
132
+ || q.actions !== intent.actions || q.expires_at !== intent.expires_at || !Number.isSafeInteger(q.legacy_nonce) || q.legacy_nonce < 0
133
+ || !Number.isSafeInteger(q.deadline) || q.deadline <= 0 || q.deadline >= intent.expires_at)
134
+ throw new Error('accountant allowance quote does not match the creator intent');
135
+ if (signed ? typeof q.signature !== 'string' || !/^0x[0-9a-f]{128}$/i.test(q.signature) || /^0x0{128}$/i.test(q.signature) : q.signature !== null)
136
+ throw new Error('invalid accountant allowance quote signature');
137
+ const quote = q;
138
+ const digest = allowanceReserveDigest(d.settlement, d.chainId, { slot: intent.slot, legacyNonce: BigInt(quote.legacy_nonce), allowanceId: id,
139
+ amount: BigInt(intent.amount), maxOpCost: BigInt(intent.max_op_cost), actions: intent.actions, expiresAt: BigInt(intent.expires_at),
140
+ assignmentBlock: quote.quote_block, deadline: BigInt(quote.deadline) });
141
+ if (!same(quote.digest, digest))
142
+ throw new Error('accountant allowance quote digest mismatch');
143
+ return quote;
144
+ }
145
+ const unsignedQuote = (q) => JSON.stringify([q.slot.toLowerCase(), q.allowance_id.toLowerCase(), q.quote_block.toLowerCase(), q.legacy_nonce, q.deadline, q.digest.toLowerCase()]);
146
+ async function askAllowance(url, method, intent, block, d, timeout, signal) {
147
+ const answer = await post(`${url}/v1/prepaid/allowances/${method}`, { intent, quote_block: block }, timeout, signal);
148
+ if (answer.status === 402)
149
+ throw new UnderfundedSlotError({ slotId: intent.slot, status: 402, url, message: 'accountant allowance request refused (402): insufficient available TASRA' });
150
+ if (method === 'authorize' && answer.status === 503 && labelled(answer.text, 'reservation quorum not prepared'))
151
+ throw new PaidReservationQuorumNotPreparedError();
152
+ if (method === 'prepare' && (answer.status === 403 || answer.status === 409))
153
+ throw new AllowanceRefusedError(`accountant allowance request refused (${answer.status}): ${answer.text}`);
154
+ if (transient(answer.status)) {
155
+ const unavailable = new Unavailable(`accountant allowance request refused (${answer.status}): ${answer.text}`);
156
+ if (method === 'prepare' && answer.status === 503) {
157
+ unavailable.preWrite = labelled(answer.text, 'reservation assignments unavailable') || labelled(answer.text, 'quote block is stale, future or mismatched');
158
+ unavailable.notYetVisible = labelled(answer.text, 'quote block not yet visible');
159
+ }
160
+ throw unavailable;
161
+ }
162
+ if (answer.json === undefined)
163
+ throw new Error(`accountant allowance request refused (${answer.status}): ${answer.text}`);
164
+ return parseQuote(answer.json, intent, d, method === 'authorize');
165
+ }
166
+ /**
167
+ * Prepare at every responsive member at one NAMED quote block, then a quorum signature from a
168
+ * prepared one (robustness audit 2026-11-13, P1-P3, as `collectQuote` in reservation.ts). The first
169
+ * round names `first()` (the observed block, else the client's latest); a member's answer that
170
+ * recorded nothing - the pre-write 503, a stale named block, a definite 402/403/409, "not yet
171
+ * visible" - is that member's, and every such earlier member is asked again at the seed's block.
172
+ * When every member answers so, the round is repeated once at the client's fresh latest block. No
173
+ * prepare is ever sent without a block; a transport failure is never repeated to that member.
174
+ */
175
+ async function collectAllowanceQuote(urls, intent, d, timeout, signal, first, latest) {
176
+ let seed, last;
177
+ const classify = (error) => {
178
+ if (error instanceof UnderfundedSlotError || error instanceof AllowanceRefusedError)
179
+ return 'pre-write';
180
+ if (!(error instanceof Unavailable))
181
+ return undefined;
182
+ return error.notYetVisible ? 'not-visible' : error.preWrite ? 'pre-write' : 'unavailable';
183
+ };
184
+ let answers = [];
185
+ const seedRound = async (block) => {
186
+ answers = urls.map(() => undefined);
187
+ for (const [index, url] of urls.entries()) {
188
+ try {
189
+ const quote = await askAllowance(url, 'prepare', intent, block, d, timeout, signal);
190
+ if (!same(quote.quote_block, block))
191
+ throw new Error('accountant prepared the allowance at a different quote block than the one named');
192
+ seed = { quote, index };
193
+ return;
194
+ }
195
+ catch (error) {
196
+ const answer = classify(error);
197
+ if (answer === undefined)
198
+ throw error;
199
+ answers[index] = answer;
200
+ last = error;
201
+ }
202
+ }
203
+ };
204
+ const named = await untilAborted(first(), signal);
205
+ await seedRound(named);
206
+ if (!seed && urls.length > 0 && answers.every(a => a === 'pre-write' || a === 'not-visible')) {
207
+ const head = await untilAborted(latest(), signal);
208
+ if (!same(head, named) || answers.includes('not-visible'))
209
+ await seedRound(head);
210
+ }
211
+ if (!seed)
212
+ throw last ?? new Error('no reachable accountant prepared the allowance');
213
+ const { quote, index } = seed, prepared = [urls[index]];
214
+ const rest = urls.filter((_, i) => i > index || answers[i] === 'pre-write' || answers[i] === 'not-visible');
215
+ const results = await Promise.allSettled(rest.map(url => askAllowance(url, 'prepare', intent, quote.quote_block, d, timeout, signal)));
216
+ for (const [i, result] of results.entries()) {
217
+ if (result.status === 'rejected') {
218
+ if (classify(result.reason) === undefined)
219
+ throw result.reason;
220
+ continue;
221
+ }
222
+ if (unsignedQuote(result.value) !== unsignedQuote(quote))
223
+ throw new Error('accountants disagree on the allowance');
224
+ prepared.push(rest[i]);
225
+ }
226
+ for (const url of prepared) {
227
+ liveIntent(intent);
228
+ try {
229
+ const authorized = await askAllowance(url, 'authorize', intent, quote.quote_block, d, timeout, signal);
230
+ if (unsignedQuote(authorized) !== unsignedQuote(quote))
231
+ throw new Error('authorization changed the prepared allowance');
232
+ return { quote, authorized };
233
+ }
234
+ catch (error) {
235
+ if (!(error instanceof Unavailable))
236
+ throw error;
237
+ last = error;
238
+ }
239
+ }
240
+ throw last ?? new Error('no prepared accountant returned a quorum allowance authorization');
241
+ }
242
+ function reservationArgs(quote, intent) {
243
+ return { slotId: intent.slot, legacyNonce: BigInt(quote.legacy_nonce), intentHash: quote.intent_hash, amount: BigInt(intent.amount),
244
+ maxOpCost: BigInt(intent.max_op_cost), actions: intent.actions, expiresAt: BigInt(intent.expires_at), assignmentBlock: quote.quote_block,
245
+ deadline: BigInt(quote.deadline) };
246
+ }
247
+ /**
248
+ * Read `Settlement.prepaidAllowance(id)` at a canonical block (`blockHash`), or at a fresh head.
249
+ * @param client - Trusted RPC client.
250
+ * @param deployment - Approved deployment.
251
+ * @param id - Allowance id.
252
+ * @param blockHash - Canonical block to read at; a fresh latest head (<= 30 s) when absent.
253
+ */
254
+ export async function readPrepaidAllowance(client, deployment, id, blockHash) {
255
+ if (!HEX32.test(id) || same(id, ZERO32))
256
+ throw new Error('invalid allowance id');
257
+ if (await chainIdOf(client) !== deployment.chainId)
258
+ throw new Error('allowance RPC chain mismatch');
259
+ const block = blockHash ? await client.getBlock({ blockHash }) : await client.getBlock({ blockTag: 'latest' });
260
+ if (block.number === null || block.hash === null || (blockHash && !same(block.hash, blockHash)))
261
+ throw new Error('allowance observation block unavailable');
262
+ if (!blockHash && (BigInt(now()) - block.timestamp > 30n || block.timestamp - BigInt(now()) > 2n))
263
+ throw new Error('allowance observation head is stale');
264
+ const data = await pinnedCall(client, block.hash, deployment.settlement, encodeFunctionData({ abi: settlementAbi, functionName: 'prepaidAllowance', args: [id] }));
265
+ if (data === undefined)
266
+ throw new Error('empty prepaidAllowance response');
267
+ const [slotId, assignmentBlock, amount, spent, maxOpCost, expiresAt, reservedAt, actions, closed] = decodeFunctionResult({ abi: settlementAbi, functionName: 'prepaidAllowance', data });
268
+ return { allowanceId: id, slotId, assignmentBlock, amount, spent, maxOpCost, expiresAt, reservedAt, actions, closed,
269
+ blockNumber: block.number, blockHash: block.hash, blockTimestamp: block.timestamp };
270
+ }
271
+ /** Whether the read record is THIS intent's mined allowance. */
272
+ function minedAs(state, intent, quote) {
273
+ return same(state.slotId, intent.slot) && same(state.assignmentBlock, quote.quote_block) && state.amount === BigInt(intent.amount)
274
+ && state.maxOpCost === BigInt(intent.max_op_cost) && state.actions === intent.actions && state.expiresAt === BigInt(intent.expires_at);
275
+ }
276
+ /**
277
+ * Reserve one allowance for a creator-signed intent: quorum quote, one bounded legacy transaction,
278
+ * the durable checkpoints, the receipt and the mined record. Never resubmits or replaces; an
279
+ * outcome unknown after `prepared` is {@link PaidReservationUncertainError} (its `requestId` is the
280
+ * allowance id).
281
+ * @param client - Trusted RPC client; submission retries disabled.
282
+ * @param wallet - Dedicated account-bound gas payer.
283
+ * @param deployment - Approved deployment.
284
+ * @param original - Creator-signed allowance intent.
285
+ * @param options - Endpoints, gas limits and mandatory durable persistence.
286
+ */
287
+ export async function reservePrepaidAllowance(client, wallet, deployment, original, options) {
288
+ const intent = structuredClone(original), d = { ...deployment }, opts = { ...options, accountantUrls: [...options.accountantUrls] }, signal = opts.signal;
289
+ const payer = { ...wallet.account }, payerChain = { ...wallet.chain };
290
+ checkIntent(intent, d);
291
+ liveIntent(intent);
292
+ if (typeof opts.maxGas !== 'bigint' || typeof opts.maxGasPrice !== 'bigint' || opts.maxGas <= 0n || opts.maxGas >= 1n << 64n || opts.maxGasPrice <= 0n
293
+ || opts.maxGasPrice >= 1n << 128n || typeof opts.persist !== 'function')
294
+ throw new Error('invalid allowance gas budget or journal');
295
+ const requestTimeout = opts.requestTimeoutMs ?? 85000, receiptTimeout = opts.receiptTimeoutMs ?? 60000, confirmations = opts.confirmations ?? 1;
296
+ if (!Number.isSafeInteger(requestTimeout) || requestTimeout < 1 || requestTimeout > 85000 || !Number.isSafeInteger(receiptTimeout) || receiptTimeout < 1
297
+ || receiptTimeout > 120000 || !Number.isSafeInteger(confirmations) || confirmations < 1 || confirmations > 64)
298
+ throw new Error('invalid allowance timeout or confirmations');
299
+ if (opts.quoteBlock !== undefined && (typeof opts.quoteBlock !== 'string' || !HEX32.test(opts.quoteBlock) || same(opts.quoteBlock, ZERO32)))
300
+ throw new Error('invalid allowance quote block');
301
+ const id = prepaidAllowanceId(intent);
302
+ signal?.throwIfAborted();
303
+ const urls = accountantEndpoints(opts, d.chainId);
304
+ if (payer.type !== 'local' && payer.type !== 'json-rpc')
305
+ throw new Error('allowance reservation requires an EOA gas payer');
306
+ if (payerChain.id !== d.chainId)
307
+ throw new Error('allowance RPC/wallet chain mismatch');
308
+ // The wallet's and the reader's chain IDs are independent reads (a new wallet client is not
309
+ // cached yet): asked together, judged in the original order, before anything is contacted.
310
+ const [walletChain, readerChain] = await Promise.allSettled([chainIdOf(wallet), chainIdOf(client)]);
311
+ if (walletChain.status === 'rejected')
312
+ throw walletChain.reason;
313
+ if (walletChain.value !== d.chainId)
314
+ throw new Error('allowance RPC/wallet chain mismatch');
315
+ if (readerChain.status === 'rejected')
316
+ throw readerChain.reason;
317
+ if (readerChain.value !== d.chainId)
318
+ throw new Error('allowance RPC/wallet chain mismatch');
319
+ const latestHash = async () => {
320
+ const head = await client.getBlock({ blockTag: 'latest' });
321
+ if (head.hash === null)
322
+ throw new Error('latest block has no hash');
323
+ return head.hash;
324
+ };
325
+ const pinned = opts.quoteBlock;
326
+ const { quote, authorized } = await collectAllowanceQuote(urls, intent, d, requestTimeout, signal, async () => pinned ?? latestHash(), latestHash);
327
+ const args = reservationArgs(quote, intent);
328
+ const data = encodeFunctionData({ abi: settlementAbi, functionName: 'reservePrepaidAllowanceBls', args: [args, authorized.signature] });
329
+ const block = await client.getBlock({ blockHash: quote.quote_block });
330
+ const fresh = () => {
331
+ if (block.number === null || block.hash === null || !same(block.hash, quote.quote_block)
332
+ || BigInt(now()) - block.timestamp > BigInt(ALLOWANCE_QUOTE_MAX_AGE_SECS) || block.timestamp - BigInt(now()) > 2n)
333
+ throw new Error('allowance quote block is stale or invalid');
334
+ liveIntent(intent);
335
+ if (quote.deadline <= now())
336
+ throw new Error('allowance authorization deadline passed');
337
+ };
338
+ fresh();
339
+ const at = (to, callData) => client.call({ to, data: callData, account: payer, blockHash: quote.quote_block, requireCanonical: true, batch: false });
340
+ // The simulation verifies the quorum signature and the contract's own checks without gas.
341
+ const [existingRead, slotRead, , fees] = await Promise.all([
342
+ at(d.settlement, encodeFunctionData({ abi: settlementAbi, functionName: 'prepaidAllowance', args: [id] })),
343
+ at(d.keyRegistry, encodeFunctionData({ abi: keyRegistryAbi, functionName: 'getKeySlot', args: [intent.slot] })),
344
+ at(d.settlement, data),
345
+ Promise.all([client.getGasPrice(), client.estimateGas({ account: payer.address, to: d.settlement, data, value: 0n, gasPrice: 0n, type: 'legacy' }),
346
+ client.getTransactionCount({ address: payer.address, blockTag: 'pending' }), client.getBalance({ address: payer.address, blockTag: 'pending' })]),
347
+ ]);
348
+ if (existingRead.data === undefined || slotRead.data === undefined)
349
+ throw new Error('empty allowance reservation observation');
350
+ const existing = decodeFunctionResult({ abi: settlementAbi, functionName: 'prepaidAllowance', data: existingRead.data });
351
+ if (!same(existing[1], ZERO32))
352
+ throw new Error('allowance already reserved; read it instead of spending again');
353
+ const slot = decodeFunctionResult({ abi: keyRegistryAbi, functionName: 'getKeySlot', data: slotRead.data });
354
+ const creator = await recoverTypedDataAddress({ ...prepaidAllowanceIntentTypedData(intent), signature: intent.signature });
355
+ if (!slot.exists || slot.cancelled || (slot.expiry !== 0n && slot.expiry <= BigInt(now())) || !same(creator, slot.creator))
356
+ throw new Error('allowance intent is not from an active slot creator');
357
+ const [gasPrice, gas, nonce, balance] = fees;
358
+ if (gas <= 0n || gas > opts.maxGas || gasPrice <= 0n || gasPrice > opts.maxGasPrice)
359
+ throw new Error('allowance reservation exceeds native gas budget');
360
+ if (balance < gas * gasPrice)
361
+ throw new UnderfundedGasPayerError({ payer: payer.address, availableNativeUnits: balance, requiredNativeUnits: gas * gasPrice });
362
+ signal?.throwIfAborted();
363
+ if (block.number === null)
364
+ throw new Error('allowance quote has no block number');
365
+ // The quote block's canonical recheck: by the head follower only where it proves this exact block
366
+ // canonical (as for every other paid observation), otherwise by number.
367
+ if (headFollowerOf(client)?.isCanonical({ blockNumber: block.number, blockHash: quote.quote_block, blockTimestamp: block.timestamp }) !== true) {
368
+ const canonical = await client.getBlock({ blockNumber: block.number });
369
+ if (canonical.hash === null || !same(canonical.hash, quote.quote_block))
370
+ throw new Error('allowance quote reorganized');
371
+ }
372
+ fresh();
373
+ const record = { schema: 1, allowanceId: id, intent, quote: authorized,
374
+ transaction: { chainId: d.chainId, from: payer.address, to: d.settlement, data, value: '0', nonce, gas: gas.toString(), gasPrice: gasPrice.toString() } };
375
+ let raw, transactionHash;
376
+ if (payer.type === 'local') {
377
+ raw = await wallet.signTransaction({ account: payer, chain: payerChain, to: d.settlement, data, value: 0n, nonce, gas, gasPrice, type: 'legacy' });
378
+ const signed = parseTransaction(raw), sender = await recoverTransactionAddress({ serializedTransaction: raw });
379
+ if (signed.type !== 'legacy' || signed.chainId !== d.chainId || !same(sender, payer.address) || !signed.to || !same(signed.to, d.settlement)
380
+ || !signed.data || !same(signed.data, data) || (signed.value ?? 0n) !== 0n || signed.nonce !== nonce || signed.gas !== gas || signed.gasPrice !== gasPrice)
381
+ throw new Error('signed transaction differs from the durable allowance reservation');
382
+ transactionHash = keccak256(raw);
383
+ fresh();
384
+ }
385
+ signal?.throwIfAborted();
386
+ await opts.persist({ phase: 'prepared', record: structuredClone(record), ...(transactionHash ? { transactionHash } : {}) });
387
+ try {
388
+ fresh();
389
+ if (raw !== undefined) {
390
+ const returned = await wallet.request({ method: 'eth_sendRawTransaction', params: [raw] }, { retryCount: 0 });
391
+ if (returned === undefined || transactionHash === undefined || !same(returned, transactionHash))
392
+ throw new Error('RPC returned another signed transaction hash');
393
+ }
394
+ else {
395
+ transactionHash = await wallet.request({ method: 'eth_sendTransaction', params: [{ from: payer.address, to: d.settlement, data, value: '0x0', nonce: toHex(nonce),
396
+ gas: toHex(gas), gasPrice: toHex(gasPrice), type: '0x0', chainId: toHex(d.chainId) }] }, { retryCount: 0 });
397
+ }
398
+ if (typeof transactionHash !== 'string' || !HEX32.test(transactionHash) || same(transactionHash, ZERO32))
399
+ throw new Error('invalid allowance transaction hash');
400
+ await opts.persist({ phase: 'submitted', allowanceId: id, transactionHash });
401
+ const sent = transactionHash;
402
+ const mined = await untilAborted(pollTransactionReceipt(client, sent, { confirmations, timeoutMs: receiptTimeout, signal }), signal);
403
+ if (!same(mined.transactionHash, sent) || mined.status !== 'success')
404
+ throw new Error('allowance transaction reverted or was replaced');
405
+ const [transaction, allowance, minedBlock] = await untilAborted(Promise.all([client.getTransaction({ hash: sent }),
406
+ readPrepaidAllowance(client, d, id, mined.blockHash), client.getBlock({ blockNumber: mined.blockNumber })]), signal);
407
+ if (transaction.to === null || !same(transaction.to, d.settlement) || !same(transaction.from, record.transaction.from) || !same(transaction.input, data)
408
+ || transaction.value !== 0n || transaction.nonce !== nonce || transaction.type !== 'legacy' || transaction.gas !== gas || transaction.gasPrice !== gasPrice
409
+ || transaction.chainId !== d.chainId || transaction.blockHash === null || !same(transaction.blockHash, mined.blockHash))
410
+ throw new Error('mined transaction differs from the durable allowance reservation');
411
+ if (!minedAs(allowance, intent, quote) || allowance.closed)
412
+ throw new Error('mined allowance differs from the signed intent and quote');
413
+ if (minedBlock.hash === null || !same(minedBlock.hash, mined.blockHash))
414
+ throw new Error('allowance receipt reorganized');
415
+ await opts.persist({ phase: 'confirmed', allowanceId: id, transactionHash: sent, blockHash: mined.blockHash });
416
+ return { transactionHash: sent, allowance, quote: authorized };
417
+ }
418
+ catch (cause) {
419
+ throw new PaidReservationUncertainError(id, transactionHash, cause);
420
+ }
421
+ }
422
+ /**
423
+ * Whether a prepared allowance reservation is mined as signed, read at a fresh head. `reserved`
424
+ * proves it; `not-reserved` is final only once a canonical block is past the quote deadline
425
+ * (the contract refuses the signed quote from then on); otherwise `uncertain`.
426
+ * @param client - Trusted RPC client.
427
+ * @param deployment - Approved deployment.
428
+ * @param record - The durable `prepared` record.
429
+ */
430
+ export async function reconcilePrepaidAllowance(client, deployment, record) {
431
+ checkIntent(record.intent, deployment);
432
+ if (!same(record.allowanceId, prepaidAllowanceId(record.intent)))
433
+ throw new Error('allowance record identity mismatch');
434
+ parseQuote(record.quote, record.intent, deployment, true);
435
+ const allowance = await readPrepaidAllowance(client, deployment, record.allowanceId);
436
+ if (!same(allowance.assignmentBlock, ZERO32)) {
437
+ if (!minedAs(allowance, record.intent, record.quote))
438
+ throw new Error('mined allowance differs from the saved record');
439
+ return { state: 'reserved', allowance };
440
+ }
441
+ return { state: allowance.blockTimestamp > BigInt(record.quote.deadline) ? 'not-reserved' : 'uncertain', allowance };
442
+ }
443
+ // ---- Group key and voucher verification ---------------------------------------------------
444
+ /** Group keys by quote block hash (state at a block hash is immutable). Bounded, oldest first out. */
445
+ const MAX_GROUP_KEYS = 64;
446
+ const groupKeys = new WeakMap();
447
+ /**
448
+ * `beacon.mpk()` at a canonical block, via `Settlement.beacon()` read at the same block.
449
+ * @param client - Trusted RPC client.
450
+ * @param deployment - Approved deployment (with the approved beacon, when known).
451
+ * @param blockHash - Quote block.
452
+ */
453
+ export function readAccountantGroupKey(client, deployment, blockHash) {
454
+ if (!HEX32.test(blockHash) || same(blockHash, ZERO32))
455
+ return Promise.reject(new Error('group key read needs a block'));
456
+ let cache = groupKeys.get(client);
457
+ if (!cache)
458
+ groupKeys.set(client, cache = new Map());
459
+ // Keyed by the approved beacon too: a read without one never answers a call that must check
460
+ // Settlement names exactly the approved beacon (review F5).
461
+ const key = `${deployment.settlement.toLowerCase()}:${(deployment.beacon ?? '').toLowerCase()}:${blockHash.toLowerCase()}`;
462
+ const hit = cache.get(key);
463
+ if (hit)
464
+ return hit;
465
+ const read = (async () => {
466
+ const mpkCall = encodeFunctionData({ abi: thresholdRandomBeaconAbi, functionName: 'mpk' });
467
+ // With an approved beacon, Settlement must name exactly it, so its mpk is read in the same
468
+ // round (both pinned to the block) and used only once that is confirmed: one RPC round.
469
+ const approvedMpk = deployment.beacon ? pinnedCall(client, blockHash, deployment.beacon, mpkCall) : undefined;
470
+ approvedMpk?.catch(() => { });
471
+ const beaconData = await pinnedCall(client, blockHash, deployment.settlement, encodeFunctionData({ abi: settlementAbi, functionName: 'beacon' }));
472
+ if (beaconData === undefined)
473
+ throw new Error('empty Settlement.beacon response');
474
+ const beacon = decodeFunctionResult({ abi: settlementAbi, functionName: 'beacon', data: beaconData });
475
+ if (deployment.beacon && !same(beacon, deployment.beacon))
476
+ throw new Error('Settlement names another beacon than the approved one');
477
+ const mpkData = await (approvedMpk ?? pinnedCall(client, blockHash, beacon, mpkCall));
478
+ if (mpkData === undefined)
479
+ throw new Error('empty beacon.mpk response');
480
+ const mpk = hexToBytes(decodeFunctionResult({ abi: thresholdRandomBeaconAbi, functionName: 'mpk', data: mpkData }));
481
+ if (mpk.length !== 128 || mpk.every(b => b === 0))
482
+ throw new Error('accountant group key is not set at the quote block');
483
+ return mpk;
484
+ })();
485
+ if (cache.size >= MAX_GROUP_KEYS)
486
+ cache.delete(cache.keys().next().value);
487
+ cache.set(key, read);
488
+ read.catch(() => { if (cache.get(key) === read)
489
+ cache.delete(key); });
490
+ return read;
491
+ }
492
+ /** Verified voucher signatures (digest + signature + key), bounded. */
493
+ const MAX_VERIFIED_VOUCHERS = 1024;
494
+ const verifiedVouchers = new Set();
495
+ /**
496
+ * Verify a debit voucher's shape and its threshold signature against `beacon.mpk()` at its quote block.
497
+ * @param client - Trusted RPC client.
498
+ * @param deployment - Approved deployment.
499
+ * @param voucher - Untrusted voucher.
500
+ */
501
+ export async function verifyDebitVoucher(client, deployment, voucher) {
502
+ assertDebitVoucherWire(voucher);
503
+ const digest = debitVoucherDigest(deployment.settlement, deployment.chainId, { allowanceId: voucher.allowance_id, seq: BigInt(voucher.seq),
504
+ requestId: voucher.request_id, cost: BigInt(voucher.cost), cumulative: BigInt(voucher.cumulative), quoteBlock: voucher.quote_block });
505
+ const mpk = await readAccountantGroupKey(client, deployment, voucher.quote_block);
506
+ const key = voucherKey(digest, voucher.signature, mpk);
507
+ if (verifiedVouchers.has(key))
508
+ return;
509
+ if (!verifyBn254(mpk, hexToBytes(digest), hexToBytes(voucher.signature)))
510
+ throw new Error('debit voucher signature does not verify against the accountant group key');
511
+ rememberVoucher(key);
512
+ }
513
+ // Exact (locally recomputed digest, signature bytes, group key bytes) triples whose pairing check PASSED.
514
+ function voucherKey(digest, signature, mpk) {
515
+ return `${digest.toLowerCase()}:${signature.toLowerCase()}:${bytesToHex(mpk)}`;
516
+ }
517
+ function rememberVoucher(key) {
518
+ if (verifiedVouchers.size >= MAX_VERIFIED_VOUCHERS)
519
+ verifiedVouchers.delete(verifiedVouchers.values().next().value);
520
+ verifiedVouchers.add(key);
521
+ }
522
+ /** A voucher round ended without `k` verified partials. */
523
+ export class DebitVoucherError extends Error {
524
+ outcomes;
525
+ partials;
526
+ threshold;
527
+ /** Stable reason. */
528
+ code = 'debit-voucher-unavailable';
529
+ constructor(/** Every member's outcome. */ outcomes, /** Partials obtained. */ partials,
530
+ /** Threshold, when any member named it. */ threshold) {
531
+ super(`debit voucher round got ${partials} verified partial(s)${threshold ? ` of ${threshold}` : ''}`);
532
+ this.outcomes = outcomes;
533
+ this.partials = partials;
534
+ this.threshold = threshold;
535
+ this.name = 'DebitVoucherError';
536
+ }
537
+ /** True when no member is unavailable: every member that did not sign definitely refused. */
538
+ get definite() { return this.outcomes.every(o => o.kind !== 'unavailable'); }
539
+ /** True when any member signed this seq for this request (it is then bound to it at those members). */
540
+ get claimed() { return this.partials > 0; }
541
+ }
542
+ function expectedCumulative(request, cost) {
543
+ return request.previous ? BigInt(request.previous.cumulative) + cost : cost;
544
+ }
545
+ /** Every check of one member's answer EXCEPT the pairing (see {@link partialVerifies}). */
546
+ function checkPartial(value, request, d, requestId) {
547
+ if (!value || typeof value !== 'object' || Array.isArray(value))
548
+ throw new Error('invalid debit partial');
549
+ const p = value;
550
+ const fields = ['allowance_id', 'seq', 'request_id', 'cost', 'cumulative', 'quote_block', 'digest', 'identifier', 'partial', 'verifying_share', 'sharing', 'threshold', 'members'];
551
+ if (Object.keys(p).length !== fields.length || fields.some(k => !Object.hasOwn(p, k)))
552
+ throw new Error('invalid debit partial fields');
553
+ const w = p;
554
+ for (const k of ['allowance_id', 'request_id', 'quote_block', 'digest', 'sharing'])
555
+ if (typeof w[k] !== 'string' || !HEX32.test(w[k]))
556
+ throw new Error('invalid debit partial hash');
557
+ if (typeof w.partial !== 'string' || !/^0x[0-9a-f]{128}$/i.test(w.partial) || typeof w.verifying_share !== 'string' || !/^0x[0-9a-f]{256}$/i.test(w.verifying_share))
558
+ throw new Error('invalid debit partial encoding');
559
+ if (typeof w.cost !== 'string' || !/^[0-9]{1,78}$/.test(w.cost) || typeof w.cumulative !== 'string' || !/^[0-9]{1,78}$/.test(w.cumulative))
560
+ throw new Error('invalid debit partial amounts');
561
+ if (!Number.isSafeInteger(w.identifier) || w.identifier < 1 || w.identifier > 65535 || !Number.isSafeInteger(w.threshold) || !Number.isSafeInteger(w.members)
562
+ || w.threshold < 1 || w.members < w.threshold || w.members > 65535 || 2 * w.threshold <= w.members)
563
+ throw new Error('invalid debit partial sharing (voucher signing requires 2k > n)');
564
+ const cost = BigInt(w.cost);
565
+ if (!same(w.allowance_id, request.payment.allowance_id) || w.seq !== request.seq || !same(w.request_id, requestId) || !same(w.quote_block, request.quoteBlock)
566
+ || cost <= 0n || cost > BigInt(request.payment.max_cost) || cost > request.maxOpCost || BigInt(w.cumulative) !== expectedCumulative(request, cost))
567
+ throw new Error('debit partial does not match the request');
568
+ const digest = debitVoucherDigest(d.settlement, d.chainId, { allowanceId: w.allowance_id, seq: BigInt(w.seq), requestId, cost, cumulative: BigInt(w.cumulative), quoteBlock: w.quote_block });
569
+ if (!same(w.digest, digest))
570
+ throw new Error('debit partial digest mismatch');
571
+ return w;
572
+ }
573
+ /** One member's partial against its own verifying share (one pairing check). */
574
+ function partialVerifies(p) {
575
+ return verifyBn254(hexToBytes(p.verifying_share), hexToBytes(p.digest), hexToBytes(p.partial));
576
+ }
577
+ /** k-subsets tried per sharing before a round gives up (a lying verifying share defeats a subset, not the round). */
578
+ const MAX_SUBSETS = 16;
579
+ /**
580
+ * Obtain one debit voucher: the same request to every accountant in parallel, each answer checked
581
+ * against the request, `k` partials of one sharing combined and the aggregate verified against
582
+ * `beacon.mpk()` at the quote block (read while the members answer).
583
+ *
584
+ * The voucher is returned as soon as `k` answers combine into an aggregate the group key verifies:
585
+ * that check alone makes the voucher valid, so the round neither waits for the remaining members
586
+ * (their requests run on in the background; the voucher reaches them by the push) nor checks each
587
+ * partial against its share first. Only when an aggregate fails are the partials checked one by
588
+ * one, which names the member whose partial does not verify and drops it from the next subsets.
589
+ * Without `k` the round waits for every member, checks every partial and throws
590
+ * {@link DebitVoucherError} with each member's outcome.
591
+ * @param client - Trusted RPC client (group key read).
592
+ * @param deployment - Approved deployment (with the approved beacon, when known).
593
+ * @param request - Payment, sequence, previous voucher, journaled quote block and the allowance cap.
594
+ * @param options - Endpoints, timeout, cancellation and already-known partials.
595
+ * @returns The voucher, the `k` partials combined into it and the outcomes of the members that had answered.
596
+ */
597
+ export async function collectDebitVoucher(client, deployment, request, options) {
598
+ const d = { ...deployment }, payment = structuredClone(request.payment);
599
+ assertPaymentIntentWire(payment);
600
+ if (payment.allowance_id === undefined || payment.debit_voucher !== undefined)
601
+ throw new Error('a debit request carries an allowance payment without a voucher');
602
+ if (payment.chain_id !== d.chainId || !same(payment.settlement, d.settlement) || !same(payment.key_registry, d.keyRegistry))
603
+ throw new Error('debit payment deployment mismatch');
604
+ if (!Number.isSafeInteger(request.seq) || request.seq < 1 || (request.seq === 1) !== (request.previous === undefined))
605
+ throw new Error('seq must be 1 without a previous voucher, previous.seq + 1 with one');
606
+ if (request.previous) {
607
+ assertDebitVoucherWire(request.previous);
608
+ if (request.previous.seq + 1 !== request.seq || !same(request.previous.allowance_id, payment.allowance_id))
609
+ throw new Error('previous voucher does not precede this debit');
610
+ }
611
+ if (!HEX32.test(request.quoteBlock) || same(request.quoteBlock, ZERO32))
612
+ throw new Error('debit round needs its journaled quote block');
613
+ const timeout = options.requestTimeoutMs ?? 15_000;
614
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 60_000)
615
+ throw new Error('invalid debit request timeout');
616
+ const urls = accountantEndpoints(options, d.chainId), requestId = prepaidRequestId(payment);
617
+ const body = { intent: payment, seq: request.seq, previous: request.previous ?? null, quote_block: request.quoteBlock };
618
+ // Candidates: shape-checked partials by identifier (a known partial is re-checked the same way).
619
+ const candidates = new Map();
620
+ for (const p of options.known ?? []) {
621
+ const shaped = checkPartial(p, request, d, requestId);
622
+ candidates.set(shaped.identifier, shaped);
623
+ }
624
+ // The group key is read while the members answer; a failed read is judged only when it is needed.
625
+ const groupKey = readAccountantGroupKey(client, d, request.quoteBlock);
626
+ groupKey.catch(() => { });
627
+ const outcomes = urls.map(() => undefined);
628
+ const ask = async (url) => {
629
+ try {
630
+ const answer = await post(`${url}/v1/prepaid/allowances/${payment.allowance_id}/debits`, body, timeout, options.signal);
631
+ if (answer.json === undefined)
632
+ return transient(answer.status) ? { url, kind: 'unavailable', reason: `(${answer.status}) ${answer.text}` }
633
+ : { url, kind: 'refused', status: answer.status, reason: answer.text };
634
+ return { url, kind: 'partial', partial: checkPartial(answer.json, request, d, requestId) };
635
+ }
636
+ catch (error) {
637
+ options.signal?.throwIfAborted();
638
+ if (error instanceof Unavailable)
639
+ return { url, kind: 'unavailable', reason: error.message };
640
+ return { url, kind: 'refused', status: 0, reason: error instanceof Error ? error.message.slice(0, 256) : 'invalid answer' };
641
+ }
642
+ };
643
+ const inFlight = new Map();
644
+ urls.forEach((url, i) => {
645
+ const answered = ask(url).then(outcome => {
646
+ outcomes[i] = outcome;
647
+ if (outcome.kind === 'partial' && !candidates.has(outcome.partial.identifier))
648
+ candidates.set(outcome.partial.identifier, outcome.partial);
649
+ return i;
650
+ });
651
+ // An early voucher leaves the rest running; an abort of one of them must not go unhandled.
652
+ answered.catch(() => { });
653
+ inFlight.set(i, answered);
654
+ });
655
+ // Identifiers whose partial failed its own check, and k-subsets already combined.
656
+ const invalid = new Set(), checked = new Set();
657
+ const tried = new Set();
658
+ let strict = false;
659
+ let threshold;
660
+ const refuse = (identifier) => {
661
+ invalid.add(identifier);
662
+ const i = outcomes.findIndex(o => o?.kind === 'partial' && o.partial.identifier === identifier);
663
+ if (i >= 0)
664
+ outcomes[i] = { url: outcomes[i].url, kind: 'refused', status: 0, reason: `partial of member ${identifier} does not verify against its share` };
665
+ };
666
+ // Partials of one sharing only: a reshare between members' answers must never mix.
667
+ const group = () => {
668
+ const bySharing = new Map();
669
+ for (const p of candidates.values()) {
670
+ if (invalid.has(p.identifier))
671
+ continue;
672
+ const key = `${p.sharing.toLowerCase()}:${p.threshold}:${p.members}:${p.cost}`;
673
+ bySharing.set(key, [...bySharing.get(key) ?? [], p]);
674
+ }
675
+ return [...bySharing.values()].sort((a, b) => b.length - a.length)[0] ?? [];
676
+ };
677
+ /** A voucher from the current candidates, or undefined (not yet `k`, or no untried subset verifies). */
678
+ const attempt = async () => {
679
+ let members = group();
680
+ threshold = members[0]?.threshold ?? threshold;
681
+ if (!threshold || members.length < threshold)
682
+ return undefined;
683
+ if (strict) {
684
+ for (const p of members)
685
+ if (!checked.has(p.identifier)) {
686
+ checked.add(p.identifier);
687
+ if (!partialVerifies(p))
688
+ refuse(p.identifier);
689
+ }
690
+ members = group();
691
+ if (members.length < threshold)
692
+ return undefined;
693
+ }
694
+ const k = threshold;
695
+ const sorted = [...members].sort((a, b) => a.identifier - b.identifier), first = sorted[0];
696
+ const mpk = await groupKey;
697
+ const digest = hexToBytes(first.digest);
698
+ for (const subset of subsets(sorted.length, k, MAX_SUBSETS * 4)) {
699
+ const used = subset.map(i => sorted[i]), key = used.map(p => p.identifier).join(',');
700
+ if (tried.has(key))
701
+ continue;
702
+ if (tried.size >= MAX_SUBSETS)
703
+ break;
704
+ tried.add(key);
705
+ const signature = interpolateBn254(used.map(p => ({ identifier: p.identifier, partial: hexToBytes(p.partial) })), k);
706
+ if (signature && verifyBn254(mpk, digest, signature)) {
707
+ const voucher = { allowance_id: first.allowance_id, seq: first.seq, request_id: first.request_id, cost: first.cost,
708
+ cumulative: first.cumulative, quote_block: first.quote_block, signature: bytesToHex(signature) };
709
+ assertDebitVoucherWire(voucher);
710
+ // This exact aggregate just passed the group-key pairing check over the digest every partial was
711
+ // checked to carry (recomputed locally in checkPartial): the immediate verifyDebitVoucher of the
712
+ // same voucher at the same quote block need not repeat it. Keyed by the locally derived digest.
713
+ rememberVoucher(voucherKey(first.digest, voucher.signature, mpk));
714
+ return { voucher, partials: used };
715
+ }
716
+ // A failed aggregate: from now on every partial is checked against its share before it is
717
+ // combined, so the member that broke it is named and left out.
718
+ if (!strict) {
719
+ strict = true;
720
+ return attempt();
721
+ }
722
+ }
723
+ return undefined;
724
+ };
725
+ for (;;) {
726
+ const done = await attempt();
727
+ if (done)
728
+ return { ...done, outcomes: outcomes.filter((o) => o !== undefined) };
729
+ if (inFlight.size === 0)
730
+ break;
731
+ const i = await Promise.race(inFlight.values());
732
+ inFlight.delete(i);
733
+ }
734
+ // Every member answered and no voucher: check every partial for the outcome classes.
735
+ for (const p of candidates.values())
736
+ if (!invalid.has(p.identifier) && !checked.has(p.identifier) && !partialVerifies(p))
737
+ refuse(p.identifier);
738
+ const verified = [...candidates.values()].filter(p => !invalid.has(p.identifier));
739
+ throw new DebitVoucherError(outcomes, verified.length, verified[0]?.threshold ?? threshold);
740
+ }
741
+ /** Up to `limit` k-subsets of 0..n-1 in lexicographic order. */
742
+ function* subsets(n, k, limit) {
743
+ const index = Array.from({ length: k }, (_, i) => i);
744
+ for (let produced = 0; produced < limit; produced++) {
745
+ yield [...index];
746
+ let i = k - 1;
747
+ while (i >= 0 && index[i] === n - k + i)
748
+ i--;
749
+ if (i < 0)
750
+ return;
751
+ index[i]++;
752
+ for (let j = i + 1; j < k; j++)
753
+ index[j] = index[j - 1] + 1;
754
+ }
755
+ }
756
+ /**
757
+ * Push an aggregated debit voucher to accountant members (`POST /v1/prepaid/allowances/{id}/vouchers`).
758
+ * A member learns a seq's aggregate from the next debit's `previous`; the last seq of a lane is
759
+ * never anyone's `previous`, so this is how members that will never see it as `previous` learn it.
760
+ * Each member verifies it against the group key at its quote block; the push is idempotent.
761
+ * Never rejects for a member failure: every member's answer is returned as an outcome.
762
+ * @param chainId - Deployment chain (endpoint transport policy).
763
+ * @param voucher - A verified aggregated voucher.
764
+ * @param options - Endpoints, timeout and concurrency.
765
+ */
766
+ export async function pushDebitVoucher(chainId, voucher, options) {
767
+ assertDebitVoucherWire(voucher);
768
+ const timeout = options.requestTimeoutMs ?? 10_000, concurrency = options.concurrency ?? 4;
769
+ if (!Number.isSafeInteger(timeout) || timeout < 1 || timeout > 60_000)
770
+ throw new Error('invalid voucher push timeout');
771
+ if (!Number.isSafeInteger(concurrency) || concurrency < 1 || concurrency > 32)
772
+ throw new Error('invalid voucher push concurrency');
773
+ const urls = accountantEndpoints(options, chainId);
774
+ // Exactly the DebitVoucher wire fields: the member's body is deny_unknown_fields.
775
+ const body = { allowance_id: voucher.allowance_id, seq: voucher.seq, request_id: voucher.request_id, cost: voucher.cost,
776
+ cumulative: voucher.cumulative, quote_block: voucher.quote_block, signature: voucher.signature };
777
+ const outcomes = new Array(urls.length);
778
+ let next = 0;
779
+ const worker = async () => {
780
+ for (let i = next++; i < urls.length; i = next++) {
781
+ const url = urls[i];
782
+ try {
783
+ const answer = await post(`${url}/v1/prepaid/allowances/${voucher.allowance_id}/vouchers`, body, timeout);
784
+ const json = answer.json;
785
+ if (json === undefined)
786
+ outcomes[i] = { url, kind: 'failed', status: answer.status, reason: answer.text };
787
+ else if (!json || typeof json !== 'object' || json.seq !== voucher.seq || typeof json.recorded !== 'string' || !['unchanged', 'attached', 'observed'].includes(json.recorded)) {
788
+ outcomes[i] = { url, kind: 'failed', status: 0, reason: 'invalid voucher push answer' };
789
+ }
790
+ else
791
+ outcomes[i] = { url, kind: 'accepted', recorded: json.recorded };
792
+ }
793
+ catch (error) {
794
+ outcomes[i] = { url, kind: 'failed', status: 0, reason: error instanceof Error ? error.message.slice(0, 256) : 'voucher push failed' };
795
+ }
796
+ }
797
+ };
798
+ await Promise.all(Array.from({ length: Math.min(concurrency, urls.length) }, worker));
799
+ return outcomes;
800
+ }