@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,219 @@
1
+ const HEX32 = /^0x[0-9a-f]{64}$/i;
2
+ function parseHead(value) {
3
+ const b = value;
4
+ if (!b || typeof b.number !== 'bigint' || typeof b.timestamp !== 'bigint' || typeof b.hash !== 'string' || typeof b.parentHash !== 'string'
5
+ || !HEX32.test(b.hash) || !HEX32.test(b.parentHash) || b.number < 0n || b.timestamp < 0n)
6
+ return undefined;
7
+ return { blockNumber: b.number, blockHash: b.hash.toLowerCase(), parentHash: b.parentHash.toLowerCase(), blockTimestamp: b.timestamp };
8
+ }
9
+ /**
10
+ * Create a head follower for `client`. It does nothing until started or fed.
11
+ * @param client Trusted client of the deployment (the same RPC the operation reads).
12
+ * @param options Finality, window, liveness and polling.
13
+ */
14
+ export function createHeadFollower(client, options = {}) {
15
+ const finality = options.finality ?? 'probabilistic', window = options.window ?? 64;
16
+ const liveAfterMs = options.liveAfterMs ?? 2_000, maxTipAgeMs = options.maxTipAgeMs;
17
+ const pollMs = options.pollMs ?? Math.max(50, Math.min(1_000, Math.floor(liveAfterMs / 2))), now = options.now ?? Date.now;
18
+ if (finality !== 'instant' && finality !== 'probabilistic')
19
+ throw new Error('Invalid head follower finality');
20
+ if (!Number.isSafeInteger(window) || window < 2 || window > 1024)
21
+ throw new Error('Invalid head follower window');
22
+ // Both bounds stay within about one block interval: a looser follower would let a security
23
+ // decision act on an older head than the per-request `latest` read it replaces.
24
+ if (!Number.isSafeInteger(liveAfterMs) || liveAfterMs < 1 || liveAfterMs > 2_000)
25
+ throw new Error('Invalid head follower liveness');
26
+ if (maxTipAgeMs !== undefined && (!Number.isSafeInteger(maxTipAgeMs) || maxTipAgeMs < 1 || maxTipAgeMs > 2_000))
27
+ throw new Error('Invalid head follower tip age');
28
+ // A healthy follower re-confirms its tip before it stops being live, idle chain included.
29
+ if (!Number.isSafeInteger(pollMs) || pollMs < 50 || pollMs >= liveAfterMs)
30
+ throw new Error('Invalid head follower poll interval');
31
+ let chain = [];
32
+ let finalized;
33
+ let heardAt = -Infinity, gapCount = 0, minedFloor = 0n;
34
+ let queue = Promise.resolve();
35
+ let timer, unwatch, running = false;
36
+ const listeners = new Set();
37
+ const live = () => {
38
+ if (chain.length === 0)
39
+ return false;
40
+ const at = now();
41
+ return at - heardAt <= liveAfterMs && (maxTipAgeMs === undefined || at - Number(chain[chain.length - 1].blockTimestamp) * 1000 <= maxTipAgeMs);
42
+ };
43
+ const indexOf = (hash) => {
44
+ for (let i = chain.length - 1; i >= 0; i--)
45
+ if (chain[i].blockHash === hash)
46
+ return i;
47
+ return -1;
48
+ };
49
+ const emit = () => {
50
+ const tip = chain[chain.length - 1];
51
+ for (const listener of listeners) {
52
+ try {
53
+ listener(tip);
54
+ }
55
+ catch { /* a pre-read never affects the follower */ }
56
+ }
57
+ };
58
+ const settle = (next) => {
59
+ chain = next.length > window ? next.slice(next.length - window) : next;
60
+ heardAt = now();
61
+ emit();
62
+ };
63
+ const parent = async (hash) => {
64
+ try {
65
+ return parseHead(await client.getBlock({ blockHash: hash }));
66
+ }
67
+ catch {
68
+ return undefined;
69
+ }
70
+ };
71
+ async function link(head) {
72
+ if (chain.length === 0)
73
+ return settle([head]);
74
+ const tip = chain[chain.length - 1];
75
+ if (head.blockHash === tip.blockHash) {
76
+ heardAt = now();
77
+ return;
78
+ }
79
+ // An older header the chain already holds (a lagging RPC backend): nothing new, not a heartbeat.
80
+ if (indexOf(head.blockHash) !== -1)
81
+ return;
82
+ if (head.blockNumber === tip.blockNumber + 1n && head.parentHash === tip.blockHash)
83
+ return settle([...chain, head]);
84
+ // Missed heads or a reorg: walk back through parents to a header the chain holds.
85
+ const path = [head];
86
+ let current = head;
87
+ for (let steps = 0; steps < window; steps++) {
88
+ const at = indexOf(current.parentHash);
89
+ // The parent must sit exactly one below: a hash match at another height is no link.
90
+ if (at !== -1) {
91
+ if (chain[at].blockNumber + 1n !== current.blockNumber)
92
+ break;
93
+ return settle([...chain.slice(0, at + 1), ...path.reverse()]);
94
+ }
95
+ if (current.blockNumber === 0n || current.blockNumber - 1n < chain[0].blockNumber)
96
+ break;
97
+ const previous = await parent(current.parentHash);
98
+ if (!previous || previous.blockHash !== current.parentHash || previous.blockNumber !== current.blockNumber - 1n)
99
+ break;
100
+ path.push(previous);
101
+ current = previous;
102
+ }
103
+ // A gap: vouch only for what follows this header.
104
+ gapCount++;
105
+ settle([head]);
106
+ }
107
+ const follower = {
108
+ finality,
109
+ tip: () => live() && chain[chain.length - 1].blockNumber >= minedFloor ? { ...chain[chain.length - 1] } : undefined,
110
+ noteMinedBlock(blockNumber) { if (typeof blockNumber === 'bigint' && blockNumber > minedFloor)
111
+ minedFloor = blockNumber; },
112
+ isCanonical(at) {
113
+ if (finality !== 'instant' || !live() || chain.length === 0)
114
+ return undefined;
115
+ const first = chain[0].blockNumber, last = chain[chain.length - 1].blockNumber;
116
+ if (at.blockNumber < first || at.blockNumber > last)
117
+ return undefined;
118
+ const held = chain[Number(at.blockNumber - first)].blockHash === at.blockHash.toLowerCase();
119
+ if (!held)
120
+ return false;
121
+ // Final only at or below the RPC's finalized head, and only when that head is in this chain.
122
+ if (!finalized || at.blockNumber > finalized.blockNumber || finalized.blockNumber < first || finalized.blockNumber > last
123
+ || chain[Number(finalized.blockNumber - first)].blockHash !== finalized.blockHash)
124
+ return undefined;
125
+ return true;
126
+ },
127
+ live,
128
+ ingest(header) {
129
+ const head = parseHead(header);
130
+ if (!head)
131
+ return queue;
132
+ queue = queue.then(() => link(head)).catch(() => { });
133
+ return queue;
134
+ },
135
+ ingestFinalized(header) {
136
+ const head = parseHead(header);
137
+ if (!head)
138
+ return queue;
139
+ queue = queue.then(() => { if (!finalized || head.blockNumber >= finalized.blockNumber)
140
+ finalized = { blockNumber: head.blockNumber, blockHash: head.blockHash }; }).catch(() => { });
141
+ return queue;
142
+ },
143
+ onHead(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; },
144
+ gaps: () => gapCount,
145
+ start() {
146
+ if (running)
147
+ return;
148
+ running = true;
149
+ if (client.transport.type === 'webSocket') {
150
+ unwatch = client.watchBlocks({ emitOnBegin: true, includeTransactions: false, onError: () => { }, onBlock: block => {
151
+ // The finalized head is read at every new head (it is not part of the subscription).
152
+ void client.getBlock({ blockTag: 'finalized' }).then(final => follower.ingestFinalized(final), () => { }).finally(() => { void follower.ingest(block); });
153
+ } });
154
+ return;
155
+ }
156
+ const poll = async () => {
157
+ // `latest` and `finalized` together (one JSON-RPC batch on a batching transport).
158
+ try {
159
+ const [latest, final] = await Promise.all([client.getBlock({ blockTag: 'latest' }), client.getBlock({ blockTag: 'finalized' })]);
160
+ await follower.ingestFinalized(final);
161
+ await follower.ingest(latest);
162
+ }
163
+ catch { /* liveness lapses */ }
164
+ if (running) {
165
+ timer = setTimeout(() => { void poll(); }, pollMs);
166
+ timer.unref?.();
167
+ }
168
+ };
169
+ void poll();
170
+ },
171
+ stop() {
172
+ running = false;
173
+ if (timer)
174
+ clearTimeout(timer);
175
+ unwatch?.();
176
+ timer = undefined;
177
+ unwatch = undefined;
178
+ chain = [];
179
+ heardAt = -Infinity;
180
+ finalized = undefined;
181
+ },
182
+ };
183
+ return follower;
184
+ }
185
+ const followers = new WeakMap();
186
+ /**
187
+ * The follower attached to `client`, if any.
188
+ * @param client Client the follower was attached to.
189
+ */
190
+ export function headFollowerOf(client) {
191
+ return followers.get(client);
192
+ }
193
+ /**
194
+ * Follow `client`'s chain head: paid operations on this client then read block-pinned facts from
195
+ * the followed tip and its pre-reads, falling back to RPC whenever the follower cannot vouch.
196
+ * Replaces (and stops) a follower attached before. Returns the started follower.
197
+ * @param client Trusted client of the deployment.
198
+ * @param options Finality (declare `instant` only for a chain whose accepted blocks are final), window, liveness, polling.
199
+ */
200
+ export function followHeads(client, options = {}) {
201
+ followers.get(client)?.stop();
202
+ const follower = createHeadFollower(client, options);
203
+ followers.set(client, follower);
204
+ follower.start();
205
+ return follower;
206
+ }
207
+ /**
208
+ * Detach and stop the follower of `client`.
209
+ * @param client Client whose follower to stop.
210
+ */
211
+ export function unfollowHeads(client) {
212
+ followers.get(client)?.stop();
213
+ followers.delete(client);
214
+ }
215
+ /** Internal (tests and fixtures): attach an unstarted follower. */
216
+ export function attachHeadFollower(client, follower) {
217
+ followers.get(client)?.stop();
218
+ followers.set(client, follower);
219
+ }
@@ -0,0 +1,23 @@
1
+ import type { PublicClient } from 'viem';
2
+ import { type FollowedHead } from './headFollower.js';
3
+ /** Most interests per client; the oldest registration is dropped first. */
4
+ export declare const MAX_PREFETCH_INTERESTS = 256;
5
+ /**
6
+ * How long an interest registered without an expiry keeps being pre-read after its last
7
+ * registration. Every use re-registers it, so a slot or service in use stays warm, while one the
8
+ * client stopped using stops costing reads: the idle cost of a client follows what it is doing,
9
+ * not every slot it ever touched.
10
+ */
11
+ export declare const HEAD_PREFETCH_IDLE_MS = 60000;
12
+ /**
13
+ * Pre-read for `key` at every new followed head until `until` (ms; default:
14
+ * {@link HEAD_PREFETCH_IDLE_MS} after this registration). Re-registering a key refreshes its read
15
+ * and expiry. Without a follower on `client` this does nothing.
16
+ * @param client Client whose follower reports heads.
17
+ * @param key Stable interest identity.
18
+ * @param read Block-pinned reads at the new tip.
19
+ * @param until Expiry in ms since the epoch.
20
+ */
21
+ export declare function registerHeadPrefetch(client: PublicClient, key: string, read: (tip: FollowedHead) => Promise<unknown>, until?: number): void;
22
+ /** Stop pre-reading for `key`. */
23
+ export declare function unregisterHeadPrefetch(client: PublicClient, key: string): void;
@@ -0,0 +1,67 @@
1
+ import { headFollowerOf } from './headFollower.js';
2
+ /** Most interests per client; the oldest registration is dropped first. */
3
+ export const MAX_PREFETCH_INTERESTS = 256;
4
+ /**
5
+ * How long an interest registered without an expiry keeps being pre-read after its last
6
+ * registration. Every use re-registers it, so a slot or service in use stays warm, while one the
7
+ * client stopped using stops costing reads: the idle cost of a client follows what it is doing,
8
+ * not every slot it ever touched.
9
+ */
10
+ export const HEAD_PREFETCH_IDLE_MS = 60_000;
11
+ const registries = new WeakMap();
12
+ function registry(client) {
13
+ const follower = headFollowerOf(client);
14
+ if (!follower)
15
+ return undefined;
16
+ let r = registries.get(client);
17
+ if (r && r.follower !== follower) {
18
+ r.unsubscribe();
19
+ r = undefined;
20
+ }
21
+ if (!r) {
22
+ const interests = new Map();
23
+ const unsubscribe = follower.onHead(tip => {
24
+ // Nothing is pre-read at a head the follower does not vouch for: its answers could never be served.
25
+ if (follower.isCanonical(tip) !== true)
26
+ return;
27
+ const now = Date.now();
28
+ for (const [key, interest] of interests) {
29
+ if (interest.until <= now) {
30
+ interests.delete(key);
31
+ continue;
32
+ }
33
+ void interest.read(tip).catch(() => { });
34
+ }
35
+ });
36
+ registries.set(client, r = { follower, interests, unsubscribe });
37
+ }
38
+ return r;
39
+ }
40
+ /**
41
+ * Pre-read for `key` at every new followed head until `until` (ms; default:
42
+ * {@link HEAD_PREFETCH_IDLE_MS} after this registration). Re-registering a key refreshes its read
43
+ * and expiry. Without a follower on `client` this does nothing.
44
+ * @param client Client whose follower reports heads.
45
+ * @param key Stable interest identity.
46
+ * @param read Block-pinned reads at the new tip.
47
+ * @param until Expiry in ms since the epoch.
48
+ */
49
+ export function registerHeadPrefetch(client, key, read, until = Date.now() + HEAD_PREFETCH_IDLE_MS) {
50
+ const r = registry(client);
51
+ if (!r)
52
+ return;
53
+ const known = r.interests.delete(key);
54
+ if (r.interests.size >= MAX_PREFETCH_INTERESTS)
55
+ r.interests.delete(r.interests.keys().next().value);
56
+ r.interests.set(key, { read, until });
57
+ if (known)
58
+ return;
59
+ // A new interest reads the current tip at once too: the next operation finds it warm.
60
+ const tip = r.follower.tip();
61
+ if (tip && r.follower.isCanonical(tip) === true)
62
+ void read(tip).catch(() => { });
63
+ }
64
+ /** Stop pre-reading for `key`. */
65
+ export function unregisterHeadPrefetch(client, key) {
66
+ registries.get(client)?.interests.delete(key);
67
+ }
@@ -1,5 +1,24 @@
1
1
  export * from './abis/index.js';
