@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
@@ -1,7 +1,8 @@
1
1
  import { requireRule } from './ruleInput.js';
2
2
  import { networkNameForChain, resolveNetworkProfile, assertEurcFaucetAllowed } from './networks.js';
3
- import { SlotCommitmentExpiredError } from './commitmentRecovery.js';
4
- import { requestSlotSeed } from './slotSeed.js';
3
+ import { SlotCommitmentExpiredError, SlotRevealNotYetError, SlotSeedUnavailableError } from './commitmentRecovery.js';
4
+ import { DEFAULT_SLOT_SEED_HEDGE_MS, DEFAULT_SLOT_SEED_RETRY_MS, requestSlotSeed } from './slotSeed.js';
5
+ import { resolveAccountantUrls } from './discovery.js';
5
6
  // Client-side ON-CHAIN WRITE path: the client is a sovereign actor with its own
6
7
  // EVM account that signs its own transactions - no relayer/provisioner.
7
8
  //
@@ -15,7 +16,7 @@ import { requestSlotSeed } from './slotSeed.js';
15
16
  //
16
17
  // Lives in the `@t3foundry/tasra-sdk/chain` subpath (viem). Browser + Node (uses
17
18
  // globalThis.crypto for slot/salt randomness; no Node-only APIs).
18
- import { createPublicClient, createWalletClient, defineChain, http, concat, encodeFunctionData, keccak256, parseEventLogs, toHex, } from 'viem';
19
+ import { createPublicClient, createWalletClient, defineChain, http, concat, encodeFunctionData, isAddress, keccak256, parseEventLogs, toHex, } from 'viem';
19
20
  import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
20
21
  import { createTasraChainClient } from './client.js';
21
22
  import { createRegisteredRelaySubmitter } from './registeredRelay.js';
@@ -25,7 +26,10 @@ import { isOauthEnvelope, loadRego } from '../auth/rego.js';
25
26
  import { TasraError } from '../errors.js';
26
27
  import { keyRegistryAbi } from './abis/keyRegistry.js';
27
28
  import { RuleAmendmentError, immutableError, pendingError, readAmendmentOnChain, sameAddress, } from './ruleAmendmentCore.js';
29
+ import { SlotHandoffError, adminAcceptVerdict, adminOfferVerdict, creatorAcceptVerdict, creatorOfferVerdict, readHandoffOnChain, } from './slotHandoff.js';
28
30
  import { nodeRegistryAbi } from './abis/nodeRegistry.js';
31
+ import { RotationLockError, assertRotationAllowed, readRotationLockOnChain } from './rotationLock.js';
32
+ import { checkReshareOnChain } from './reshareRoster.js';
29
33
  /**
30
34
  * Return whether active operators include both tagged keepers and other roles, making an unfiltered draw include non-keepers.
31
35
  * @param active Total active operator count.
@@ -58,6 +62,7 @@ import { mockEurcAbi } from './abis/mockEurc.js';
58
62
  import { treasuryAbi } from './abis/treasury.js';
59
63
  import { tasraVestingVaultAbi } from './abis/tasraVestingVault.js';
60
64
  import { DEFAULT_CHAIN_ID, requireAddress, requireVaultAddress, } from './deployments.js';
65
+ import { pollTransactionReceipt, WRITE_POLL_INTERVAL_MS } from './receipt.js';
61
66
  /** `KeyRegistry.Mode` enum order. */
62
67
  const SLOT_MODES = ['frost', 'bls', 'tecdsa', 'bls-bn254', 'tecdsa-p256'];
