@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,64 @@
1
+ import { type Address, type Hex, type PublicClient } from 'viem';
2
+ import { TasraError } from '../errors.js';
3
+ /** Largest committee the network deals a key to (`KeyRegistry.MAX_N`). */
4
+ export declare const MAX_RESHARE_PARTIES = 50;
5
+ /**
6
+ * Stable refusal categories of the reshare roster check; branch on `code`, never on the message.
7
+ * None is retryable: each needs a different roster or threshold.
8
+ */
9
+ export type ReshareRosterErrorCode = 'keeps-too-few' | 'invalid-roster' | 'no-slot';
10
+ /** A reshare roster refused before any vote was signed. */
11
+ export declare class ReshareRosterError extends TasraError {
12
+ /** Refusal category; never infer it from the message. */
13
+ readonly code: ReshareRosterErrorCode;
14
+ /** Current members the roster keeps; set for `keeps-too-few`. */
15
+ readonly staying?: number;
16
+ /** Current threshold the roster must keep; set for `keeps-too-few`. */
17
+ readonly k?: number;
18
+ constructor(code: ReshareRosterErrorCode, message: string, opts?: {
19
+ staying?: number;
20
+ k?: number;
21
+ });
22
+ }
23
+ /** A threshold-ECDSA reshare proposal: the slot's current committee and the roster to vote for. */
24
+ export interface TecdsaReshareRosterInput {
25
+ /** The slot's current roster (`KeyRegistry.assignedNodes`). */
26
+ current: readonly Address[];
27
+ /** The slot's current threshold `k`. */
28
+ currentK: number;
29
+ /** The proposed roster, in the order the vote will carry it. */
30
+ next: readonly Address[];
31
+ /** The proposed threshold. */
32
+ k: number;
33
+ /** The proposed committee size; must equal the roster length. */
34
+ n: number;
35
+ }
36
+ /** How a valid proposal moves the committee. Addresses are checksummed. */
37
+ export interface TecdsaReshareRosterPlan {
38
+ /** Current members that stay; these are the dealers, at least the current `k` of them. */
39
+ staying: Address[];
40
+ /** New members that receive a share without dealing. */
41
+ joining: Address[];
42
+ /** Current members that leave the committee. */
43
+ leaving: Address[];
44
+ }
45
+ /**
46
+ * Check a threshold-ECDSA reshare proposal against the network's overlap rule before anything is signed: a
47
+ * well-formed roster (`n` distinct addresses, `2 <= k <= n <= 50`, since threshold ECDSA needs at
48
+ * least two signers) that keeps at least the current `k` members. Refuses `invalid-roster` and
49
+ * `keeps-too-few` as a `ReshareRosterError`.
50
+ * @param input Current committee and threshold, and the proposed roster and threshold.
51
+ */
52
+ export declare function checkTecdsaReshareRoster(input: TecdsaReshareRosterInput): TecdsaReshareRosterPlan;
53
+ /**
54
+ * Read the slot and, for a threshold-ECDSA slot, apply {@link checkTecdsaReshareRoster} to the
55
+ * proposal. Returns the plan for a tECDSA slot and `undefined` for any other mode, whose committee
56
+ * the network may replace whole. Refuses `no-slot`, `invalid-roster` and `keeps-too-few`.
57
+ * @param read A `readContract` function, from a viem public client.
58
+ * @param keyRegistry KeyRegistry address of the deployment.
59
+ * @param slotId Slot the reshare targets.
60
+ * @param next The proposed roster.
61
+ * @param k The proposed threshold.
62
+ * @param n The proposed committee size.
63
+ */
64
+ export declare function checkReshareOnChain(read: PublicClient['readContract'], keyRegistry: Address, slotId: Hex, next: readonly Address[], k: number, n: number): Promise<TecdsaReshareRosterPlan | undefined>;
@@ -0,0 +1,85 @@
1
+ // The reshare roster rule for threshold-ECDSA slots (network ADR-0099 D2).
2
+ //
3
+ // A tECDSA key is re-dealt only by members that STAY in the new roster: each dealer sub-shares its
4
+ // own share of the key. So the new roster must keep at least the current `k` members, or no keeper
5
+ // can deal and every one of them refuses the ceremony while the chain moves to a roster its shares
6
+ // do not match. A full-committee swap therefore takes two reshares. Newer KeyRegistry deployments
7
+ // revert `TecdsaReshareKeepsTooFew(staying, k)` at the finalizing vote; older ones accept such a
8
+ // roster, so the SDK refuses it before any vote is signed, whichever registry it talks to. FROST
9
+ // and BLS committees may still be replaced whole.
10
+ import { getAddress, isAddress } from 'viem';
11
+ import { TasraError } from '../errors.js';
12
+ import { keyRegistryAbi } from './abis/keyRegistry.js';
13
+ /** Largest committee the network deals a key to (`KeyRegistry.MAX_N`). */
14
+ export const MAX_RESHARE_PARTIES = 50;
15
+ /** A reshare roster refused before any vote was signed. */
16
+ export class ReshareRosterError extends TasraError {
17
+ /** Refusal category; never infer it from the message. */
18
+ code;
19
+ /** Current members the roster keeps; set for `keeps-too-few`. */
20
+ staying;
21
+ /** Current threshold the roster must keep; set for `keeps-too-few`. */
22
+ k;
23
+ constructor(code, message, opts = {}) {
24
+ super(message);
25
+ this.code = code;
26
+ if (opts.staying !== undefined)
27
+ this.staying = opts.staying;
28
+ if (opts.k !== undefined)
29
+ this.k = opts.k;
30
+ }
31
+ }
32
+ function checksummed(list, what) {
33
+ return list.map(a => {
34
+ if (typeof a !== 'string' || !isAddress(a, { strict: false }))
35
+ throw new ReshareRosterError('invalid-roster', `${what} holds ${JSON.stringify(a)}, which is not an address`);
36
+ return getAddress(a);
37
+ });
38
+ }
39
+ /**
40
+ * Check a threshold-ECDSA reshare proposal against the network's overlap rule before anything is signed: a
41
+ * well-formed roster (`n` distinct addresses, `2 <= k <= n <= 50`, since threshold ECDSA needs at
42
+ * least two signers) that keeps at least the current `k` members. Refuses `invalid-roster` and
43
+ * `keeps-too-few` as a `ReshareRosterError`.
44
+ * @param input Current committee and threshold, and the proposed roster and threshold.
45
+ */
46
+ export function checkTecdsaReshareRoster(input) {
47
+ const { currentK, k, n } = input;
48
+ const current = checksummed(input.current, 'the current roster');
49
+ const next = checksummed(input.next, 'the proposed roster');
50
+ if (!Number.isSafeInteger(k) || !Number.isSafeInteger(n) || k < 2 || k > n || n > MAX_RESHARE_PARTIES || next.length !== n) {
51
+ throw new ReshareRosterError('invalid-roster', `a threshold-ECDSA reshare needs 2 <= k <= n <= ${MAX_RESHARE_PARTIES} and n roster entries; got k=${k}, n=${n} with ${next.length} operators`);
52
+ }
53
+ if (new Set(next).size !== next.length)
54
+ throw new ReshareRosterError('invalid-roster', 'the proposed roster lists an operator more than once');
55
+ if (!Number.isSafeInteger(currentK) || currentK < 1)
56
+ throw new ReshareRosterError('invalid-roster', `the current threshold ${currentK} is not a positive integer`);
57
+ const now = new Set(current), after = new Set(next);
58
+ const staying = next.filter(a => now.has(a));
59
+ if (staying.length < currentK) {
60
+ throw new ReshareRosterError('keeps-too-few', `the proposed roster keeps ${staying.length} of the current members, but a threshold-ECDSA key is re-dealt only by members that stay, so it must keep at least the current k=${currentK}; ` +
61
+ 'replace fewer members now and the rest in a second reshare', { staying: staying.length, k: currentK });
62
+ }
63
+ return { staying, joining: next.filter(a => !now.has(a)), leaving: current.filter(a => !after.has(a)) };
64
+ }
65
+ /**
66
+ * Read the slot and, for a threshold-ECDSA slot, apply {@link checkTecdsaReshareRoster} to the
67
+ * proposal. Returns the plan for a tECDSA slot and `undefined` for any other mode, whose committee
68
+ * the network may replace whole. Refuses `no-slot`, `invalid-roster` and `keeps-too-few`.
69
+ * @param read A `readContract` function, from a viem public client.
70
+ * @param keyRegistry KeyRegistry address of the deployment.
71
+ * @param slotId Slot the reshare targets.
72
+ * @param next The proposed roster.
73
+ * @param k The proposed threshold.
74
+ * @param n The proposed committee size.
75
+ */
76
+ export async function checkReshareOnChain(read, keyRegistry, slotId, next, k, n) {
77
+ const slot = await read({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'getKeySlot', args: [slotId] });
78
+ if (!slot.exists)
79
+ throw new ReshareRosterError('no-slot', `slot ${slotId} does not exist on this KeyRegistry; check the slot id and the network`);
80
+ const mode = Number(slot.mode);
81
+ if (mode !== 2 && mode !== 4)
82
+ return undefined;
83
+ const current = await read({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'assignedNodes', args: [slotId] });
84
+ return checkTecdsaReshareRoster({ current, currentK: Number(slot.threshold.k), next, k, n });
85
+ }
@@ -1,3 +1,11 @@
1
+ import type { Hex } from 'viem';
2
+ /**
3
+ * The revert data viem kept somewhere in the error's `cause` chain. RPC transports differ on where
4
+ * they put it (`EstimateGasExecutionError` to `ExecutionRevertedError` to `RpcRequestError.data` on
5
+ * an Avalanche C-chain node), so walk the chain rather than guess a shape.
6
+ * @param error RPC or viem error whose nested causes may contain revert data.
7
+ */
8
+ export declare function revertData(error: unknown): Hex | undefined;
1
9
  /**
2
10
  * `CommitRevealRequired()`, or `InsufficientFilteredPool(3, 5)`, for an error carrying revert data
3
11
  * this package's ABIs can decode; `undefined` when there is no data, or when it belongs to a
@@ -19,8 +19,9 @@ const ERROR_ITEMS = Object.values(CONTRACT_ABIS)
19
19
  * The revert data viem kept somewhere in the error's `cause` chain. RPC transports differ on where
20
20
  * they put it (`EstimateGasExecutionError` to `ExecutionRevertedError` to `RpcRequestError.data` on
21
21
  * an Avalanche C-chain node), so walk the chain rather than guess a shape.
22
+ * @param error RPC or viem error whose nested causes may contain revert data.
22
23
  */