2
- export { SlotCommitmentExpiredError, assertExpiredSlotCommitment } from './commitmentRecovery.js';
2
+ export { UnderfundedSlotError, UnderfundedGasPayerError, PaidBackoffError, PaidApprovalUnresolvedError, PaidReservationQuotaError } from '../errors.js';
3
+ export { readSlotFunding, readPaidOperationReceipt, resolvePaidKeeperTarget, discoverPaidOperationContext, readCurrentBeaconEpoch, readBeaconDrawState, PaidDrawMovedError } from './prepaid.js';
4
+ export type { BeaconDrawState } from './prepaid.js';
5
+ export { readBillingMode, createBillingModeDetector, requirePrepaidSlot, BillingModeError } from './billing.js';
6
+ export { drawnVerifierWitnesses, fetchDrawnVerifierWitnesses } from './verifierSnapshot.js';
7
+ export { encodePrepaidFaultContest, contestPrepaidFault, readPrepaidFaultResolution, submitPrepaidFaultClaim, readPrepaidFaultStatus, PREPAID_FAULT_KINDS, MAX_PREPAID_FAULT_BUNDLE_BYTES } from './prepaidFault.js';
8
+ export type { PrepaidFaultKind, PrepaidFaultVerdict, PrepaidFaultHttpOptions } from './prepaidFault.js';
9
+ export type { OriginalVerifierPolicy } from './verifierSnapshot.js';
10
+ export type { BillingMode, BillingModeObservation, BillingDeployment, BillingModeDetector } from './billing.js';
11
+ export type { PrepaidDeployment, PrepaidObservation, SlotFunding, PaidOperationReceipt, ExpectedPaidOperation, PaidKeeperEndpoint, PaidKeeperTarget, PaidKeeperTransportOptions, PaidContextDeployment, PaidContextOptions, DiscoveredPaymentFields, PaidOperationContext, DrawnPaidOperationContext, UndrawnPaidOperationContext, UndrawnPaymentFields, PaymentDrawFieldName } from './prepaid.js';
12
+ export { reservePaidOperation, reconcilePaidReservation, PaidReservationUncertainError, PaidReservationAbortedError, PaidReservationStaleEpochError, PaidReservationQuorumNotPreparedError } from './reservation.js';
13
+ export { followHeads, unfollowHeads, headFollowerOf, createHeadFollower, type HeadFollower, type HeadFollowerOptions, type FollowedHead } from './headFollower.js';
14
+ export type { PaidReservationQuote, PaidReservationRecord, PaidReservationCheckpoint, ReservePaidOperationOptions, PaidReservationResolution } from './reservation.js';
15
+ export { reservePrepaidAllowance, reconcilePrepaidAllowance, readPrepaidAllowance, prepaidAllowanceId, collectDebitVoucher, verifyDebitVoucher, readAccountantGroupKey, DebitVoucherError, ALLOWANCE_MAX_LIFETIME_SECS, ALLOWANCE_QUOTE_MAX_AGE_SECS } from './allowance.js';
16
+ export type { PrepaidAllowanceState, PrepaidAllowanceQuote, PrepaidAllowanceReservationRecord, PrepaidAllowanceCheckpoint, ReservePrepaidAllowanceOptions, DebitPartialWire, DebitRequest, DebitMemberOutcome, CollectDebitVoucherOptions } from './allowance.js';
17
+ export { SlotCommitmentExpiredError, SlotRevealNotYetError, SlotSeedUnavailableError, assertExpiredSlotCommitment } from './commitmentRecovery.js';
18
+ export { createPrepaidEscapeClient, decodePrepaidEscapeRevert, decodePrepaidEscapeLogs, prepaidEscapeId, MAX_ESCAPE_PER_CALL, MAX_ESCAPE_REQUESTS } from './prepaidEscape.js';
19
+ export type { PrepaidEscapeClient, PrepaidEscapeDeployment, PrepaidEscapeRequestState, PrepaidEscapeStatus, PrepaidEscapeObservation, PrepaidEscapeRecord, PrepaidEscapeCheckpoint, EscapePrepaidArgs, PrepaidEscapeCallResult, PrepaidEscapeResult, ReconcileEscapeArgs, PrepaidEscapeResolution, PrepaidEscapeEvents } from './prepaidEscape.js';
20
+ export { PrepaidEscapeError, PrepaidEscapeUncertainError, isPrepaidEscapeError } from '../errors.js';
21
+ export type { PrepaidEscapeCode } from '../errors.js';
3
22
  export { addressBookFromBroadcast, addressBookFromEnv, addressBookFromObject, DEFAULT_CHAIN_ID, requireAddress, requireVaultAddress, vaultKey, VAULT_TRANCHES, } from './deployments.js';