63
68
  function modeIndex(mode) {
@@ -67,14 +72,15 @@ function modeIndex(mode) {
67
72
  return i;
68
73
  }
69
74
  /** `KeyRegistry.AuthType` enum order - APPEND-only on-chain, so never reorder. */
70
- const SLOT_AUTH_TYPES = ['unspecified', 'oid4vp', 'oauth'];
71
- function authTypeIndex(auth) {
72
- if (auth === undefined)
73
- return 0;
74
- const i = SLOT_AUTH_TYPES.indexOf(auth);
75
+ const SLOT_AUTH_TYPES = ['unspecified', 'oid4vp', 'oauth', 'governance'];
76
+ function authTypeIndex(auth, mode) {
77
+ const i = SLOT_AUTH_TYPES.indexOf(auth ?? 'unspecified');
75
78
  if (i < 0) {
76
79
  throw new TasraError(`createSlot: unknown authType ${JSON.stringify(auth)} (expected ${SLOT_AUTH_TYPES.join(' | ')})`);
77
80
  }
81
+ if ((auth === 'governance') !== (mode === 'bls-bn254')) {
82
+ throw new TasraError('createSlot: governance authorization is required only for bls-bn254 authority slots');
83
+ }
78
84
  return i;
79
85
  }
80
86
  /**
@@ -117,6 +123,55 @@ async function creationRule(args, what) {
117
123
  return rule;
118
124
  }
119
125
  const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000';
126
+ /**
127
+ * `slotCommits` as a path-recording registry returns it: the four historical words plus
128
+ * `frozenAt` and the reveal path. Kept beside the generated ABI rather than in it, because the
129
+ * generated four-output form is what every other reader decodes - and decodes on BOTH registry
130
+ * generations - while this six-output form fails to decode on an older one, which is exactly the
131
+ * signal [`readCommitPath`] needs.
132
+ */
133
+ const slotCommitsWithPathAbi = [{
134
+ type: 'function', name: 'slotCommits', stateMutability: 'view',
135
+ inputs: [{ name: 'commitment', type: 'bytes32' }],
136
+ outputs: [
137
+ { name: 'targetEpoch', type: 'uint64' }, { name: 'expiryEpoch', type: 'uint64' },
138
+ { name: 'creator', type: 'address' }, { name: 'used', type: 'bool' },
139
+ { name: 'frozenAt', type: 'uint48' }, { name: 'path', type: 'uint8' },
140
+ ],
141
+ }];
142
+ /**
143
+ * The reveal path `commitment` is bound to, or - for one not committed yet - `unbound` on a
144
+ * path-recording registry and `legacy` on an older one.
145
+ *
146
+ * ⚠⚠ ONLY A SHORT DECODE reads as `legacy` (an older registry's four-word `slotCommits`). Any other
147
+ * failure - an RPC hiccup, a missing contract - PROPAGATES. It used to read as `legacy` too, which
148
+ * commits through `commitKeySlot`: on a path-recording registry that is a BEACON-EPOCH commitment,
149
+ * which no accountant will seed and which can only be revealed one to two epochs later.
150
+ */
151
+ async function readCommitPath(pub, keyRegistry, commitment) {
152
+ let r;
153
+ try {
154
+ r = await pub.readContract({ address: keyRegistry, abi: slotCommitsWithPathAbi, functionName: 'slotCommits', args: [commitment] });
155
+ }
156
+ catch (e) {
157
+ if (isShortDecode(e))
158
+ return 'legacy';
159
+ throw e;
160
+ }
161
+ if (!Array.isArray(r) || r.length < 6)
162
+ return 'legacy';
163
+ const path = Number(r[5]);
164
+ return path === 1 ? 'epoch' : path === 2 ? 'seeded' : 'unbound';
165
+ }
166
+ /** A return too short for the six-word ABI: what a pre-reveal-path registry's four words decode as. */
167
+ function isShortDecode(e) {
168
+ for (let c = e, depth = 0; c && depth < 8; c = c.cause, depth++) {
169
+ const name = c.name;
170
+ if (name === 'AbiDecodingDataSizeTooSmallError' || name === 'PositionOutOfBoundsError')
171
+ return true;
172
+ }
173
+ return false;
174
+ }
120
175
  /** Refuse a value that is not 0x-prefixed 32-byte hex, before any chain call. */
121
176
  function requireBytes32(value, field, what) {
122
177
  if (typeof value !== 'string' || !/^0x[0-9a-fA-F]{64}$/.test(value)) {
@@ -188,11 +243,30 @@ export async function amendmentPreflight(rule, state, slotId, what) {
188
243
  * not the `salt` passed to createKeySlot - that is the committee-selection
189
244
  * salt and never touches the rule.
190
245
  */
246
+ // One approve-then-fund at a time per (chain, token, owner, spender) in this process. `approve` SETS
247
+ // the allowance, so two concurrent fundSlot calls from one owner (write clients made per slot share
248
+ // no state) could mine approve, approve, fund, fund: the second fund then finds the allowance the
249
+ // first consumed and reverts. The receipt wait's 1 s grid used to space them by chance.
250
+ const fundingQueues = new Map();
251
+ function oneFundingAtATime(key, work) {
252
+ const previous = fundingQueues.get(key) ?? Promise.resolve();
253
+ const run = previous.then(work, work);
254
+ const tail = run.then(() => undefined, () => undefined);
255
+ fundingQueues.set(key, tail);
256
+ void tail.then(() => { if (fundingQueues.get(key) === tail)
257
+ fundingQueues.delete(key); });
258
+ return run;
259
+ }
260
+ /** How long a write step waits for its receipt: viem's waitForTransactionReceipt default, unchanged. */
261
+ export const WRITE_RECEIPT_TIMEOUT_MS = 180_000;
191
262
  /**
192
263
  * Wait for a receipt and reject reverted transactions. Receipt availability alone does not prove execution succeeded.
264
+ * The receipt of exactly `hash` is asked for 250 ms after the call, then less and less often (at
265
+ * most every 1 s; pollTransactionReceipt), instead of on viem's fixed 1 s grid: one confirmation,
266
+ * the same 180 s deadline (viem's WaitForTransactionReceiptTimeoutError), a reverted one refused.
193
267
  */
194
268
  async function confirmed(pub, hash, what) {
195
- const receipt = await pub.waitForTransactionReceipt({ hash });
269
+ const receipt = await pollTransactionReceipt(pub, hash, { confirmations: 1, timeoutMs: WRITE_RECEIPT_TIMEOUT_MS });
196
270
  if (receipt.status !== 'success') {
197
271
  throw new Error(`${what} REVERTED on chain (tx ${hash}) — the call did not take effect`);
198
272
  }
@@ -268,7 +342,9 @@ export function createTasraWriteClient(cfg) {
268
342
  // Reads and receipt-waiting always go through OUR PublicClient, never the
269
343
  // supplied wallet's transport - an injected provider is rate-limited, may be on
270
344
  // a different node, and can be unavailable while the user's tab is backgrounded.
271
- const pub = createPublicClient({ chain, transport: http(cfg.rpcUrl) });
345
+ // viem receipt waits (none in confirmed(), which polls 250 ms growing) poll every second; the
346
+ // block-number cache keeps viem's 4 s default so nothing else reads the head more often.
347
+ const pub = createPublicClient({ chain, transport: http(cfg.rpcUrl), pollingInterval: WRITE_POLL_INTERVAL_MS, cacheTime: 4_000 });
272
348
  const addr = cfg.addresses;
273
349
  const relay = cfg.relay;
274
350
  let lastRelay;
@@ -437,8 +513,7 @@ export function createTasraWriteClient(cfg) {
437
513
  `but the slot asks for n=${n}, so the filtered draw cannot be seated and the chain ` +
438
514
  `would revert InsufficientFilteredPool(${candidates}, ${n}).\n` +
439
515
  'Refused before sending because the mistake is not recoverable: with commit-reveal the ' +
440
- 'commit is already paid for and the shortfall surfaces only at the REVEAL, a beacon ' +
441
- 'epoch later.\n' +
516
+ 'commit is already paid for and the shortfall surfaces only at the REVEAL.\n' +
442
517
  '⚠ A keeper answering HTTP is not necessarily ACTIVE here: unbonding, retired and ' +
443
518
  'slashed-to-deactivate operators keep serving while the registry excludes them from ' +
444
519
  'every draw. Size n from this count, not from how many endpoints respond.');
@@ -475,9 +550,9 @@ export function createTasraWriteClient(cfg) {
475
550
  // Named `…Hash` only because `ruleCommitment` is the function that derives it;
476
551
  // this is the SALTED value the contract stores as `KeySlot.ruleCommitment`.
477
552
  const ruleCommitmentHash = ruleCommitment(ruleSalt, rule);
478
- const tags = await resolveDrawTags(args.tags, args.n);
479
553
  const mode = modeIndex(args.mode);
480
- const auth = authTypeIndex(args.authType);
554
+ const auth = authTypeIndex(args.authType, args.mode);
555
+ const tags = await resolveDrawTags(args.tags, args.n);
481
556
  // The `…WithPolicy` entry point is used only when there is a policy: a slot with
482
557
  // no amendment authority is created through the original function, so the common
483
558
  // path keeps its long-standing, widely-verified call shape.
@@ -499,16 +574,21 @@ export function createTasraWriteClient(cfg) {
499
574
  }
500
575
  /**
501
576
  * Grinding-resistant slot creation - the production default:
502
- * commit the params, request an accountant seed, then reveal+create. Falls back
503
- * to the beacon-epoch wait when a usable seed is unavailable. Needs a beacon
504
- * (ThresholdRandomBeacon address in the book, or resolved from KeyRegistry.randomBeacon).
505
- * `onEpoch` reports fallback wait progress; `seeded` identifies the completed path.
577
+ * commit the params, obtain an accountant seed for the commitment, then reveal+create in the
578
+ * next transaction. There is NO beacon-epoch wait: without a seed it throws
579
+ * {@link SlotSeedUnavailableError}, which says whether a commitment was sent and how to resume.
580
+ * A beacon-epoch commitment made by an older SDK is reconciled by an explicit resume
581
+ * (`recovery.commitTx`), which checks its target epoch once ({@link SlotRevealNotYetError}).
506
582
  */
507
583
  async function createSlotCommitReveal(args) {
508
- const maxWaitMs = args.maxWaitMs ?? 180_000;
509
584
  args.signal?.throwIfAborted();
510
- if (!Number.isSafeInteger(maxWaitMs) || maxWaitMs < 1 || maxWaitMs > 2_147_483_647)
511
- throw new Error('Invalid commit-reveal wait');
585
+ // ⚠ The beacon-epoch path is gone. An untyped caller still passing `slotSeed: false` asked for
586
+ // the wait explicitly; refusing says so, where ignoring it would silently change the path.
587
+ if (args.slotSeed === false) {
588
+ throw new TasraError('createSlotCommitReveal: the beacon-epoch creation path was removed (it waited one to two beacon epochs); slots are created only with an accountant seed');
589
+ }
590
+ const seedRetryMs = args.slotSeedRetryMs ?? DEFAULT_SLOT_SEED_RETRY_MS;
591
+ const seedHedgeMs = args.slotSeedHedgeMs ?? DEFAULT_SLOT_SEED_HEDGE_MS;
512
592
  if (args.exportable)
513
593
  throw new Error('Commit-reveal does not support raw-export slots');
514
594
  const rule = await creationRule(args, 'createSlotCommitReveal');
@@ -516,11 +596,11 @@ export function createTasraWriteClient(cfg) {
516
596
  const salt = args.salt ?? random32();
517
597
  const ruleSalt = args.ruleSalt ?? random32();
518
598
  const ruleCommitmentHash = ruleCommitment(ruleSalt, rule);
519
- const tags = await resolveDrawTags(args.tags, args.n);
520
599
  const mode = modeIndex(args.mode);
521
600
  // `auth` is not an input to `computeCommitment` - the commitment deliberately
522
601
  // does not cover it, so it is passed at the REVEAL only.
523
- const auth = authTypeIndex(args.authType);
602
+ const auth = authTypeIndex(args.authType, args.mode);
603
+ const tags = await resolveDrawTags(args.tags, args.n);
524
604
  // Application descriptors already pin KeyRegistry. Its configured beacon is
525
605
  // authoritative when the caller has no separate beacon address in its book.
526
606
  const beacon = addr.ThresholdRandomBeacon ?? await pub.readContract({
@@ -529,18 +609,18 @@ export function createTasraWriteClient(cfg) {
529
609
  if (!beacon || beacon === '0x0000000000000000000000000000000000000000')
530
610
  throw new Error('KeyRegistry has no random beacon');
531
611
  // Validated UP FRONT, before the commit is signed. A policy the chain would
532
- // reject must not be discovered at the reveal, minutes and one beacon epoch
533
- // later, when the commit has already been paid for.
612
+ // reject must not be discovered at the reveal, when the commit has already been paid for.
534
613
  const policy = args.rulePolicy ? await policyTuple(args.rulePolicy) : null;
535
- const commitment = (await pub.readContract({
536
- address: requireAddress(addr, 'KeyRegistry'),
614
+ const keyReg = requireAddress(addr, 'KeyRegistry');
615
+ const commitmentFor = (s) => pub.readContract({
616
+ address: keyReg,
537
617
  abi: keyRegistryAbi,
538
618
  functionName: 'computeCommitment',
539
- args: [slotId, ruleCommitmentHash, args.k, args.n, mode, salt, tags, account.address],
540
- }));
541
- const keyReg = requireAddress(addr, 'KeyRegistry');
542
- const beaconEpoch = () => pub.readContract({ address: beacon, abi: thresholdRandomBeaconAbi, functionName: 'epoch' });
543
- const sleep = (ms) => new Promise(r => setTimeout(r, ms));
619
+ args: [slotId, ruleCommitmentHash, args.k, args.n, mode, s, tags, account.address],
620
+ });
621
+ const commitment = await commitmentFor(salt);
622
+ const readCommit = async (c) => (await pub.readContract({ address: keyReg, abi: keyRegistryAbi, functionName: 'slotCommits', args: [c] }));
623
+ const seedChain = () => createTasraChainClient({ rpcUrl: cfg.rpcUrl, addresses: cfg.addresses, chainId: chain.id });
544
624
  const transact = async (step, name, values, seeded) => {
545
625
  args.signal?.throwIfAborted();
546
626
  await args.recovery?.onTransaction({ step, phase: 'submitting', seeded });
@@ -549,138 +629,153 @@ export function createTasraWriteClient(cfg) {
549
629
  await args.recovery?.onTransaction({ step, phase: 'submitted', hash, seeded });
550
630
  return hash;
551
631
  };
552
- const commitTx = args.recovery?.commitTx ?? await transact('commit', 'commitKeySlot', [commitment]);
553
- await confirmed(pub, commitTx, 'commitKeySlot');
554
- await args.recovery?.onTransaction({ step: 'commit', phase: 'confirmed', hash: commitTx });
555
- // Read the ACTUAL target epoch the contract pinned (computing it client-side
556
- // races the ~20s beacon). slotCommits to (targetEpoch, expiryEpoch, creator, used).
557
- const commit = (await pub.readContract({ address: keyReg, abi: keyRegistryAbi, functionName: 'slotCommits', args: [commitment] }));
632
+ // ⚠⚠ WHICH REVEAL THE COMMIT ADMITS IS FIXED AT COMMIT (ADR-0080: one commitment, one draw).
633
+ // Only `commitKeySlotSeeded` admits the accountant-seeded reveal; `commitKeySlot` binds the
634
+ // BEACON-EPOCH one, which this SDK no longer sends: its reveal waits one to two beacon epochs
635
+ // (`COMMIT_GAP = 2`; one to two HOURS at the production cadence) and its seed comes from the
636
+ // same accountant set, so it adds a wait and no liveness.
637
+ // A registry from before reveal paths (four-word `slotCommits`) admits both reveals from
638
+ // `commitKeySlot` and has no `commitKeySlotSeeded`; it keeps that call and is seeded too.
639
+ let accountantUrls = args.accountantUrls;
640
+ let commitPath;
641
+ if (args.recovery?.commitTx) {
642
+ // The saved commit decides; the creation it belongs to is checked against slotCommits below.
643
+ commitPath = await readCommitPath(pub, keyReg, commitment);
644
+ }
645
+ else {
646
+ let discovery;
647
+ const [urls, registry] = await Promise.all([
648
+ accountantUrls ?? resolveAccountantUrls(seedChain()).catch((e) => {
649
+ discovery = `accountant discovery failed: ${e instanceof Error ? e.message : String(e)}`;
650
+ return [];
651
+ }),
652
+ // Probed on this (not yet committed) commitment: a path-recording registry answers six
653
+ // words for it, an older one four.
654
+ readCommitPath(pub, keyReg, commitment),
655
+ ]);
656
+ accountantUrls = urls;
657
+ // No accountant to ask means no seed, and no seed means no reveal: refuse BEFORE paying for
658
+ // a commitment that could not be completed.
659
+ if (!urls.length) {
660
+ const failure = { rounds: 0, answers: [], reason: discovery ?? 'no accountant registered' };
661
+ args.onSeedError?.(failure);
662
+ throw new SlotSeedUnavailableError({ slotId, committed: false, commitment, failure });
663
+ }
664
+ commitPath = registry === 'legacy' ? 'legacy' : 'seeded';
665
+ }
666
+ const seededCommit = commitPath === 'seeded';
667
+ const commitName = seededCommit ? 'commitKeySlotSeeded' : 'commitKeySlot';
668
+ const commitTx = args.recovery?.commitTx ?? await transact('commit', commitName, [commitment], seededCommit);
669
+ await confirmed(pub, commitTx, commitName);
670
+ await args.recovery?.onTransaction({ step: 'commit', phase: 'confirmed', hash: commitTx, seeded: seededCommit });
671
+ // slotCommits -> (targetEpoch, expiryEpoch, creator, used).
672
+ const commit = await readCommit(commitment);
558
673
  const targetEpoch = Number(commit[0]);
674
+ // An older SDK completed a seeded-path commitment it could not seed through a SECOND commitment
675
+ // on the epoch path, with a salt DERIVED from the first. A resumed creation must find it rather
676
+ // than leave it dangling; this SDK never makes one.
677
+ const fallbackSalt = keccak256(concat([toHex('tasra/slot-create/epoch-fallback/v1'), salt]));
678
+ let fallback = null;
679
+ if (seededCommit && args.recovery) {
680
+ const c = await commitmentFor(fallbackSalt);
681
+ const fc = await readCommit(c);
682
+ if (fc[2].toLowerCase() === account.address.toLowerCase())
683
+ fallback = { commitment: c, commit: fc };
684
+ }
559
685
  if (args.recovery) {
560
686
  if (commit[2].toLowerCase() !== account.address.toLowerCase() || commit[0] === 0n)
561
687
  throw new TasraError('Saved creation does not match this creator and commitment');
688
+ const consumed = commit[3] || Boolean(fallback?.commit[3]);
562
689
  if (args.recovery.revealTx) {
563
690
  await confirmed(pub, args.recovery.revealTx, 'revealKeySlot');
564
- const completed = await pub.readContract({ address: keyReg, abi: keyRegistryAbi, functionName: 'slotCommits', args: [commitment] });
565
- if (!completed[3])
691
+ const done = (await readCommit(commitment))[3] || (fallback ? (await readCommit(fallback.commitment))[3] : false);
692
+ if (!done)
566
693
  throw new TasraError('Saved reveal did not consume this commitment');
567
694
  await args.recovery.onTransaction({ step: 'reveal', phase: 'confirmed', hash: args.recovery.revealTx, seeded: args.recovery.seeded });
568
- return { slotId, commitTx, revealTx: args.recovery.revealTx, targetEpoch, ruleSalt, rule, seeded: args.recovery.seeded ?? false };
695
+ return { slotId, commitTx, revealTx: args.recovery.revealTx, targetEpoch: Number((fallback?.commit ?? commit)[0]), ruleSalt, rule, seeded: args.recovery.seeded ?? false };
569
696
  }
570
- if (commit[3])
697
+ if (consumed)
571
698
  throw new TasraError('Commitment already consumed; reconcile the reveal hash before continuing');
572
699
  }
573
- // accountant-seeded creation FAST PATH: ask the accountant set to threshold-sign this commitment, and reveal
574
- // immediately instead of waiting for `targetEpoch`.
575
- //
576
- // Strictly an optimisation, and written so it can only ever cost time. Every way it can go
577
- // wrong - no accountant reachable, a KeyRegistry too old to have `commitSeedDigest`, a set
578
- // whose group key is not the beacon's - lands in the epoch wait below, which is what this
579
- // path did before it existed. The commitment is unchanged either way, so nothing is lost by
580
- // trying.
581
- // The seeded reveal draws a DIFFERENT committee than the epoch path would, because the seed
582
- // is different. That is the mechanism, not a side effect: both seeds post-date the
583
- // commitment, so both are ungrindable, and the creator does not get to pick which it gets.
700
+ // RECOVERY OF AN EXISTING BEACON-EPOCH COMMITMENT (an older SDK's): one check, never a wait.
701
+ // Revealable now -> reveal once. Not yet -> SlotRevealNotYetError naming the epoch. Past its
702
+ // expiry -> SlotCommitmentExpiredError, as before.
703
+ const epochCommit = fallback
704
+ ? { commitment: fallback.commitment, commit: fallback.commit, salt: fallbackSalt }
705
+ : commitPath === 'epoch' ? { commitment, commit, salt } : null;
706
+ if (epochCommit) {
707
+ const target = Number(epochCommit.commit[0]);
708
+ const cur = Number(await pub.readContract({ address: beacon, abi: thresholdRandomBeaconAbi, functionName: 'epoch' }));
709
+ if (BigInt(cur) > epochCommit.commit[1])
710
+ throw new SlotCommitmentExpiredError(chain.id, keyReg, slotId, epochCommit.commitment, account.address, epochCommit.salt);
711
+ if (cur < target)
712
+ throw new SlotRevealNotYetError(slotId, epochCommit.commitment, target, cur, Number(epochCommit.commit[1]));
713
+ // With a policy, the reveal PINS IT in the same transaction: as a follow-up call it is
714
+ // unwinnable from a wallet that prompts, because the DKG starts the instant this lands.
715
+ const revealTx = policy
716
+ ? await transact('reveal', 'revealKeySlotWithPolicy', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, epochCommit.salt, tags, policy], false)
717
+ : await transact('reveal', 'revealKeySlot', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, epochCommit.salt, tags], false);
718
+ await confirmed(pub, revealTx, 'revealKeySlot');
719
+ await args.recovery?.onTransaction({ step: 'reveal', phase: 'confirmed', hash: revealTx, seeded: false });
720
+ return { slotId, commitTx, revealTx, targetEpoch: target, ruleSalt, rule, seeded: false };
721
+ }
722
+ // A RESUMED commitment may have outlived its reveal window (a fresh one was committed a moment
723
+ // ago and cannot have): say so before asking for a seed the reveal could not use.
724
+ if (args.recovery) {
725
+ const cur = await pub.readContract({ address: beacon, abi: thresholdRandomBeaconAbi, functionName: 'epoch' });
726
+ if (BigInt(cur) > commit[1])
727
+ throw new SlotCommitmentExpiredError(chain.id, keyReg, slotId, commitment, account.address, salt);
728
+ }
729
+ // THE CREATION PATH: ask the accountant set to threshold-sign this commitment, and reveal at once.
730
+ // The seed is deterministic (one commitment, one BLS signature, one committee), so asking several
731
+ // accountants concurrently or again later can never yield a different draw.
584
732
  let seed = null;
585
- if (args.slotSeed !== false) {
586
- try {
587
- seed = await requestSlotSeed(createTasraChainClient({ rpcUrl: cfg.rpcUrl, addresses: cfg.addresses, chainId: chain.id }), keyReg, commitment, { urls: args.accountantUrls, timeoutMs: args.slotSeedTimeoutMs });
588
- }
589
- catch {
590
- seed = null;
591
- }
733
+ let failure;
734
+ try {
735
+ seed = await requestSlotSeed(seedChain(), keyReg, commitment, {
736
+ urls: accountantUrls,
737
+ timeoutMs: args.slotSeedTimeoutMs,
738
+ // The commit receipt is in; an accountant whose view is a block behind answers 404, and
739
+ // one already leading another creator's round answers 503. Both clear in well under a
740
+ // second; the window bounds the rest.
741
+ retryForMs: seedRetryMs,
742
+ hedgeMs: seedHedgeMs,
743
+ signal: args.signal,
744
+ onFailure: f => { failure = f; },
745
+ });
592
746
  }
593
- args.onSeed?.(seed);
594
- if (seed) {
595
- try {
596
- const seededTx = policy
597
- ? await transact('reveal', 'revealKeySlotWithSeedAndPolicy', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags, seed.signature, policy], true)
598
- : await transact('reveal', 'revealKeySlotWithSeed', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags, seed.signature], true);
599
- await confirmed(pub, seededTx, 'revealKeySlotWithSeed');
600
- await args.recovery?.onTransaction({ step: 'reveal', phase: 'confirmed', hash: seededTx, seeded: true });
601
- return { slotId, commitTx, revealTx: seededTx, targetEpoch, ruleSalt, rule, seeded: true };
602
- }
603
- catch (e) {
604
- // Under a relay this must rethrow. The relay submitter owns the retries of the one
605
- // request it signed, and falling through would start a second signed request against the
606
- // same forwarder nonce - the defect that wedges every later write by this signer.
607
- // Without a relay, a reverted seeded reveal has spent gas and left the commitment
608
- // untouched, so the epoch wait below still completes the creation.
609
- if (relay || args.recovery)
610
- throw e;
611
- }
747
+ catch (e) {
748
+ if (args.signal?.aborted)
749
+ throw e;
750
+ failure = { rounds: 0, answers: [], reason: `seed request failed: ${e instanceof Error ? e.message : String(e)}` };
612
751
  }
613
- // Wait for the beacon to reach the target, then reveal - retrying across the
614
- // epoch boundary (EpochNotReached / BeaconSeedUnavailable can transiently fire
615
- // until the seed for the target epoch has landed).
616
- const deadline = Date.now() + maxWaitMs;
617
- let revealTx;
618
- let prevEpoch = -1;
619
- while (!revealTx) {
620
- args.signal?.throwIfAborted();
621
- const cur = Number(await beaconEpoch());
622
- args.onEpoch?.(cur, targetEpoch);
623
- if (!commit[3] && BigInt(cur) > commit[1])
624
- throw new SlotCommitmentExpiredError(chain.id, keyReg, slotId, commitment, account.address, salt);
625
- if (cur < targetEpoch) {
626
- if (Date.now() > deadline)
627
- throw new Error(`beacon did not reach target epoch ${targetEpoch} (at ${cur})`);
628
- // The beacon is anchored to CHAIN time (tick = block.timestamp / interval).
629
- // On a mint-on-demand chain (the local dev chain), block.timestamp only
630
- // advances when a transaction mints a block - so an idle chain freezes the
631
- // beacon and this wait would always hit its deadline. When the epoch has
632
- // not moved since the last poll AND the head is stale, nudge chain time
633
- // with a zero-value self-transfer. On live chains (Fuji, mainnet) blocks
634
- // flow continuously, the head is never stale, and no nudge is ever sent.
635
- if (!relay && cur === prevEpoch) {
636
- try {
637
- const head = await pub.getBlock();
638
- const nowSecs = BigInt(Math.floor(Date.now() / 1000));
639
- if (nowSecs - head.timestamp > 5n && wallet.account) {
640
- const nudge = await wallet.sendTransaction({ to: wallet.account.address, value: 0n });
641
- await confirmed(pub, nudge, 'chain-time nudge');
642
- }
643
- }
644
- catch {
645
- // Best-effort: a failed nudge leaves us exactly where a passive wait would be.
646
- }
647
- }
648
- prevEpoch = cur;
649
- await sleep(3000);
650
- continue;
651
- }
652
- try {
653
- // With a policy, the reveal PINS IT in the same transaction. That is the
654
- // whole point: as a follow-up call it is unwinnable from a wallet that
655
- // prompts, because the DKG starts the instant this transaction lands.
656
- revealTx = policy
657
- ? await transact('reveal', 'revealKeySlotWithPolicy', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags, policy], false)
658
- : await transact('reveal', 'revealKeySlot', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags], false);
659
- await confirmed(pub, revealTx, 'revealKeySlot');
660
- await args.recovery?.onTransaction({ step: 'reveal', phase: 'confirmed', hash: revealTx, seeded: false });
661
- }
662
- catch (e) {
663
- revealTx = undefined;
664
- // The relay submitter owns bounded retries of one signed request. Never start a
665
- // replacement attempt or a direct write from this epoch-wait loop.
666
- if (relay || args.recovery)
667
- throw e;
668
- if (Date.now() > deadline)
669
- throw e;
670
- await sleep(3000);
671
- }
752
+ if (!seed) {
753
+ const f = failure ?? { rounds: 0, answers: [], reason: 'no seed' };
754
+ args.onSeedError?.(f);
755
+ throw new SlotSeedUnavailableError({ slotId, committed: true, commitment, commitTx, expiryEpoch: Number(commit[1]), failure: f });
672
756
  }
673
- return { slotId, commitTx, revealTx, targetEpoch, ruleSalt, rule, seeded: false };
757
+ args.onSeed?.(seed);
758
+ // A failed reveal is RETHROWN, never retried here: a relay submitter owns the retries of the one
759
+ // request it signed, and a direct-wallet revert has left the commitment untouched, so resuming
760
+ // the same creation (recovery.commitTx) asks for the same seed and reveals again.
761
+ const seededTx = policy
762
+ ? await transact('reveal', 'revealKeySlotWithSeedAndPolicy', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags, seed.signature, policy], true)
763
+ : await transact('reveal', 'revealKeySlotWithSeed', [slotId, ruleCommitmentHash, args.k, args.n, mode, auth, salt, tags, seed.signature], true);
764
+ await confirmed(pub, seededTx, 'revealKeySlotWithSeed');
765
+ await args.recovery?.onTransaction({ step: 'reveal', phase: 'confirmed', hash: seededTx, seeded: true });
766
+ return { slotId, commitTx, revealTx: seededTx, targetEpoch, ruleSalt, rule, seeded: true };
674
767
  }
675
768
  /** Prepay a slot's metered usage: approve TSRA then Settlement.fund(slot, amount). */
676
769
  async function fundSlot(slotId, amount) {
677
770
  const token = requireAddress(addr, 'TasraToken');
678
771
  const settlement = requireAddress(addr, 'Settlement');
679
- const approveTx = await wallet.writeContract({ address: token, abi: tasraTokenAbi, functionName: 'approve', args: [settlement, amount] });
680
- await confirmed(pub, approveTx, 'approve');
681
- const fundTx = await sendCall(settlement, settlementAbi, 'fund', [slotId, amount], 'fund');
682
- await confirmed(pub, fundTx, 'fund');
683
- return { approveTx, fundTx, relay: relay ? lastRelay : undefined };
772
+ return oneFundingAtATime(`${chain.id}|${token}|${account.address}|${settlement}`.toLowerCase(), async () => {
773
+ const approveTx = await wallet.writeContract({ address: token, abi: tasraTokenAbi, functionName: 'approve', args: [settlement, amount] });
774
+ await confirmed(pub, approveTx, 'approve');
775
+ const fundTx = await sendCall(settlement, settlementAbi, 'fund', [slotId, amount], 'fund');
776
+ await confirmed(pub, fundTx, 'fund');
777
+ return { approveTx, fundTx, relay: relay ? lastRelay : undefined };
778
+ });
684
779
  }
685
780
  /** Send native ETH (gas) - e.g. a funded key backing a faucet. */
686
781
  async function sendEth(to, wei) {
@@ -715,14 +810,18 @@ export function createTasraWriteClient(cfg) {
715
810
  return h;
716
811
  }
717
812
  // slot lifecycle (KeyRegistry; gated to the slot's creator/owner)
718
- /** Rotate a slot's key - re-DKG under a new epoch. */
813
+ /** Rotate a slot's key - re-DKG under a new epoch. A locked slot is refused before signing. */
719
814
  async function rotateKey(slotId, reason = '') {
815
+ requireBytes32(slotId, 'slotId', 'rotateKey');
816
+ await assertRotationAllowed(pub.readContract, requireAddress(addr, 'KeyRegistry'), slotId, 'rotateKey');
720
817
  const h = await wallet.writeContract({ address: requireAddress(addr, 'KeyRegistry'), abi: keyRegistryAbi, functionName: 'rotateKey', args: [slotId, reason] });
721
818
  await confirmed(pub, h, 'rotateKey');
722
819
  return h;
723
820
  }
724
- /** Reshare a slot to a new operator set / threshold. */
821
+ /** Reshare a slot to a new operator set / threshold; a tECDSA roster is checked before signing. */
725
822
  async function reshareKey(slotId, newOperators, k, n, reason = '') {
823
+ requireBytes32(slotId, 'slotId', 'reshareKey');
824
+ await checkReshareOnChain(pub.readContract, requireAddress(addr, 'KeyRegistry'), slotId, newOperators, k, n);
726
825
  const h = await wallet.writeContract({ address: requireAddress(addr, 'KeyRegistry'), abi: keyRegistryAbi, functionName: 'reshareKey', args: [slotId, newOperators, k, n, reason] });
727
826
  await confirmed(pub, h, 'reshareKey');
728
827
  return h;
@@ -857,6 +956,130 @@ export function createTasraWriteClient(cfg) {
857
956
  await confirmed(pub, h, what);
858
957
  return h;
859
958
  }
959
+ // slot hand-offs (KeyRegistry.proposeCreator / acceptCreator / proposeRuleAdmin / acceptRuleAdmin)
960
+ // Each step judges from one read, refuses before signing, and reads the slot again to confirm.
961
+ /** Send one hand-off step, then return the slot's state read back. */
962
+ async function handoffStep(slotId, what, functionName, args, verdict, alsoRequire) {
963
+ requireBytes32(slotId, 'slotId', what);
964
+ const keyRegistry = requireAddress(addr, 'KeyRegistry');
965
+ const before = await readHandoffOnChain(pub.readContract, keyRegistry, slotId);
966
+ verdict(before);
967
+ await alsoRequire?.();
968
+ const txHash = await sendCall(keyRegistry, keyRegistryAbi, functionName, args, what);
969
+ await confirmed(pub, txHash, what);
970
+ return { txHash, before, after: await readHandoffOnChain(pub.readContract, keyRegistry, slotId) };
971
+ }
972
+ const notConfirmed = (slotId, what, txHash, seen) => new SlotHandoffError('not-confirmed', slotId, `${what}: tx ${txHash} confirmed but slot ${slotId} shows ${seen}`);
973
+ const requireRecipient = (to, what, withdraw) => {
974
+ if (typeof to !== 'string' || !isAddress(to, { strict: false }) || sameAddress(to, ZERO_ADDRESS)) {
975
+ throw new TasraError(`${what}: to must be a non-zero address; withdraw with ${withdraw}`);
976
+ }
977
+ };
978
+ // Keepers recover every creator signature (operation, payment intent, execution certificate) with
979
+ // ecrecover; there is no contract-signature path, so a contract creator could never sign a paid
980
+ // operation of the slot. An EIP-7702 delegated account still signs with its own key.
981
+ const requireAccountRecipient = async (slotId, to, what) => {
982
+ const code = await pub.getCode({ address: to });
983
+ if (code && code !== '0x' && !/^0xef0100[0-9a-f]{40}$/i.test(code)) {
984
+ throw new SlotHandoffError('contract-holder', slotId, `${what}: ${to} is a contract; keepers accept creator signatures from an externally owned account only, ` +
985
+ 'so a contract creator could not sign any paid operation of this slot');
986
+ }
987
+ };
988
+ /** Offer the slot to `to` as its creator; see {@link TasraWriteClient.proposeSlotTransfer}. */
989
+ async function proposeSlotTransfer(slotId, to) {
990
+ const what = 'proposeSlotTransfer';
991
+ requireRecipient(to, what, 'withdrawSlotTransfer');
992
+ const { txHash, before, after } = await handoffStep(slotId, what, 'proposeCreator', [slotId, to], s => creatorOfferVerdict(s, slotId, account.address, to), () => requireAccountRecipient(slotId, to, what));
993
+ if (!after.pendingCreator || !sameAddress(after.pendingCreator, to)) {
994
+ throw notConfirmed(slotId, what, txHash, `pending creator ${after.pendingCreator ?? 'none'}`);
995
+ }
996
+ let prepaidBalance;
997
+ let reservedBalance;
998
+ if (addr.Settlement) {
999
+ const settlement = addr.Settlement;
1000
+ prepaidBalance = await pub.readContract({ address: settlement, abi: settlementAbi, functionName: 'balanceOf', args: [slotId] });
1001
+ // Absent on a Settlement without prepaid reservations.
1002
+ reservedBalance = await pub
1003
+ .readContract({ address: settlement, abi: settlementAbi, functionName: 'reservedBalanceOf', args: [slotId] })
1004
+ .catch(() => undefined);
1005
+ }
1006
+ return {
1007
+ slotId,
1008
+ txHash,
1009
+ to,
1010
+ ruleAdmin: before.ruleAdmin,
1011
+ guardian: before.guardian,
1012
+ callerIsRuleAdmin: !!before.ruleAdmin && sameAddress(before.ruleAdmin, account.address),
1013
+ ...(prepaidBalance !== undefined ? { prepaidBalance } : {}),
1014
+ ...(reservedBalance !== undefined ? { reservedBalance } : {}),
1015
+ relay: lastRelay?.txHash === txHash ? lastRelay : undefined,
1016
+ };
1017
+ }
1018
+ /** Withdraw the pending creator offer; creator only. */
1019
+ async function withdrawSlotTransfer(slotId) {
1020
+ const what = 'withdrawSlotTransfer';
1021
+ const { txHash, after } = await handoffStep(slotId, what, 'proposeCreator', [slotId, ZERO_ADDRESS], s => creatorOfferVerdict(s, slotId, account.address, ZERO_ADDRESS));
1022
+ if (after.pendingCreator)
1023
+ throw notConfirmed(slotId, what, txHash, `pending creator ${after.pendingCreator}`);
1024
+ return txHash;
1025
+ }
1026
+ /** Become the slot's creator; the offered wallet only. */
1027
+ async function acceptSlotTransfer(slotId) {
1028
+ const what = 'acceptSlotTransfer';
1029
+ const { txHash, after } = await handoffStep(slotId, what, 'acceptCreator', [slotId], s => creatorAcceptVerdict(s, slotId, account.address));
1030
+ if (!sameAddress(after.creator, account.address) || after.pendingCreator)
1031
+ throw notConfirmed(slotId, what, txHash, `creator ${after.creator}`);
1032
+ return txHash;
1033
+ }
1034
+ /** Offer the slot's rule admin role to `to`; rule admin only, never to the guardian. */
1035
+ async function proposeRuleAdminTransfer(slotId, to) {
1036
+ const what = 'proposeRuleAdminTransfer';
1037
+ requireRecipient(to, what, 'withdrawRuleAdminTransfer');
1038
+ const { txHash, after } = await handoffStep(slotId, what, 'proposeRuleAdmin', [slotId, to], s => adminOfferVerdict(s, slotId, account.address, to));
1039
+ if (!after.pendingRuleAdmin || !sameAddress(after.pendingRuleAdmin, to)) {
1040
+ throw notConfirmed(slotId, what, txHash, `pending rule admin ${after.pendingRuleAdmin ?? 'none'}`);
1041
+ }
1042
+ return txHash;
1043
+ }
1044
+ /** Withdraw the pending rule admin offer; rule admin only. */
1045
+ async function withdrawRuleAdminTransfer(slotId) {
1046
+ const what = 'withdrawRuleAdminTransfer';
1047
+ const { txHash, after } = await handoffStep(slotId, what, 'proposeRuleAdmin', [slotId, ZERO_ADDRESS], s => adminOfferVerdict(s, slotId, account.address, ZERO_ADDRESS));
1048
+ if (after.pendingRuleAdmin)
1049
+ throw notConfirmed(slotId, what, txHash, `pending rule admin ${after.pendingRuleAdmin}`);
1050
+ return txHash;
1051
+ }
1052
+ /** Become the slot's rule admin; the offered wallet only. */
1053
+ async function acceptRuleAdminTransfer(slotId) {
1054
+ const what = 'acceptRuleAdminTransfer';
1055
+ const { txHash, after } = await handoffStep(slotId, what, 'acceptRuleAdmin', [slotId], s => adminAcceptVerdict(s, slotId, account.address));
1056
+ if (!after.ruleAdmin || !sameAddress(after.ruleAdmin, account.address) || after.pendingRuleAdmin) {
1057
+ throw notConfirmed(slotId, what, txHash, `rule admin ${after.ruleAdmin ?? 'none'}`);
1058
+ }
1059
+ return txHash;
1060
+ }
1061
+ // rotation lock (KeyRegistry.lockKeyRotation, ADR-0099)
1062
+ /** Lock the slot's key against every rotation; creator only, set-once. */
1063
+ async function lockKeyRotation(slotId) {
1064
+ const what = 'lockKeyRotation';
1065
+ requireBytes32(slotId, 'slotId', what);
1066
+ const keyRegistry = requireAddress(addr, 'KeyRegistry');
1067
+ const before = await readRotationLockOnChain(pub.readContract, keyRegistry, slotId);
1068
+ if (before.cancelled)
1069
+ throw new RotationLockError('cancelled', slotId, `${what}: slot ${slotId} is cancelled; a cancelled slot cannot be locked`);
1070
+ if (before.locked)
1071
+ return { phase: 'already-locked', slotId, lockedByCreator: before.lockedByCreator, lockedByMode: before.lockedByMode };
1072
+ if (!sameAddress(before.creator, account.address)) {
1073
+ throw new RotationLockError('not-creator', slotId, `${what}: slot ${slotId} has creator ${before.creator}, but this client signs as ${account.address}`);
1074
+ }
1075
+ const txHash = await sendCall(keyRegistry, keyRegistryAbi, what, [slotId], what);
1076
+ await confirmed(pub, txHash, what);
1077
+ const after = await readRotationLockOnChain(pub.readContract, keyRegistry, slotId);
1078
+ if (!after.lockedByCreator) {
1079
+ throw new RotationLockError('not-confirmed', slotId, `${what}: tx ${txHash} confirmed but slot ${slotId} shows lastRotatedAt ${after.lastRotatedAt}, not the lock`);
1080
+ }
1081
+ return { phase: 'locked', slotId, txHash, relay: lastRelay?.txHash === txHash ? lastRelay : undefined };
1082
+ }
860
1083
  // TASRA tokenomics (BondingCurve / TasraToken)
861
1084
  /** Buy TSRA from the bonding curve. Approve `eurcAmount` of EURC to the
862
1085
  * BondingCurve first; read balances for the fill. */
@@ -924,6 +1147,15 @@ export function createTasraWriteClient(cfg) {
924
1147
  endorseRuleUpdate,
925
1148
  vetoRuleUpdate,
926
1149
  activateRuleUpdate,
1150
+ // slot hand-offs
1151
+ proposeSlotTransfer,
1152
+ withdrawSlotTransfer,
1153
+ acceptSlotTransfer,
1154
+ proposeRuleAdminTransfer,
1155
+ withdrawRuleAdminTransfer,
1156
+ acceptRuleAdminTransfer,
1157
+ // rotation lock
1158
+ lockKeyRotation,
927
1159
  // tokenomics
928
1160
  buyTsra,
929
1161
  approveEurcForCurve,