@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,339 @@
1
+ import { encodeAbiParameters, keccak256, toHex } from 'viem';
2
+ import { typedDataHash as hashTypedData } from '../internal/typedData.js';
3
+ import { keccak_256 } from '@noble/hashes/sha3';
4
+ import { concatBytes } from '@noble/hashes/utils';
5
+ import { bytesToHex, hexToBytes } from '../crypto/hex.js';
6
+ function uint(n, bits, name) {
7
+ if (!Number.isSafeInteger(n) || n < 0 || BigInt(n) >= (1n << BigInt(bits)))
8
+ throw new Error(`${name}: invalid uint${bits}`);
9
+ }
10
+ function be(n, size) {
11
+ let value = BigInt(n);
12
+ const result = new Uint8Array(size);
13
+ for (let i = size - 1; i >= 0; i--) {
14
+ result[i] = Number(value & 255n);
15
+ value >>= 8n;
16
+ }
17
+ return result;
18
+ }
19
+ function hex(value, size, name) {
20
+ if (typeof value !== 'string' || !new RegExp(`^0x[0-9a-f]{${size * 2}}$`, 'i').test(value))
21
+ throw new Error(`${name}: invalid ${size}-byte hex`);
22
+ }
23
+ function key(value) {
24
+ if (!Array.isArray(value) || value.length !== 32 || !Array.from(value).every(v => Number.isInteger(v) && v >= 0 && v <= 255) || value.every(v => v === 0)) {
25
+ throw new Error('invalid paid keeper key');
26
+ }
27
+ }
28
+ /**
29
+ * Hash a validated assignment using the platform's fixed-width canonical encoding.
30
+ * @param a - Fixed sharing and registered keeper keys from independent discovery.
31
+ */
32
+ export function keeperAssignmentCommitment(a) {
33
+ uint(a.key_epoch, 64, 'key_epoch');
34
+ uint(a.committee_version, 64, 'committee_version');
35
+ uint(a.threshold, 16, 'threshold');
36
+ key(a.coordinator);
37
+ if (!Array.isArray(a.contributors) || a.contributors.length > 256 || a.threshold === 0 || a.threshold > a.contributors.length)
38
+ throw new Error('invalid paid keeper threshold');
39
+ const keys = Array.from(a.contributors, k => {
40
+ key(k);
41
+ return bytesToHex(Uint8Array.from(k));
42
+ });
43
+ if (keys.some((k, i) => i > 0 && k <= keys[i - 1]) || !keys.includes(bytesToHex(Uint8Array.from(a.coordinator))))
44
+ throw new Error('invalid paid keeper membership/order');
45
+ return bytesToHex(keccak_256(concatBytes(new TextEncoder().encode('keykeeper/paid-keeper-assignment/v1'), be(a.key_epoch, 8), be(a.committee_version, 8), be(a.threshold, 2), Uint8Array.from(a.coordinator), be(keys.length, 4), ...a.contributors.map(k => Uint8Array.from(k)))));
46
+ }
47
+ const ACTIONS = { 'sign': 0, 'decrypt': 1, 'eoa-sign': 2, 'ibe-extract': 3, 'dual-approve': 6 };
48
+ const BASE_FIELDS = [
49
+ { name: 'keyRegistry', type: 'address' }, { name: 'slotId', type: 'bytes32' },
50
+ { name: 'action', type: 'uint8' }, { name: 'payloadDigest', type: 'bytes32' },
51
+ { name: 'sessionCommitment', type: 'bytes32' }, { name: 'nonce', type: 'bytes32' },
52
+ { name: 'maxCost', type: 'uint256' }, { name: 'expires', type: 'uint64' },
53
+ { name: 'verificationEpoch', type: 'uint64' }, { name: 'verificationSeed', type: 'bytes32' },
54
+ { name: 'verificationRoot', type: 'bytes32' }, { name: 'verificationRegistrySize', type: 'uint32' },
55
+ { name: 'verificationCommittee', type: 'uint32' }, { name: 'verificationQuorum', type: 'uint32' },
56
+ { name: 'keeperAssignment', type: 'bytes32' },
57
+ ];
58
+ const TYPES = { SlotAssignedPaymentIntent: BASE_FIELDS };
59
+ /** Prepaid allowances: a distinct type (same domain), so a per-operation signature never debits an allowance or the other way round. */
60
+ const ALLOWANCE_PAYMENT_TYPES = { SlotAllowancePaymentIntent: [...BASE_FIELDS, { name: 'allowanceId', type: 'bytes32' }] };
61
+ const ALLOWANCE_INTENT_TYPES = { SlotPrepaidAllowanceIntent: [
62
+ { name: 'keyRegistry', type: 'address' }, { name: 'slotId', type: 'bytes32' }, { name: 'intentNonce', type: 'bytes32' },
63
+ { name: 'amount', type: 'uint256' }, { name: 'maxOpCost', type: 'uint256' }, { name: 'actions', type: 'uint32' },
64
+ { name: 'expiresAt', type: 'uint64' }, { name: 'verificationEpoch', type: 'uint64' }, { name: 'verificationSeed', type: 'bytes32' },
65
+ { name: 'verificationRoot', type: 'bytes32' }, { name: 'verificationRegistrySize', type: 'uint32' },
66
+ { name: 'verificationCommittee', type: 'uint32' }, { name: 'verificationQuorum', type: 'uint32' },
67
+ { name: 'keeperAssignment', type: 'bytes32' },
68
+ ] };
69
+ const PAYMENT_DOMAIN = { name: 'Keykeeper Assigned Slot Payment', version: '1' };
70
+ const ZERO32 = /^0x0{64}$/i;
71
+ function units(value, name) {
72
+ if (typeof value !== 'string' || !/^[0-9]{1,78}$/.test(value) || BigInt(value) >= 1n << 256n)
73
+ throw new Error(`${name}: invalid decimal TASRA base units`);
74
+ return BigInt(value);
75
+ }
76
+ function verifierPolicy(p, what) {
77
+ for (const k of ['verification_registry_size', 'verification_committee', 'verification_quorum'])
78
+ uint(p[k], 32, k);
79
+ if (!p.verification_quorum || p.verification_quorum > p.verification_committee || p.verification_committee > p.verification_registry_size)
80
+ throw new Error(`invalid ${what} verifier policy`);
81
+ }
82
+ function baseMessage(p) {
83
+ uint(p.chain_id, 64, 'chain_id');
84
+ uint(p.expires, 64, 'expires');
85
+ uint(p.verification_epoch, 64, 'verification_epoch');
86
+ for (const k of ['settlement', 'key_registry'])
87
+ hex(p[k], 20, k);
88
+ for (const k of ['slot', 'payload_digest', 'session_commitment', 'nonce', 'verification_seed', 'verification_root'])
89
+ hex(p[k], 32, k);
90
+ if (!Object.hasOwn(ACTIONS, p.action))
91
+ throw new Error('unsupported payment action');
92
+ units(p.max_cost, 'max_cost');
93
+ verifierPolicy(p, 'payment');
94
+ return {
95
+ keyRegistry: p.key_registry, slotId: p.slot, action: ACTIONS[p.action], payloadDigest: p.payload_digest,
96
+ sessionCommitment: p.session_commitment, nonce: p.nonce, maxCost: BigInt(p.max_cost), expires: BigInt(p.expires),
97
+ verificationEpoch: BigInt(p.verification_epoch), verificationSeed: p.verification_seed, verificationRoot: p.verification_root,
98
+ verificationRegistrySize: p.verification_registry_size, verificationCommittee: p.verification_committee,
99
+ verificationQuorum: p.verification_quorum, keeperAssignment: keeperAssignmentCommitment(p.keeper_assignment),
100
+ };
101
+ }
102
+ /**
103
+ * Build creator EIP-712 data. Validate chain backing, price, expiry and creator independently before spending.
104
+ * A payment naming an `allowance_id` (a prepaid allowance) is the distinct `SlotAllowancePaymentIntent`; the
105
+ * `debit_voucher` is never part of the signed data.
106
+ * @param p - Creator payment intent before attaching its signature.
107
+ */
108
+ export function paymentIntentTypedData(p) {
109
+ const domain = { ...PAYMENT_DOMAIN, chainId: p.chain_id, verifyingContract: p.settlement };
110
+ if (p.allowance_id !== undefined) {
111
+ hex(p.allowance_id, 32, 'allowance_id');
112
+ if (ZERO32.test(p.allowance_id))
113
+ throw new Error('allowance_id: must be nonzero');
114
+ return { domain, primaryType: 'SlotAllowancePaymentIntent', types: ALLOWANCE_PAYMENT_TYPES,
115
+ message: { ...baseMessage(p), allowanceId: p.allowance_id } };
116
+ }
117
+ return { domain, primaryType: 'SlotAssignedPaymentIntent', types: TYPES, message: baseMessage(p) };
118
+ }
119
+ /**
120
+ * Hash the creator intent. A matching hash is not proof of a mined reservation or a valid creator signature.
121
+ * @param p - Creator payment intent; a signature is not part of the EIP-712 preimage.
122
+ */
123
+ export function paymentIntentHash(p) {
124
+ return hashTypedData(paymentIntentTypedData(p));
125
+ }
126
+ /**
127
+ * Derive the Settlement reservation identity for this exact payment and operation. Unchanged by
128
+ * Prepaid allowances: an allowance-backed payment's own signing hash is the authorization commitment, so
129
+ * the ID binds the allowance too.
130
+ * @param p - Fixed creator intent; neither hashing nor an ID proves a mined reservation.
131
+ */
132
+ export function prepaidRequestId(p) {
133
+ const intentHash = paymentIntentHash(p);
134
+ return bytesToHex(keccak_256(concatBytes(new TextEncoder().encode('keykeeper/prepaid-request/v1'), be(p.chain_id, 8), new Uint8Array(12), hexToBytes(p.settlement), hexToBytes(p.slot), Uint8Array.of(ACTIONS[p.action]), hexToBytes(p.payload_digest), hexToBytes(intentHash))));
135
+ }
136
+ /**
137
+ * Validate a debit voucher's shape (not its signature). Mirrors the readers' constructor: nonzero
138
+ * ids, cost and quote block, `cumulative >= cost`, a 64-byte non-infinity signature encoding.
139
+ * @param value - Untrusted voucher.
140
+ */
141
+ export function assertDebitVoucherWire(value) {
142
+ if (!value || typeof value !== 'object' || Array.isArray(value))
143
+ throw new Error('debit voucher must be an object');
144
+ const v = value;
145
+ const fields = ['allowance_id', 'seq', 'request_id', 'cost', 'cumulative', 'quote_block', 'signature'];
146
+ if (Object.keys(v).length !== fields.length || fields.some(k => !Object.hasOwn(v, k)))
147
+ throw new Error('invalid debit voucher fields');
148
+ for (const k of ['allowance_id', 'request_id', 'quote_block']) {
149
+ hex(v[k], 32, `debit voucher ${k}`);
150
+ if (ZERO32.test(v[k]))
151
+ throw new Error(`debit voucher ${k} must be nonzero`);
152
+ }
153
+ if (typeof v.seq !== 'number')
154
+ throw new Error('debit voucher seq: invalid');
155
+ uint(v.seq, 64, 'debit voucher seq');
156
+ const cost = units(v.cost, 'debit voucher cost'), cumulative = units(v.cumulative, 'debit voucher cumulative');
157
+ if (cost === 0n || cumulative < cost)
158
+ throw new Error('debit voucher cost must be nonzero and at most its cumulative total');
159
+ hex(v.signature, 64, 'debit voucher signature');
160
+ if (/^0x0{128}$/i.test(v.signature))
161
+ throw new Error('debit voucher signature is the point at infinity');
162
+ }
163
+ /**
164
+ * Validate the wire representation and its signed commitment, without chain access.
165
+ * @param value - Untrusted payment object; signature encoding is checked, not signer recovery.
166
+ */
167
+ export function assertPaymentIntentWire(value) {
168
+ if (!value || typeof value !== 'object' || Array.isArray(value))
169
+ throw new Error('payment must be an object');
170
+ const p = value;
171
+ hex(p.signature, 65, 'payment signature');
172
+ paymentIntentHash(p);
173
+ if (p.debit_voucher !== undefined) {
174
+ if (p.allowance_id === undefined)
175
+ throw new Error('a debit voucher needs the allowance_id it debits');
176
+ assertDebitVoucherWire(p.debit_voucher);
177
+ if (p.debit_voucher.allowance_id.toLowerCase() !== p.allowance_id.toLowerCase())
178
+ throw new Error('debit voucher names a different allowance than the payment intent');
179
+ if (p.debit_voucher.request_id.toLowerCase() !== prepaidRequestId(p).toLowerCase())
180
+ throw new Error('debit voucher debits a different request');
181
+ if (BigInt(p.debit_voucher.cost) > BigInt(p.max_cost))
182
+ throw new Error('debit voucher cost exceeds the payment cap');
183
+ }
184
+ }
185
+ /** `ALLOWANCE_ACTIONS`: sign, decrypt, eoa-sign, ibe-extract and dual-approve. */
186
+ export const ALLOWANCE_ACTIONS = Object.values(ACTIONS).reduce((bits, ordinal) => bits | (1 << ordinal), 0);
187
+ /**
188
+ * The actions bitmap of an allowance (bit `i` = `PrepaidAction` ordinal `i`).
189
+ * @param actions - Paid actions the allowance funds; at least one.
190
+ */
191
+ export function allowanceActionBits(actions) {
192
+ if (!actions.length)
193
+ throw new Error('an allowance funds at least one action');
194
+ return actions.reduce((bits, action) => {
195
+ if (!Object.hasOwn(ACTIONS, action))
196
+ throw new Error('unsupported allowance action');
197
+ return bits | (1 << ACTIONS[action]);
198
+ }, 0);
199
+ }
200
+ /**
201
+ * Whether an allowance's actions bitmap funds `action`.
202
+ * @param actions - Allowance bitmap.
203
+ * @param action - Paid action of one operation.
204
+ */
205
+ export function allowanceFunds(actions, action) {
206
+ return Object.hasOwn(ACTIONS, action) && (actions & (1 << ACTIONS[action])) !== 0;
207
+ }
208
+ /**
209
+ * Build the creator EIP-712 data of an allowance intent (the payment domain: chain + Settlement).
210
+ * @param p - Allowance intent before attaching its signature.
211
+ */
212
+ export function prepaidAllowanceIntentTypedData(p) {
213
+ uint(p.chain_id, 64, 'chain_id');
214
+ uint(p.expires_at, 64, 'expires_at');
215
+ uint(p.verification_epoch, 64, 'verification_epoch');
216
+ uint(p.actions, 32, 'actions');
217
+ for (const k of ['settlement', 'key_registry'])
218
+ hex(p[k], 20, k);
219
+ for (const k of ['slot', 'intent_nonce', 'verification_seed', 'verification_root'])
220
+ hex(p[k], 32, k);
221
+ const amount = units(p.amount, 'amount'), maxOpCost = units(p.max_op_cost, 'max_op_cost');
222
+ if (amount === 0n || maxOpCost === 0n || maxOpCost > amount)
223
+ throw new Error('allowance amount and per-operation cap must be nonzero, cap <= amount');
224
+ if (p.actions === 0 || (p.actions & ~ALLOWANCE_ACTIONS) !== 0)
225
+ throw new Error('allowance actions must name only authorized operations');
226
+ if (ZERO32.test(p.intent_nonce) || ZERO32.test(p.verification_seed))
227
+ throw new Error('allowance intent needs a nonzero nonce and verification seed');
228
+ verifierPolicy(p, 'allowance');
229
+ return {
230
+ domain: { ...PAYMENT_DOMAIN, chainId: p.chain_id, verifyingContract: p.settlement },
231
+ primaryType: 'SlotPrepaidAllowanceIntent', types: ALLOWANCE_INTENT_TYPES,
232
+ message: {
233
+ keyRegistry: p.key_registry, slotId: p.slot, intentNonce: p.intent_nonce, amount, maxOpCost, actions: p.actions,
234
+ expiresAt: BigInt(p.expires_at), verificationEpoch: BigInt(p.verification_epoch), verificationSeed: p.verification_seed,
235
+ verificationRoot: p.verification_root, verificationRegistrySize: p.verification_registry_size,
236
+ verificationCommittee: p.verification_committee, verificationQuorum: p.verification_quorum,
237
+ keeperAssignment: keeperAssignmentCommitment(p.keeper_assignment),
238
+ },
239
+ };
240
+ }
241
+ /**
242
+ * The allowance intent's EIP-712 signing hash: the `intentHash` argument of `reservePrepaidAllowanceBls`.
243
+ * @param p - Allowance intent; the signature is not part of the preimage.
244
+ */
245
+ export function prepaidAllowanceIntentHash(p) {
246
+ return hashTypedData(prepaidAllowanceIntentTypedData(p));
247
+ }
248
+ const word = (name) => keccak256(toHex(name));
249
+ /** Domain strings of the prepaid-allowance encodings. A change is a NEW name, never a digit. */
250
+ export const PREPAID_ALLOWANCE_DOMAINS = {
251
+ allowanceId: 'keykeeper/prepaid-allowance-id/v1',
252
+ reserve: 'keykeeper/prepaid-allowance-reserve/v1',
253
+ debitVoucher: 'keykeeper/prepaid-debit/v1',
254
+ allowanceSettle: 'keykeeper/prepaid-allowance-settle/v1',
255
+ close: 'keykeeper/prepaid-allowance-close/v1',
256
+ };
257
+ /**
258
+ * `keccak256(abi.encode(ID_DOMAIN, chainid, settlement, slotId, intentHash))`: the id every reader
259
+ * derives from the creator's intent (chain id BEFORE the Settlement here, after it elsewhere).
260
+ * @param chainId - EVM chain.
261
+ * @param settlement - Settlement proxy.
262
+ * @param slot - Slot.
263
+ * @param intentHash - {@link prepaidAllowanceIntentHash} of the creator intent.
264
+ */
265
+ export function allowanceId(chainId, settlement, slot, intentHash) {
266
+ return keccak256(encodeAbiParameters([{ type: 'bytes32' }, { type: 'uint256' }, { type: 'address' }, { type: 'bytes32' }, { type: 'bytes32' }], [word(PREPAID_ALLOWANCE_DOMAINS.allowanceId), BigInt(chainId), settlement, slot, intentHash]));
267
+ }
268
+ /**
269
+ * The reserve digest (`keykeeper/prepaid-allowance-reserve/v1`).
270
+ * @param settlement - Settlement proxy.
271
+ * @param chainId - EVM chain.
272
+ * @param a - Reservation arguments.
273
+ */
274
+ export function allowanceReserveDigest(settlement, chainId, a) {
275
+ return keccak256(encodeAbiParameters([
276
+ { type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }, { type: 'bytes32' }, { type: 'uint64' }, { type: 'bytes32' },
277
+ { type: 'uint256' }, { type: 'uint256' }, { type: 'uint32' }, { type: 'uint64' }, { type: 'bytes32' }, { type: 'uint64' },
278
+ ], [word(PREPAID_ALLOWANCE_DOMAINS.reserve), settlement, BigInt(chainId), a.slot, a.legacyNonce, a.allowanceId,
279
+ a.amount, a.maxOpCost, a.actions, a.expiresAt, a.assignmentBlock, a.deadline]));
280
+ }
281
+ /**
282
+ * The debit-voucher digest (`keykeeper/prepaid-debit/v1`) the accountant threshold key signs.
283
+ * @param settlement - Settlement proxy.
284
+ * @param chainId - EVM chain.
285
+ * @param v - Voucher fields.
286
+ */
287
+ export function debitVoucherDigest(settlement, chainId, v) {
288
+ return keccak256(encodeAbiParameters([
289
+ { type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }, { type: 'bytes32' }, { type: 'uint64' }, { type: 'bytes32' },
290
+ { type: 'uint256' }, { type: 'uint256' }, { type: 'bytes32' },
291
+ ], [word(PREPAID_ALLOWANCE_DOMAINS.debitVoucher), settlement, BigInt(chainId), v.allowanceId, v.seq, v.requestId, v.cost, v.cumulative, v.quoteBlock]));
292
+ }
293
+ /**
294
+ * {@link debitVoucherDigest} of a wire voucher.
295
+ * @param settlement - Settlement proxy.
296
+ * @param chainId - EVM chain.
297
+ * @param v - Shape-checked voucher.
298
+ */
299
+ export function debitVoucherWireDigest(settlement, chainId, v) {
300
+ assertDebitVoucherWire(v);
301
+ return debitVoucherDigest(settlement, chainId, { allowanceId: v.allowance_id, seq: BigInt(v.seq), requestId: v.request_id,
302
+ cost: BigInt(v.cost), cumulative: BigInt(v.cumulative), quoteBlock: v.quote_block });
303
+ }
304
+ /**
305
+ * The allowance-settle digest (`keykeeper/prepaid-allowance-settle/v1`).
306
+ * @param settlement - Settlement proxy.
307
+ * @param chainId - EVM chain.
308
+ * @param s - Settlement arguments.
309
+ */
310
+ export function allowanceSettleDigest(settlement, chainId, s) {
311
+ return keccak256(encodeAbiParameters([
312
+ { type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }, { type: 'bytes32' }, { type: 'bytes32[]' }, { type: 'uint256[]' },
313
+ { type: 'uint256[]' }, { type: 'bytes32' }, { type: 'bytes32' }, { type: 'bytes32' }, { type: 'uint64' },
314
+ ], [word(PREPAID_ALLOWANCE_DOMAINS.allowanceSettle), settlement, BigInt(chainId), s.allowanceId, [...s.requestIds], [...s.costs], [...s.paid],
315
+ s.batchId, s.root, s.evidenceHash, s.deadline]));
316
+ }
317
+ /**
318
+ * The close digest (`keykeeper/prepaid-allowance-close/v1`).
319
+ * @param settlement - Settlement proxy.
320
+ * @param chainId - EVM chain.
321
+ * @param allowance - Allowance.
322
+ * @param finalCumulative - Every debit the quorum issued.
323
+ * @param deadline - Deadline.
324
+ */
325
+ export function allowanceCloseDigest(settlement, chainId, allowance, finalCumulative, deadline) {
326
+ return keccak256(encodeAbiParameters([{ type: 'bytes32' }, { type: 'address' }, { type: 'uint256' }, { type: 'bytes32' }, { type: 'uint256' }, { type: 'uint64' }], [word(PREPAID_ALLOWANCE_DOMAINS.close), settlement, BigInt(chainId), allowance, finalCumulative, deadline]));
327
+ }
328
+ /**
329
+ * Commit a fixed presentation random and audience before reserving a payment.
330
+ * @param random - Fixed 32-byte cryptographic presentation random.
331
+ * @param clientId - Verifier-agent audience used for the presentation.
332
+ * @param operationExp - Original signed operation expiry in Unix seconds.
333
+ */
334
+ export function paymentSessionCommitment(random, clientId, operationExp) {
335
+ hex(random, 32, 'random');
336
+ uint(operationExp, 64, 'operation expiry');
337
+ const audience = new TextEncoder().encode(clientId);
338
+ return bytesToHex(keccak_256(concatBytes(new TextEncoder().encode('keykeeper/payment-session/v1'), hexToBytes(random), be(audience.length, 8), audience, be(operationExp, 8))));
339
+ }
@@ -0,0 +1,136 @@
1
+ import { type Hex } from 'viem';
2
+ import { type PaymentIntentWire } from './payment.js';
3
+ import { type ClientExecutionSigner, type ExecutionConsent, type ExecutionConsentPolicy, type ExecutionStage } from './execution.js';
4
+ /** Exact request identity in the keeper's public evidence; wire bytes are unsigned arrays. */
5
+ export interface PaidExecutionRequest {
6
+ /** Original deployment chain ID. */
7
+ chain_id: number;
8
+ /** Settlement address left-padded to 32 bytes. */
9
+ settlement: number[];
10
+ /** Original slot. */
11
+ slot: number[];
12
+ /** Stable paid action ordinal, not an arbitrary enum supplied by a server. */
13
+ action: number;
14
+ /** Original operation payload commitment. */
15
+ payload_digest: number[];
16
+ /** Locally retained creator payment hash. */
17
+ authorization_commitment: number[];
18
+ }
19
+ /** Completed durable work report. Recovery deliberately refuses non-success outcomes. */
20
+ export interface CompletedPaidExecutionReport {
21
+ /** Exact original reserved request. */
22
+ request: PaidExecutionRequest;
23
+ /** Worker identity, matched to independently authenticated assignment. */
24
+ operator_key: number[];
25
+ /** Original paid stage. */
26
+ stage: ExecutionStage;
27
+ /** Original client consent, input and backing binding. */
28
+ binding: number[];
29
+ /** Original canonical admission block, not the latest block. */
30
+ reservation_block: number[];
31
+ /** Original reserved fee, unsigned big-endian TASRA base units. */
32
+ cost: number[];
33
+ /** Successful result commitment; absence or failure never triggers another execution. */
34
+ outcome: {
35
+ succeeded: {
36
+ result_commitment: number[];
37
+ };
38
+ };
39
+ }
40
+ /** Untrusted public evidence from a keeper; authenticated before a recovery request is signed. */
41
+ export interface SignedPaidExecutionReport {
42
+ /** Completed report; not a work permit or a computation proof. */
43
+ report: CompletedPaidExecutionReport;
44
+ /** Registered worker's Ed25519 signature over the report signing hash. */
45
+ signature: Hex;
46
+ /** Original client approval retained alongside the durable paid start. */
47
+ consent: ExecutionConsent;
48
+ }
49
+ /** Fresh client authorization to read one exact retained result; grants no work or fee authority. */
50
+ export interface ExecutionRecoveryAuthorization {
51
+ /** Independently selected stage. */
52
+ stage: ExecutionStage;
53
+ /** Independently authenticated serving worker. */
54
+ operator_key: Hex;
55
+ /** Exact original execution binding from authenticated evidence. */
56
+ execution_binding: Hex;
57
+ /** Fresh client clock, within the service's 60-second read window and two-second future skew. */
58
+ issued_at: number;
59
+ /** Nonzero client-generated read correlation nonce; repeated reads remain permitted. */
60
+ nonce: Hex;
61
+ /** Original creator-certified client's fresh Ed25519 signature. */
62
+ signature: Hex;
63
+ }
64
+ /** Independently selected worker and original client key; never copied from a received report. */
65
+ export interface ExecutionRecoveryTarget {
66
+ /** Stage whose completed result the application intends to read. */
67
+ stage: ExecutionStage;
68
+ /** Key authenticated from the signed keeper assignment and canonical historical roster. */
69
+ operatorKey: Hex;
70
+ /** Public key retained from the client's original creator certificate. */
71
+ executionKey: Hex;
72
+ }
73
+ /** Keeper recovery response containing exact committed JSON bytes as a string. */
74
+ export interface RecoveredExecutionReply {
75
+ /** Signed evidence for these exact bytes and their original paid admission. */
76
+ execution: SignedPaidExecutionReport;
77
+ /** Explicit commitment scheme; matched to the independently retained action. */
78
+ encoding: 'json' | 'ibe-extract';
79
+ /** Exact retained JSON; parsing or reserializing before hashing changes its commitment. */
80
+ result_json: string;
81
+ }
82
+ /**
83
+ * Build a public evidence query identity from the locally retained payment, never a server proposal.
84
+ * @param payment Original creator-signed payment. This does not disclose private operation inputs.
85
+ */
86
+ export declare function paidExecutionRequest(payment: PaymentIntentWire): PaidExecutionRequest;
87
+ /**
88
+ * Reconstruct the Rust worker signing hash for a completed result. This does not verify its signer.
89
+ * @param payment Original retained creator payment, used to recompute the complete request identity.
90
+ * @param report Untrusted completed report with strict wire shape.
91
+ */
92
+ export declare function paidExecutionReportSigningHash(payment: PaymentIntentWire, report: CompletedPaidExecutionReport): Hex;
93
+ /**
94
+ * Authenticate public recovery evidence against independently established historical financial policy.
95
+ * The policy time must equal the original accepted time, not the current recovery clock.
96
+ * @param options Retained payment/client identity, historical creator and fee, expected worker and untrusted evidence.
97
+ */
98
+ export declare function verifyPaidExecutionEvidence(options: {
99
+ payment: PaymentIntentWire;
100
+ policy: ExecutionConsentPolicy;
101
+ target: ExecutionRecoveryTarget;
102
+ execution: SignedPaidExecutionReport;
103
+ }): Promise<void>;
104
+ /**
105
+ * Reconstruct the domain-separated fresh read hash. It cannot authorize another paid operation.
106
+ * @param payment Original payment, including its signed assignment and complete request identity.
107
+ * @param authorization Exact stage, worker, original binding, clock and client nonce.
108
+ */
109
+ export declare function executionRecoverySigningHash(payment: PaymentIntentWire, authorization: Omit<ExecutionRecoveryAuthorization, 'signature'>): Hex;
110
+ /**
111
+ * Ask the original local client for a fresh read signature only after verifying work and financial evidence.
112
+ * Applications must supply independently authenticated canonical history, not a server-provided policy.
113
+ * @param options Retained payment, independently selected worker/client, historical policy and fresh clock.
114
+ */
115
+ export declare function createExecutionRecoveryAuthorization(options: {
116
+ payment: PaymentIntentWire;
117
+ policy: ExecutionConsentPolicy;
118
+ target: ExecutionRecoveryTarget;
119
+ execution: SignedPaidExecutionReport;
120
+ signer: ClientExecutionSigner;
121
+ nowSecs: number;
122
+ nonce?: Hex;
123
+ }): Promise<ExecutionRecoveryAuthorization>;
124
+ /**
125
+ * Verify the returned worker evidence and exact result bytes against the previously authenticated report.
126
+ * Returns the retained JSON string only after its commitment matches; callers decode the operation's
127
+ * internal result format themselves. It may differ from the original HTTP envelope and audit metadata.
128
+ * @param options Original identity and history, authenticated expected report, and untrusted response.
129
+ */
130
+ export declare function verifyRecoveredExecutionResult(options: {
131
+ payment: PaymentIntentWire;
132
+ policy: ExecutionConsentPolicy;
133
+ target: ExecutionRecoveryTarget;
134
+ expectedExecution: SignedPaidExecutionReport;
135
+ reply: RecoveredExecutionReply;
136
+ }): Promise<string>;