@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
@@ -2,6 +2,7 @@ import { type Account, type Address, type Chain, type Hex, type Transport, type
2
2
  import type { TasraChainClient } from './client.js';
3
3
  import { type ServiceDiscoveryTransport } from './serviceIdentity.js';
4
4
  import { type ServiceApproval } from './services.js';
5
+ import { type RelayVoucher, type RelaySponsorshipConfig } from './relayVoucher.js';
5
6
  /**
6
7
  * Guarded discovery and transaction relay transport with bounded response bodies.
7
8
  */
@@ -12,6 +13,21 @@ export interface RelayTransport extends ServiceDiscoveryTransport {
12
13
  maxBytes: number;
13
14
  signal: AbortSignal;
14
15
  }): Promise<Uint8Array>;
16
+ /** Optional: the same guarded request, also reporting status and `Retry-After` for busy refusals. */
17
+ relayExchange?(url: string, options: {
18
+ body?: Uint8Array;
19
+ maxBytes: number;
20
+ signal: AbortSignal;
21
+ }): Promise<RelayHttpResponse>;
22
+ }
23
+ /** Bounded relayer reply with the wait it requested, if any. */
24
+ export interface RelayHttpResponse {
25
+ /** HTTP status: 200/202 accepted or status, 422 a pre-acceptance refusal. */
26
+ status: number;
27
+ /** Bounded JSON body. */
28
+ body: Uint8Array;
29
+ /** Parsed `Retry-After` in ms, when sent. */
30
+ retryAfterMs?: number;
15
31
  }
16
32
  /**
17
33
  * Chain, forwarder, signer and exact calldata identifying a relay operation.
@@ -34,6 +50,8 @@ export interface RelayIntent {
34
50
  * Approved relay providers, pinned forwarder and durable recovery callbacks.
35
51
  */
