@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,148 @@
1
+ // Clients for prepaid payout faults: the accountant witness intake, its health status, and
2
+ // the PrepaidFaultOracle that executes a threshold-signed verdict.
3
+ //
4
+ // A victim (or anyone holding signed evidence) hands an accountant a proof bundle; the
5
+ // accountant set adjudicates and threshold-signs a verdict; anyone may relay that verdict to
6
+ // the oracle, which slashes the offender (and pays a bounty to the under-credited worker).
7
+ // None of these calls is retried automatically: a lost claim reply is re-sent by the caller
8
+ // once it has decided to, and a contest transaction is reconciled like any other write.
9
+ import { encodeFunctionData } from 'viem';
10
+ import { prepaidFaultOracleAbi } from './abis/prepaidFaultOracle.js';
11
+ import { revertError } from './revertReason.js';
12
+ import { httpError, TasraError } from '../errors.js';
13
+ /** Fault kinds in the oracle's enum order. */
14
+ export const PREPAID_FAULT_KINDS = ['WrongPayout', 'KeeperUndercredit', 'KeeperOvercredit', 'VerifierUndercredit', 'VerifierOvercredit'];
15
+ /** Accountant claim intake byte limit (the witness's own bundle maximum). */
16
+ export const MAX_PREPAID_FAULT_BUNDLE_BYTES = 768 * 1024;
17
+ const HEX32 = /^0x[0-9a-fA-F]{64}$/;
18
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
19
+ const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
20
+ const MAX_VERDICT_LIFETIME = 120n;
21
+ function verdictTuple(v, nowSecs) {
22
+ for (const [name, value] of [['slotId', v.slotId], ['requestId', v.requestId], ['batchId', v.batchId], ['evidenceHash', v.evidenceHash]]) {
23
+ if (typeof value !== 'string' || !HEX32.test(value) || /^0x0{64}$/.test(value))
24
+ throw new TasraError(`Invalid prepaid fault verdict ${name}`);
25
+ }
26
+ if (!ADDRESS.test(v.offender) || v.offender.toLowerCase() === ZERO_ADDRESS || !ADDRESS.test(v.beneficiary))
27
+ throw new TasraError('Invalid prepaid fault verdict offender or beneficiary');
28
+ const kind = PREPAID_FAULT_KINDS.indexOf(v.kind);
29
+ if (kind < 0)
30
+ throw new TasraError('Invalid prepaid fault kind');
31
+ const undercredit = v.kind === 'KeeperUndercredit' || v.kind === 'VerifierUndercredit';
32
+ const none = v.beneficiary.toLowerCase() === ZERO_ADDRESS;
33
+ if (undercredit ? none || v.beneficiary.toLowerCase() === v.offender.toLowerCase() : !none)
34
+ throw new TasraError('Only an under-credit verdict names a beneficiary, and never the offender');
35
+ if (typeof v.epoch !== 'bigint' || v.epoch < 0n || v.epoch >= 2n ** 64n || typeof v.deadline !== 'bigint'
36
+ || v.deadline <= nowSecs || v.deadline - nowSecs > MAX_VERDICT_LIFETIME)
37
+ throw new TasraError('Prepaid fault verdict epoch or deadline is outside the oracle window');
38
+ return { slotId: v.slotId, requestId: v.requestId, batchId: v.batchId, evidenceHash: v.evidenceHash, offender: v.offender,
39
+ beneficiary: v.beneficiary, kind, epoch: v.epoch, deadline: v.deadline };
40
+ }
41
+ function signatureBytes(signature) {
42
+ if (typeof signature !== 'string' || !/^0x(?:[0-9a-fA-F]{2}){1,512}$/.test(signature))
43
+ throw new TasraError('Invalid prepaid fault verdict signature');
44
+ return signature;
45
+ }
46
+ /**
47
+ * Calldata for `PrepaidFaultOracle.contest`, after the oracle's local preconditions
48
+ * (nonzero subject, beneficiary rule, a deadline within 120 s). Chain-dependent checks
49
+ * (current epoch, settled request and batch, signature) stay with the oracle.
50
+ * @param verdict Threshold-signed verdict.
51
+ * @param signature BN254 threshold signature over the verdict digest.
52
+ * @param nowSecs Current time in Unix seconds (default: now).
53
+ */
54
+ export function encodePrepaidFaultContest(verdict, signature, nowSecs = BigInt(Math.floor(Date.now() / 1000))) {
55
+ return encodeFunctionData({ abi: prepaidFaultOracleAbi, functionName: 'contest', args: [verdictTuple(verdict, nowSecs), signatureBytes(signature)] });
56
+ }
57
+ /**
58
+ * Whether the oracle already punished this offender for this batch (one resolution per
59
+ * offender and batch, whatever the kind or evidence).
60
+ * @param client Trusted RPC client.
61
+ * @param oracle Independently approved PrepaidFaultOracle.
62
+ * @param subject Slot, batch and offender.
63
+ */
64
+ export async function readPrepaidFaultResolution(client, oracle, subject) {
65
+ if (!ADDRESS.test(oracle) || !HEX32.test(subject.slotId) || !HEX32.test(subject.batchId) || !ADDRESS.test(subject.offender))
66
+ throw new TasraError('Invalid prepaid fault resolution query');
67
+ const block = await client.getBlockNumber({ cacheTime: 0 });
68
+ const resolutionId = await client.readContract({ address: oracle, abi: prepaidFaultOracleAbi, functionName: 'resolutionId', args: [subject.slotId, subject.batchId, subject.offender], blockNumber: block });
69
+ const resolved = await client.readContract({ address: oracle, abi: prepaidFaultOracleAbi, functionName: 'resolved', args: [resolutionId], blockNumber: block });
70
+ return { resolutionId, resolved };
71
+ }
72
+ /**
73
+ * Relay a threshold-signed verdict to the oracle. The call is simulated first, so an oracle
74
+ * refusal (WrongEpoch, AlreadyResolved, BadSignature, ...) is named and nothing is sent; the
75
+ * transaction is then sent once and its hash returned. Reconcile an unknown outcome with
76
+ * {@link readPrepaidFaultResolution}; never resend blindly.
77
+ * @param client Trusted RPC client.
78
+ * @param wallet Account- and chain-bound sender (any account: contest is permissionless).
79
+ * @param oracle Independently approved PrepaidFaultOracle.
80
+ * @param verdict Threshold-signed verdict.
81
+ * @param signature BN254 threshold signature over the verdict digest.
82
+ */
83
+ export async function contestPrepaidFault(client, wallet, oracle, verdict, signature) {
84
+ if (!ADDRESS.test(oracle) || /^0x0{40}$/.test(oracle))
85
+ throw new TasraError('Invalid PrepaidFaultOracle address');
86
+ const args = [verdictTuple(verdict, BigInt(Math.floor(Date.now() / 1000))), signatureBytes(signature)];
87
+ const { request } = await client.simulateContract({ address: oracle, abi: prepaidFaultOracleAbi, functionName: 'contest', args, account: wallet.account })
88
+ .catch((error) => { throw revertError(error, 'prepaid fault contest refused'); });
89
+ return wallet.writeContract(request);
90
+ }
91
+ function accountantUrl(base, path, allowLocalHttp) {
92
+ const url = new URL(base);
93
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
94
+ if (url.username || url.password || url.search || url.hash || !(url.protocol === 'https:' || (allowLocalHttp && loopback && url.protocol === 'http:')))
95
+ throw new TasraError('Invalid accountant endpoint');
96
+ return url.toString().replace(/\/$/, '') + path;
97
+ }
98
+ function deadline(options) {
99
+ const ms = options.timeoutMs ?? 30_000;
100
+ if (!Number.isSafeInteger(ms) || ms < 1 || ms > 120_000)
101
+ throw new TasraError('Invalid accountant request timeout');
102
+ return options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(ms)]) : AbortSignal.timeout(ms);
103
+ }
104
+ /**
105
+ * Hand a proof bundle to an accountant's fault witness (`POST /v1/prepaid-fault/claim`).
106
+ * Resolves on HTTP 202 (authenticated and durably stored). Any other status throws a
107
+ * TasraHttpError with the service's `Retry-After`: 400 malformed, 403 nothing authenticated,
108
+ * 413 too large are final; 408, 429 and 503 may be sent again later. Never re-sent here.
109
+ * @param base Approved accountant origin.
110
+ * @param bundle Proof bundle (`version` 1, `slot`, `batch_id`, `reconcile_block`, signed records).
111
+ * @param options Fetch, cancellation, deadline and local HTTP allowance.
112
+ */
113
+ export async function submitPrepaidFaultClaim(base, bundle, options = {}) {
114
+ if (!bundle || typeof bundle !== 'object' || Array.isArray(bundle) || bundle.version !== 1
115
+ || typeof bundle.slot !== 'string' || !HEX32.test(bundle.slot) || typeof bundle.batch_id !== 'string' || !HEX32.test(bundle.batch_id)
116
+ || !Number.isSafeInteger(bundle.reconcile_block) || Number(bundle.reconcile_block) < 0 || !Array.isArray(bundle.requests))
117
+ throw new TasraError('Invalid prepaid fault proof bundle');
118
+ const body = JSON.stringify(bundle);
119
+ if (new TextEncoder().encode(body).length > MAX_PREPAID_FAULT_BUNDLE_BYTES)
120
+ throw new TasraError('Prepaid fault proof bundle exceeds the witness limit');
121
+ const url = accountantUrl(base, '/v1/prepaid-fault/claim', options.allowLocalHttp === true);
122
+ const response = await (options.fetch ?? globalThis.fetch)(url, { method: 'POST', body, headers: { 'content-type': 'application/json' },
123
+ redirect: 'error', credentials: 'omit', cache: 'no-store', signal: deadline(options) });
124
+ if (response.status === 202) {
125
+ await response.body?.cancel().catch(() => { });
126
+ return { status: 202 };
127
+ }
128
+ throw await httpError(response, url, 'prepaid-fault/claim');
129
+ }
130
+ /**
131
+ * Read an accountant fault witness's adjudication health (`GET /v1/prepaid-fault/status`).
132
+ * The body is returned as parsed JSON, bounded to 64 KiB; it is a monitoring view, not evidence.
133
+ * @param base Approved accountant origin.
134
+ * @param options Fetch, cancellation, deadline and local HTTP allowance.
135
+ */
136
+ export async function readPrepaidFaultStatus(base, options = {}) {
137
+ const url = accountantUrl(base, '/v1/prepaid-fault/status', options.allowLocalHttp === true);
138
+ const response = await (options.fetch ?? globalThis.fetch)(url, { headers: { accept: 'application/json' }, redirect: 'error', credentials: 'omit', cache: 'no-store', signal: deadline(options) });
139
+ if (response.status !== 200)
140
+ throw await httpError(response, url, 'prepaid-fault/status');
141
+ const text = await response.text();
142
+ if (text.length > 65_536)
143
+ throw new TasraError('Prepaid fault status exceeds its bound');
144
+ const value = JSON.parse(text);
145
+ if (!value || typeof value !== 'object' || Array.isArray(value))
146
+ throw new TasraError('Invalid prepaid fault status');
147
+ return value;
148
+ }
@@ -0,0 +1,24 @@
1
+ import { type Hash, type PublicClient, type TransactionReceipt } from 'viem';
2
+ /**
3
+ * Receipt polling interval of the SDK's own write clients, ms. viem polls every 4 s unless the
4
+ * chain names a block time; Avalanche produces a block in about 2 s, so a write landed on a 4 s grid.
5
+ */
6
+ export declare const WRITE_POLL_INTERVAL_MS = 1000;
7
+ /** Options for {@link pollTransactionReceipt}. */
8
+ export interface PollReceiptOptions {
9
+ /** Blocks the receipt's block must have on top of it, counting itself (1..64). */
10
+ confirmations: number;
11
+ /** Deadline for the whole wait, ms. */
12
+ timeoutMs: number;
13
+ /** Stops the wait (and every further read). */
14
+ signal?: AbortSignal;
15
+ }
16
+ /**
17
+ * The receipt of `hash` once it has `confirmations` blocks, read directly with a short, growing
18
+ * interval. Throws viem's WaitForTransactionReceiptTimeoutError at the deadline; any RPC error
19
+ * other than "receipt not found" is thrown at once.
20
+ * @param client Trusted public client.
21
+ * @param hash Broadcast transaction hash.
22
+ * @param options Confirmations, deadline and cancellation.
23
+ */
24
+ export declare function pollTransactionReceipt(client: PublicClient, hash: Hash, options: PollReceiptOptions): Promise<TransactionReceipt>;
@@ -0,0 +1,82 @@
1
+ // Waiting for the receipt of ONE broadcast transaction on the paid path.
2
+ //
3
+ // viem's waitForTransactionReceipt watches the head on a fixed interval (1 s as configured here
4
+ // before, 4 s by default) and then reads the transaction and its receipt: a reservation landed on a
5
+ // one-second grid and cost a head read per tick plus a transaction read. This asks for the receipt
6
+ // itself, soon after the broadcast and then less and less often (250 ms growing by half, at most
7
+ // 1 s), so a transaction mined in a few hundred milliseconds is seen then, with fewer requests.
8
+ // Nothing is decided here: a missing receipt keeps waiting until the deadline, any other RPC error
9
+ // ends the wait, and the caller still verifies the transaction, its block and its effects.
10
+ import { WaitForTransactionReceiptTimeoutError } from 'viem';
11
+ import { headFollowerOf } from './headFollower.js';
12
+ import { isViemError } from '../internal/viemErrors.js';
13
+ /** First pause before asking again, ms. */
14
+ const FIRST_POLL_MS = 250;
15
+ /** Longest pause between two receipt (or head) reads, ms. */
16
+ const MAX_POLL_MS = 1_000;
17
+ /**
18
+ * Receipt polling interval of the SDK's own write clients, ms. viem polls every 4 s unless the
19
+ * chain names a block time; Avalanche produces a block in about 2 s, so a write landed on a 4 s grid.
20
+ */
21
+ export const WRITE_POLL_INTERVAL_MS = 1_000;
22
+ function pause(ms, signal) {
23
+ return new Promise((resolve, reject) => {
24
+ if (signal?.aborted) {
25
+ reject(signal.reason);
26
+ return;
27
+ }
28
+ const timer = setTimeout(() => { signal?.removeEventListener('abort', abort); resolve(); }, ms);
29
+ const abort = () => { clearTimeout(timer); reject(signal.reason); };
30
+ signal?.addEventListener('abort', abort, { once: true });
31
+ });
32
+ }
33
+ /**
34
+ * The receipt of `hash` once it has `confirmations` blocks, read directly with a short, growing
35
+ * interval. Throws viem's WaitForTransactionReceiptTimeoutError at the deadline; any RPC error
36
+ * other than "receipt not found" is thrown at once.
37
+ * @param client Trusted public client.
38
+ * @param hash Broadcast transaction hash.
39
+ * @param options Confirmations, deadline and cancellation.
40
+ */
41
+ export async function pollTransactionReceipt(client, hash, options) {
42
+ // The deadline is a timer (as in viem), not a clock reading: one abort ends the pause in progress.
43
+ const deadline = new AbortController();
44
+ const timer = setTimeout(() => deadline.abort(new WaitForTransactionReceiptTimeoutError({ hash })), options.timeoutMs);
45
+ const active = options.signal ? AbortSignal.any([options.signal, deadline.signal]) : deadline.signal;
46
+ let delay = FIRST_POLL_MS;
47
+ const next = async () => {
48
+ await pause(delay, active);
49
+ delay = Math.min(MAX_POLL_MS, Math.round(delay * 1.5));
50
+ };
51
+ try {
52
+ let receipt;
53
+ for (;;) {
54
+ active.throwIfAborted();
55
+ try {
56
+ receipt = await client.getTransactionReceipt({ hash });
57
+ // Reads after this must not use a followed tip from before the transaction.
58
+ headFollowerOf(client)?.noteMinedBlock(receipt.blockNumber);
59
+ break;
60
+ }
61
+ // By name: a caller's client built from another copy of viem (its CommonJS entry, say) throws
62
+ // its own TransactionReceiptNotFoundError class, which instanceof would not recognise.
63
+ catch (error) {
64
+ if (!isViemError(error, 'TransactionReceiptNotFoundError'))
65
+ throw error;
66
+ }
67
+ await next();
68
+ }
69
+ if (options.confirmations <= 1)
70
+ return receipt;
71
+ delay = FIRST_POLL_MS;
72
+ for (;;) {
73
+ active.throwIfAborted();
74
+ if (await client.getBlockNumber({ cacheTime: 0 }) - receipt.blockNumber + 1n >= BigInt(options.confirmations))
75
+ return receipt;
76
+ await next();
77
+ }
78
+ }
79
+ finally {
80
+ clearTimeout(timer);
81
+ }
82
+ }
@@ -2,6 +2,7 @@ import { type ServiceDiscoveryTransport } from './serviceIdentity.js';
2
2
  import type { TasraChainClient } from './client.js';