4
23
  export type { AddressBook, Address, VaultTranche } from './deployments.js';
5
24
  export { NETWORKS, networkNameForChain, resolveNetworkProfile, assertEurcFaucetAllowed } from './networks.js';
@@ -7,7 +26,7 @@ export type { NetworkName, NetworkPreset, ResolvedNetworkProfile } from './netwo
7
26
  export { CONTRACT_CATEGORY, categoryFor, eventNamesOf, decodeContractLogs, jsonSafe, } from './events.js';
8
27
  export type { EventCategory, DecodedEvent } from './events.js';
9
28
  export { createTasraChainClient } from './client.js';
10
- export type { ChainClientConfig, GetLogsWindowedOpts, TasraChainClient, } from './client.js';
29
+ export type { ChainClientConfig, RpcBatchOptions, GetLogsWindowedOpts, TasraChainClient, } from './client.js';
11
30
  export { nodeApi, verifierApi, parsePrometheus } from './offchain.js';
12
31
  export type { FetchOpts, NodeInfo, KeySlotSummary, KeyListReply, SignedHeartbeat, MeteringReply, VerifierInfo, } from './offchain.js';
13
32
  export { truncateHex, formatUnits, formatBps, formatWad } from './format.js';
@@ -17,11 +36,19 @@ export type { ProvisionRuleArgs, ProvisionRuleResult, KeeperProvisionResult } fr
17
36
  export type { RuleInput } from './ruleInput.js';