36
52
  export interface RegisteredRelayConfig {
53
+ /** Holder-bound voucher flow for user-class calls; requires durable persistAttempt. */
54
+ sponsorship?: RelaySponsorshipConfig;
37
55
  /** Application approvals, in preference order. Registry membership alone never selects a service. */
38
56
  approvals: readonly ServiceApproval[];
39
57
  /** Guarded HTTP transport for service authentication and relay submission. */
@@ -44,7 +62,7 @@ export interface RegisteredRelayConfig {
44
62
  label?: string;
45
63
  /** Persist the signed reconciliation handle before its first POST. */
46
64
  persistAttempt?: (attempt: RelayAttempt) => Promise<void>;
47
- /** Load this durable operation's previous attempt before signing, including after a restart. */
65
+ /** Load this durable operation's previous attempt before signing, including after a restart. Unknown execution blocks replacement, including a consumed nonce outside the log window. */
48
66
  resumeAttempt?: (intent: RelayIntent) => Promise<RelayAttempt | undefined>;
49
67
  /** Relay status polling interval in milliseconds; defaults to 1500. */
50
68
  pollMs?: number;
@@ -54,7 +72,17 @@ export interface RegisteredRelayConfig {
54
72
  maxAttempts?: number;
55
73
  /** Status polling budget per provider in milliseconds; defaults to 10000 and cannot exceed 30000. */
56
74
  attemptMs?: number;
75
+ /** Re-sends of the identical signed request to one provider after a busy refusal, 0..5 (default 3). Waits honor `Retry-After`, at most 10 s in total per provider. */
76
+ busyRetries?: number;
57
77
  }
78
+ /**
79
+ * True for a relayer refusal about its own load rather than the request: a full lane, a full
80
+ * journal or an unavailable shared sponsorship budget. The relayer answers these 422 `rejected`
81
+ * with `Retry-After` before journaling anything. "shared daily spend cap reached", quota and
82
+ * policy refusals are not busy.
83
+ * @param reason The `reason` text of a relayer `rejected` status.
84
+ */
85
+ export declare function isRelayBusyReason(reason: unknown): boolean;
58
86
  /**
59
87
  * Verified forwarded transaction result with optional gas and native-token cost.
60
88
  */
@@ -138,6 +166,8 @@ export declare const relayForwarderAbi: readonly [{
138
166
  }];
139
167
  /** JSON-safe reconciliation handle. Persist before POST to resume safely after a client restart. */
140
168
  export interface RelayAttempt {
169
+ /** Wallet voucher persisted before relay submission, bound to this exact signed request. */
170
+ voucher?: RelayVoucher;
141
171
  /** Chain bound into the signed forward request. */
142
172
  chainId: number;
143
173
  /** Pinned forwarder contract expected to execute the request. */
@@ -2,6 +2,52 @@ import { decodeEventLog, encodeFunctionData, hashTypedData, parseAbi } from 'vie
2
2
  import { authenticateApprovedService } from './serviceIdentity.js';
3
3
  import { SERVICE_TYPES } from './services.js';
4
4
  import { revertError } from './revertReason.js';
5
+ import { retryDelayMs } from '../retry.js';
6
+ import { assertRelayVoucher, assertRelayVoucherIntent } from './relayVoucher.js';
7
+ /**
8
+ * True for a relayer refusal about its own load rather than the request: a full lane, a full
9
+ * journal or an unavailable shared sponsorship budget. The relayer answers these 422 `rejected`
10
+ * with `Retry-After` before journaling anything. "shared daily spend cap reached", quota and
11
+ * policy refusals are not busy.
12
+ * @param reason The `reason` text of a relayer `rejected` status.
13
+ */
14
+ export function isRelayBusyReason(reason) {
15
+ return typeof reason === 'string' && reason.length <= 512 && reason.startsWith('relayer busy:');
16
+ }
17
+ /**
18
+ * The reason of a definitive pre-acceptance refusal: a 422 `rejected` reply whose reason is not a
19
+ * busy one (identity budget, policy, voucher). Accepted replies, busy refusals and anything that
20
+ * does not parse are undefined. Certification run 42: an identity-budget refusal was otherwise
21
+ * ignored and the last provider was watched for the whole relay budget.
22
+ */
23
+ function definitiveRefusal(reply) {
24
+ if (reply.status !== 422 || reply.body.length > 4_096)
25
+ return undefined;
26
+ try {
27
+ const status = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(reply.body));
28
+ if (status?.state !== 'rejected' || typeof status.reason !== 'string' || status.reason.length > 512 || isRelayBusyReason(status.reason))
29
+ return undefined;
30
+ return status.reason;
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ }
36
+ /** Busy-refusal parse of a POST reply; anything else (accepted, other refusals, garbage) is undefined. */
37
+ function busyRefusal(reply) {
38
+ if (reply.status !== 422 || reply.body.length > 4_096)
39
+ return undefined;
40
+ try {
41
+ const status = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(reply.body));
42
+ if (status?.state !== 'rejected' || !isRelayBusyReason(status.reason))
43
+ return undefined;
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ const after = reply.retryAfterMs;
49
+ return after !== undefined && Number.isSafeInteger(after) && after >= 0 ? { retryAfterMs: after } : {};
50
+ }
5
51
  /**
6
52
  * Forwarder ABI used to submit requests, read nonces and verify execution events.
7
53
  */
@@ -85,11 +131,9 @@ async function reconcile(chain, attempt, budget) {
85
131
  throw new RelayOutcomeUnknownError(attempt, 'Forwarder nonce moved backwards');
86
132
  if (nonce > BigInt(attempt.request.nonce)) {
87
133
  const start = BigInt(attempt.fromBlock);
88
- // OUT OF RANGE IS TERMINAL, not TRANSIENT. The nonce is already consumed, so this exact
89
- // request can never execute again whatever took it - the forwarder rejects a spent nonce.
90
- // All that is lost is WHICH request consumed it, and no amount of waiting recovers that:
91
- // every new block moves `start` further outside the window. Throwing here made callers
92
- // retry forever and permanently wedged a deployment's entire write path.
134
+ // A spent nonce prevents this exact request executing again, but does not prove whether
135
+ // its inner call already ran. Report the bounded history gap without scanning indefinitely;
136
+ // callers must preserve the original and must not infer permission for a new operation.
93
137
  if (start < 0n || head.number - start > 10000n)
94
138
  return { expired: false, unresolvable: true };
95
139
  for (let from = start; from <= head.number; from += 2000n) {
@@ -138,14 +182,20 @@ export function createRegisteredRelaySubmitter(chain, config, wallet, options =
138
182
  }
139
183
  if (!/^0x[0-9a-fA-F]{40}$/.test(config.forwarder) || /^0x0{40}$/.test(config.forwarder))
140
184
  throw new Error('Invalid pinned relay forwarder');
141
- const cfg = { ...config, approvals: config.approvals.map(a => Object.freeze({ ...a })) };
142
- const timeout = cfg.timeoutMs ?? 120_000, pollMs = cfg.pollMs ?? 1_500, attemptMs = cfg.attemptMs ?? 10_000;
185
+ const cfg = { ...config, sponsorship: config.sponsorship && Object.freeze({ ...config.sponsorship }), approvals: config.approvals.map(a => Object.freeze({ ...a })) };
186
+ if (cfg.sponsorship && (!/^0x[0-9a-fA-F]{64}$/.test(cfg.sponsorship.slotId) || /^0x0{64}$/.test(cfg.sponsorship.slotId) ||
187
+ typeof cfg.sponsorship.authorize !== 'function' || typeof (cfg.persistAttempt ?? options.persistAttempt) !== 'function'))
188
+ throw new Error('Relay sponsorship requires an approved slot, wallet authorization and durable persistence');
189
+ const timeout = cfg.timeoutMs ?? 120_000, pollMs = cfg.pollMs ?? 1_500, attemptMs = cfg.attemptMs ?? 10_000, busyRetries = cfg.busyRetries ?? 3;
143
190
  const attempts = cfg.maxAttempts ?? Math.min(3, cfg.approvals.length);
144
191
  if (!cfg.approvals.length || cfg.approvals.length > 16 || cfg.approvals.some(a => a.serviceType !== SERVICE_TYPES.gasRelayer) ||
145
192
  !Number.isInteger(attempts) || attempts < 1 || attempts > 3 || attempts > cfg.approvals.length ||
146
193
  !Number.isSafeInteger(timeout) || timeout < 1 || timeout > 120_000 || !Number.isSafeInteger(pollMs) || pollMs < 10 ||
147
- !Number.isSafeInteger(attemptMs) || attemptMs < 1 || attemptMs > 30_000)
194
+ !Number.isSafeInteger(attemptMs) || attemptMs < 1 || attemptMs > 30_000 || !Number.isSafeInteger(busyRetries) || busyRetries < 0 || busyRetries > 5)
148
195
  throw new Error('Invalid registered relayer policy');
196
+ const exchange = (url, options) => cfg.transport.relayExchange ? cfg.transport.relayExchange(url, options)
197
+ // A transport without status reporting: a 422 body still names the refusal; assume the relayer's 1 s hint.
198
+ : cfg.transport.relayRequest(url, options).then(bytes => ({ status: 422, body: bytes, retryAfterMs: 1_000 }));
149
199
  let serial = Promise.resolve();
150
200
  let pending;
151
201
  async function submit(to, data, label) {
@@ -171,32 +221,36 @@ export function createRegisteredRelaySubmitter(chain, config, wallet, options =
171
221
  const result = await reconcile(chain, previousAttempt, budget);
172
222
  if (result.receipt)
173
223
  return result.receipt;
174
- // `unresolvable` must not resume and must not block. Its nonce is spent, so replaying
175
- // the stored attempt is guaranteed to be rejected; but blocking on it never clears
176
- // either, because the scan window only recedes. Fall through and sign a FRESH request
177
- // at the current nonce - the caller was told (via the journal) that the old one is
178
- // terminal-with-unknown-outcome and is responsible for not redoing work that landed.
179
- if (result.unresolvable)
180
- pending = undefined;
181
- else if (!result.expired) {
224
+ // Unknown execution never authorizes a replacement, regardless of sponsorship.
225
+ if (result.unresolvable) {
182
226
  pending = previousAttempt;
183
227
  throw new RelayOutcomeUnknownError(previousAttempt);
184
228
  }
229
+ if (!result.expired) {
230
+ if (cfg.sponsorship)
231
+ attempt = Object.freeze({ ...previousAttempt, request: Object.freeze({ ...previousAttempt.request }) });
232
+ else {
233
+ pending = previousAttempt;
234
+ throw new RelayOutcomeUnknownError(previousAttempt);
235
+ }
236
+ }
185
237
  }
186
- const fromBlock = await budget.run(() => chain.client.getBlockNumber({ cacheTime: 0 }));
187
- const nonce = await budget.run(() => chain.client.readContract({ address: cfg.forwarder, abi: relayForwarderAbi, functionName: 'nonces', args: [from] }));
188
- // The inner call is estimated without an ABI, so viem cannot name a custom error; decode it, or a
189
- // deployment that refuses the write (CommitRevealRequired(), say) reads as an unexplained revert.
190
- const estimate = await budget.run(() => chain.client.estimateGas({ account: from, to, data }))
191
- .catch(e => { throw revertError(e, 'relay: the inner call reverts at estimation'); });
192
- const gas = estimate + estimate / 4n + 10000n;
193
- if (nonce > BigInt(Number.MAX_SAFE_INTEGER) || gas > BigInt(Number.MAX_SAFE_INTEGER))
194
- throw new Error('Relay nonce or gas exceeds the exact JSON integer range');
195
- const request = { from, to, value: '0', gas: Number(gas), nonce: Number(nonce), deadline: Math.floor(Date.now() / 1000) + 300, data, signature: '0x', label: label ?? cfg.label ?? '' };
196
- const unsigned = { chainId, forwarder: cfg.forwarder, request };
197
- request.signature = await budget.run(() => wallet.signTypedData({ account: wallet.account, ...typed(unsigned) }));
198
- attempt = Object.freeze({ ...unsigned, request: Object.freeze(request), fromBlock: fromBlock.toString(), id: hashTypedData(typed(unsigned)) });
199
- const body = new TextEncoder().encode(JSON.stringify(request));
238
+ if (!attempt) {
239
+ const fromBlock = await budget.run(() => chain.client.getBlockNumber({ cacheTime: 0 }));
240
+ const nonce = await budget.run(() => chain.client.readContract({ address: cfg.forwarder, abi: relayForwarderAbi, functionName: 'nonces', args: [from] }));
241
+ // The inner call is estimated without an ABI, so viem cannot name a custom error; decode it, or a
242
+ // deployment that refuses the write (CommitRevealRequired(), say) reads as an unexplained revert.
243
+ const estimate = await budget.run(() => chain.client.estimateGas({ account: from, to, data }))
244
+ .catch(e => { throw revertError(e, 'relay: the inner call reverts at estimation'); });
245
+ const gas = estimate + estimate / 4n + 10000n;
246
+ if (nonce > BigInt(Number.MAX_SAFE_INTEGER) || gas > BigInt(Number.MAX_SAFE_INTEGER))
247
+ throw new Error('Relay nonce or gas exceeds the exact JSON integer range');
248
+ const request = { from, to, value: '0', gas: Number(gas), nonce: Number(nonce), deadline: Math.floor(Date.now() / 1000) + 300, data, signature: '0x', label: label ?? cfg.label ?? '' };
249
+ const unsigned = { chainId, forwarder: cfg.forwarder, request };
250
+ request.signature = await budget.run(() => wallet.signTypedData({ account: wallet.account, ...typed(unsigned) }));
251
+ attempt = Object.freeze({ ...unsigned, request: Object.freeze(request), fromBlock: fromBlock.toString(), id: hashTypedData(typed(unsigned)) });
252
+ }
253
+ let body = new TextEncoder().encode(JSON.stringify(attempt.request));
200
254
  if (body.length > 65_536)
201
255
  throw new Error('Relay request too large');
202
256
  // The application can durably store this handle before any endpoint receives it.
@@ -204,7 +258,9 @@ export function createRegisteredRelaySubmitter(chain, config, wallet, options =
204
258
  if (persist)
205
259
  await budget.run(() => persist(attempt));
206
260
  let contacted = false;
207
- for (const approval of cfg.approvals.slice(0, attempts)) {
261
+ let refusal;
262
+ const candidates = cfg.approvals.slice(0, attempts);
263
+ for (const [index, approval] of candidates.entries()) {
208
264
  if (contacted) {
209
265
  const result = await reconcile(chain, attempt, budget);
210
266
  if (result.receipt) {
@@ -229,15 +285,70 @@ export function createRegisteredRelaySubmitter(chain, config, wallet, options =
229
285
  budget.signal.throwIfAborted();
230
286
  continue;
231
287
  }
288
+ if (cfg.sponsorship) {
289
+ if (!attempt.voucher) {
290
+ const intentBody = new TextEncoder().encode(JSON.stringify({ kind: 'forward', ...attempt.request }));
291
+ const bytes = await budget.run(() => cfg.transport.relayRequest(endpoint + '/v1/relay/voucher-intent', { body: intentBody, maxBytes: 65_536, signal: budget.signal }));
292
+ if (bytes.length > 65_536)
293
+ throw new Error('Relay voucher intent too large');
294
+ const intent = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
295
+ assertRelayVoucherIntent(intent, attempt, cfg.sponsorship.slotId);
296
+ const voucher = JSON.parse(JSON.stringify(await budget.run(() => cfg.sponsorship.authorize({ attempt: attempt, intent, signal: budget.signal }))));
297
+ assertRelayVoucher(voucher, attempt, cfg.sponsorship.slotId);
298
+ const freeze = (value) => { for (const child of Object.values(value))
299
+ if (child && typeof child === 'object')
300
+ freeze(child); Object.freeze(value); };
301
+ freeze(voucher);
302
+ attempt = Object.freeze({ ...attempt, voucher });
303
+ }
304
+ assertRelayVoucher(attempt.voucher, attempt, cfg.sponsorship.slotId);
305
+ body = new TextEncoder().encode(JSON.stringify({ ...attempt.request, voucher: attempt.voucher }));
306
+ if (body.length > 65_536)
307
+ throw new Error('Relay request too large');
308
+ // The voucher and original forward signature are retained together before any gas can be spent.
309
+ await budget.run(() => persist(attempt));
310
+ }
232
311
  pending = attempt;
233
312
  contacted = true;
234
- try {
235
- await budget.run(() => cfg.transport.relayRequest(endpoint + '/v1/relay/forward', { body, maxBytes: 4_096, signal: budget.signal }));
236
- }
237
- catch {
238
- budget.signal.throwIfAborted();
313
+ // A busy refusal (full lane/journal, unavailable shared budget) is answered before anything
314
+ // is journaled. Re-send the IDENTICAL signed bytes after the requested wait: the forwarder
315
+ // spends this nonce once, so a repeat can never execute the call twice. Nothing is re-signed.
316
+ let busySends = 0, busyWaited = 0;
317
+ // Returns the reason when this provider refused the request outright; undefined otherwise.
318
+ const post = async () => {
319
+ for (;;) {
320
+ let busy;
321
+ try {
322
+ const reply = await budget.run(() => exchange(endpoint + '/v1/relay/forward', { body, maxBytes: 4_096, signal: budget.signal }));
323
+ const refused = definitiveRefusal(reply);
324
+ if (refused !== undefined)
325
+ return refused;
326
+ busy = busyRefusal(reply);
327
+ }
328
+ catch {
329
+ budget.signal.throwIfAborted();
330
+ }
331
+ if (!busy)
332
+ return undefined;
333
+ const delay = retryDelayMs(busySends, busy.retryAfterMs ?? 1_000, { maxAttempts: busyRetries + 1, maxDelayMs: 10_000, maxTotalWaitMs: 10_000 }, busyWaited);
334
+ if (delay === undefined)
335
+ return undefined;
336
+ busySends++;
337
+ busyWaited += delay;
338
+ await budget.run(() => new Promise(resolve => setTimeout(resolve, delay)));
339
+ }
340
+ };
341
+ const refused = await post();
342
+ // A definitive refusal was answered before anything was journaled: nothing to watch here.
343
+ // Fail over (reconciling first, as for any contacted provider), or stop with its reason.
344
+ if (refused !== undefined) {
345
+ refusal = refused;
346
+ continue;
239
347
  }
240
- const until = Date.now() + attemptMs;
348
+ // attemptMs is the failover window to the NEXT provider. The last provider has no successor, so its
349
+ // accepted request is watched for the rest of the relay budget rather than declared unknown early
350
+ // (a single approved relayer serialising several applications mined the call after 18 s).
351
+ const until = index < candidates.length - 1 ? Date.now() + attemptMs : Number.POSITIVE_INFINITY;
241
352
  do {
242
353
  // A lost POST response still has a deterministic status ID.
243
354
  try {
@@ -254,12 +365,20 @@ export function createRegisteredRelaySubmitter(chain, config, wallet, options =
254
365
  return receipt;
255
366
  }
256
367
  }
257
- if (['failed', 'rejected', 'unknown'].includes(status.state))
368
+ if (status.state === 'rejected' && isRelayBusyReason(status.reason) && busySends < busyRetries) {
369
+ // Same identical bytes; counted against the same per-provider busy budget.
370
+ busySends++;
371
+ await budget.run(() => new Promise(resolve => setTimeout(resolve, Math.min(1_000, Math.max(1, until - Date.now())))));
372
+ await post();
373
+ }
374
+ else if (['failed', 'rejected', 'unknown'].includes(status.state))
258
375
  break;
259
376
  }
260
377
  catch {
261
378
  budget.signal.throwIfAborted();
262
- break;
379
+ // A lost or unreadable status fails over to the next provider; the last one is reconciled on chain.
380
+ if (index < candidates.length - 1)
381
+ break;
263
382
  }
264
383
  const result = await reconcile(chain, attempt, budget);
265
384
  if (result.receipt) {
@@ -270,6 +389,9 @@ export function createRegisteredRelaySubmitter(chain, config, wallet, options =
270
389
  pending = undefined;
271
390
  throw new Error('Forward request expired without execution');
272
391
  }
392
+ // A nonce spent beyond the log window is a final verdict: stop watching, keep the original.
393
+ if (result.unresolvable)
394
+ break;
273
395
  await budget.run(() => new Promise(resolve => setTimeout(resolve, Math.min(pollMs, Math.max(1, until - Date.now())))));
274
396
  } while (Date.now() < until);
275
397
  }
@@ -284,7 +406,7 @@ export function createRegisteredRelaySubmitter(chain, config, wallet, options =
284
406
  pending = undefined;
285
407
  throw new Error('Forward request expired without execution');
286
408
  }
287
- throw new RelayOutcomeUnknownError(attempt);
409
+ throw new RelayOutcomeUnknownError(attempt, refusal === undefined ? undefined : `relayer refused: ${refusal}`);
288
410
  }
289
411
  catch (error) {
290
412
  if (pending)
@@ -302,9 +424,8 @@ export function createRegisteredRelaySubmitter(chain, config, wallet, options =
302
424
  return undefined;
303
425
  const current = pending;
304
426
  const result = await reconcileRelayAttempt(chain, current);
305
- // `unresolvable` frees the signer too: the nonce is spent, so holding the slot blocks
306
- // every future write for an attempt that can never complete.
307
- if (pending === current && (result.receipt || result.expired || result.unresolvable))
427
+ // Only verified execution or a proven unused expired nonce releases the signer.
428
+ if (pending === current && (result.receipt || result.expired))
308
429
  pending = undefined;
309
430
  return result;
310
431
  },
@@ -0,0 +1,64 @@
1
+ import { type Hex } from 'viem';
2
+ import type { PresentationDelegation, PresentationOperation } from '../verifier-agent/index.js';
3
+ import { type CompoundTokenWire, type StatusAttestationWire } from '../committee/token.js';
4
+ import type { RelayAttempt } from './registeredRelay.js';
5
+ /** Sponsor-signed operation returned by an authenticated relayer, before wallet consent. */
6
+ export interface RelayVoucherIntent {
7
+ /** Relay action binding the prepared request digest to the sponsorship slot. */
8
+ operation: PresentationOperation;
9
+ /** Sponsor delegate's EIP-712 operation signature. */
10
+ operation_sig: string;
11
+ /** Slot creator's authorization of that sponsor delegate. */
12
+ delegation: PresentationDelegation;
13
+ /** Original forward request's EIP-712 digest, presented as the session message. */
14
+ message_hex: string;
15
+ /** Independently approved sponsorship slot. */
16
+ sponsorship_slot: string;
17
+ }
18
+ /** Holder-bound authorization for exactly one forwarded request, in relayer wire format. */
19
+ export interface RelayVoucher {
20
+ /** Unpaid committee token; relay sponsorship does not reserve slot credit. */
21
+ compound_token: CompoundTokenWire;
22
+ /** Snapshot membership proofs accompanying the token signatures. */
23
+ verifier_proofs: {
24
+ verifier_index: number;
25
+ operator: string;
26
+ pubkey: string;
27
+ proof: string[];
28
+ }[];
29
+ /** Freshness attestations, when supplied outside the token. */
30
+ status_attestations?: StatusAttestationWire[];
31
+ /** Sealed evidence carried unchanged when supplied by the agent. */
32
+ evidence_ct?: string;
33
+ }
34
+ /** Wallet consent callback and an independently approved sponsorship slot. */
35
+ export interface RelaySponsorshipConfig {
36
+ /** Expected slot, reviewed independently of the relayer's reply. */
37
+ slotId: Hex;
38
+ /**
39
+ * Complete an OID4VP session through an approved verifier-agent using this sponsor intent.
40
+ * Authenticate the agent, its Request Object and creator authorization before presenting
41
+ * credentials. Persist wallet-session recovery under attempt.id; honor signal cancellation.
42
+ * Return the resulting wire voucher, without a new forward signature or payment reservation.
43
+ * The relayer independently verifies committee signatures, membership and revocation status.
44
+ */
45
+ authorize(context: {
46
+ attempt: RelayAttempt;
47
+ intent: RelayVoucherIntent;
48
+ signal: AbortSignal;
49
+ }): Promise<RelayVoucher>;
50
+ }
51
+ /**
52
+ * Validate intent shape and exact request/chain/slot binding; creator authority is verified by the approved agent.
53
+ * @param raw Sponsor intent received from the authenticated approved relayer.
54
+ * @param attempt Original signed forward request, retained before wallet authorization.
55
+ * @param slotId Independently approved sponsorship slot.
56
+ */
57
+ export declare function assertRelayVoucherIntent(raw: unknown, attempt: RelayAttempt, slotId: Hex): asserts raw is RelayVoucherIntent;
58
+ /**
59
+ * Validate voucher shape/binding before submission; signature, standing and status authority remain the relayer's gate.
60
+ * @param raw Wire voucher returned by the application's approved wallet flow.
61
+ * @param attempt Original signed forward request to which the voucher must be bound.
62
+ * @param slotId Independently approved sponsorship slot.
63
+ */
64
+ export declare function assertRelayVoucher(raw: unknown, attempt: RelayAttempt, slotId: Hex): asserts raw is RelayVoucher;
@@ -0,0 +1,69 @@
1
+ import { sha256 } from 'viem';
2
+ import { assertCompoundTokenWire } from '../verifier-agent/index.js';
3
+ import { assertStatusAttestationsWire } from '../committee/token.js';
4
+ import { requestHash } from '../oid4vp/binding.js';
5
+ import { bytesToHex, hexToBytes } from '../crypto/hex.js';
6
+ const hex = (value, size) => typeof value === 'string' && new RegExp(`^(?:0x)?[0-9a-fA-F]{${size * 2}}$`).test(value);
7
+ const same = (a, b) => typeof a === 'string' && a.replace(/^0x/, '').toLowerCase() === b.replace(/^0x/, '').toLowerCase();
8
+ const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
9
+ const integer = (value) => Number.isSafeInteger(value) && Number(value) >= 0;
10
+ /**
11
+ * Validate intent shape and exact request/chain/slot binding; creator authority is verified by the approved agent.
12
+ * @param raw Sponsor intent received from the authenticated approved relayer.
13
+ * @param attempt Original signed forward request, retained before wallet authorization.
14
+ * @param slotId Independently approved sponsorship slot.
15
+ */
16
+ export function assertRelayVoucherIntent(raw, attempt, slotId) {
17
+ if (!hex(slotId, 32) || !hex(attempt.id, 32) || !integer(attempt.chainId) || attempt.chainId === 0)
18
+ throw new Error('Invalid relay voucher domain');
19
+ const now = Math.floor(Date.now() / 1000);
20
+ if (!object(raw) || !object(raw.operation) || !object(raw.delegation))
21
+ throw new Error('Invalid relay voucher intent');
22
+ const o = raw.operation, d = raw.delegation;
23
+ if (o.action !== 'relay' || o.chain_id !== attempt.chainId || !same(o.slot_id, slotId) ||
24
+ !same(raw.sponsorship_slot, slotId) || !same(raw.message_hex, attempt.id) || !same(o.payload_digest, sha256(attempt.id)) ||
25
+ !hex(raw.operation_sig, 65) || typeof o.description !== 'string' || o.description.length > 4096 ||
26
+ !integer(o.exp) || o.exp <= now || o.exp > attempt.request.deadline || o.exp > now + 3600 ||
27
+ d.chain_id !== attempt.chainId || !Array.isArray(d.slot_ids) || d.slot_ids.length > 256 || !d.slot_ids.some(s => same(s, slotId)) ||
28
+ !d.slot_ids.every(s => hex(s, 32)) || !Array.isArray(d.actions) || d.actions.length > 16 || !d.actions.includes('relay') ||
29
+ !d.actions.every(a => typeof a === 'string' && a.length <= 64) || !hex(d.delegate, 20) || !hex(d.signature, 65) ||
30
+ !integer(d.exp) || d.exp < o.exp || d.exp > now + 30 * 24 * 3600 || !integer(d.nonce))
31
+ throw new Error('Relay voucher intent does not bind this request and sponsorship slot');
32
+ }
33
+ /**
34
+ * Validate voucher shape/binding before submission; signature, standing and status authority remain the relayer's gate.
35
+ * @param raw Wire voucher returned by the application's approved wallet flow.
36
+ * @param attempt Original signed forward request to which the voucher must be bound.
37
+ * @param slotId Independently approved sponsorship slot.
38
+ */
39
+ export function assertRelayVoucher(raw, attempt, slotId) {
40
+ if (!hex(slotId, 32) || !hex(attempt.id, 32) || !integer(attempt.chainId) || attempt.chainId === 0)
41
+ throw new Error('Invalid relay voucher domain');
42
+ if (!object(raw))
43
+ throw new Error('Invalid relay voucher');
44
+ if (Object.keys(raw).some(k => !['compound_token', 'verifier_proofs', 'status_attestations', 'evidence_ct'].includes(k)))
45
+ throw new Error('Unexpected relay voucher field');
46
+ const t = assertCompoundTokenWire(raw.compound_token, attempt.id);
47
+ const expected = bytesToHex(requestHash(attempt.chainId, hexToBytes(slotId), 'relay', hexToBytes(sha256(attempt.id))));
48
+ const now = Math.floor(Date.now() / 1000);
49
+ if (!same(t.slot_id, slotId) || !same(t.request_hash, expected) || t.binding !== 'holder_key' ||
50
+ t.token_type !== 'JWT' || t.identity_hash != null || t.payment_hash != null || t.payment != null ||
51
+ !integer(t.iat) || !integer(t.exp) || t.exp <= now || t.iat > now || !integer(t.epoch) || t.epoch === 0 ||
52
+ !Array.isArray(raw.verifier_proofs) || raw.verifier_proofs.length < 1 || raw.verifier_proofs.length > 64)
53
+ throw new Error('Relay voucher does not bind this request and sponsorship slot');
54
+ const indexes = new Set();
55
+ for (const p of raw.verifier_proofs) {
56
+ if (!object(p) || !integer(p.verifier_index) || p.verifier_index > 0xffff_ffff || indexes.has(p.verifier_index) ||
57
+ !hex(p.operator, 20) || !hex(p.pubkey, 32) || !Array.isArray(p.proof) || p.proof.length > 32 || !p.proof.every(s => hex(s, 32)))
58
+ throw new Error('Invalid relay voucher membership proof');
59
+ indexes.add(p.verifier_index);
60
+ }
61
+ for (const s of t.signatures) {
62
+ if (!indexes.has(s.verifier_index) || !hex(s.signature, 64))
63
+ throw new Error('Relay voucher signature lacks a membership proof');
64
+ }
65
+ if (raw.status_attestations !== undefined)
66
+ assertStatusAttestationsWire(raw.status_attestations, indexes.size);
67
+ if (raw.evidence_ct !== undefined && (typeof raw.evidence_ct !== 'string' || raw.evidence_ct.length > 65_536))
68
+ throw new Error('Invalid relay voucher evidence');
69
+ }