3
3
  import type { ServiceApproval } from './services.js';
4
4
  import { type CreateSessionParams, type CreateSessionResult, type SessionStatusResult } from '../verifier-agent/index.js';
5
+ import { type PaymentIntentWire } from '../committee/payment.js';
5
6
  /**
6
7
  * Guarded HTTPS transport for service discovery and verifier-agent sessions.
7
8
  */
@@ -13,7 +14,31 @@ export interface AgentTransport extends ServiceDiscoveryTransport {
13
14
  maxBytes: number;
14
15
  signal: AbortSignal;
15
16
  }): Promise<Uint8Array>;
17
+ /**
18
+ * Optional session-creation exchange that also returns a 503 with its status and Retry-After, so
19
+ * the agent's one retryable pre-creation refusal can be retried. Without it creation never retries.
20
+ */
21
+ agentExchange?(url: string, options: {
22
+ body: Uint8Array;
23
+ maxBytes: number;
24
+ signal: AbortSignal;
25
+ }): Promise<AgentHttpResponse>;
16
26
  }
27
+ /** A session-creation reply read with its status; the body stays bounded by the caller. */
28
+ export interface AgentHttpResponse {
29
+ /** HTTP status of the reply. */
30
+ status: number;
31
+ /** Bounded reply bytes. */
32
+ body: Uint8Array;
33
+ /** Parsed Retry-After, in milliseconds, when the agent sent one. */
34
+ retryAfterMs?: number;
35
+ }
36
+ /**
37
+ * The verifier-agent's fixed reason for an unpaid creation refused because the current and
38
+ * previous epoch have no anchored verifier snapshot yet. It is answered before anything is stored
39
+ * or charged, with Retry-After; it is the only creation refusal that is retried.
40
+ */
41
+ export declare const SNAPSHOT_PENDING_REASON = "verifier snapshot not yet anchored for the current or previous epoch; nothing was created - retry this request";
17
42
  /** Both the application and committee verifiers must independently approve this verifier-agent identity. */