18
37
  export { readRuleAmendment, amendSlotRule, RuleAmendmentError } from './ruleAmendment.js';
19
38
  export type { RuleAmendmentStatus, RuleAmendmentErrorCode, AmendSlotRuleArgs, AmendSlotRuleResult, AmendmentPhase } from './ruleAmendment.js';
20
- export type { CreateSlotArgs, CreateSlotFromPolicyArgs, CommitRevealOptions, ProposeRuleArgs, ProposeRuleResult, RelayConfig, RelayReceipt, TasraWriteClient, SlotAuthType, SlotMode, WriteClientConfig, WriteClientKeyConfig, WriteClientWalletConfig, } from './write.js';
39
+ export { readSlotHandoff, SlotHandoffError } from './slotHandoff.js';
40
+ export type { SlotHandoffStatus, SlotHandoffErrorCode } from './slotHandoff.js';
41
+ export { readRotationLock, isRotationLocked, decodeRotationLockRevert, decodeKeyRotationLockedLogs, RotationLockError, ROTATION_LOCK_SENTINEL, ROTATION_LOCK_SELECTORS } from './rotationLock.js';
42
+ export type { RotationLockStatus, RotationLockErrorCode, RotationLockRevert, KeyRotationLockedEvent } from './rotationLock.js';
43
+ export { checkTecdsaReshareRoster, ReshareRosterError, MAX_RESHARE_PARTIES } from './reshareRoster.js';
44
+ export type { TecdsaReshareRosterInput, TecdsaReshareRosterPlan, ReshareRosterErrorCode } from './reshareRoster.js';
45
+ export { readCustodyHealth, verifyCustodyHealthReply, parseCustodyStatement, custodyStatementHash, verifyCustodyStatement, custodyStatementIsCurrent, assessCustodyHealth, CustodyHealthError, CUSTODY_HEALTH_DOMAIN, CUSTODY_STATEMENT_MAX_AGE_SECS } from './custodyHealth.js';
46
+ export type { CustodyStatement, CustodyFailure, CustodyReshareState, CustodyHealthErrorCode, ExpectedCustodyReply, VerifiedCustodyReport, CustodyHealthLevel, ReadCustodyHealthOptions, CustodyHealthReport } from './custodyHealth.js';
47
+ export type { CreateSlotArgs, CreateSlotFromPolicyArgs, CommitRevealOptions, ProposeRuleArgs, ProposeRuleResult, SlotTransferProposal, RotationLockResult, RelayConfig, RelayReceipt, TasraWriteClient, SlotAuthType, SlotMode, WriteClientConfig, WriteClientKeyConfig, WriteClientWalletConfig, } from './write.js';
21
48
  export { VERIFIER_TAG, ACCOUNTANT_TAG, resolveSlotKeeperUrls, resolveVerifierDirectory, resolveSlotGroupKey, resolveAccountantUrls, } from './discovery.js';
22
49
  export type { SlotGroupKey } from './discovery.js';
23
- export { requestSlotSeed } from './slotSeed.js';
24
- export type { SlotSeed, SlotSeedOptions } from './slotSeed.js';
50
+ export { DEFAULT_SLOT_SEED_HEDGE_MS, DEFAULT_SLOT_SEED_RETRY_MS, requestSlotSeed } from './slotSeed.js';
51
+ export type { SlotSeed, SlotSeedAnswer, SlotSeedFailure, SlotSeedOptions } from './slotSeed.js';
25
52
  export { createCommitteeSlotClient } from './committeeClient.js';
