@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,746 @@
1
+ import { decodeFunctionResult, encodeAbiParameters, encodeFunctionData, keccak256, parseTransaction, recoverTransactionAddress, recoverTypedDataAddress, toHex } from 'viem';
2
+ import { assertPaymentIntentWire, paymentIntentTypedData, prepaidRequestId } from '../committee/payment.js';
3
+ import { settlementAbi } from './abis/settlement.js';
4
+ import { keyRegistryAbi } from './abis/keyRegistry.js';
5
+ import { readPaidOperationReceipt } from './prepaid.js';
6
+ import { PaidBackoffError, PaidReservationQuotaError, UnderfundedSlotError, UnderfundedGasPayerError } from '../errors.js';
7
+ import { PaidBackoff, paidServerWaitMs, systemPacingClock } from './paidPacing.js';
8
+ import { chainIdOf } from './chainId.js';
9
+ import { pollTransactionReceipt } from './receipt.js';
10
+ import { headFollowerOf } from './headFollower.js';
11
+ /** How old a discovery block may be to be named by the first prepare (the accountants accept a quote block up to 30 s old, and authorize re-judges it). */
12
+ const PIN_MAX_AGE_SECS = 20n;
13
+ /** The caller aborted before anything was prepared or broadcast; nothing was sent or journaled. Reserving again is safe. */
14
+ export class PaidReservationAbortedError extends Error {
15
+ /** Stable machine-readable reason. */
16
+ code = 'aborted';
17
+ /** Request ID that was not reserved. */
18
+ requestId;
19
+ constructor(requestId, cause) {
20
+ super('reservation aborted before preparation; nothing was sent', { cause });
21
+ this.name = 'PaidReservationAbortedError';
22
+ this.requestId = requestId;
23
+ }
24
+ }
25
+ /** Reservation submission may have happened; inspect the saved identity before further spending. */
26
+ export class PaidReservationUncertainError extends Error {
27
+ /** Stable machine-readable reason. */
28
+ code = 'reservation-uncertain';
29
+ /** Original request ID for readPaidOperationReceipt and durable journal lookup. */
30
+ requestId;
31
+ /** Transaction hash when received; absence does not establish that no transaction was sent. */
32
+ transactionHash;
33
+ constructor(requestId, transactionHash, cause) {
34
+ super('reservation outcome needs reconciliation; retain the prepared record and do not resubmit', { cause });
35
+ this.name = 'PaidReservationUncertainError';
36
+ this.requestId = requestId;
37
+ this.transactionHash = transactionHash;
38
+ }
39
+ }
40
+ /**
41
+ * The accountant's unpinned `prepare` refused the intent because its signed verifier epoch is no
42
+ * longer the beacon's current or previous one at the accountant's own latest block (the reservation
43
+ * waited past an epoch tick). This client sent no transaction, but the intent is NOT dead: an
44
+ * accountant judges the epoch at a client-pinned quote block up to MAX_QUOTE_AGE (30 s) old, and
45
+ * `reservePrepaid*` is permissionless, so whoever holds the intent may still get it reserved until
46
+ * its payment expires. Keep its journal and reconcile it; never replace it with a re-signed intent
47
+ * while it can still land.
48
+ */
49
+ export class PaidReservationStaleEpochError extends Error {
50
+ verificationEpoch;
51
+ /** Stable machine-readable reason. */
52
+ code = 'stale-verification-epoch';
53
+ constructor(
54
+ /** The intent's signed verifier epoch the accountant refused. */
55
+ verificationEpoch) {
56
+ super(`accountant refused verifier epoch ${verificationEpoch} as no longer current or previous; nothing was sent`);
57
+ this.verificationEpoch = verificationEpoch;
58
+ this.name = 'PaidReservationStaleEpochError';
59
+ }
60
+ }
61
+ const HEX32 = /^0x[0-9a-f]{64}$/i;
62
+ const MAX_BODY = 64 * 1024;
63
+ /** The accountant's fixed 503 reason for an intent epoch outside {latest-1, latest} (assignments.rs). */
64
+ const STALE_EPOCH_REASON = 'reservation verifier epoch is not current or previous';
65
+ /** Longest 503 reason read; the accountant's reasons are one short line. */
66
+ const MAX_REASON = 512;
67
+ const now = () => Math.floor(Date.now() / 1000);
68
+ const same = (a, b) => a.toLowerCase() === b.toLowerCase();
69
+ function live(payment, quote) {
70
+ const at = now();
71
+ if (payment.expires <= at || payment.expires > at + 3600)
72
+ throw new Error('payment expiry is outside the allowed lifetime');
73
+ if (quote && (quote.deadline <= at || quote.deadline > payment.expires || quote.deadline > at + 120))
74
+ throw new Error('reservation quote deadline is expired or outside consent');
75
+ }
76
+ function parseQuote(value, payment, signed, historical = false) {
77
+ if (!value || typeof value !== 'object' || Array.isArray(value))
78
+ throw new Error('invalid accountant quote');
79
+ const q = value;
80
+ const fields = ['slot', 'quote_block', 'request_ids', 'costs', 'legacy_nonce', 'deadline', 'digest', 'signature', 'mined'];
81
+ if (Object.keys(q).length !== fields.length || fields.some(k => !Object.hasOwn(q, k)))
82
+ throw new Error('invalid accountant quote fields');
83
+ for (const key of ['slot', 'quote_block', 'digest'])
84
+ if (typeof q[key] !== 'string' || !HEX32.test(q[key]))
85
+ throw new Error('invalid accountant quote hash');
86
+ if (!same(q.slot, payment.slot) || /^0x0{64}$/i.test(q.quote_block) || q.mined !== false
87
+ || !Array.isArray(q.request_ids) || q.request_ids.length !== 1 || typeof q.request_ids[0] !== 'string' || !same(q.request_ids[0], prepaidRequestId(payment))
88
+ || !Array.isArray(q.costs) || q.costs.length !== 1 || typeof q.costs[0] !== 'string' || !/^[0-9]{1,78}$/.test(q.costs[0])
89
+ || BigInt(q.costs[0]) <= 0n || BigInt(q.costs[0]) > BigInt(payment.max_cost)
90
+ || !Number.isSafeInteger(q.legacy_nonce) || q.legacy_nonce < 0
91
+ || !Number.isSafeInteger(q.deadline) || q.deadline <= 0 || q.deadline > payment.expires)
92
+ throw new Error('accountant quote does not match consent');
93
+ if (signed ? typeof q.signature !== 'string' || !/^0x[0-9a-f]{128}$/i.test(q.signature) || /^0x0{128}$/i.test(q.signature) : q.signature !== null)
94
+ throw new Error('invalid accountant quote signature');
95
+ const quote = q;
96
+ if (!historical)
97
+ live(payment, quote);
98
+ const digest = keccak256(encodeAbiParameters([
99
+ { type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }, { type: 'bytes32' }, { type: 'uint64' },
100
+ { type: 'bytes32' }, { type: 'bytes32[]' }, { type: 'uint256[]' }, { type: 'uint64' },
101
+ ], [keccak256(toHex('keykeeper/prepaid-reserve-assigned/v1')), payment.settlement, BigInt(payment.chain_id), payment.slot,
102
+ BigInt(quote.legacy_nonce), quote.quote_block, quote.request_ids, [BigInt(quote.costs[0])], BigInt(quote.deadline)]));
103
+ if (!same(quote.digest, digest))
104
+ throw new Error('accountant quote digest mismatch');
105
+ return quote;
106
+ }
107
+ /**
108
+ * Verify a saved reservation transaction after restart without submitting or replacing anything.
109
+ * Expired intents remain recoverable. Missing transactions, unavailable historical state, reorgs
110
+ * and insufficient confirmations fail closed; none prove that the operation was never submitted.
111
+ * A reverted result proves only this transaction's failure, not absence of another reservation.
112
+ * @param client - Trusted bounded public RPC client with canonical historical reads.
113
+ * @param deployment - Independently approved original deployment.
114
+ * @param original - Original durable preparation; never a newly created replacement intent.
115
+ * @param expected - Independently selected original slot, action and payload digest.
116
+ * @param transactionHash - Saved or independently found candidate hash; its entire identity is checked.
117
+ * @param confirmations - Required inclusion depth, 1..64 (default 1).
118
+ */
119
+ export async function reconcilePaidReservation(client, deployment, original, expected, transactionHash, confirmations = 1) {
120
+ const d = { ...deployment }, record = structuredClone(original), operation = { ...expected };
121
+ const payment = record.payment;
122
+ assertPaymentIntentWire(payment);
123
+ const requestId = prepaidRequestId(payment), tx = record.transaction;
124
+ if (record.schema !== 1 || record.requestId !== requestId || !Number.isSafeInteger(d.chainId) || d.chainId <= 0
125
+ || [d.settlement, d.keyRegistry].some(address => !/^0x[0-9a-f]{40}$/i.test(address) || /^0x0{40}$/i.test(address))
126
+ || payment.chain_id !== d.chainId || !same(payment.settlement, d.settlement) || !same(payment.key_registry, d.keyRegistry)
127
+ || !same(payment.slot, operation.slot) || payment.action !== operation.action || !same(payment.payload_digest, operation.payloadDigest)
128
+ || !HEX32.test(transactionHash) || /^0x0{64}$/i.test(transactionHash) || !Number.isSafeInteger(confirmations) || confirmations < 1 || confirmations > 64)
129
+ throw new Error('invalid reservation recovery identity or confirmations');
130
+ const quote = parseQuote(record.quote, payment, true, true);
131
+ const data = encodeFunctionData({ abi: settlementAbi, functionName: 'reservePrepaidBls', args: [payment.slot, BigInt(quote.legacy_nonce), quote.quote_block,
132
+ [requestId], [BigInt(quote.costs[0])], BigInt(quote.deadline), quote.signature] });
133
+ if (!tx || tx.chainId !== d.chainId || !/^0x[0-9a-f]{40}$/i.test(tx.from) || /^0x0{40}$/i.test(tx.from)
134
+ || !same(tx.to, d.settlement) || !same(tx.data, data) || tx.value !== '0'
135
+ || !Number.isSafeInteger(tx.nonce) || tx.nonce < 0 || typeof tx.gas !== 'string' || !/^[1-9][0-9]{0,77}$/.test(tx.gas) || BigInt(tx.gas) >= 1n << 64n
136
+ || typeof tx.gasPrice !== 'string' || !/^[1-9][0-9]{0,77}$/.test(tx.gasPrice) || BigInt(tx.gasPrice) >= 1n << 128n)
137
+ throw new Error('invalid saved reservation transaction');
138
+ if (await chainIdOf(client) !== d.chainId)
139
+ throw new Error('reservation recovery chain mismatch');
140
+ const [transaction, mined, head, quoteBlock] = await Promise.all([
141
+ client.getTransaction({ hash: transactionHash }), client.getTransactionReceipt({ hash: transactionHash }),
142
+ client.getBlock({ blockTag: 'latest' }), client.getBlock({ blockHash: quote.quote_block }),
143
+ ]);
144
+ const fresh = () => {
145
+ if (head.number === null || head.hash === null || !HEX32.test(head.hash) || /^0x0{64}$/i.test(head.hash)
146
+ || BigInt(now()) - head.timestamp > 30n || head.timestamp - BigInt(now()) > 2n)
147
+ throw new Error('reservation recovery head is stale or unavailable');
148
+ };
149
+ fresh();
150
+ if (transaction.to === null || !same(transaction.hash, transactionHash) || !same(mined.transactionHash, transactionHash)
151
+ || !same(transaction.to, tx.to) || !same(transaction.from, tx.from) || !same(transaction.input, tx.data)
152
+ || transaction.value !== 0n || transaction.nonce !== tx.nonce || transaction.type !== 'legacy' || transaction.chainId !== tx.chainId
153
+ || transaction.gas !== BigInt(tx.gas) || transaction.gasPrice !== BigInt(tx.gasPrice)
154
+ || transaction.blockHash === null || !same(transaction.blockHash, mined.blockHash) || transaction.blockNumber !== mined.blockNumber
155
+ || mined.to === null || !same(mined.to, tx.to) || !same(mined.from, tx.from) || mined.type !== 'legacy'
156
+ || mined.gasUsed <= 0n || mined.gasUsed > BigInt(tx.gas) || mined.effectiveGasPrice !== BigInt(tx.gasPrice)
157
+ || !['success', 'reverted'].includes(mined.status))
158
+ throw new Error('candidate transaction differs from the saved reservation');
159
+ if (head.number === null || head.hash === null || head.number < mined.blockNumber + BigInt(confirmations - 1))
160
+ throw new Error('reservation recovery needs more confirmations');
161
+ if (quoteBlock.number === null || quoteBlock.hash === null || !same(quoteBlock.hash, quote.quote_block)
162
+ || quoteBlock.number > mined.blockNumber)
163
+ throw new Error('invalid original reservation quote block');
164
+ const result = await client.call({ to: d.keyRegistry, data: encodeFunctionData({ abi: keyRegistryAbi, functionName: 'getKeySlot', args: [payment.slot] }),
165
+ blockHash: quote.quote_block, requireCanonical: true, batch: false });
166
+ if (result.data === undefined)
167
+ throw new Error('original slot creator unavailable');
168
+ const slot = decodeFunctionResult({ abi: keyRegistryAbi, functionName: 'getKeySlot', data: result.data });
169
+ const creator = await recoverTypedDataAddress({ ...paymentIntentTypedData(payment), signature: payment.signature });
170
+ if (!slot.exists || slot.cancelled || (slot.expiry !== 0n && slot.expiry <= quoteBlock.timestamp) || !same(creator, slot.creator))
171
+ throw new Error('saved payment is not from the original active slot creator');
172
+ const receipt = mined.status === 'success' ? await readPaidOperationReceipt(client, d, payment, operation, { atLeastBlock: mined.blockNumber }) : undefined;
173
+ if (receipt && (receipt.blockNumber < mined.blockNumber || receipt.cost !== BigInt(quote.costs[0]) || !same(receipt.assignmentBlock, quote.quote_block)))
174
+ throw new Error('recovered reservation differs from the saved quote');
175
+ const [canonicalMined, canonicalQuote, canonicalHead] = await Promise.all([
176
+ client.getBlock({ blockNumber: mined.blockNumber }), client.getBlock({ blockNumber: quoteBlock.number }), client.getBlock({ blockNumber: head.number }),
177
+ ]);
178
+ if (canonicalMined.hash === null || !same(canonicalMined.hash, mined.blockHash)
179
+ || canonicalQuote.hash === null || !same(canonicalQuote.hash, quote.quote_block)
180
+ || canonicalHead.hash === null || !same(canonicalHead.hash, head.hash))
181
+ throw new Error('reservation recovery observation reorganized');
182
+ fresh();
183
+ const observed = { blockNumber: head.number, blockHash: head.hash, blockTimestamp: head.timestamp, requestId, transactionHash,
184
+ transactionBlockNumber: mined.blockNumber, transactionBlockHash: mined.blockHash,
185
+ gasUsed: mined.gasUsed, gasPrice: mined.effectiveGasPrice, gasCost: mined.gasUsed * mined.effectiveGasPrice };
186
+ return receipt ? { ...observed, status: 'success', receipt } : { ...observed, status: 'reverted' };
187
+ }
188
+ function unsigned(q) {
189
+ return JSON.stringify([q.slot.toLowerCase(), q.quote_block.toLowerCase(), q.request_ids.map(s => s.toLowerCase()), q.costs.map(s => BigInt(s).toString()), q.legacy_nonce, q.deadline, q.digest.toLowerCase()]);
190
+ }
191
+ /**
192
+ * Validated, de-duplicated accountant base URLs (HTTPS; HTTP only on local chain 43112 when allowed).
193
+ * @param options Endpoints and the local HTTP exception.
194
+ * @param chainId Deployment chain.
195
+ */
196
+ export function accountantEndpoints(options, chainId) {
197
+ if (options.accountantUrls.length < 1 || options.accountantUrls.length > 32)
198
+ throw new Error('supply 1..32 accountant endpoints');
199
+ const urls = options.accountantUrls.map(value => {
200
+ const url = new URL(value);
201
+ if (url.username || url.password || url.search || url.hash || (url.protocol !== 'https:'
202
+ && !(options.allowLocalHttp && chainId === 43112 && url.protocol === 'http:')))
203
+ throw new Error('invalid accountant endpoint transport');
204
+ return url.toString().replace(/\/+$/, '');
205
+ });
206
+ if (new Set(urls).size !== urls.length)
207
+ throw new Error('duplicate accountant endpoints');
208
+ return urls;
209
+ }
210
+ /**
211
+ * Settle with `work`, or reject with the abort reason as soon as `signal` aborts (work keeps running).
212
+ * @param work Pending work that is not cancelled by the abort.
213
+ * @param signal Optional cancellation of the wait only.
214
+ */
215
+ export function untilAborted(work, signal) {
216
+ if (!signal)
217
+ return work;
218
+ return new Promise((resolve, reject) => {
219
+ const abort = () => reject(signal.reason);
220
+ if (signal.aborted) {
221
+ work.catch(() => { });
222
+ abort();
223
+ return;
224
+ }
225
+ signal.addEventListener('abort', abort, { once: true });
226
+ work.then(value => { signal.removeEventListener('abort', abort); resolve(value); }, (error) => { signal.removeEventListener('abort', abort); reject(error); });
227
+ });
228
+ }
229
+ /** At most `limit` bytes of a refusal body as text, '' when unreadable; the rest is cancelled. */
230
+ async function boundedText(response, limit) {
231
+ if (!response.body)
232
+ return '';
233
+ const reader = response.body.getReader(), chunks = [];
234
+ let size = 0;
235
+ try {
236
+ while (size < limit) {
237
+ const { done, value } = await reader.read();
238
+ if (done)
239
+ break;
240
+ chunks.push(value.subarray(0, limit - size));
241
+ size += Math.min(value.length, limit - size);
242
+ }
243
+ }
244
+ catch {
245
+ return '';
246
+ }
247
+ finally {
248
+ void reader.cancel().catch(() => { });
249
+ reader.releaseLock();
250
+ }
251
+ const bytes = new Uint8Array(size);
252
+ let offset = 0;
253
+ for (const chunk of chunks) {
254
+ bytes.set(chunk, offset);
255
+ offset += chunk.length;
256
+ }
257
+ return new TextDecoder().decode(bytes);
258
+ }
259
+ /** Ceiling on how long one `prepare` may wait out the accountant's reservation quota, ms. */
260
+ const PREPARE_RETRY_BUDGET_MS = 150_000;
261
+ /** Least time a REPEATED prepare must have left in its window; its HTTP timeout is then the time left. */
262
+ const PREPARE_ATTEMPT_BUDGET_MS = 10_000;
263
+ // Availability is distinct from policy/credit refusals or an invalid successful response.
264
+ // Only this private error permits trying a different endpoint before any transaction exists.
265
+ class AccountantUnavailableError extends Error {
266
+ /** A 503 to a prepare carrying {@link PRE_WRITE_REASON} or {@link STALE_BLOCK_REASON}: refused before anything was recorded. */
267
+ preWrite;
268
+ /** A 503 to a prepare carrying {@link NOT_YET_VISIBLE_REASON}: the member's RPC has not served the named block yet. */
269
+ notYetVisible;
270
+ constructor(message, options) {
271
+ super(message, options);
272
+ this.preWrite = options?.preWrite === true;
273
+ this.notYetVisible = options?.notYetVisible === true;
274
+ }
275
+ }
276
+ /**
277
+ * A definite 403/409 to a `prepare` (creator, consent, assignment or cutover at the quote block):
278
+ * judged BEFORE the accountant records anything, so it is that member's answer - another member may
279
+ * seed, and this one is asked again at the seed's block (robustness audit 2026-11-13, P3). A 402 is
280
+ * the same kind of answer, carried as {@link UnderfundedSlotError}.
281
+ */
282
+ class AccountantRefusedError extends Error {
283
+ }
284
+ /** A prepared member's `authorize` lead was refused by members that never approved the digest: no other prepared leader can gather k either. */
285
+ export class PaidReservationQuorumNotPreparedError extends Error {
286
+ /** Stable machine-readable reason. */
287
+ code = 'quorum-not-prepared';
288
+ constructor() {
289
+ super('accountant reservation quorum not prepared: members that never approved this reservation refused to sign it; nothing was sent');
290
+ this.name = 'PaidReservationQuorumNotPreparedError';
291
+ }
292
+ }
293
+ /**
294
+ * The accountant's fixed 503 label for a failed verifier-assignment check (every release; the
295
+ * detail follows a `:`). That check runs BEFORE the reservation archive record and the signer's
296
+ * digest approval - the only things a `prepare` writes - so a member answering it recorded and
297
+ * approved nothing. It is what an accountant deciding at a head older than the client's answers:
298
+ * 2026-11-12 cert run 16, the previous epoch's verifier anchor landed in the block after the beacon
299
+ * advanced and every rolled-back accountant decided one block before it, where it was still empty.
300
+ */
301
+ const PRE_WRITE_REASON = 'reservation assignments unavailable';
302
+ /** The named block is outside the accountant's freshness bound: judged right after the read, before anything is recorded. */
303
+ const STALE_BLOCK_REASON = 'quote block is stale, future or mismatched';
304
+ /** A newer accountant's RPC has not served the named block yet, after its own bounded wait: nothing was read or recorded. */
305
+ const NOT_YET_VISIBLE_REASON = 'quote block not yet visible';
306
+ /** A newer accountant's lead was refused by members that never approved the digest. */
307
+ const QUORUM_NOT_PREPARED_REASON = 'reservation quorum not prepared';
308
+ const labelled = (text, label) => {
309
+ const t = text.trimStart();
310
+ return t.startsWith(label) && (t.length === label.length || t[label.length] === ':');
311
+ };
312
+ /**
313
+ * The prepare retry window: never more than {@link PREPARE_RETRY_BUDGET_MS} and never more than HALF
314
+ * of what is left of the signed payment expiry, so the authorize, the mined reservation and the
315
+ * credential session keep at least the other half.
316
+ */
317
+ function prepareRetryWindowMs(expires, nowMs) {
318
+ return Math.min(PREPARE_RETRY_BUDGET_MS, Math.max(0, Math.floor((expires - Math.floor(nowMs / 1000)) / 2)) * 1000);
319
+ }
320
+ /**
321
+ * One accountant reservation exchange; every attempt sends the SAME request bytes.
322
+ *
323
+ * Only `prepare` is ever repeated, and only after a 429 carrying a valid `Retry-After` (or
324
+ * `x-ratelimit-after`): the accountant answers its per-creator reservation quota that way BEFORE
325
+ * recording or signing anything, and nothing is on chain until the single reservation transaction
326
+ * after `authorize`. Every other status (503 included), every `authorize` answer and every transport
327
+ * error keeps its existing meaning. A repeated prepare needs {@link PREPARE_ATTEMPT_BUDGET_MS} left in
328
+ * its window and its HTTP timeout is cut to the time left.
329
+ */
330
+ async function ask(endpoint, method, payment, block, timeout, signal, clock = systemPacingClock) {
331
+ const url = `${endpoint}/v1/prepaid/reservations/${method}`, request = JSON.stringify({ intents: [payment], quote_block: block });
332
+ const backoff = new PaidBackoff(clock, 'POST /v1/prepaid/reservations/prepare', clock.now() + prepareRetryWindowMs(payment.expires, clock.now()), PREPARE_ATTEMPT_BUDGET_MS);
333
+ let response, hint;
334
+ const quota = (cause) => cause instanceof PaidBackoffError && hint !== undefined
335
+ ? new PaidReservationQuotaError({ reason: cause.code, url, retryAfterMs: hint, cause }) : cause;
336
+ for (;;) {
337
+ let limit = timeout;
338
+ // Re-read after a sleep: an overrun never leads to a late send.
339
+ if (backoff.retries > 0)
340
+ try {
341
+ limit = Math.min(timeout, backoff.readyToSend());
342
+ }
343
+ catch (cause) {
344
+ throw quota(cause);
345
+ }
346
+ const deadline = AbortSignal.timeout(limit);
347
+ try {
348
+ response = await fetch(url, { method: 'POST', redirect: 'error',
349
+ headers: { 'content-type': 'application/json' }, body: request, signal: signal ? AbortSignal.any([signal, deadline]) : deadline });
350
+ }
351
+ catch (cause) {
352
+ signal?.throwIfAborted();
353
+ throw new AccountantUnavailableError('accountant reservation transport unavailable', { cause });
354
+ }
355
+ hint = paidServerWaitMs(response.headers?.get('retry-after'), response.headers?.get('x-ratelimit-after'));
356
+ if (method !== 'prepare' || response.status !== 429 || hint === undefined)
357
+ break;
358
+ void response.body?.cancel().catch(() => { });
359
+ try {
360
+ await backoff.wait(429, hint, signal);
361
+ }
362
+ catch (cause) {
363
+ throw quota(cause);
364
+ }
365
+ }
366
+ if (!response.ok) {
367
+ if (response.status === 503) {
368
+ const reason = await boundedText(response, MAX_REASON);
369
+ if (method === 'prepare') {
370
+ // Every member judges the named block alike: an epoch stale there is stale everywhere.
371
+ if (reason.includes(STALE_EPOCH_REASON))
372
+ throw new PaidReservationStaleEpochError(payment.verification_epoch);
373
+ throw new AccountantUnavailableError('accountant reservation request refused (503)', {
374
+ preWrite: labelled(reason, PRE_WRITE_REASON) || labelled(reason, STALE_BLOCK_REASON),
375
+ notYetVisible: labelled(reason, NOT_YET_VISIBLE_REASON)
376
+ });
377
+ }
378
+ if (labelled(reason, QUORUM_NOT_PREPARED_REASON))
379
+ throw new PaidReservationQuorumNotPreparedError();
380
+ throw new AccountantUnavailableError('accountant reservation request refused (503)');
381
+ }
382
+ void response.body?.cancel().catch(() => { });
383
+ if (response.status >= 500 && response.status < 600)
384
+ throw new AccountantUnavailableError(`accountant reservation request refused (${response.status})`);
385
+ if (response.status === 402)
386
+ throw new UnderfundedSlotError({ slotId: payment.slot, status: 402,
387
+ url, message: 'accountant reservation request refused (402): insufficient available TASRA' });
388
+ if (method === 'prepare' && (response.status === 403 || response.status === 409))
389
+ throw new AccountantRefusedError(`accountant reservation request refused (${response.status})`);
390
+ throw new Error(`accountant reservation request refused (${response.status})`);
391
+ }
392
+ if (!response.body)
393
+ throw new Error(`accountant reservation request refused (${response.status})`);
394
+ const reader = response.body.getReader();
395
+ const chunks = [];
396
+ let size = 0;
397
+ try {
398
+ for (;;) {
399
+ const { done, value } = await reader.read().catch((cause) => {
400
+ signal?.throwIfAborted();
401
+ throw new AccountantUnavailableError('accountant reservation response interrupted', { cause });
402
+ });
403
+ if (done)
404
+ break;
405
+ size += value.length;
406
+ if (size > MAX_BODY)
407
+ throw new Error('accountant quote exceeds 64 KiB');
408
+ chunks.push(value);
409
+ }
410
+ }
411
+ finally {
412
+ // Cancelling one branch of a tee can await its untouched sibling indefinitely.
413
+ // Initiate cancellation without making cleanup an unbounded request tail.
414
+ void reader.cancel().catch(() => { });
415
+ reader.releaseLock();
416
+ }
417
+ const body = new Uint8Array(size);
418
+ let offset = 0;
419
+ for (const chunk of chunks) {
420
+ body.set(chunk, offset);
421
+ offset += chunk.length;
422
+ }
423
+ return parseQuote(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(body)), payment, method === 'authorize');
424
+ }
425
+ /**
426
+ * One intent and quote across available members; no transaction or journal mutation here.
427
+ *
428
+ * Robustness audit 2026-11-13 (P1-P3, P7): every round NAMES one block - the first one `first()`,
429
+ * the discovery block or the client's fresh head - so every member judges the signed intent at the
430
+ * same chain state. A member's answer that recorded nothing (the pre-write 503, a stale named block,
431
+ * a definite 402/403/409, or "block not yet visible") is that member's answer, not the
432
+ * collection's: another member may seed, and every such member is asked once more at the seed's
433
+ * block with the same intent. When EVERY member answers so in the first round, the round is
434
+ * repeated ONCE at the client's fresh `latest` block. A transport error (whose effect is unknown)
435
+ * is never repeated to that member, and a prepared member's "quorum not prepared" ends the
436
+ * collection (every other prepared leader asks the same members).
437
+ */
438
+ async function collectQuote(urls, payment, requestTimeout, signal, clock, first, latest) {
439
+ const budget = prepareRetryWindowMs(payment.expires, clock.now()), end = clock.now() + budget;
440
+ if (budget <= 0)
441
+ throw new Error('payment expired before reservation collection');
442
+ const limit = AbortSignal.timeout(budget), bounded = signal ? AbortSignal.any([signal, limit]) : limit;
443
+ const remaining = () => {
444
+ bounded.throwIfAborted();
445
+ const left = end - clock.now();
446
+ if (left <= 0)
447
+ throw new Error('reservation collection exhausted its shared time budget');
448
+ return Math.min(requestTimeout, left);
449
+ };
450
+ const request = async (url, method, block) => {
451
+ try {
452
+ const result = await ask(url, method, payment, block, remaining(), bounded, clock);
453
+ remaining();
454
+ return result;
455
+ }
456
+ catch (error) {
457
+ bounded.throwIfAborted();
458
+ throw error;
459
+ }
460
+ };
461
+ // The member's answer when it recorded nothing; `undefined` for an error that ends the collection.
462
+ const classify = (error) => {
463
+ if (error instanceof UnderfundedSlotError || error instanceof AccountantRefusedError)
464
+ return 'pre-write';
465
+ if (!(error instanceof AccountantUnavailableError))
466
+ return undefined;
467
+ return error.notYetVisible ? 'not-visible' : error.preWrite ? 'pre-write' : 'unavailable';
468
+ };
469
+ let seed, lastFailure;
470
+ const failed = (error) => { lastFailure = error instanceof Error ? error : new Error(String(error)); };
471
+ let answers = [];
472
+ const seedRound = async (block) => {
473
+ answers = urls.map(() => undefined);
474
+ for (const [index, url] of urls.entries()) {
475
+ try {
476
+ const quote = await request(url, 'prepare', block);
477
+ if (!same(quote.quote_block, block))
478
+ throw new Error('accountant prepared a different quote block than the one named');
479
+ seed = { quote, index };
480
+ return;
481
+ }
482
+ catch (error) {
483
+ const answer = classify(error);
484
+ if (answer === undefined)
485
+ throw error;
486
+ answers[index] = answer;
487
+ failed(error);
488
+ }
489
+ }
490
+ };
491
+ const named = await untilAborted(first(), bounded);
492
+ remaining();
493
+ await seedRound(named);
494
+ if (!seed && urls.length > 0 && answers.every(answer => answer === 'pre-write')) {
495
+ const head = await untilAborted(latest(), bounded);
496
+ remaining();
497
+ if (!same(head, named))
498
+ await seedRound(head);
499
+ }
500
+ if (!seed)
501
+ throw lastFailure ?? new Error('no reachable accountant prepared the reservation');
502
+ const { quote, index } = seed, prepared = [urls[index]];
503
+ // Every OTHER member once at the seed's exact block: every later one, and every earlier one whose
504
+ // answer recorded nothing. A dissenting quote or a malformed success stops the collection.
505
+ const candidates = urls.filter((_, i) => i > index || answers[i] === 'pre-write' || answers[i] === 'not-visible');
506
+ const preparations = await Promise.allSettled(candidates.map(url => request(url, 'prepare', quote.quote_block)));
507
+ for (const [i, result] of preparations.entries()) {
508
+ if (result.status === 'rejected') {
509
+ // That member's answer; k independent preparations are the accountants' own threshold check.
510
+ if (classify(result.reason) === undefined)
511
+ throw result.reason;
512
+ continue;
513
+ }
514
+ if (unsigned(result.value) !== unsigned(quote))
515
+ throw new Error('accountants disagree on reservation');
516
+ prepared.push(candidates[i]);
517
+ }
518
+ for (const url of prepared) {
519
+ live(payment, quote);
520
+ try {
521
+ const authorized = await request(url, 'authorize', quote.quote_block);
522
+ if (unsigned(authorized) !== unsigned(quote))
523
+ throw new Error('authorization changed the prepared reservation');
524
+ return { quote, authorized };
525
+ }
526
+ catch (error) {
527
+ if (!(error instanceof AccountantUnavailableError))
528
+ throw error;
529
+ failed(error);
530
+ }
531
+ }
532
+ throw lastFailure ?? new Error('no prepared accountant returned a quorum authorization');
533
+ }
534
+ /**
535
+ * Reserve TASRA for a fixed creator-signed operation using an accountant threshold quote.
536
+ * Does not create an intent, approve tokens, activate a slot, authorize credentials or do keeper
537
+ * work. Before broadcast, unavailable accountants can be skipped while collecting the same quote
538
+ * and quorum authorization. One broadcast attempt only; no replacement or implicit gas funding.
539
+ * @param client - Trusted bounded public RPC client; use retryCount: 0 for submissions.
540
+ * @param wallet - Account-bound gas payer on the selected chain; no automatic wallet retries.
541
+ * @param deployment - Independently approved deployment.
542
+ * @param original - Creator intent from independently verified assignment/session discovery.
543
+ * @param expected - Independently derived operation.
544
+ * @param options - Fee limits, accountant endpoints and mandatory durable persistence.
545
+ */
546
+ export async function reservePaidOperation(client, wallet, deployment, original, expected, options) {
547
+ const signal = options.signal, progress = { preparing: false };
548
+ try {
549
+ return await reserveOnce(client, wallet, deployment, original, expected, options, progress);
550
+ }
551
+ catch (error) {
552
+ // Before the durable preparation nothing was journaled or sent: the abort is a clean refusal.
553
+ if (!progress.preparing && progress.requestId && signal?.aborted && !(error instanceof PaidReservationUncertainError))
554
+ throw new PaidReservationAbortedError(progress.requestId, signal.reason ?? error);
555
+ throw error;
556
+ }
557
+ }
558
+ async function reserveOnce(client, wallet, deployment, original, expected, options, progress) {
559
+ // Snapshot caller-owned inputs before the first await; storage receives its own copy too.
560
+ const payment = structuredClone(original), d = { ...deployment }, operation = { ...expected };
561
+ const opts = { ...options, accountantUrls: [...options.accountantUrls], ...(options.quoteBlock ? { quoteBlock: { ...options.quoteBlock } } : {}) }, signal = opts.signal;
562
+ const payer = { ...wallet.account }, payerChain = { ...wallet.chain };
563
+ assertPaymentIntentWire(payment);
564
+ if (!Number.isSafeInteger(d.chainId) || d.chainId <= 0 || payment.chain_id !== d.chainId
565
+ || !same(payment.settlement, d.settlement) || !same(payment.key_registry, d.keyRegistry)
566
+ || !same(payment.slot, operation.slot) || payment.action !== operation.action || !same(payment.payload_digest, operation.payloadDigest))
567
+ throw new Error('payment deployment or operation mismatch');
568
+ if (typeof opts.maxGas !== 'bigint' || typeof opts.maxGasPrice !== 'bigint' || opts.maxGas <= 0n || opts.maxGas >= 1n << 64n || opts.maxGasPrice <= 0n || opts.maxGasPrice >= 1n << 128n || typeof opts.persist !== 'function')
569
+ throw new Error('invalid reservation gas budget or journal');
570
+ const requestTimeout = opts.requestTimeoutMs ?? 85000, receiptTimeout = opts.receiptTimeoutMs ?? 60000, confirmations = opts.confirmations ?? 1;
571
+ if (!Number.isSafeInteger(requestTimeout) || requestTimeout < 1 || requestTimeout > 85000
572
+ || !Number.isSafeInteger(receiptTimeout) || receiptTimeout < 1 || receiptTimeout > 120000
573
+ || !Number.isSafeInteger(confirmations) || confirmations < 1 || confirmations > 64)
574
+ throw new Error('invalid reservation timeout or confirmations');
575
+ live(payment);
576
+ progress.requestId = prepaidRequestId(payment);
577
+ signal?.throwIfAborted();
578
+ const urls = accountantEndpoints(opts, d.chainId);
579
+ if (payer.type !== 'local' && payer.type !== 'json-rpc')
580
+ throw new Error('reservation requires an EOA gas payer');
581
+ if (payerChain.id !== d.chainId)
582
+ throw new Error('reservation RPC/wallet chain mismatch');
583
+ // The wallet's and the reader's chain IDs are independent reads (a new wallet client is not
584
+ // cached yet): asked together, judged in the original order, before anything is contacted.
585
+ const [walletChain, readerChain] = await Promise.allSettled([chainIdOf(wallet), chainIdOf(client)]);
586
+ if (walletChain.status === 'rejected')
587
+ throw walletChain.reason;
588
+ if (walletChain.value !== d.chainId)
589
+ throw new Error('reservation RPC/wallet chain mismatch');
590
+ if (readerChain.status === 'rejected')
591
+ throw readerChain.reason;
592
+ if (readerChain.value !== d.chainId)
593
+ throw new Error('reservation RPC/wallet chain mismatch');
594
+ const clock = opts.clock ?? systemPacingClock;
595
+ const latestHash = async () => {
596
+ const head = await client.getBlock({ blockTag: 'latest' });
597
+ if (head.hash === null)
598
+ throw new Error('latest block has no hash');
599
+ return head.hash;
600
+ };
601
+ // P1: the first prepare names the discovery block while it is fresh enough for the whole
602
+ // collection, else the client's own fresh head - never no block.
603
+ const pinned = opts.quoteBlock;
604
+ const firstBlock = async () => pinned && HEX32.test(pinned.blockHash) && typeof pinned.blockTimestamp === 'bigint'
605
+ && BigInt(now()) - pinned.blockTimestamp <= PIN_MAX_AGE_SECS && pinned.blockTimestamp - BigInt(now()) <= 2n ? pinned.blockHash : latestHash();
606
+ const { quote, authorized } = await collectQuote(urls, payment, requestTimeout, signal, clock, firstBlock, latestHash);
607
+ const requestId = prepaidRequestId(payment);
608
+ const args = [payment.slot, BigInt(quote.legacy_nonce), quote.quote_block, [requestId], [BigInt(quote.costs[0])], BigInt(quote.deadline)];
609
+ const data = encodeFunctionData({ abi: settlementAbi, functionName: 'reservePrepaidBls', args: [...args, authorized.signature] });
610
+ // The quote block's header is read beside the observations below (all pinned to that same hash)
611
+ // and judged before them, as when it was read first on its own.
612
+ const blockRead = client.getBlock({ blockHash: quote.quote_block });
613
+ blockRead.catch(() => { });
614
+ const call = async (to, data) => {
615
+ const result = await client.call({ to, data, account: payer, blockHash: quote.quote_block, requireCanonical: true, batch: false });
616
+ if (result.data === undefined)
617
+ throw new Error('empty reservation observation');
618
+ return result.data;
619
+ };
620
+ // Every observation below is independent of the others: they are sent together and judged in the
621
+ // order they were once read one by one, so the same answer refuses with the same error.
622
+ const settled = (work) => work.then(value => ({ value }), (error) => ({ error }));
623
+ const outcome = (result) => { if ('error' in result)
624
+ throw result.error; return result.value; };
625
+ const [digestRead, costRead, slotRead, simulation, feeReads] = await Promise.all([
626
+ settled(call(d.settlement, encodeFunctionData({ abi: settlementAbi, functionName: 'prepaidReserveDigest', args }))),
627
+ settled(call(d.settlement, encodeFunctionData({ abi: settlementAbi, functionName: 'prepaidCost', args: [payment.slot, requestId] }))),
628
+ settled(call(d.keyRegistry, encodeFunctionData({ abi: keyRegistryAbi, functionName: 'getKeySlot', args: [payment.slot] }))),
629
+ // Contract simulation verifies the accountant threshold signature and reservation state without gas.
630
+ settled(client.call({ to: d.settlement, data, account: payer, blockHash: quote.quote_block, requireCanonical: true, batch: false })),
631
+ settled(Promise.all([
632
+ // A local Account makes viem prepare EIP-1559 fees during estimation, but
633
+ // this flow signs a bounded legacy transaction below. Estimate execution
634
+ // with zero simulation fees, then check the actual legacy gas cost. Without
635
+ // this separation a balance-capped BN254 precompile can report BadSignature.
636
+ client.getGasPrice(), client.estimateGas({ account: payer.address, to: d.settlement, data, value: 0n, gasPrice: 0n, type: 'legacy' }),
637
+ client.getTransactionCount({ address: payer.address, blockTag: 'pending' }),
638
+ client.getBalance({ address: payer.address, blockTag: 'pending' }),
639
+ ])),
640
+ ]);
641
+ const block = await blockRead;
642
+ const fresh = () => {
643
+ if (block.number === null || block.hash === null || !same(block.hash, quote.quote_block)
644
+ || BigInt(now()) - block.timestamp > 30n || block.timestamp - BigInt(now()) > 2n)
645
+ throw new Error('reservation quote block is stale or invalid');
646
+ live(payment, quote);
647
+ };
648
+ fresh();
649
+ const digest = decodeFunctionResult({ abi: settlementAbi, functionName: 'prepaidReserveDigest', data: outcome(digestRead) });
650
+ if (!same(digest, quote.digest))
651
+ throw new Error('deployment reservation digest mismatch');
652
+ const previousCost = decodeFunctionResult({ abi: settlementAbi, functionName: 'prepaidCost', data: outcome(costRead) });
653
+ if (previousCost !== 0n)
654
+ throw new Error('operation already reserved; inspect its receipt instead of spending again');
655
+ const slot = decodeFunctionResult({ abi: keyRegistryAbi, functionName: 'getKeySlot', data: outcome(slotRead) });
656
+ const creator = await recoverTypedDataAddress({ ...paymentIntentTypedData(payment), signature: payment.signature });
657
+ if (!slot.exists || slot.cancelled || (slot.expiry !== 0n && slot.expiry <= BigInt(now())) || !same(creator, slot.creator))
658
+ throw new Error('reservation intent is not from an active slot creator');
659
+ outcome(simulation);
660
+ const [gasPrice, gas, nonce, balance] = outcome(feeReads);
661
+ if (gas <= 0n || gas > opts.maxGas || gasPrice <= 0n || gasPrice > opts.maxGasPrice)
662
+ throw new Error('reservation exceeds native gas budget');
663
+ const requiredNativeUnits = gas * gasPrice;
664
+ if (balance < requiredNativeUnits)
665
+ throw new UnderfundedGasPayerError({ payer: payer.address, availableNativeUnits: balance, requiredNativeUnits });
666
+ signal?.throwIfAborted();
667
+ if (block.number === null)
668
+ throw new Error('reservation quote has no block number');
669
+ // The canonical recheck of the quote block after its reads: answered by the head follower only
670
+ // when it proves this exact block canonical (instant finality, live, gap-free, at or below the
671
+ // finalized head), as for every other paid observation; anything else reads it by number.
672
+ if (headFollowerOf(client)?.isCanonical({ blockNumber: block.number, blockHash: quote.quote_block, blockTimestamp: block.timestamp }) !== true) {
673
+ const canonical = await client.getBlock({ blockNumber: block.number });
674
+ if (canonical.hash === null || !same(canonical.hash, quote.quote_block))
675
+ throw new Error('reservation quote reorganized');
676
+ }
677
+ fresh();
678
+ const record = { schema: 1, requestId, payment, quote: authorized,
679
+ transaction: { chainId: d.chainId, from: payer.address, to: d.settlement, data, value: '0', nonce, gas: gas.toString(), gasPrice: gasPrice.toString() } };
680
+ // A local signer signs BEFORE the durable preparation, so the exact transaction hash is
681
+ // journaled before anything can be broadcast. Signing alone sends nothing; a failure here
682
+ // leaves no preparation and therefore provably no transaction.
683
+ let raw, transactionHash;
684
+ if (payer.type === 'local') {
685
+ raw = await wallet.signTransaction({ account: payer, chain: payerChain,
686
+ to: d.settlement, data, value: 0n, nonce, gas, gasPrice, type: 'legacy' });
687
+ const signed = parseTransaction(raw), sender = await recoverTransactionAddress({ serializedTransaction: raw });
688
+ if (signed.type !== 'legacy' || signed.chainId !== d.chainId || !same(sender, payer.address)
689
+ || !signed.to || !same(signed.to, d.settlement) || !signed.data || !same(signed.data, data)
690
+ || (signed.value ?? 0n) !== 0n || signed.nonce !== nonce || signed.gas !== gas || signed.gasPrice !== gasPrice)
691
+ throw new Error('signed transaction differs from the durable reservation');
692
+ transactionHash = keccak256(raw);
693
+ fresh();
694
+ }
695
+ // The last point an abort is honoured: from the durable preparation on, the single broadcast
696
+ // proceeds and every checkpoint is written in full, so the journal is never left half-written.
697
+ signal?.throwIfAborted();
698
+ progress.preparing = true;
699
+ await opts.persist({ phase: 'prepared', record: structuredClone(record), ...(transactionHash ? { transactionHash } : {}) });
700
+ try {
701
+ fresh();
702
+ // Viem's generic sendTransaction can retry through wallet_sendTransaction on certain
703
+ // RPC errors. Use exactly one RPC submission, including when the outcome is uncertain.
704
+ if (raw !== undefined) {
705
+ const returned = await wallet.request({ method: 'eth_sendRawTransaction', params: [raw] }, { retryCount: 0 });
706
+ if (returned === undefined || transactionHash === undefined || !same(returned, transactionHash))
707
+ throw new Error('RPC returned another signed transaction hash');
708
+ }
709
+ else {
710
+ transactionHash = await wallet.request({ method: 'eth_sendTransaction', params: [{ from: payer.address,
711
+ to: d.settlement, data, value: '0x0', nonce: toHex(nonce), gas: toHex(gas), gasPrice: toHex(gasPrice),
712
+ type: '0x0', chainId: toHex(d.chainId) }] }, { retryCount: 0 });
713
+ }
714
+ if (typeof transactionHash !== 'string' || !HEX32.test(transactionHash) || /^0x0{64}$/i.test(transactionHash))
715
+ throw new Error('invalid reservation transaction hash');
716
+ await opts.persist({ phase: 'submitted', requestId, transactionHash });
717
+ // A broadcast transaction cannot be cancelled: an abort only ends this wait, as uncertain.
718
+ const sent = transactionHash;
719
+ const mined = await untilAborted(pollTransactionReceipt(client, sent, { confirmations, timeoutMs: receiptTimeout, signal }), signal);
720
+ if (!same(mined.transactionHash, transactionHash) || mined.status !== 'success')
721
+ throw new Error('reservation transaction reverted or was replaced');
722
+ // The mined transaction, the reservation it made and its block are read together, and judged
723
+ // in the order they were once read one by one.
724
+ const [transactionRead, receiptRead, minedBlockRead] = await untilAborted(Promise.all([
725
+ settled(client.getTransaction({ hash: sent })), settled(readPaidOperationReceipt(client, d, payment, operation, { atLeastBlock: mined.blockNumber })),
726
+ settled(client.getBlock({ blockNumber: mined.blockNumber }))
727
+ ]), signal);
728
+ const transaction = outcome(transactionRead);
729
+ if (transaction.to === null || !same(transaction.to, d.settlement) || !same(transaction.from, record.transaction.from)
730
+ || !same(transaction.input, data) || transaction.value !== 0n || transaction.nonce !== nonce
731
+ || transaction.type !== 'legacy' || transaction.gas !== gas || transaction.gasPrice !== gasPrice || transaction.chainId !== d.chainId
732
+ || transaction.blockHash === null || !same(transaction.blockHash, mined.blockHash))
733
+ throw new Error('mined transaction differs from the durable reservation');
734
+ const receipt = outcome(receiptRead);
735
+ if (receipt.blockNumber < mined.blockNumber || receipt.cost !== BigInt(quote.costs[0]) || !same(receipt.assignmentBlock, quote.quote_block))
736
+ throw new Error('mined reservation differs from the saved quote');
737
+ const minedBlock = outcome(minedBlockRead);
738
+ if (minedBlock.hash === null || !same(minedBlock.hash, mined.blockHash))
739
+ throw new Error('reservation receipt reorganized');
740
+ await opts.persist({ phase: 'confirmed', requestId, transactionHash, blockHash: mined.blockHash });
741
+ return { transactionHash, receipt };
742
+ }
743
+ catch (cause) {
744
+ throw new PaidReservationUncertainError(requestId, transactionHash, cause);
745
+ }
746
+ }