18
43
  export interface ApprovedAgentProfile {
19
44
  /**
@@ -33,19 +58,51 @@ export interface ApprovedAgentProfile {
33
58
  * Session pinned to its authenticated provider, with a closure for polling that provider.
34
59
  */
35
60
  export interface RegisteredAgentSession extends Readonly<CreateSessionResult> {
61
+ /** Expected paid-token commitment, fixed before the session POST. */
62
+ readonly paymentHash?: string;
63
+ /** Defensive copy of the fixed spending intent, when this session is prepaid. */
64
+ readonly payment?: PaymentIntentWire;
65
+ /** Presentation random bound by the spending intent to the approved audience. */
66
+ readonly random?: string;
36
67
  /**
37
68
  * Provider identity and endpoint pinned when the session was opened.
38
69
  */
39
70
  readonly profile: Readonly<ApprovedAgentProfile>;
71
+ /** Private JSON checkpoint for unpaid sessions. Save before wallet delivery; paid sessions use payment recovery. */
72
+ readonly unpaidRecovery?: UnpaidAgentSessionRecovery;
40
73
  /** Poll only the original endpoint/profile. A provider change requires a fresh wallet session. */
41
74
  poll(signal?: AbortSignal): Promise<SessionStatusResult>;
42
75
  }
76
+ /** Private application state for restoring the original unpaid session, never a provider approval. */
77
+ export interface UnpaidAgentSessionRecovery extends CreateSessionResult {
78
+ /** Checkpoint format. */
79
+ version: 1;
80
+ /** Creation identity, compared with independent approvals and the live registry. */
81
+ serviceProfile: {
82
+ chainId: number;
83
+ registry: string;
84
+ serviceId: string;
85
+ serviceType: 1;
86
+ owner: string;
87
+ revision: string;
88
+ manifestHash: string;
89
+ authKey: string;
90
+ endpoint: string;
91
+ clientId: string;
92
+ };
93
+ /** Pending owner at creation; a later transfer stops recovery before bearer delivery. */
94
+ pendingOwner: string;
95
+ }
43
96
  /**
44
97
  * Session creation may have reached the provider, so automatic retry is unsafe.
45
98
  */
46
99
  export declare class AgentSessionCreationUnknownError extends Error {
47
- readonly profile: Readonly<ApprovedAgentProfile>;
48
- constructor(/** Approved verifier-agent profile whose session creation outcome is unknown. */ profile: Readonly<ApprovedAgentProfile>);
100
+ /** Approved verifier-agent profile whose session creation outcome is unknown. */ readonly profile: Readonly<ApprovedAgentProfile>;
101
+ /** Retained payment commitment; reconcile it before another paid session attempt. */ readonly paymentHash?: string | undefined;
102
+ constructor(
103
+ /** Approved verifier-agent profile whose session creation outcome is unknown. */ profile: Readonly<ApprovedAgentProfile>,
104
+ /** Retained payment commitment; reconcile it before another paid session attempt. */ paymentHash?: string | undefined,
105
+ /** The transport failure behind the uncertainty, kept so the reason can be diagnosed. */ cause?: unknown);
49
106
  }
50
107
  /**
51
108
  * Selection authenticates public metadata first. Once POSTed, never silently switch providers.
@@ -56,7 +113,15 @@ export declare function createRegisteredAgentClient(chain: TasraChainClient, con
56
113
  profiles: readonly ApprovedAgentProfile[];
57
114
  transport: AgentTransport;
58
115
  }): {
59
- /** At most three discovery candidates; optional index explicitly starts a new independent session. */
116
+ /**
117
+ * Restore private unpaid-session state without creating another session. Independent
118
+ * approvals and live registry identity are checked before sending its bearer. Save the
119
+ * original operation separately and verify its wallet binding before presenting.
120
+ */
121
+ restoreUnpaidSession(input: UnpaidAgentSessionRecovery, options?: {
122
+ signal?: AbortSignal;
123
+ }): Promise<RegisteredAgentSession>;
124
+ /** At most three unpaid discovery candidates. A paid session uses only its selected profile. */
60
125
  createSession(params: CreateSessionParams, options?: {
61
126
  profileIndex?: number;
62
127
  signal?: AbortSignal;
@@ -1,13 +1,31 @@
1
1
  import { authenticateApprovedService, validateServiceEndpoint } from './serviceIdentity.js';
2
2
  import { parseVerifierAgentSessionStatus } from '../verifier-agent/index.js';
3
+ import { sessionPaymentFields } from '../verifier-agent/payment.js';
4
+ import { paymentIntentHash } from '../committee/payment.js';
5
+ import { chainIdOf } from './chainId.js';
6
+ /**
7
+ * The verifier-agent's fixed reason for an unpaid creation refused because the current and
8
+ * previous epoch have no anchored verifier snapshot yet. It is answered before anything is stored
9
+ * or charged, with Retry-After; it is the only creation refusal that is retried.
10
+ */
11
+ export const SNAPSHOT_PENDING_REASON = 'verifier snapshot not yet anchored for the current or previous epoch; nothing was created - retry this request';
12
+ const SNAPSHOT_RETRY_ATTEMPTS = 5, SNAPSHOT_RETRY_MAX_WAIT_MS = 10_000;
3
13
  /**
4
14
  * Session creation may have reached the provider, so automatic retry is unsafe.
5
15
  */
6
16
  export class AgentSessionCreationUnknownError extends Error {
7
17
  profile;
8
- constructor(/** Approved verifier-agent profile whose session creation outcome is unknown. */ profile) {
9
- super('Agent session creation has an uncertain result; explicitly open a fresh wallet session to retry. No session secret or presentation is transferred.');
18
+ paymentHash;
19
+ constructor(
20
+ /** Approved verifier-agent profile whose session creation outcome is unknown. */ profile,
21
+ /** Retained payment commitment; reconcile it before another paid session attempt. */ paymentHash,
22
+ /** The transport failure behind the uncertainty, kept so the reason can be diagnosed. */ cause) {
23
+ super((paymentHash
24
+ ? 'Paid agent session creation has an uncertain result; retain the original payment and reconcile it before another session attempt.'
25
+ : 'Agent session creation has an uncertain result; explicitly open a fresh wallet session to retry. No session secret or presentation is transferred.')
26
+ + (cause instanceof Error ? ` Transport: ${cause.message}` : ''), { cause });
10
27
  this.profile = profile;
28
+ this.paymentHash = paymentHash;
11
29
  this.name = 'AgentSessionCreationUnknownError';
12
30
  }
13
31
  }
@@ -48,6 +66,53 @@ function equalPin(actual, expected) {
48
66
  return false;
49
67
  return Object.entries(expected).every(([key, value]) => actual[key] === value);
50
68
  }
69
+ function metadata(data, profile, expected) {
70
+ if (!equalPin(data.service_profile, expected) || typeof data.session_id !== 'string' || !/^[0-9a-f]{64}$/.test(data.session_id)
71
+ || typeof data.poll_secret !== 'string' || !/^[0-9a-f]{64}$/.test(data.poll_secret))
72
+ throw new Error('Agent session profile or identifiers mismatch');
73
+ const requestUri = `${profile.endpoint}/v1/request/${data.session_id}`;
74
+ if (data.request_uri !== requestUri || typeof data.qr_payload !== 'string' || !data.qr_payload.startsWith('openid4vp://?'))
75
+ throw new Error('Agent wallet request destination mismatch');
76
+ const qr = new URL(data.qr_payload);
77
+ if (qr.searchParams.get('client_id') !== profile.clientId || qr.searchParams.get('request_uri') !== requestUri || [...qr.searchParams.keys()].length !== 2)
78
+ throw new Error('Agent wallet audience or request URI mismatch');
79
+ return { sessionId: data.session_id, pollSecret: data.poll_secret, requestUri, qrPayload: data.qr_payload };
80
+ }
81
+ function retainedSession(chain, transport, profile, expected, pendingOwner, input, paid) {
82
+ const { sessionId, pollSecret, requestUri, qrPayload } = input;
83
+ expected = Object.freeze({ ...expected });
84
+ pendingOwner = pendingOwner.toLowerCase();
85
+ const paymentHash = paid.payment && paymentIntentHash(paid.payment);
86
+ const checkpoint = { version: 1, sessionId, pollSecret, requestUri, qrPayload, serviceProfile: expected, pendingOwner };
87
+ // Routing, identity and bearer live in this closure; callers receive defensive checkpoints.
88
+ return Object.freeze({ sessionId, pollSecret, requestUri, qrPayload, profile,
89
+ ...(paid.payment ? { paymentHash, random: paid.random } : {}),
90
+ get payment() { return paid.payment && structuredClone(paid.payment); },
91
+ get unpaidRecovery() { return paid.payment ? undefined : structuredClone(checkpoint); },
92
+ poll: (pollSignal) => bounded(pollSignal, async (activeSignal) => {
93
+ const a = profile.approval;
94
+ if (chain.addresses.ServiceRegistry?.toLowerCase() !== a.registry.toLowerCase() || await chainIdOf(chain.client) !== a.chainId)
95
+ throw new Error('Agent session chain/registry changed');
96
+ activeSignal.throwIfAborted();
97
+ // The current registration at the latest block, in one call.
98
+ const current = await chain.readers.serviceRegistry.getService(a.serviceId);
99
+ activeSignal.throwIfAborted();
100
+ if (current.status > 1 || current.revision < a.revision || current.serviceType !== 1
101
+ || current.owner.toLowerCase() !== expected.owner || current.authKey.toLowerCase() !== expected.authKey
102
+ || current.pendingOwner.toLowerCase() !== pendingOwner || current.manifestHash.toLowerCase() !== a.manifestHash.toLowerCase()
103
+ || current.endpoint !== profile.endpoint)
104
+ throw new Error('Agent session profile changed; retain the original session for recovery');
105
+ const reply = decode(await transport.agentRequest(`${profile.endpoint}/v1/sessions/${sessionId}`, { bearer: pollSecret, maxBytes: 1_048_576, signal: activeSignal }), 1_048_576);
106
+ const binding = reply.binding_preimage;
107
+ const token = reply.compound_token;
108
+ if (!paid.payment && [reply.payment, reply.payment_hash, binding?.payment, binding?.payment_hash, token?.payment, token?.payment_hash].some(value => value != null))
109
+ throw new Error('Paid agent state cannot use unpaid session recovery');
110
+ if (!(reply.status === 'failed' && reply.binding_preimage == null && reply.compound_token == null) && !equalPin(reply.binding_preimage?.service_profile, expected))
111
+ throw new Error('Agent result belongs to another session profile');
112
+ return parseVerifierAgentSessionStatus(reply, sessionId);
113
+ }),
114
+ });
115
+ }
51
116
  /**
52
117
  * Selection authenticates public metadata first. Once POSTed, never silently switch providers.
53
118
  * @param chain Reader for the approved service registry.
@@ -56,7 +121,7 @@ function equalPin(actual, expected) {
56
121
  export function createRegisteredAgentClient(chain, config) {
57
122
  if (!Array.isArray(config.profiles) || !config.profiles.length || config.profiles.length > 16 || typeof config.transport?.agentRequest !== 'function' || typeof config.transport.request !== 'function')
58
123
  throw new Error('Approved agent profiles and a guarded transport are required');
59
- const profiles = config.profiles.map(p => {
124
+ const profiles = config.profiles.map((p) => {
60
125
  validateServiceEndpoint(p.endpoint);
61
126
  if (p.approval.serviceType !== 1 || !/^decentralized_identifier:did:web:[a-z0-9.-]+(?:(?:%3A)[0-9]+)?$/.test(p.clientId))
62
127
  throw new Error('Invalid verifier-agent profile');
@@ -64,13 +129,48 @@ export function createRegisteredAgentClient(chain, config) {
64
129
  });
65
130
  const transport = config.transport;
66
131
  return {
67
- /** At most three discovery candidates; optional index explicitly starts a new independent session. */
132
+ /**
133
+ * Restore private unpaid-session state without creating another session. Independent
134
+ * approvals and live registry identity are checked before sending its bearer. Save the
135
+ * original operation separately and verify its wallet binding before presenting.
136
+ */
137
+ async restoreUnpaidSession(input, options = {}) {
138
+ options.signal?.throwIfAborted();
139
+ const saved = decode(new TextEncoder().encode(JSON.stringify(input)), 32_768);
140
+ const keys = ['version', 'sessionId', 'pollSecret', 'requestUri', 'qrPayload', 'serviceProfile', 'pendingOwner'];
141
+ if (saved.version !== 1 || Object.keys(saved).length !== keys.length || keys.some(key => !(key in saved))
142
+ || typeof saved.pendingOwner !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(saved.pendingOwner)
143
+ || !saved.serviceProfile || typeof saved.serviceProfile !== 'object' || Array.isArray(saved.serviceProfile))
144
+ throw new Error('Invalid unpaid agent recovery checkpoint');
145
+ const service = saved.serviceProfile;
146
+ if (typeof service.authKey !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(service.authKey))
147
+ throw new Error('Invalid unpaid agent recovery identity');
148
+ const profile = profiles.find(p => {
149
+ const expected = pin(p, { authKey: service.authKey });
150
+ return Object.keys(service).length === Object.keys(expected).length && equalPin(service, expected);
151
+ });
152
+ if (!profile)
153
+ throw new Error('Original agent recovery profile is not independently approved');
154
+ const expected = pin(profile, { authKey: service.authKey });
155
+ const info = metadata({ session_id: saved.sessionId, poll_secret: saved.pollSecret, request_uri: saved.requestUri, qr_payload: saved.qrPayload, service_profile: service }, profile, expected);
156
+ const session = retainedSession(chain, transport, profile, expected, saved.pendingOwner, info, {});
157
+ // Poll applies the same live checks as a surviving session closure, including draining.
158
+ await session.poll(options.signal);
159
+ return session;
160
+ },
161
+ /** At most three unpaid discovery candidates. A paid session uses only its selected profile. */
68
162
  async createSession(params, options = {}) {
163
+ params = structuredClone(params);
164
+ const paid = sessionPaymentFields(params);
165
+ const paymentHash = paid.payment && paymentIntentHash(paid.payment);
69
166
  const start = options.profileIndex ?? 0;
70
167
  if (!Number.isInteger(start) || start < 0 || start >= profiles.length)
71
168
  throw new Error('Invalid agent profile index');
72
169
  return bounded(options.signal, async (signal) => {
73
- for (const profile of profiles.slice(start, start + 3)) {
170
+ for (const profile of profiles.slice(start, start + (paid.payment ? 1 : 3))) {
171
+ // Do this before discovery or POST: a paid session cannot be redrawn at another
172
+ // audience, and the caller cannot change the committed random or expiry.
173
+ sessionPaymentFields(params, profile.clientId);
74
174
  let record;
75
175
  try {
76
176
  const result = await authenticateApprovedService(chain, profile.approval, {
@@ -87,54 +187,55 @@ export function createRegisteredAgentClient(chain, config) {
87
187
  }
88
188
  if (params.operation.chain_id !== profile.approval.chainId)
89
189
  throw new Error('Agent operation chain mismatch');
90
- const body = new TextEncoder().encode(JSON.stringify({ operation: params.operation, operation_sig: params.operationSig, delegation: params.delegation, message_hex: params.messageHex }));
190
+ const body = new TextEncoder().encode(JSON.stringify({ operation: params.operation, operation_sig: params.operationSig, delegation: params.delegation, message_hex: params.messageHex, ...paid }));
91
191
  if (body.length > 65_536)
92
192
  throw new Error('Agent session request too large');
93
193
  signal.throwIfAborted();
94
194
  let data;
95
195
  try {
96
- data = decode(await transport.agentRequest(profile.endpoint + '/v1/sessions', { body, maxBytes: 32_768, signal }), 32_768);
196
+ data = decode(await createPost(transport, profile.endpoint + '/v1/sessions', body, Boolean(paymentHash), signal), 32_768);
97
197
  }
98
- catch {
99
- throw new AgentSessionCreationUnknownError(profile);
198
+ catch (error) {
199
+ throw new AgentSessionCreationUnknownError(profile, paymentHash, error);
100
200
  }
101
201
  const expected = pin(profile, record);
102
- if (!equalPin(data.service_profile, expected) || typeof data.session_id !== 'string' || !/^[0-9a-f]{64}$/.test(data.session_id)
103
- || typeof data.poll_secret !== 'string' || !/^[0-9a-f]{64}$/.test(data.poll_secret))
104
- throw new Error('Agent session profile or identifiers mismatch');
105
- const sessionId = data.session_id, pollSecret = data.poll_secret;
106
- const requestUri = `${profile.endpoint}/v1/request/${sessionId}`;
107
- if (data.request_uri !== requestUri || typeof data.qr_payload !== 'string' || !data.qr_payload.startsWith('openid4vp://?'))
108
- throw new Error('Agent wallet request destination mismatch');
109
- const qr = new URL(data.qr_payload);
110
- if (qr.searchParams.get('client_id') !== profile.clientId || qr.searchParams.get('request_uri') !== requestUri || [...qr.searchParams.keys()].length !== 2)
111
- throw new Error('Agent wallet audience or request URI mismatch');
112
- // Closure-owned routing and secret prevent a caller's mutable session object from
113
- // redirecting a bearer. Replicas sit behind this one approved base endpoint.
114
- return Object.freeze({ sessionId, pollSecret, requestUri, qrPayload: data.qr_payload, profile,
115
- poll: (pollSignal) => bounded(pollSignal, async (activeSignal) => {
116
- const a = profile.approval;
117
- if (chain.addresses.ServiceRegistry?.toLowerCase() !== a.registry.toLowerCase() || await chain.client.getChainId() !== a.chainId)
118
- throw new Error('Agent session chain/registry changed');
119
- activeSignal.throwIfAborted();
120
- const block = await chain.client.getBlockNumber({ cacheTime: 0 });
121
- activeSignal.throwIfAborted();
122
- const current = await chain.readers.serviceRegistry.getService(a.serviceId, block);
123
- activeSignal.throwIfAborted();
124
- if (current.status > 1 || current.revision < a.revision || current.serviceType !== 1
125
- || current.owner.toLowerCase() !== record.owner.toLowerCase() || current.authKey.toLowerCase() !== record.authKey.toLowerCase()
126
- || current.pendingOwner.toLowerCase() !== record.pendingOwner.toLowerCase() || current.manifestHash.toLowerCase() !== a.manifestHash.toLowerCase()
127
- || current.endpoint !== profile.endpoint)
128
- throw new Error('Agent session profile changed; open a fresh wallet session');
129
- const reply = decode(await transport.agentRequest(`${profile.endpoint}/v1/sessions/${sessionId}`, { bearer: pollSecret, maxBytes: 1_048_576, signal: activeSignal }), 1_048_576);
130
- if (!(reply.status === 'failed' && reply.binding_preimage == null && reply.compound_token == null) && !equalPin(reply.binding_preimage?.service_profile, expected))
131
- throw new Error('Agent result belongs to another session profile');
132
- return parseVerifierAgentSessionStatus(reply, sessionId);
133
- }),
134
- });
202
+ return retainedSession(chain, transport, profile, expected, record.pendingOwner, metadata(data, profile, expected), paid);
135
203
  }
136
204
  throw new Error('No approved verifier-agent authenticated');
137
205
  });
138
206
  },
139
207
  };
140
208
  }
209
+ /** True when a creation reply is exactly the agent's retryable not-yet-anchored refusal. */
210
+ function snapshotPending(reply) {
211
+ if (reply.status !== 503 || reply.retryAfterMs === undefined)
212
+ return false;
213
+ try {
214
+ return decode(reply.body, 4_096).error === SNAPSHOT_PENDING_REASON;
215
+ }
216
+ catch {
217
+ return false;
218
+ }
219
+ }
220
+ /**
221
+ * POST one session creation. Only an UNPAID creation answered with the snapshot-pending refusal is
222
+ * re-sent (identical bytes, after the agent's hint, at most five times): that refusal is by contract
223
+ * given before anything is stored or charged. Any other reply or failure is left to the caller.
224
+ */
225
+ async function createPost(transport, url, body, paid, signal) {
226
+ if (!transport.agentExchange)
227
+ return transport.agentRequest(url, { body, maxBytes: 32_768, signal });
228
+ for (let attempt = 1;; attempt++) {
229
+ const reply = await transport.agentExchange(url, { body, maxBytes: 32_768, signal });
230
+ if (reply.status === 201)
231
+ return reply.body;
232
+ if (paid || attempt >= SNAPSHOT_RETRY_ATTEMPTS || !snapshotPending(reply))
233
+ throw new Error(`Agent session creation refused (HTTP ${reply.status})`);
234
+ const wait = Math.min(reply.retryAfterMs, SNAPSHOT_RETRY_MAX_WAIT_MS);
235
+ await new Promise((resolve, reject) => {
236
+ const abort = () => { clearTimeout(timer); reject(signal.reason); };
237
+ const timer = setTimeout(() => { signal.removeEventListener('abort', abort); resolve(); }, wait);
238
+ signal.addEventListener('abort', abort, { once: true });
239
+ });
240
+ }
241
+ }
@@ -3,6 +3,7 @@ import type { VerifiedRequestObject } from '../oid4vp/request-object.js';
3
3
  import type { SessionStatusResult } from '../verifier-agent/index.js';
4
4
  import { type PresentationDelegation, type PresentationOperation, type WaitOpts } from '../verifier-agent/index.js';
5
5
  import { type RegisteredAgentSession, type createRegisteredAgentClient } from './registeredAgent.js';
6
+ import { type PaymentIntentWire } from '../committee/payment.js';
6
7
  /**
7
8
  * Authenticated provider session bound to one signed operation and request hash.
8
9
  */
@@ -25,11 +26,19 @@ export interface RegisteredVerifierAgentSession extends RegisteredAgentSession {
25
26
  * @param client Registered agent client with independently approved providers.
26
27
  * @param opts Exact operation, authorizing signer and optional delegation or cancellation.
27
28
  */
28
- export declare function openRegisteredVerifierAgentSession(client: ReturnType<typeof createRegisteredAgentClient>, opts: OperationInput & {
29
+ export declare function openRegisteredVerifierAgentSession(client: Pick<ReturnType<typeof createRegisteredAgentClient>, 'createSession'>, opts: OperationInput & {
30
+ /** Creator or delegated presentation signer; payment consent remains the creator's. */
29
31
  signer: TypedDataSigner;
32
+ /** Optional presentation delegation. */
30
33
  delegation?: PresentationDelegation;
34
+ /** Explicit approved provider index; paid sessions never fall back to another profile. */
31
35
  profileIndex?: number;
36
+ /** Cancellation of pending authorization work. */
32
37
  signal?: AbortSignal;
38
+ /** Existing reservation intent, fixed before the session. Operation expiry must match it. */
39
+ payment?: PaymentIntentWire;
40
+ /** Presentation random committed in payment.session_commitment. */
41
+ random?: string;
33
42
  }): Promise<RegisteredVerifierAgentSession>;
34
43
  /**
35
44
  * Poll the original authenticated session only; no URL reconstruction or provider failover.