26
53
  export type { CommitteeSlotClient, CommitteeSlotClientConfig, SlotCommitteeSignOptions, SlotCommitteeDecryptOptions, CommitteeSignOptions, CommitteeDecryptOptions, } from './committeeClient.js';
27
54
  export { createTasraSlotClient } from './slotClient.js';
@@ -30,10 +57,25 @@ export { SERVICE_TYPES, SERVICE_STATUSES, deriveServiceId, hashServiceManifest,
30
57
  export type { ServiceType, ServiceStatus, ServiceRecord, ServiceApproval } from './services.js';
31
58
  export { SERVICE_MANIFEST_PATH, SERVICE_IDENTITY_PATH, SERVICE_MANIFEST_MAX_BYTES, SERVICE_IDENTITY_MAX_BYTES, SERVICE_CHALLENGE_SECONDS, SERVICE_CHALLENGE_LIFETIME_SECONDS, SERVICE_IDENTITY_PROTOCOL, validateServiceEndpoint, encodeServiceManifest, verifyServiceManifest, serviceChallengeTypedData, encodeServiceChallenge, parseServiceChallenge, validateServiceChallenge, verifyServiceIdentity, authenticateApprovedService } from './serviceIdentity.js';
32
59
  export type { ServiceManifest, ServiceChallenge, ServiceDiscoveryTransport, AuthenticatedService } from './serviceIdentity.js';
33
- export { createRegisteredRelaySubmitter, reconcileRelayAttempt, RelayOutcomeUnknownError } from './registeredRelay.js';
34
- export type { RegisteredRelayConfig, RelayTransport, RelayAttempt, RelayIntent, RelayReconciliation } from './registeredRelay.js';
60
+ export { createRegisteredRelaySubmitter, reconcileRelayAttempt, RelayOutcomeUnknownError, isRelayBusyReason } from './registeredRelay.js';
61
+ export type { RegisteredRelayConfig, RelayTransport, RelayAttempt, RelayIntent, RelayReconciliation, RelayHttpResponse } from './registeredRelay.js';
62
+ export type { RelayVoucher, RelayVoucherIntent, RelaySponsorshipConfig } from './relayVoucher.js';
63
+ export { assertRelayVoucher, assertRelayVoucherIntent } from './relayVoucher.js';
35
64
  export { createRegisteredAgentClient, AgentSessionCreationUnknownError } from './registeredAgent.js';
36
- export type { AgentTransport, ApprovedAgentProfile, RegisteredAgentSession } from './registeredAgent.js';
65
+ export type { AgentTransport, ApprovedAgentProfile, RegisteredAgentSession, UnpaidAgentSessionRecovery } from './registeredAgent.js';
66
+ export type { PaidAgentHttpResponse, PaidAgentTransport } from './paidAgentTransport.js';
67
+ export { prepareRegisteredPaidSession, PaidAgentControlError, BATCH_APPROVAL_CAPABILITY, PROPOSAL_WAIT_CAPABILITY, MAX_PROPOSAL_WAIT_MS } from './registeredPaidAgent.js';
68
+ export type { RegisteredPaidAgentSession, PaidAgentSessionParams, ClientApprovedPresentation, PaidRetainedPresentation, PaidAgentProposal, PaidPacingOptions, RetainedPaidApproval, PaidApprovalDelivery, PaidApprovalBatchReply } from './registeredPaidAgent.js';
69
+ export { paidServerWaitMs, systemPacingClock } from './paidPacing.js';
70
+ export type { PaidPacingClock } from './paidPacing.js';
71
+ export { readClientExecutionPolicy } from './prepaid.js';
72
+ export type { ClientExecutionDeployment, ClientExecutionObservation, PaidVerifierWitness } from './prepaid.js';
73
+ export { readKeeperExecutionRecoveryPolicy } from './prepaid.js';
74
+ export type { KeeperExecutionRecoveryObservation } from './prepaid.js';
75
+ export { recoverKeeperExecution, KeeperRecoveryError } from './keeperRecovery.js';
76
+ export type { KeeperRecoveryHttpResponse, KeeperRecoveryTransport, RecoveredKeeperExecution, RecoverKeeperExecutionOptions } from './keeperRecovery.js';
77
+ export { createKeeperExecutionApprover } from './keeperExecution.js';
78
+ export type { KeeperExecutionClientConsent, KeeperExecutionApproverOptions } from './keeperExecution.js';
37
79
  export { parseApplicationServiceProfiles, applicationServiceProfilesDocument } from './serviceProfiles.js';
38
80
  export type { ApplicationServiceProfiles, ApprovedServiceProfile } from './serviceProfiles.js';
39
81
  export { openRegisteredVerifierAgentSession, awaitRegisteredVerifierAgentResult, assertRegisteredWalletRequest } from './registeredOperation.js';
@@ -5,7 +5,19 @@
5
5
  // entry stays lean and viem is only pulled in when chain features are imported.
6
6
  // Contract ABIs (generated from the Foundry artifacts) + nametoabi map.
7
7
  export * from './abis/index.js';
8
- export { SlotCommitmentExpiredError, assertExpiredSlotCommitment } from './commitmentRecovery.js';
8
+ export { UnderfundedSlotError, UnderfundedGasPayerError, PaidBackoffError, PaidApprovalUnresolvedError, PaidReservationQuotaError } from '../errors.js';
9
+ export { readSlotFunding, readPaidOperationReceipt, resolvePaidKeeperTarget, discoverPaidOperationContext, readCurrentBeaconEpoch, readBeaconDrawState, PaidDrawMovedError } from './prepaid.js';
10
+ export { readBillingMode, createBillingModeDetector, requirePrepaidSlot, BillingModeError } from './billing.js';
11
+ export { drawnVerifierWitnesses, fetchDrawnVerifierWitnesses } from './verifierSnapshot.js';
12
+ export { encodePrepaidFaultContest, contestPrepaidFault, readPrepaidFaultResolution, submitPrepaidFaultClaim, readPrepaidFaultStatus, PREPAID_FAULT_KINDS, MAX_PREPAID_FAULT_BUNDLE_BYTES } from './prepaidFault.js';
13
+ export { reservePaidOperation, reconcilePaidReservation, PaidReservationUncertainError, PaidReservationAbortedError, PaidReservationStaleEpochError, PaidReservationQuorumNotPreparedError } from './reservation.js';
14
+ export { followHeads, unfollowHeads, headFollowerOf, createHeadFollower } from './headFollower.js';
15
+ // ADR-0090 prepaid allowances: reserve once, debit per operation by accountant-quorum voucher.
16
+ export { reservePrepaidAllowance, reconcilePrepaidAllowance, readPrepaidAllowance, prepaidAllowanceId, collectDebitVoucher, verifyDebitVoucher, readAccountantGroupKey, DebitVoucherError, ALLOWANCE_MAX_LIFETIME_SECS, ALLOWANCE_QUOTE_MAX_AGE_SECS } from './allowance.js';
17
+ export { SlotCommitmentExpiredError, SlotRevealNotYetError, SlotSeedUnavailableError, assertExpiredSlotCommitment } from './commitmentRecovery.js';
18
+ // Payer-side prepaid timeout escape: refund reservations nobody reconciled within the governed delay.
19
+ export { createPrepaidEscapeClient, decodePrepaidEscapeRevert, decodePrepaidEscapeLogs, prepaidEscapeId, MAX_ESCAPE_PER_CALL, MAX_ESCAPE_REQUESTS } from './prepaidEscape.js';
20
+ export { PrepaidEscapeError, PrepaidEscapeUncertainError, isPrepaidEscapeError } from '../errors.js';
9
21
  // Deployment address discovery.
10
22
  export { addressBookFromBroadcast, addressBookFromEnv, addressBookFromObject, DEFAULT_CHAIN_ID, requireAddress, requireVaultAddress, vaultKey, VAULT_TRANCHES, } from './deployments.js';
11
23
  // Network presets: chain id + RPC per known network. Only `local` today.
@@ -31,13 +43,19 @@ export { createTasraWriteClient, generateClientKey, ruleCommitment, verifyRuleCo
31
43
  export { provisionRule, provisionRuleTypedData, PROVISION_RULE_ACTION } from './provisionRule.js';
32
44
  // Rule amendment: the status read and the end-to-end driver (the four writes live on the write client).
33
45
  export { readRuleAmendment, amendSlotRule, RuleAmendmentError } from './ruleAmendment.js';
46
+ // Slot hand-offs: the read and the typed refusal (the six writes live on the write client).
47
+ export { readSlotHandoff, SlotHandoffError } from './slotHandoff.js';
48
+ // ADR-0099: the rotation lock, the tECDSA reshare roster rule and the keepers' signed custody health.
49
+ export { readRotationLock, isRotationLocked, decodeRotationLockRevert, decodeKeyRotationLockedLogs, RotationLockError, ROTATION_LOCK_SENTINEL, ROTATION_LOCK_SELECTORS } from './rotationLock.js';
50
+ export { checkTecdsaReshareRoster, ReshareRosterError, MAX_RESHARE_PARTIES } from './reshareRoster.js';
51
+ export { readCustodyHealth, verifyCustodyHealthReply, parseCustodyStatement, custodyStatementHash, verifyCustodyStatement, custodyStatementIsCurrent, assessCustodyHealth, CustodyHealthError, CUSTODY_HEALTH_DOMAIN, CUSTODY_STATEMENT_MAX_AGE_SECS } from './custodyHealth.js';
34
52
  // Slot-driven on-chain discovery: resolve a slot's keeper URLs, the active verifier
35
53
  // directory, and the slot's group key straight from the registry.
36
54
  export { VERIFIER_TAG, ACCOUNTANT_TAG, resolveSlotKeeperUrls, resolveVerifierDirectory, resolveSlotGroupKey, resolveAccountantUrls, } from './discovery.js';
37
55
  // accountant-seeded creation: the per-commitment draw seed. `createSlotCommitReveal` uses this internally; it is
38
56
  // exported for a caller that drives commit and reveal itself (the CLI does) or wants to inspect
39
57
  // what the accountant set answered before spending gas.
40
- export { requestSlotSeed } from './slotSeed.js';
58
+ export { DEFAULT_SLOT_SEED_HEDGE_MS, DEFAULT_SLOT_SEED_RETRY_MS, requestSlotSeed } from './slotSeed.js';
41
59
  // The few-lines committee surface, driven by just a slot id: discovers the
42
60
  // keeper node + verifier set from chain, then sign / encrypt / decrypt.
43
61
  export { createCommitteeSlotClient } from './committeeClient.js';
@@ -48,8 +66,15 @@ export { createTasraSlotClient } from './slotClient.js';
48
66
  // Provider-owned service directory (metadata; endpoint authentication remains separate).
49
67
  export { SERVICE_TYPES, SERVICE_STATUSES, deriveServiceId, hashServiceManifest, readApprovedServiceRecord } from './services.js';
50
68
  export { SERVICE_MANIFEST_PATH, SERVICE_IDENTITY_PATH, SERVICE_MANIFEST_MAX_BYTES, SERVICE_IDENTITY_MAX_BYTES, SERVICE_CHALLENGE_SECONDS, SERVICE_CHALLENGE_LIFETIME_SECONDS, SERVICE_IDENTITY_PROTOCOL, validateServiceEndpoint, encodeServiceManifest, verifyServiceManifest, serviceChallengeTypedData, encodeServiceChallenge, parseServiceChallenge, validateServiceChallenge, verifyServiceIdentity, authenticateApprovedService } from './serviceIdentity.js';
51
- export { createRegisteredRelaySubmitter, reconcileRelayAttempt, RelayOutcomeUnknownError } from './registeredRelay.js';
69
+ export { createRegisteredRelaySubmitter, reconcileRelayAttempt, RelayOutcomeUnknownError, isRelayBusyReason } from './registeredRelay.js';
70
+ export { assertRelayVoucher, assertRelayVoucherIntent } from './relayVoucher.js';
52
71
  export { createRegisteredAgentClient, AgentSessionCreationUnknownError } from './registeredAgent.js';
72
+ export { prepareRegisteredPaidSession, PaidAgentControlError, BATCH_APPROVAL_CAPABILITY, PROPOSAL_WAIT_CAPABILITY, MAX_PROPOSAL_WAIT_MS } from './registeredPaidAgent.js';
73
+ export { paidServerWaitMs, systemPacingClock } from './paidPacing.js';
74
+ export { readClientExecutionPolicy } from './prepaid.js';
75
+ export { readKeeperExecutionRecoveryPolicy } from './prepaid.js';
76
+ export { recoverKeeperExecution, KeeperRecoveryError } from './keeperRecovery.js';
77
+ export { createKeeperExecutionApprover } from './keeperExecution.js';
53
78
  export { parseApplicationServiceProfiles, applicationServiceProfilesDocument } from './serviceProfiles.js';
54
79
  export { openRegisteredVerifierAgentSession, awaitRegisteredVerifierAgentResult, assertRegisteredWalletRequest } from './registeredOperation.js';
55
80
  // Versioned, digest-pinned public deployment records.
@@ -0,0 +1,44 @@
1
+ import { type PublicClient } from 'viem';
2
+ import { type ClientExecutionSigner, type ExecutionCertificate } from '../committee/execution.js';
3
+ import { type KeeperExecutionApprover } from '../committee/keeperExecution.js';
4
+ import { type PaymentIntentWire } from '../committee/payment.js';
5
+ import { type ExpectedPaidOperation, type PaidKeeperTarget, type PaidKeeperTransportOptions, type PrepaidDeployment } from './prepaid.js';
6
+ /** Client-owned certificate and signing capability for the original paid operation. */
7
+ export interface KeeperExecutionClientConsent {
8
+ /** Original creator certificate; its payment, session and public client key stay fixed. */
9
+ certificate: ExecutionCertificate;
10
+ /** Original local Ed25519 execution signer; never forward it to a service. */
11
+ signer: ClientExecutionSigner;
12
+ }
13
+ /** Independent chain and local client intent used before every keeper stage signature. */
14
+ export interface KeeperExecutionApproverOptions extends KeeperExecutionClientConsent {
15
+ /** Trusted bounded canonical RPC client for the approved chain. */
16
+ client: PublicClient;
17
+ /** Independently approved contracts and chain. */
18
+ deployment: PrepaidDeployment;
19
+ /** Original creator intent retained before its reservation. */
20
+ payment: PaymentIntentWire;
21
+ /** Intended slot, paid action and exact operation digest. */
22
+ expected: ExpectedPaidOperation;
23
+ /** Explicit local HTTP exception; official Fuji still requires HTTPS. */
24
+ transportPolicy?: PaidKeeperTransportOptions;
25
+ /** Caller-approved routing map; never populate it from a service response. */
26
+ keeperUrl?: (registeredUrl: string) => string;
27
+ }
28
+ /**
29
+ * Create a client-only keeper approver bound to one independently retained payment and operation.
30
+ * Before each signing callback, use canonical reserved TASRA, creator consent and eligible worker
31
+ * sharing read within the last 15 seconds: the parallel approvals of one operation share one such
32
+ * read, and an older one is read again. Sign the complete local request for coordinator/contributors,
33
+ * or the one IBE contributor being contacted. This helper performs no HTTP dispatch or transaction.
34
+ * @param options Approved deployment, original operation and creator-certified local signer.
35
+ */
36
+ export declare function createKeeperExecutionApprover(options: KeeperExecutionApproverOptions): KeeperExecutionApprover;
37
+ /**
38
+ * Internal: an approver whose first approvals may use `target`, a canonical read the caller has
39
+ * just made through `resolvePaidKeeperTarget` for this exact deployment, payment, operation and
40
+ * transport policy. It is reused only while it is as recent as a shared read.
41
+ * @param options Approved deployment, original operation and creator-certified local signer.
42
+ * @param target Freshly resolved target for the same payment.
43
+ */
44
+ export declare function createKeeperExecutionApproverWithTarget(options: KeeperExecutionApproverOptions, target: PaidKeeperTarget): KeeperExecutionApprover;
@@ -0,0 +1,127 @@
1
+ import { recoverTypedDataAddress } from 'viem';
2
+ import { approveExecutionRequest } from '../committee/execution.js';
3
+ import { requireKeeperExecutionPayload } from '../committee/keeperExecution.js';
4
+ import { assertPaymentIntentWire, paymentIntentHash, paymentIntentTypedData, prepaidRequestId } from '../committee/payment.js';
5
+ import { resolvePaidKeeperTarget } from './prepaid.js';
6
+ function endpoint(member, chainId, policy, route) {
7
+ const url = new URL(route(member.url));
8
+ if (url.username || url.password || url.search || url.hash || (url.protocol !== 'https:'
9
+ && !(chainId === 43112 && policy.allowLocalHttp === true && url.protocol === 'http:')))
10
+ throw new Error('Client-approved keeper route violates transport policy');
11
+ return url.toString().replace(/\/$/, '');
12
+ }
13
+ /** A canonical read this recent is shared by the approvals of one operation (half the signing window). */
14
+ const SHARED_TARGET_MAX_AGE_SECS = 15;
15
+ /**
16
+ * Create a client-only keeper approver bound to one independently retained payment and operation.
17
+ * Before each signing callback, use canonical reserved TASRA, creator consent and eligible worker
18
+ * sharing read within the last 15 seconds: the parallel approvals of one operation share one such
19
+ * read, and an older one is read again. Sign the complete local request for coordinator/contributors,
20
+ * or the one IBE contributor being contacted. This helper performs no HTTP dispatch or transaction.
21
+ * @param options Approved deployment, original operation and creator-certified local signer.
22
+ */
23
+ export function createKeeperExecutionApprover(options) {
24
+ return approverWithTarget(options);
25
+ }
26
+ /**
27
+ * Internal: an approver whose first approvals may use `target`, a canonical read the caller has
28
+ * just made through `resolvePaidKeeperTarget` for this exact deployment, payment, operation and
29
+ * transport policy. It is reused only while it is as recent as a shared read.
30
+ * @param options Approved deployment, original operation and creator-certified local signer.
31
+ * @param target Freshly resolved target for the same payment.
32
+ */
33
+ export function createKeeperExecutionApproverWithTarget(options, target) {
34
+ if (target.receipt.requestId.toLowerCase() !== prepaidRequestId(options.payment).toLowerCase())
35
+ throw new Error('Keeper target belongs to another payment');
36
+ return approverWithTarget(options, target);
37
+ }
38
+ function approverWithTarget(options, seed) {
39
+ assertPaymentIntentWire(options.payment);
40
+ const payment = structuredClone(options.payment), certificate = structuredClone(options.certificate), deployment = { ...options.deployment };
41
+ const expected = { ...options.expected }, client = options.client, signer = options.signer, transportPolicy = { ...options.transportPolicy };
42
+ const route = options.keeperUrl ?? ((url) => url);
43
+ // Fixed by the retained payment: derive once per operation, not once per keeper.
44
+ const paymentHash = paymentIntentHash(payment);
45
+ let creatorOf;
46
+ const creatorAddress = () => creatorOf ??= recoverTypedDataAddress({ ...paymentIntentTypedData(payment), signature: payment.signature });
47
+ // One shared canonical read per operation instead of one per keeper. A read made by an earlier
48
+ // approval is reused only while recent and the payment unexpired; otherwise read again. A failed
49
+ // read is never reused. Every approval still applies the unchanged 30 s signing-clock check.
50
+ let shared = seed && Promise.resolve(structuredClone(seed));
51
+ const reusable = (target) => {
52
+ const now = Math.floor(Date.now() / 1000), block = Number(target.receipt.blockTimestamp);
53
+ return now - block <= SHARED_TARGET_MAX_AGE_SECS && block - now <= 2 && payment.expires > now;
54
+ };
55
+ const resolveTarget = async () => {
56
+ const earlier = shared;
57
+ if (earlier) {
58
+ const target = await earlier;
59
+ if (reusable(target))
60
+ return target;
61
+ if (shared === earlier)
62
+ shared = undefined;
63
+ else if (shared)
64
+ return shared;
65
+ }
66
+ const fresh = resolvePaidKeeperTarget(client, deployment, payment, expected, transportPolicy);
67
+ shared = fresh;
68
+ fresh.catch(() => { if (shared === fresh)
69
+ shared = undefined; });
70
+ return fresh;
71
+ };
72
+ return async (request) => {
73
+ const { kind, signal } = request;
74
+ signal?.throwIfAborted();
75
+ requireKeeperExecutionPayload(request);
76
+ if (paymentIntentHash(request.payment) !== paymentHash)
77
+ throw new Error('Keeper approval request changed the locally retained payment');
78
+ const body = structuredClone(request.body), nodeUrl = new URL(request.nodeUrl).toString().replace(/\/$/, '');
79
+ const target = await resolveTarget();
80
+ signal?.throwIfAborted();
81
+ // The EOA-digest route signs for BOTH threshold-ECDSA curves: tecdsa (secp256k1, mode 2) and
82
+ // tecdsa-p256 (mode 4). Every other route serves exactly one slot mode.
83
+ const modes = kind === 'committee-eoa-digest' ? [2, 4] : kind === 'committee-decrypt' || kind === 'sealed-decrypt' || kind === 'session-decrypt' || kind === 'ibe-extract' ? [1] : [0];
84
+ if (!modes.includes(target.mode))
85
+ throw new Error('Keeper request route does not match the canonical slot mode');
86
+ const coordinatorUrl = endpoint(target, deployment.chainId, transportPolicy, route);
87
+ const contributors = target.contributors.map(member => ({ ...member, approvedUrl: endpoint(member, deployment.chainId, transportPolicy, route) }));
88
+ if (new Set(contributors.map(m => m.approvedUrl)).size !== contributors.length)
89
+ throw new Error('Client-approved routing aliases multiple keeper identities');
90
+ const member = contributors.find(m => m.approvedUrl === nodeUrl);
91
+ const stages = kind === 'ibe-extract' || kind === 'sealed-decrypt' || kind === 'session-decrypt'
92
+ ? member ? [{ stage: 'contributor', operatorKey: member.publicKey }] : []
93
+ : nodeUrl === coordinatorUrl ? [{ stage: 'coordinator', operatorKey: target.publicKey },
94
+ ...contributors.map(m => ({ stage: 'contributor', operatorKey: m.publicKey }))] : [];
95
+ if (stages.length === 0)
96
+ throw new Error('Keeper approval request targets a different assigned endpoint');
97
+ const creator = await creatorAddress();
98
+ const nowSecs = Math.floor(Date.now() / 1000);
99
+ requireFreshSigningClock(target.receipt.blockTimestamp);
100
+ const policy = { chainId: deployment.chainId, settlement: deployment.settlement, keyRegistry: deployment.keyRegistry,
101
+ creator, paymentHash, cost: target.receipt.cost, nowSecs };
102
+ const authorizations = [];
103
+ for (const stage of stages) {
104
+ signal?.throwIfAborted();
105
+ policy.nowSecs = requireFreshSigningClock(target.receipt.blockTimestamp);
106
+ const expires = Math.min(certificate.expires, payment.expires);
107
+ authorizations.push(await approveExecutionRequest({ payment, certificate, signer, policy,
108
+ expected: { ...stage, body }, proposal: { stage: stage.stage, operator_key: stage.operatorKey, unsigned_body: body, expires } }));
109
+ }
110
+ signal?.throwIfAborted();
111
+ requireFreshSigningClock(target.receipt.blockTimestamp);
112
+ if (authorizations.some(proof => proof.expires <= Math.floor(Date.now() / 1000)))
113
+ throw new Error('Keeper approval expired while the client was signing');
114
+ return { policy, authorizations };
115
+ };
116
+ }
117
+ function clockInteger(value) {
118
+ if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER))
119
+ throw new Error('Canonical keeper clock exceeds the safe integer range');
120
+ return Number(value);
121
+ }
122
+ function requireFreshSigningClock(timestamp) {
123
+ const now = Math.floor(Date.now() / 1000), block = clockInteger(timestamp);
124
+ if (now - block > 30 || block - now > 2)
125
+ throw new Error('Canonical keeper policy aged before client dispatch');
126
+ return now;
127
+ }