23
- function revertData(error) {
24
+ export function revertData(error) {
24
25
  const seen = new Set();
25
26
  for (let e = error; e && typeof e === 'object' && !seen.has(e); e = e.cause) {
26
27
  seen.add(e);
@@ -0,0 +1,130 @@
1
+ import { type Address, type Hex, type Log, type PublicClient } from 'viem';
2
+ import { TasraError } from '../errors.js';
3
+ import type { TasraChainClient } from './client.js';
4
+ /** `lastRotatedAt` value the contract writes to lock a slot: 2^64 - 1, never a real timestamp. */
5
+ export declare const ROTATION_LOCK_SENTINEL: bigint;
6
+ /**
7
+ * Selectors and the event topic of the rotation-lock additions to `KeyRegistry`, each the keccak256 of
8
+ * the Solidity signature in its comment. A stale signature is a different selector, so a test pins
9
+ * each value against its signature and against the vendored ABI.
10
+ */
11
+ export declare const ROTATION_LOCK_SELECTORS: {
12
+ /** `lockKeyRotation(bytes32)` */
13
+ readonly lockKeyRotation: "0x1fdf5ba1";
14
+ /** `lastRotatedAt(bytes32)` */
15
+ readonly lastRotatedAt: "0x530a2a9e";
16
+ /** Custom error `RotationLocked()` */
17
+ readonly RotationLocked: "0x47fa0746";
18
+ /** Custom error `TecdsaReshareKeepsTooFew(uint16,uint16)` */
19
+ readonly TecdsaReshareKeepsTooFew: "0xb0b6baae";
20
+ /** Event topic 0 of `KeyRotationLocked(bytes32)` */
21
+ readonly KeyRotationLocked: "0x1fb1f37197926bacece99747def77fb2d50c2841cc13663da1a7a70fee302771";
22
+ };
23
+ /**
24
+ * Stable refusal categories of the rotation lock API; branch on `code`, never on the message.
25
+ * None is retryable: each needs a different slot, key or registry first.
26
+ */
27
+ export type RotationLockErrorCode = 'no-slot' | 'cancelled' | 'unsupported' | 'not-creator' | 'locked' | 'not-confirmed';
28
+ /** A lock or rotation refused before signing, or a lock the chain did not show after it mined. */
29
+ export declare class RotationLockError extends TasraError {
30
+ /** Refusal category; never infer it from the message. */
31
+ readonly code: RotationLockErrorCode;
32
+ /** Slot the refused call targeted. */
33
+ readonly slotId: Hex;
34
+ constructor(code: RotationLockErrorCode, slotId: Hex, message: string, opts?: {
35
+ cause?: unknown;
36
+ });
37
+ }
38
+ /** A slot's rotation lock as the chain records it. */
39
+ export interface RotationLockStatus {
40
+ /** Slot that was read. */
41
+ slotId: Hex;
42
+ /** Slot creator, the only account that may call `lockKeyRotation`. */
43
+ creator: Address;
44
+ /** `KeyRegistry.Mode` ordinal: 0 FROST, 1 BLS, 2 secp256k1 tECDSA, 3 BLS-BN254, 4 P-256 tECDSA. */
45
+ mode: number;
46
+ /** Whether the slot is cancelled; a cancelled slot cannot be locked. */
47
+ cancelled: boolean;
48
+ /** Raw `lastRotatedAt`: 0 never rotated, a block timestamp, or the lock sentinel. */
49
+ lastRotatedAt: bigint;
50
+ /** The creator called `lockKeyRotation` (the sentinel is set). */
51
+ lockedByCreator: boolean;
52
+ /** The slot's mode is threshold ECDSA, which no rotation ever changes. */
53
+ lockedByMode: boolean;
54
+ /** Effective lock: no rotation path can change this slot's key. */
55
+ locked: boolean;
56
+ }
57
+ /**
58
+ * Read a slot's rotation lock. Refuses `no-slot`, and `unsupported` for a KeyRegistry from before
59
+ * the lock (where neither the creator lock nor the tECDSA refusal exists).
60
+ * @param read A `readContract` function, from a viem public client.
61
+ * @param keyRegistry KeyRegistry address of the deployment.
62
+ * @param slotId Slot to read.
63
+ */
64
+ export declare function readRotationLockOnChain(read: PublicClient['readContract'], keyRegistry: Address, slotId: Hex): Promise<RotationLockStatus>;
65
+ /**
66
+ * Read a slot's rotation lock: whether the creator locked it, whether its mode locks it, and the
67
+ * effective lock. Refuses `no-slot` and `unsupported` as a `RotationLockError`.
68
+ * @param chain Reader for the deployment that owns the slot.
69
+ * @param slotId Slot to read.
70
+ */
71
+ export declare function readRotationLock(chain: TasraChainClient, slotId: Hex): Promise<RotationLockStatus>;
72
+ /**
73
+ * Whether no rotation can change the slot's key: the creator locked it, or it is a threshold
74
+ * ECDSA slot (locked by its mode). Refuses `no-slot` and `unsupported` as a `RotationLockError`.
75
+ * @param chain Reader for the deployment that owns the slot.
76
+ * @param slotId Slot to read.
77
+ */
78
+ export declare function isRotationLocked(chain: TasraChainClient, slotId: Hex): Promise<boolean>;
79
+ /**
80
+ * Refuse a rotation of `slotId` before signing when no rotation can change its key. A KeyRegistry
81
+ * from before the lock has no creator lock to read, but a threshold-ECDSA rotation there still
82
+ * clears the key for good, so such a slot is refused by its mode on every registry.
83
+ * @param read A `readContract` function, from a viem public client.
84
+ * @param keyRegistry KeyRegistry address of the deployment.
85
+ * @param slotId Slot the rotation targets.
86
+ * @param what Name of the refused call, for the message.
87
+ */
88
+ export declare function assertRotationAllowed(read: PublicClient['readContract'], keyRegistry: Address, slotId: Hex, what: string): Promise<void>;
89
+ /**
90
+ * The refusal a rotation of a locked slot meets on chain, raised before signing instead.
91
+ * @param s The slot's lock status.
92
+ * @param what Name of the refused call, for the message.
93
+ */
94
+ export declare function lockedRotationError(s: RotationLockStatus, what: string): RotationLockError;
95
+ /** A decoded rotation-lock revert: the rotation lock, or a tECDSA reshare roster that keeps too few members. */
96
+ export type RotationLockRevert = {
97
+ /** `RotationLocked()`: no rotation can change this slot's key. */
98
+ name: 'RotationLocked';
99
+ } | {
100
+ /** `TecdsaReshareKeepsTooFew(staying, k)`: the threshold-ECDSA reshare roster keeps too few current members. */
101
+ name: 'TecdsaReshareKeepsTooFew';
102
+ /** Current members the roster keeps. */
103
+ staying: number;
104
+ /** Current threshold the roster must keep. */
105
+ k: number;
106
+ };
107
+ /**
108
+ * Decode `RotationLocked()` or `TecdsaReshareKeepsTooFew(staying, k)` from an error or raw revert
109
+ * data; `undefined` for anything else. Both are final: the identical call reverts again.
110
+ * @param error A viem or RPC error carrying revert data, or the revert data itself.
111
+ */
112
+ export declare function decodeRotationLockRevert(error: unknown): RotationLockRevert | undefined;
113
+ /** One `KeyRotationLocked` event. */
114
+ export interface KeyRotationLockedEvent {
115
+ /** Slot whose rotation was locked. */
116
+ slotId: Hex;
117
+ /** Contract that emitted the event; compare it with the deployment's KeyRegistry. */
118
+ address: Address;
119
+ /** Block of the event, when the log carries it. */
120
+ blockNumber: bigint | null;
121
+ /** Transaction of the event, when the log carries it. */
122
+ transactionHash: Hex | null;
123
+ }
124
+ /**
125
+ * Decode every `KeyRotationLocked(bytes32 indexed slotId)` among `logs`. Other events are skipped.
126
+ * A tECDSA slot is locked by its mode and may never emit one; use `isRotationLocked` for the state.
127
+ * @param logs Raw logs, from a receipt or `getLogs`.
128
+ * @param keyRegistry When given, logs from any other contract are skipped.
129
+ */
130
+ export declare function decodeKeyRotationLockedLogs(logs: readonly Log[], keyRegistry?: Address): KeyRotationLockedEvent[];
@@ -0,0 +1,168 @@
1
+ // The rotation lock (network ADR-0099). A slot's key can be locked against every rotation, for
2
+ // good: the creator locks it with `KeyRegistry.lockKeyRotation`, and a threshold-ECDSA slot
3
+ // (`tecdsa`, `tecdsa-p256`) is locked by its mode, whether or not anyone called it. A rotation
4
+ // would clear a tECDSA slot's key, and with it the EVM address of record, while no keeper can
5
+ // re-key a tECDSA epoch. Resharing is not affected: it moves the shares and keeps the key.
6
+ //
7
+ // The contract stores the lock as the `lastRotatedAt` sentinel 2^64 - 1, so every reader derives
8
+ // the effective lock the same way the keepers do:
9
+ // lastRotatedAt(slot) == 2^64 - 1, or the slot's mode is tecdsa / tecdsa-p256.
10
+ // This module holds that read, the refusals a writer raises before signing, and the decoders for
11
+ // the lock's error and event, plus the reshare overlap revert.
12
+ import { decodeErrorResult, parseEventLogs } from 'viem';
13
+ import { TasraError } from '../errors.js';
14
+ import { viemErrorChainHas } from '../internal/viemErrors.js';
15
+ import { keyRegistryAbi } from './abis/keyRegistry.js';
16
+ import { requireAddress } from './deployments.js';
17
+ import { revertData } from './revertReason.js';
18
+ /** `lastRotatedAt` value the contract writes to lock a slot: 2^64 - 1, never a real timestamp. */
19
+ export const ROTATION_LOCK_SENTINEL = (1n << 64n) - 1n;
20
+ /**
21
+ * Selectors and the event topic of the rotation-lock additions to `KeyRegistry`, each the keccak256 of
22
+ * the Solidity signature in its comment. A stale signature is a different selector, so a test pins
23
+ * each value against its signature and against the vendored ABI.
24
+ */
25
+ export const ROTATION_LOCK_SELECTORS = {
26
+ /** `lockKeyRotation(bytes32)` */
27
+ lockKeyRotation: '0x1fdf5ba1',
28
+ /** `lastRotatedAt(bytes32)` */
29
+ lastRotatedAt: '0x530a2a9e',
30
+ /** Custom error `RotationLocked()` */
31
+ RotationLocked: '0x47fa0746',
32
+ /** Custom error `TecdsaReshareKeepsTooFew(uint16,uint16)` */
33
+ TecdsaReshareKeepsTooFew: '0xb0b6baae',
34
+ /** Event topic 0 of `KeyRotationLocked(bytes32)` */
35
+ KeyRotationLocked: '0x1fb1f37197926bacece99747def77fb2d50c2841cc13663da1a7a70fee302771',
36
+ };
37
+ /** `KeyRegistry.Mode` ordinals locked by mode: `Tecdsa` (2) and `TecdsaP256` (4). */
38
+ const LOCKED_MODES = [2, 4];
39
+ /** A lock or rotation refused before signing, or a lock the chain did not show after it mined. */
40
+ export class RotationLockError extends TasraError {
41
+ /** Refusal category; never infer it from the message. */
42
+ code;
43
+ /** Slot the refused call targeted. */
44
+ slotId;
45
+ constructor(code, slotId, message, opts = {}) {
46
+ super(message, { cause: opts.cause });
47
+ this.code = code;
48
+ this.slotId = slotId;
49
+ }
50
+ }
51
+ /** True when a read reverted or returned no data, as a missing selector does. */
52
+ function missingFunction(e) {
53
+ // By name: the read comes from the caller's client, whose viem copy may not be this package's.
54
+ return viemErrorChainHas(e, ['ContractFunctionRevertedError', 'ContractFunctionZeroDataError']);
55
+ }
56
+ /**
57
+ * Read a slot's rotation lock. Refuses `no-slot`, and `unsupported` for a KeyRegistry from before
58
+ * the lock (where neither the creator lock nor the tECDSA refusal exists).
59
+ * @param read A `readContract` function, from a viem public client.
60
+ * @param keyRegistry KeyRegistry address of the deployment.
61
+ * @param slotId Slot to read.
62
+ */
63
+ export async function readRotationLockOnChain(read, keyRegistry, slotId) {
64
+ const slot = await read({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'getKeySlot', args: [slotId] });
65
+ if (!slot.exists)
66
+ throw new RotationLockError('no-slot', slotId, `slot ${slotId} does not exist on this KeyRegistry; check the slot id and the network`);
67
+ let last;
68
+ try {
69
+ last = await read({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'lastRotatedAt', args: [slotId] });
70
+ }
71
+ catch (e) {
72
+ // A public mapping getter cannot revert on a registry that has it.
73
+ if (!missingFunction(e))
74
+ throw e;
75
+ throw new RotationLockError('unsupported', slotId, `the KeyRegistry ${keyRegistry} has no rotation lock; it predates the upgrade that adds it`, { cause: e });
76
+ }
77
+ const mode = Number(slot.mode);
78
+ const lockedByCreator = last === ROTATION_LOCK_SENTINEL;
79
+ const lockedByMode = LOCKED_MODES.includes(mode);
80
+ return {
81
+ slotId, creator: slot.creator, mode, cancelled: slot.cancelled, lastRotatedAt: last,
82
+ lockedByCreator, lockedByMode, locked: lockedByCreator || lockedByMode,
83
+ };
84
+ }
85
+ /**
86
+ * Read a slot's rotation lock: whether the creator locked it, whether its mode locks it, and the
87
+ * effective lock. Refuses `no-slot` and `unsupported` as a `RotationLockError`.
88
+ * @param chain Reader for the deployment that owns the slot.
89
+ * @param slotId Slot to read.
90
+ */
91
+ export function readRotationLock(chain, slotId) {
92
+ return readRotationLockOnChain(chain.client.readContract, requireAddress(chain.addresses, 'KeyRegistry'), slotId);
93
+ }
94
+ /**
95
+ * Whether no rotation can change the slot's key: the creator locked it, or it is a threshold
96
+ * ECDSA slot (locked by its mode). Refuses `no-slot` and `unsupported` as a `RotationLockError`.
97
+ * @param chain Reader for the deployment that owns the slot.
98
+ * @param slotId Slot to read.
99
+ */
100
+ export async function isRotationLocked(chain, slotId) {
101
+ return (await readRotationLock(chain, slotId)).locked;
102
+ }
103
+ /**
104
+ * Refuse a rotation of `slotId` before signing when no rotation can change its key. A KeyRegistry
105
+ * from before the lock has no creator lock to read, but a threshold-ECDSA rotation there still
106
+ * clears the key for good, so such a slot is refused by its mode on every registry.
107
+ * @param read A `readContract` function, from a viem public client.
108
+ * @param keyRegistry KeyRegistry address of the deployment.
109
+ * @param slotId Slot the rotation targets.
110
+ * @param what Name of the refused call, for the message.
111
+ */
112
+ export async function assertRotationAllowed(read, keyRegistry, slotId, what) {
113
+ let s;
114
+ try {
115
+ s = await readRotationLockOnChain(read, keyRegistry, slotId);
116
+ }
117
+ catch (e) {
118
+ if (!(e instanceof RotationLockError) || e.code !== 'unsupported')
119
+ throw e;
120
+ const slot = await read({ address: keyRegistry, abi: keyRegistryAbi, functionName: 'getKeySlot', args: [slotId] });
121
+ const mode = Number(slot.mode);
122
+ s = { slotId, creator: slot.creator, mode, cancelled: slot.cancelled, lastRotatedAt: 0n, lockedByCreator: false,
123
+ lockedByMode: LOCKED_MODES.includes(mode), locked: LOCKED_MODES.includes(mode) };
124
+ }
125
+ if (s.locked)
126
+ throw lockedRotationError(s, what);
127
+ }
128
+ /**
129
+ * The refusal a rotation of a locked slot meets on chain, raised before signing instead.
130
+ * @param s The slot's lock status.
131
+ * @param what Name of the refused call, for the message.
132
+ */
133
+ export function lockedRotationError(s, what) {
134
+ const why = s.lockedByCreator ? 'its creator locked rotation' : 'it is a threshold-ECDSA slot, locked by its mode';
135
+ return new RotationLockError('locked', s.slotId, `${what}: slot ${s.slotId} never rotates (${why}); the chain reverts RotationLocked(). Change its keepers with a reshare, or cancel it and create a new slot for a new key`);
136
+ }
137
+ const REVERT_ITEMS = keyRegistryAbi.filter(i => i.type === 'error' && (i.name === 'RotationLocked' || i.name === 'TecdsaReshareKeepsTooFew'));
138
+ /**
139
+ * Decode `RotationLocked()` or `TecdsaReshareKeepsTooFew(staying, k)` from an error or raw revert
140
+ * data; `undefined` for anything else. Both are final: the identical call reverts again.
141
+ * @param error A viem or RPC error carrying revert data, or the revert data itself.
142
+ */
143
+ export function decodeRotationLockRevert(error) {
144
+ const data = typeof error === 'string' ? (/^0x[0-9a-fA-F]{8,}$/.test(error) ? error : undefined) : revertData(error);
145
+ if (!data)
146
+ return undefined;
147
+ try {
148
+ const decoded = decodeErrorResult({ abi: REVERT_ITEMS, data });
149
+ if (decoded.errorName === 'RotationLocked')
150
+ return { name: 'RotationLocked' };
151
+ const [staying, k] = decoded.args;
152
+ return { name: 'TecdsaReshareKeepsTooFew', staying: Number(staying), k: Number(k) };
153
+ }
154
+ catch {
155
+ return undefined;
156
+ }
157
+ }
158
+ /**
159
+ * Decode every `KeyRotationLocked(bytes32 indexed slotId)` among `logs`. Other events are skipped.
160
+ * A tECDSA slot is locked by its mode and may never emit one; use `isRotationLocked` for the state.
161
+ * @param logs Raw logs, from a receipt or `getLogs`.
162
+ * @param keyRegistry When given, logs from any other contract are skipped.
163
+ */
164
+ export function decodeKeyRotationLockedLogs(logs, keyRegistry) {
165
+ return parseEventLogs({ abi: keyRegistryAbi, eventName: 'KeyRotationLocked', logs: [...logs] })
166
+ .filter(l => !keyRegistry || l.address.toLowerCase() === keyRegistry.toLowerCase())
167
+ .map(l => ({ slotId: l.args.slotId, address: l.address, blockNumber: l.blockNumber ?? null, transactionHash: l.transactionHash ?? null }));
168
+ }
@@ -0,0 +1,47 @@
1
+ /** Which protocol surface a guarded transport instance may reach. */
2
+ export type ServiceTransportMode = 'discovery' | 'relay' | 'agent' | 'wallet' | 'status' | 'paid-agent' | 'keeper-recovery';
3
+ /** One request as a transport receives it. */
4
+ export interface ServiceRequestOptions {
5
+ /** Exact request body, when the route takes one. */
6
+ body?: Uint8Array;
7
+ /** Response byte bound. */
8
+ maxBytes: number;
9
+ /** Owner bearer / poll secret, only on owner routes. */
10
+ bearer?: string;
11
+ /** Explicit method for paid-agent and keeper-recovery routes. */
12
+ method?: 'GET' | 'POST';
13
+ /** Original OAuth artifacts, only on the paid OAuth-response POST. */
14
+ oauth?: {
15
+ accessToken: string;
16
+ proof: string;
17
+ };
18
+ }
19
+ /** What the transport sends and which replies it accepts. */
20
+ export interface ServiceRequestShape {
21
+ /** HTTP method to send. */
22
+ method: 'GET' | 'POST';
23
+ /** Request headers other than length/encoding, which each transport sets itself. */
24
+ headers: Record<string, string>;
25
+ /** Accepted response media types. */
26
+ responseTypes: string[];
27
+ /** Whether this is a paid request-object (JAR) read. */
28
+ paidJar: boolean;
29
+ }
30
+ /**
31
+ * Validate a request for a transport mode and return its wire shape. Throws (without sending)
32
+ * on a path, method, body, bearer, OAuth or bound outside the mode's protocol.
33
+ * @param mode Transport surface.
34
+ * @param url Full request URL.
35
+ * @param options Body, bounds and credentials.
36
+ */
37
+ export declare function serviceRequestShape(mode: ServiceTransportMode, url: string, { body, maxBytes, bearer, method, oauth }: ServiceRequestOptions): ServiceRequestShape;
38
+ /**
39
+ * Whether a reply's status and media type are acceptable for the request. Encoding and size
40
+ * are checked by the transport while reading.
41
+ * @param mode Transport surface.
42
+ * @param shape Shape returned for the request.
43
+ * @param hasBody Whether the request carried a body.
44
+ * @param status HTTP status received.
45
+ * @param contentType Received media type, without parameters, lowercased.
46
+ */
47
+ export declare function acceptsServiceResponse(mode: ServiceTransportMode, shape: ServiceRequestShape, hasBody: boolean, status: number, contentType: string, exchange?: boolean): boolean;
@@ -0,0 +1,86 @@
1
+ // The request and response shape every guarded service transport enforces, shared by the
2
+ // Node (socket-checked) and browser (fetch) transports so the two cannot drift apart.
3
+ // This module decides only what may be sent and accepted; destination and TLS policy stay
4
+ // with each transport.
5
+ import { SERVICE_MANIFEST_PATH, SERVICE_IDENTITY_PATH, validateServiceEndpoint } from './serviceIdentity.js';
6
+ /**
7
+ * Validate a request for a transport mode and return its wire shape. Throws (without sending)
8
+ * on a path, method, body, bearer, OAuth or bound outside the mode's protocol.
9
+ * @param mode Transport surface.
10
+ * @param url Full request URL.
11
+ * @param options Body, bounds and credentials.
12
+ */
13
+ export function serviceRequestShape(mode, url, { body, maxBytes, bearer, method, oauth }) {
14
+ const relay = mode === 'relay', agent = mode === 'agent', wallet = mode === 'wallet', status = mode === 'status';
15
+ const paid = mode === 'paid-agent', recovery = mode === 'keeper-recovery';
16
+ const voucherIntent = relay && /\/v1\/relay\/voucher-intent$/.test(url);
17
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > (recovery ? 16 * 1024 * 1024 : paid ? 10 * 1024 * 1024 : agent || wallet ? 1_048_576 : relay ? voucherIntent ? 65_536 : 4_096 : 16_384) || body && body.length > (recovery ? 65_536 : paid ? 2 * 1024 * 1024 : wallet ? 1_048_576 : agent || relay ? 65_536 : 2_048))
18
+ throw new Error('Invalid service HTTP bounds');
19
+ const recoverySuffix = url.match(/\/v1\/prepaid\/execution(?:\/recover)?$/)?.[0];
20
+ if (recovery && (!recoverySuffix || method !== 'POST' || !body || bearer !== undefined || oauth !== undefined))
21
+ throw new Error('Invalid keeper recovery path, method or body');
22
+ // Queries: `?wait=1` (a held status poll) on the owner session status read, and `?wait_ms=` (a
23
+ // held proposal listing, `execution-wait`) on the owner execution listing. `execution/approve`
24
+ // (no delivery) is the batch approval route (`execution-approve-batch`).
25
+ const paidSuffix = url.match(/(?:\/v1\/sessions\/(?:refresh|revoke)|\/v1\/request\/[0-9a-f]{64}|\/v1\/sessions(?:\/[0-9a-f]{64}(?:\?wait=1|\/(?:oauth-response|execution(?:\?wait_ms=[1-9][0-9]{0,4}|\/approve|\/[0-9a-f]{64}(?:\/(?:approve|reject))?)?|presentations(?:\/[0-9a-f]{64}\/resume)?))?)?)$/)?.[0];
26
+ const paidCreate = paid && paidSuffix === '/v1/sessions';
27
+ // ADR-0090 D7 session-grant controls: a public POST (no bearer; the session-key signature in the body authorizes it).
28
+ const paidControl = paid && (paidSuffix === '/v1/sessions/refresh' || paidSuffix === '/v1/sessions/revoke');
29
+ const paidJar = paid && paidSuffix?.startsWith('/v1/request/') === true;
30
+ const paidOauth = paid && paidSuffix?.endsWith('/oauth-response') === true;
31
+ const paidWrite = paidCreate || paidControl || paidOauth || /\/(?:approve|reject|resume)$/.test(paidSuffix ?? '');
32
+ if (oauth !== undefined && (!paidOauth || typeof oauth.accessToken !== 'string' || typeof oauth.proof !== 'string'
33
+ || oauth.accessToken.length > 16 * 1024 || oauth.proof.length > 4 * 1024
34
+ || !/^[\x21-\x7e]+$/.test(oauth.accessToken) || !/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(oauth.proof)))
35
+ throw new Error('Invalid paid agent OAuth artifacts');
36
+ if (paid && (!paidSuffix || method !== (paidWrite ? 'POST' : 'GET')
37
+ || paidOauth && oauth === undefined
38
+ || (paidCreate || paidControl || paidJar ? bearer !== undefined : !/^[0-9a-f]{64}$/.test(bearer ?? ''))
39
+ || (paidCreate || paidControl || paidSuffix.endsWith('/approve') ? body === undefined : body !== undefined)))
40
+ throw new Error('Invalid paid agent path, method, body or owner bearer');
41
+ // The registry's 512-byte limit applies to the base, excluding appended protocol paths.
42
+ const relaySuffix = url.match(/\/v1\/relay\/(forward|voucher-intent|0x[0-9a-f]{64})$/)?.[0];
43
+ if (relay && (!relaySuffix || Boolean(body) !== (relaySuffix.endsWith('/forward') || voucherIntent)))
44
+ throw new Error('Invalid relay path or method');
45
+ const agentSuffix = url.match(/\/v1\/sessions(?:\/[0-9a-f]{64})?$/)?.[0];
46
+ if (agent && (!agentSuffix || (body ? agentSuffix !== '/v1/sessions' || bearer !== undefined : agentSuffix === '/v1/sessions' || !/^[0-9a-f]{64}$/.test(bearer ?? ''))))
47
+ throw new Error('Invalid agent path, method or poll secret');
48
+ if (!agent && !paid && bearer !== undefined)
49
+ throw new Error('Bearer is only allowed for agent polling');
50
+ const walletSuffix = url.match(/(?:\/\.well-known\/did\.json|\/v1\/request\/[0-9a-f]{64}|\/v1\/response\?session=[0-9a-f]{64})$/)?.[0];
51
+ if (wallet && (!walletSuffix || Boolean(body) !== walletSuffix.startsWith('/v1/response?session=')))
52
+ throw new Error('Invalid wallet path or method');
53
+ const statusSuffix = url.match(/(?:\/readyz|\/v1\/relay\/policy)$/)?.[0];
54
+ if (status && (!statusSuffix || body !== undefined))
55
+ throw new Error('Invalid service status path or method');
56
+ const contentType = status && statusSuffix === '/readyz' ? 'text/plain' : (paidJar || wallet && !body && !url.endsWith('/did.json')) ? 'application/oauth-authz-req+jwt' : 'application/json';
57
+ const responseTypes = wallet && walletSuffix === '/.well-known/did.json'
58
+ ? ['application/json', 'application/did+json', 'application/did+ld+json'] : paidJar ? [contentType, 'application/json'] : [contentType];
59
+ const suffix = recovery ? recoverySuffix : paid ? paidSuffix : status ? statusSuffix : wallet ? walletSuffix : agent ? agentSuffix : relay ? relaySuffix : [SERVICE_MANIFEST_PATH, SERVICE_IDENTITY_PATH].find(path => url.endsWith(path));
60
+ validateServiceEndpoint(suffix ? url.slice(0, -suffix.length) : url);
61
+ const headers = { ...(bearer ? oauth ? { authorization: `DPoP ${oauth.accessToken}`, dpop: oauth.proof, 'x-poll-secret': bearer } : { authorization: `Bearer ${bearer}` } : {}),
62
+ accept: responseTypes.join(', '), ...(body ? { 'content-type': wallet ? 'application/x-www-form-urlencoded' : 'application/json' } : {}) };
63
+ return { method: paid || recovery ? method : body ? 'POST' : 'GET', headers, responseTypes, paidJar };
64
+ }
65
+ /**
66
+ * Whether a reply's status and media type are acceptable for the request. Encoding and size
67
+ * are checked by the transport while reading.
68
+ * @param mode Transport surface.
69
+ * @param shape Shape returned for the request.
70
+ * @param hasBody Whether the request carried a body.
71
+ * @param status HTTP status received.
72
+ * @param contentType Received media type, without parameters, lowercased.
73
+ */
74
+ export function acceptsServiceResponse(mode, shape, hasBody, status, contentType, exchange = false) {
75
+ const paid = mode === 'paid-agent', recovery = mode === 'keeper-recovery';
76
+ // A paid 429/503 is a definite "not now": the agent's per-client limiter (tower_governor) answers
77
+ // it as text/plain before any handler runs. Its body is bounded and never interpreted, so its media
78
+ // type does not matter; only the status and the wait headers are read.
79
+ const anyType = paid && (status === 204 || status === 429 || status === 503);
80
+ const permittedStatus = paid || recovery ? [200, 201, 202, 204, 400, 401, 403, 404, 409, 410, 413, 422, 425, 429, 500, 502, 503, 504].includes(status)
81
+ // An agent session-creation exchange also reads a 503, so a retryable not-yet-anchored refusal is visible.
82
+ : mode === 'agent' ? status === (hasBody ? 201 : 200) || (exchange && hasBody && status === 503) : mode === 'relay' ? [200, 202, 422].includes(status)
83
+ : mode === 'wallet' && hasBody ? [200, 202].includes(status) : status === 200;
84
+ const permittedType = anyType || (paid ? contentType === (shape.paidJar && status === 200 ? 'application/oauth-authz-req+jwt' : 'application/json') : shape.responseTypes.includes(contentType));
85
+ return permittedStatus && permittedType;
86
+ }
@@ -1,6 +1,13 @@
1
1
  import { type Address, type Hex, type PublicClient, type ReadContractReturnType } from 'viem';
2
2
  import { serviceRegistryAbi } from './abis/serviceRegistry.js';
3
3
  import { type AddressBook } from './deployments.js';
4
+ /**
5
+ * A service's registration at the chain head: at a live head follower's tip (a block-pinned read,
6
+ * pre-read at every new head once asked for), otherwise at `latest` by RPC as before.
7
+ * @param chain Reader of the deployment.
8
+ * @param serviceId Registered service.
9
+ */
10
+ export declare function currentServiceRecord(chain: ServiceRegistryChainReader, serviceId: Hex): Promise<ReadContractReturnType<typeof serviceRegistryAbi, 'getService'>>;
4
11
  /** Permanent ServiceRegistry ABI ordinals. Registration grants no operator privileges. */
5
12
  export declare const SERVICE_TYPES: {
6
13
  readonly gasRelayer: 0;