@t3foundry/tasra-sdk 0.0.0-stage → 0.3.1-next.1

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 (322) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +94 -0
  4. package/README.md +137 -2
  5. package/SECURITY.md +115 -0
  6. package/dist/app/approvals.d.ts +50 -0
  7. package/dist/app/approvals.js +90 -0
  8. package/dist/app/authorization.d.ts +19 -0
  9. package/dist/app/authorization.js +20 -0
  10. package/dist/app/client.d.ts +231 -0
  11. package/dist/app/client.js +272 -0
  12. package/dist/app/creation.d.ts +73 -0
  13. package/dist/app/creation.js +77 -0
  14. package/dist/app/deployment.d.ts +36 -0
  15. package/dist/app/deployment.js +18 -0
  16. package/dist/app/identity.d.ts +211 -0
  17. package/dist/app/identity.js +287 -0
  18. package/dist/app/index.d.ts +22 -0
  19. package/dist/app/index.js +12 -0
  20. package/dist/app/manifest.d.ts +74 -0
  21. package/dist/app/manifest.js +120 -0
  22. package/dist/app/node.d.ts +30 -0
  23. package/dist/app/node.js +159 -0
  24. package/dist/app/ready-slot.d.ts +157 -0
  25. package/dist/app/ready-slot.js +199 -0
  26. package/dist/app/tasra-client.d.ts +125 -0
  27. package/dist/app/tasra-client.js +79 -0
  28. package/dist/app/viem.d.ts +10 -0
  29. package/dist/app/viem.js +32 -0
  30. package/dist/app/wallet.d.ts +126 -0
  31. package/dist/app/wallet.js +137 -0
  32. package/dist/auth/dpop.d.ts +86 -0
  33. package/dist/auth/dpop.js +142 -0
  34. package/dist/auth/holderProof.d.ts +102 -0
  35. package/dist/auth/holderProof.js +161 -0
  36. package/dist/auth/identityScope.d.ts +19 -0
  37. package/dist/auth/identityScope.js +82 -0
  38. package/dist/auth/index.d.ts +11 -0
  39. package/dist/auth/index.js +13 -0
  40. package/dist/auth/oid4vp.d.ts +230 -0
  41. package/dist/auth/oid4vp.js +780 -0
  42. package/dist/auth/rego/wasm/PINS.json +11 -0
  43. package/dist/auth/rego/wasm/keykeeper_rego_wasm.d.ts +76 -0
  44. package/dist/auth/rego/wasm/keykeeper_rego_wasm.js +379 -0
  45. package/dist/auth/rego/wasm/keykeeper_rego_wasm_bg.wasm +0 -0
  46. package/dist/auth/rego.d.ts +192 -0
  47. package/dist/auth/rego.js +492 -0
  48. package/dist/auth/verifier.d.ts +166 -0
  49. package/dist/auth/verifier.js +211 -0
  50. package/dist/chain/abis/accountantSetRegistry.d.ts +441 -0
  51. package/dist/chain/abis/accountantSetRegistry.js +574 -0
  52. package/dist/chain/abis/accountantSlashing.d.ts +2071 -0
  53. package/dist/chain/abis/accountantSlashing.js +2670 -0
  54. package/dist/chain/abis/bondingCurve.d.ts +398 -0
  55. package/dist/chain/abis/bondingCurve.js +521 -0
  56. package/dist/chain/abis/equivocationSlasher.d.ts +292 -0
  57. package/dist/chain/abis/equivocationSlasher.js +379 -0
  58. package/dist/chain/abis/fixedTasraPriceOracle.d.ts +52 -0
  59. package/dist/chain/abis/fixedTasraPriceOracle.js +72 -0
  60. package/dist/chain/abis/index.d.ts +12801 -0
  61. package/dist/chain/abis/index.js +64 -0
  62. package/dist/chain/abis/keeperShareRegistry.d.ts +519 -0
  63. package/dist/chain/abis/keeperShareRegistry.js +675 -0
  64. package/dist/chain/abis/keyRegistry.d.ts +2421 -0
  65. package/dist/chain/abis/keyRegistry.js +3114 -0
  66. package/dist/chain/abis/livenessRegistry.d.ts +402 -0
  67. package/dist/chain/abis/livenessRegistry.js +524 -0
  68. package/dist/chain/abis/mockEurc.d.ts +210 -0
  69. package/dist/chain/abis/mockEurc.js +276 -0
  70. package/dist/chain/abis/nodeRegistry.d.ts +1630 -0
  71. package/dist/chain/abis/nodeRegistry.js +2113 -0
  72. package/dist/chain/abis/platformExecutor.d.ts +328 -0
  73. package/dist/chain/abis/platformExecutor.js +429 -0
  74. package/dist/chain/abis/prevrandaoSaltBeacon.d.ts +16 -0
  75. package/dist/chain/abis/prevrandaoSaltBeacon.js +24 -0
  76. package/dist/chain/abis/serviceRegistry.d.ts +556 -0
  77. package/dist/chain/abis/serviceRegistry.js +719 -0
  78. package/dist/chain/abis/settlement.d.ts +1624 -0
  79. package/dist/chain/abis/settlement.js +2096 -0
  80. package/dist/chain/abis/tasraSwapRouter.d.ts +92 -0
  81. package/dist/chain/abis/tasraSwapRouter.js +122 -0
  82. package/dist/chain/abis/tasraToken.d.ts +455 -0
  83. package/dist/chain/abis/tasraToken.js +599 -0
  84. package/dist/chain/abis/tasraVestingVault.d.ts +165 -0
  85. package/dist/chain/abis/tasraVestingVault.js +215 -0
  86. package/dist/chain/abis/thresholdRandomBeacon.d.ts +378 -0
  87. package/dist/chain/abis/thresholdRandomBeacon.js +494 -0
  88. package/dist/chain/abis/treasury.d.ts +301 -0
  89. package/dist/chain/abis/treasury.js +390 -0
  90. package/dist/chain/abis/verifierSetRegistry.d.ts +445 -0
  91. package/dist/chain/abis/verifierSetRegistry.js +579 -0
  92. package/dist/chain/client.d.ts +212 -0
  93. package/dist/chain/client.js +576 -0
  94. package/dist/chain/commitmentRecovery.d.ts +21 -0
  95. package/dist/chain/commitmentRecovery.js +44 -0
  96. package/dist/chain/committeeClient.d.ts +102 -0
  97. package/dist/chain/committeeClient.js +137 -0
  98. package/dist/chain/deployments.d.ts +56 -0
  99. package/dist/chain/deployments.js +269 -0
  100. package/dist/chain/discovery.d.ts +49 -0
  101. package/dist/chain/discovery.js +107 -0
  102. package/dist/chain/events.d.ts +58 -0
  103. package/dist/chain/events.js +125 -0
  104. package/dist/chain/format.d.ts +25 -0
  105. package/dist/chain/format.js +51 -0
  106. package/dist/chain/index.d.ts +41 -0
  107. package/dist/chain/index.js +56 -0
  108. package/dist/chain/manifest.d.ts +165 -0
  109. package/dist/chain/manifest.js +132 -0
  110. package/dist/chain/network-profiles.json +75 -0
  111. package/dist/chain/networks.d.ts +73 -0
  112. package/dist/chain/networks.js +62 -0
  113. package/dist/chain/node.d.ts +44 -0
  114. package/dist/chain/node.js +176 -0
  115. package/dist/chain/offchain.d.ts +149 -0
  116. package/dist/chain/offchain.js +73 -0
  117. package/dist/chain/provisionRule.d.ts +164 -0
  118. package/dist/chain/provisionRule.js +212 -0
  119. package/dist/chain/registeredAgent.d.ts +64 -0
  120. package/dist/chain/registeredAgent.js +140 -0
  121. package/dist/chain/registeredOperation.d.ts +49 -0
  122. package/dist/chain/registeredOperation.js +136 -0
  123. package/dist/chain/registeredRelay.d.ts +206 -0
  124. package/dist/chain/registeredRelay.js +312 -0
  125. package/dist/chain/revertReason.d.ts +14 -0
  126. package/dist/chain/revertReason.js +62 -0
  127. package/dist/chain/ruleAmendment.d.ts +80 -0
  128. package/dist/chain/ruleAmendment.js +195 -0
  129. package/dist/chain/ruleAmendmentCore.d.ts +129 -0
  130. package/dist/chain/ruleAmendmentCore.js +152 -0
  131. package/dist/chain/ruleInput.d.ts +10 -0
  132. package/dist/chain/ruleInput.js +13 -0
  133. package/dist/chain/serviceIdentity.d.ts +176 -0
  134. package/dist/chain/serviceIdentity.js +237 -0
  135. package/dist/chain/serviceProfiles.d.ts +39 -0
  136. package/dist/chain/serviceProfiles.js +74 -0
  137. package/dist/chain/services.d.ts +141 -0
  138. package/dist/chain/services.js +79 -0
  139. package/dist/chain/slotClient.d.ts +55 -0
  140. package/dist/chain/slotClient.js +62 -0
  141. package/dist/chain/slotSeed.d.ts +31 -0
  142. package/dist/chain/slotSeed.js +98 -0
  143. package/dist/chain/write.d.ts +431 -0
  144. package/dist/chain/write.js +958 -0
  145. package/dist/client/client.d.ts +112 -0
  146. package/dist/client/client.js +111 -0
  147. package/dist/client/index.d.ts +3 -0
  148. package/dist/client/index.js +2 -0
  149. package/dist/client/session.d.ts +67 -0
  150. package/dist/client/session.js +238 -0
  151. package/dist/committee/client.d.ts +284 -0
  152. package/dist/committee/client.js +351 -0
  153. package/dist/committee/dual-sign.d.ts +110 -0
  154. package/dist/committee/dual-sign.js +202 -0
  155. package/dist/committee/ecdsa.d.ts +36 -0
  156. package/dist/committee/ecdsa.js +45 -0
  157. package/dist/committee/extraction.d.ts +82 -0
  158. package/dist/committee/extraction.js +96 -0
  159. package/dist/committee/index.d.ts +19 -0
  160. package/dist/committee/index.js +13 -0
  161. package/dist/committee/oauth.d.ts +51 -0
  162. package/dist/committee/oauth.js +90 -0
  163. package/dist/committee/receipts.d.ts +51 -0
  164. package/dist/committee/receipts.js +59 -0
  165. package/dist/committee/request.d.ts +264 -0
  166. package/dist/committee/request.js +305 -0
  167. package/dist/committee/token.d.ts +274 -0
  168. package/dist/committee/token.js +418 -0
  169. package/dist/crypto/constants.d.ts +10 -0
  170. package/dist/crypto/constants.js +32 -0
  171. package/dist/crypto/detect.d.ts +20 -0
  172. package/dist/crypto/detect.js +44 -0
  173. package/dist/crypto/envelope.d.ts +60 -0
  174. package/dist/crypto/envelope.js +243 -0
  175. package/dist/crypto/frost.d.ts +49 -0
  176. package/dist/crypto/frost.js +152 -0
  177. package/dist/crypto/hex.d.ts +7 -0
  178. package/dist/crypto/hex.js +24 -0
  179. package/dist/crypto/ibe-blob.d.ts +114 -0
  180. package/dist/crypto/ibe-blob.js +208 -0
  181. package/dist/crypto/ibe.d.ts +88 -0
  182. package/dist/crypto/ibe.js +262 -0
  183. package/dist/crypto/index.d.ts +12 -0
  184. package/dist/crypto/index.js +12 -0
  185. package/dist/crypto/kem.d.ts +55 -0
  186. package/dist/crypto/kem.js +241 -0
  187. package/dist/decryption/client.d.ts +64 -0
  188. package/dist/decryption/client.js +82 -0
  189. package/dist/decryption/index.d.ts +2 -0
  190. package/dist/decryption/index.js +2 -0
  191. package/dist/errors.d.ts +124 -0
  192. package/dist/errors.js +167 -0
  193. package/dist/index.d.ts +43 -0
  194. package/dist/index.js +98 -0
  195. package/dist/keys/index.d.ts +1 -0
  196. package/dist/keys/index.js +4 -0
  197. package/dist/keys/node-client.d.ts +27 -0
  198. package/dist/keys/node-client.js +97 -0
  199. package/dist/oid4vp/binding.d.ts +76 -0
  200. package/dist/oid4vp/binding.js +118 -0
  201. package/dist/oid4vp/did-web.d.ts +49 -0
  202. package/dist/oid4vp/did-web.js +57 -0
  203. package/dist/oid4vp/index.d.ts +9 -0
  204. package/dist/oid4vp/index.js +10 -0
  205. package/dist/oid4vp/jose.d.ts +166 -0
  206. package/dist/oid4vp/jose.js +242 -0
  207. package/dist/oid4vp/jwe.d.ts +30 -0
  208. package/dist/oid4vp/jwe.js +93 -0
  209. package/dist/oid4vp/oid4vci.d.ts +84 -0
  210. package/dist/oid4vp/oid4vci.js +85 -0
  211. package/dist/oid4vp/request-object.d.ts +109 -0
  212. package/dist/oid4vp/request-object.js +96 -0
  213. package/dist/oid4vp/sd-jwt.d.ts +177 -0
  214. package/dist/oid4vp/sd-jwt.js +208 -0
  215. package/dist/oid4vp/verifier-agent.d.ts +161 -0
  216. package/dist/oid4vp/verifier-agent.js +132 -0
  217. package/dist/oid4vp/wallet.d.ts +116 -0
  218. package/dist/oid4vp/wallet.js +108 -0
  219. package/dist/recipient/store.d.ts +67 -0
  220. package/dist/recipient/store.js +98 -0
  221. package/dist/signing/ecdsa.d.ts +49 -0
  222. package/dist/signing/ecdsa.js +79 -0
  223. package/dist/signing/frost.d.ts +88 -0
  224. package/dist/signing/frost.js +145 -0
  225. package/dist/signing/index.d.ts +4 -0
  226. package/dist/signing/index.js +3 -0
  227. package/dist/slots/faucet.d.ts +23 -0
  228. package/dist/slots/faucet.js +35 -0
  229. package/dist/slots/index.d.ts +2 -0
  230. package/dist/slots/index.js +4 -0
  231. package/dist/verifier-agent/index.d.ts +241 -0
  232. package/dist/verifier-agent/index.js +411 -0
  233. package/docs/DEVELOPER-EXPERIENCE.md +62 -0
  234. package/docs/README.md +33 -0
  235. package/docs/access-control.md +76 -0
  236. package/docs/ai-development.md +292 -0
  237. package/docs/api.md +338 -0
  238. package/docs/application-api.md +335 -0
  239. package/docs/architecture.md +65 -0
  240. package/docs/basics.md +48 -0
  241. package/docs/capabilities.md +86 -0
  242. package/docs/chain.md +153 -0
  243. package/docs/compatibility.md +36 -0
  244. package/docs/consumer-migrations.md +80 -0
  245. package/docs/create-slot.md +104 -0
  246. package/docs/document-signing.md +243 -0
  247. package/docs/encrypted-notes.md +129 -0
  248. package/docs/encryption.md +100 -0
  249. package/docs/errors.md +76 -0
  250. package/docs/flows.md +289 -0
  251. package/docs/fuji.md +127 -0
  252. package/docs/funding.md +126 -0
  253. package/docs/getting-started.md +94 -0
  254. package/docs/glossary.md +44 -0
  255. package/docs/installation.md +132 -0
  256. package/docs/manage-slot.md +95 -0
  257. package/docs/native-approvals.md +124 -0
  258. package/docs/prerequisites.md +137 -0
  259. package/docs/read-slot.md +41 -0
  260. package/docs/reference/README.md +30 -0
  261. package/docs/reference/app-node.md +102 -0
  262. package/docs/reference/app.md +1737 -0
  263. package/docs/reference/chain-node.md +159 -0
  264. package/docs/reference/chain.md +3609 -0
  265. package/docs/reference/committee.md +2176 -0
  266. package/docs/reference/main.md +4068 -0
  267. package/docs/reference/oid4vp.md +2547 -0
  268. package/docs/reference/verifier-agent.md +498 -0
  269. package/docs/shared-account.md +168 -0
  270. package/docs/signing-and-encryption.md +52 -0
  271. package/docs/signing.md +172 -0
  272. package/examples/committee-slot.ts +16 -0
  273. package/examples/connect-fuji.ts +41 -0
  274. package/examples/connect-network.ts +14 -0
  275. package/examples/credential-approvals.ts +46 -0
  276. package/examples/document-signing/README.md +59 -0
  277. package/examples/document-signing/backend.ts +132 -0
  278. package/examples/document-signing/build.mjs +19 -0
  279. package/examples/document-signing/config.ts +34 -0
  280. package/examples/document-signing/gitignore.template +9 -0
  281. package/examples/document-signing/model.ts +140 -0
  282. package/examples/document-signing/network.ts +58 -0
  283. package/examples/document-signing/package.json +25 -0
  284. package/examples/document-signing/public/index.html +27 -0
  285. package/examples/document-signing/public/sample.pdf +31 -0
  286. package/examples/document-signing/public/styles.css +531 -0
  287. package/examples/document-signing/server.ts +358 -0
  288. package/examples/document-signing/setup.ts +111 -0
  289. package/examples/document-signing/store.ts +105 -0
  290. package/examples/document-signing/tsconfig.json +24 -0
  291. package/examples/document-signing/verify.ts +24 -0
  292. package/examples/document-signing/web/app.ts +312 -0
  293. package/examples/document-signing/web/preview.ts +67 -0
  294. package/examples/document-signing/web/wallet.ts +146 -0
  295. package/examples/document-signing/workflow.test.ts +228 -0
  296. package/examples/document-signing/workflow.ts +241 -0
  297. package/examples/document-signing.ts +96 -0
  298. package/examples/encrypted-notes.ts +86 -0
  299. package/examples/ethers-signer.ts +204 -0
  300. package/examples/fund-slot.ts +73 -0
  301. package/examples/getting-started.ts +25 -0
  302. package/examples/learning-authorize.ts +23 -0
  303. package/examples/learning-cancel-slot.ts +11 -0
  304. package/examples/learning-context.ts +28 -0
  305. package/examples/learning-create-slot.ts +25 -0
  306. package/examples/learning-read-slot.ts +8 -0
  307. package/examples/learning-renew-slot.ts +12 -0
  308. package/examples/learning-sign.ts +8 -0
  309. package/examples/live-config.ts +71 -0
  310. package/examples/minimal.ts +6 -0
  311. package/examples/native-approvals.ts +57 -0
  312. package/examples/network.ts +58 -0
  313. package/examples/offline.ts +16 -0
  314. package/examples/personal-vault.ts +20 -0
  315. package/examples/provision-slot.ts +47 -0
  316. package/examples/shared-account.ts +46 -0
  317. package/examples/slot-address.ts +13 -0
  318. package/examples/slot-creation.ts +9 -0
  319. package/examples/tutorial-negative.ts +26 -0
  320. package/examples/tutorial-support.ts +76 -0
  321. package/examples/viem-account.ts +203 -0
  322. package/package.json +303 -4
@@ -0,0 +1,120 @@
1
+ import { sha256 } from '@noble/hashes/sha256';
2
+ import { bytesToHex } from '@noble/hashes/utils';
3
+ import { addressBookFromManifest, parseNetworkManifest } from '../chain/manifest.js';
4
+ import { NETWORKS } from '../chain/networks.js';
5
+ import { defineDeployment } from './deployment.js';
6
+ function object(value) {
7
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
8
+ }
9
+ function endpoint(value, label) {
10
+ if (typeof value !== 'string')
11
+ throw new Error(`Invalid ${label} URL`);
12
+ const url = new URL(value);
13
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password || url.hash)
14
+ throw new Error(`Invalid ${label} URL`);
15
+ return url.href;
16
+ }
17
+ function routes(input) {
18
+ if (input === undefined)
19
+ return undefined;
20
+ if (!object(input))
21
+ throw new Error('Invalid keeper URL mappings');
22
+ const mappings = new Map();
23
+ for (const [registered, reachable] of Object.entries(input)) {
24
+ const key = endpoint(registered, 'registered keeper');
25
+ endpoint(reachable, 'reachable keeper');
26
+ if (mappings.has(key))
27
+ throw new Error('Ambiguous keeper URL mappings');
28
+ mappings.set(key, reachable);
29
+ }
30
+ return registered => mappings.get(endpoint(registered, 'registered keeper')) ?? registered;
31
+ }
32
+ /**
33
+ * Validate caller-approved configuration without network I/O or readiness claims.
34
+ * @param input Downloaded network manifest or explicitly approved deployment settings.
35
+ * @returns Validated deployment and optional routing without a network request.
36
+ * @param options Explicit RPC and coordinator choices for the manifest.
37
+ */
38
+ export function resolveApplicationManifest(input, options = {}) {
39
+ if (!object(input))
40
+ throw new Error('Invalid application manifest');
41
+ if (Object.hasOwn(input, 'contracts')) {
42
+ // Refuse a hybrid document rather than choosing between conflicting addresses.
43
+ if (Object.hasOwn(input, 'addresses') || Object.hasOwn(input, 'keeperUrls') || Object.hasOwn(input, 'verifierAgentUrl'))
44
+ throw new Error('Ambiguous application manifest schema');
45
+ const manifest = parseNetworkManifest(input);
46
+ const addresses = addressBookFromManifest(manifest);
47
+ if (!options.coordinator)
48
+ throw new Error('Release manifest requires an explicit coordinator option');
49
+ function service(kind) {
50
+ const entries = manifest.services.filter(item => item.kind === kind);
51
+ if (entries.length > 1)
52
+ throw new Error(`Ambiguous ${kind} services in application manifest`);
53
+ return entries[0]?.url;
54
+ }
55
+ const manifestRpc = service('rpc'), verifierAgentUrl = service('verifier-agent');
56
+ const rpcUrl = options.rpcUrl ?? manifestRpc ?? NETWORKS[manifest.network].rpcUrl;
57
+ if (manifest.network !== 'local' && new URL(endpoint(rpcUrl, 'RPC')).protocol !== 'https:')
58
+ throw new Error('Public network RPC URL requires HTTPS');
59
+ const deployment = defineDeployment({ schemaVersion: 1, name: manifest.deploymentId, chainId: manifest.chainId,
60
+ rpcUrl, addresses, coordinator: options.coordinator, provenance: { networkRevision: `${manifest.deploymentId}@${manifest.revision}` } });
61
+ return { deployment, ...(verifierAgentUrl ? { verifierAgentUrl } : {}) };
62
+ }
63
+ if (Object.hasOwn(input, 'network') || Object.hasOwn(input, 'status') || !object(input.addresses))
64
+ throw new Error('Invalid application deployment schema');
65
+ const descriptor = input;
66
+ if (typeof descriptor.name !== 'string' || !descriptor.name.trim())
67
+ throw new Error('Invalid application deployment name');
68
+ if (descriptor.provenance !== undefined && (!object(descriptor.provenance) ||
69
+ typeof descriptor.provenance.networkRevision !== 'string' || !descriptor.provenance.networkRevision ||
70
+ descriptor.provenance.manifestSha256 !== undefined && !/^[a-f0-9]{64}$/.test(descriptor.provenance.manifestSha256)))
71
+ throw new Error('Invalid deployment provenance');
72
+ if (descriptor.verifierAgentUrl !== undefined)
73
+ endpoint(descriptor.verifierAgentUrl, 'verifier agent');
74
+ const keeperUrl = routes(descriptor.keeperUrls);
75
+ const deployment = defineDeployment({ schemaVersion: descriptor.schemaVersion, name: descriptor.name, chainId: descriptor.chainId,
76
+ rpcUrl: options.rpcUrl ?? descriptor.rpcUrl, coordinator: options.coordinator ?? descriptor.coordinator,
77
+ addresses: descriptor.addresses, ...(descriptor.provenance ? { provenance: descriptor.provenance } : {}) });
78
+ return { deployment, ...(descriptor.verifierAgentUrl !== undefined ? { verifierAgentUrl: descriptor.verifierAgentUrl } : {}), ...(keeperUrl ? { keeperUrl } : {}) };
79
+ }
80
+ /**
81
+ * Fetch a public manifest; an optional trusted pin is checked before parsing any JSON.
82
+ * @param source HTTPS manifest URL. HTTP is allowed only for loopback or with an independently trusted digest pin.
83
+ * @returns Parsed deployment after any supplied digest pin has been verified.
84
+ * @param options Trusted digest pin, manifest resolution choices and HTTP controls.
85
+ */
86
+ export async function loadApplicationManifest(source, options = {}) {
87
+ // Snapshot caller choices before a fetch can yield to application code.
88
+ options = { ...options };
89
+ const url = endpoint(source instanceof URL ? source.href : source, 'manifest');
90
+ if (options.sha256 !== undefined && !/^[a-f0-9]{64}$/.test(options.sha256))
91
+ throw new Error('Invalid manifest SHA-256 pin');
92
+ const sourceUrl = new URL(url);
93
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(sourceUrl.hostname);
94
+ if (sourceUrl.protocol !== 'https:' && !loopback && options.sha256 === undefined)
95
+ throw new Error('Remote manifest downloads require HTTPS or an independently trusted SHA-256 pin');
96
+ options.signal?.throwIfAborted();
97
+ const response = await (options.fetchImpl ?? globalThis.fetch)(url, { signal: options.signal });
98
+ if (!response.ok)
99
+ throw new Error(`Application manifest request failed (HTTP ${response.status})`);
100
+ if (response.url) {
101
+ const final = endpoint(response.url, 'manifest response');
102
+ if (sourceUrl.protocol === 'https:' && !final.startsWith('https:'))
103
+ throw new Error('Manifest redirect requires HTTPS');
104
+ if (sourceUrl.protocol === 'http:' && loopback && options.sha256 === undefined &&
105
+ !['localhost', '127.0.0.1', '[::1]'].includes(new URL(final).hostname))
106
+ throw new Error('Unpinned loopback manifest redirect must stay on loopback');
107
+ }
108
+ const bytes = new Uint8Array(await response.arrayBuffer());
109
+ options.signal?.throwIfAborted();
110
+ if (options.sha256 !== undefined && bytesToHex(sha256(bytes)) !== options.sha256)
111
+ throw new Error('Application manifest SHA-256 mismatch');
112
+ const resolved = resolveApplicationManifest(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)), options);
113
+ if (options.sha256 !== undefined) {
114
+ resolved.deployment = defineDeployment({ ...resolved.deployment, provenance: {
115
+ networkRevision: resolved.deployment.provenance?.networkRevision ?? resolved.deployment.name,
116
+ manifestSha256: options.sha256,
117
+ } });
118
+ }
119
+ return resolved;
120
+ }
@@ -0,0 +1,30 @@
1
+ import { TasraError } from '../errors.js';
2
+ /**
3
+ * Durable private state storage with exclusive locking for each named operation.
4
+ */
5
+ export interface ApplicationStore {
6
+ /**
7
+ * Load a saved value, or return undefined when the key does not exist.
8
+ */
9
+ load<T>(key: string): Promise<T | undefined>;
10
+ /**
11
+ * Atomically persist private state before resolving.
12
+ */
13
+ save<T>(key: string, value: T): Promise<void>;
14
+ /**
15
+ * Exclusively serialize work for the key across all participating processes or tabs.
16
+ */
17
+ withLock<T>(key: string, action: () => Promise<T>): Promise<T>;
18
+ }
19
+ /**
20
+ * A state lock is already held and requires reconciliation before manual removal.
21
+ */
22
+ export declare class StoreLockedError extends TasraError {
23
+ readonly key: string;
24
+ constructor(/** Store entry whose exclusive lock could not be acquired. */ key: string);
25
+ }
26
+ /**
27
+ * The directory is private, trusted application state, not an untrusted shared folder.
28
+ * @param directory Private application state directory owned by the current operating-system user.
29
+ */
30
+ export declare function createFileStore(directory: string): ApplicationStore;
@@ -0,0 +1,159 @@
1
+ /** Node-only durable private state. Import from @t3foundry/tasra-sdk/app/node. */
2
+ import { constants } from 'node:fs';
3
+ import { mkdir, lstat, open, rename, unlink } from 'node:fs/promises';
4
+ import { resolve, join } from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { TasraError } from '../errors.js';
7
+ /**
8
+ * A state lock is already held and requires reconciliation before manual removal.
9
+ */
10
+ export class StoreLockedError extends TasraError {
11
+ key;
12
+ constructor(/** Store entry whose exclusive lock could not be acquired. */ key) {
13
+ super(`State ${key} is locked; reconcile any interrupted operation before removing its lock`);
14
+ this.key = key;
15
+ }
16
+ }
17
+ function encode(value, seen = new Set()) {
18
+ if (value === null)
19
+ return ['null'];
20
+ if (value === undefined)
21
+ return ['undefined'];
22
+ if (typeof value === 'string')
23
+ return ['string', value];
24
+ if (typeof value === 'boolean')
25
+ return ['boolean', value];
26
+ if (typeof value === 'number' && Number.isFinite(value))
27
+ return ['number', value];
28
+ if (typeof value === 'bigint')
29
+ return ['bigint', value.toString()];
30
+ if (value instanceof Uint8Array)
31
+ return ['bytes', Buffer.from(value).toString('base64')];
32
+ if (typeof value !== 'object' || seen.has(value))
33
+ throw new TasraError('State must contain finite plain data without cycles');
34
+ seen.add(value);
35
+ try {
36
+ if (Array.isArray(value))
37
+ return ['array', value.map(v => encode(v, seen))];
38
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null)
39
+ throw new TasraError('State must contain plain objects');
40
+ return ['object', Object.entries(value).map(([k, v]) => [k, encode(v, seen)])];
41
+ }
42
+ finally {
43
+ seen.delete(value);
44
+ }
45
+ }
46
+ function decode(value) {
47
+ switch (value[0]) {
48
+ case 'null': return null;
49
+ case 'undefined': return undefined;
50
+ case 'string':
51
+ case 'number':
52
+ case 'boolean': return value[1];
53
+ case 'bigint': return BigInt(value[1]);
54
+ case 'bytes': return new Uint8Array(Buffer.from(value[1], 'base64'));
55
+ case 'array': return value[1].map(decode);
56
+ case 'object': return Object.fromEntries(value[1].map(([k, v]) => [k, decode(v)]));
57
+ default: throw new TasraError('Invalid state encoding');
58
+ }
59
+ }
60
+ const missing = (error) => error.code === 'ENOENT';
61
+ /**
62
+ * The directory is private, trusted application state, not an untrusted shared folder.
63
+ * @param directory Private application state directory owned by the current operating-system user.
64
+ */
65
+ export function createFileStore(directory) {
66
+ const root = resolve(directory);
67
+ const path = (key, suffix = '.json') => {
68
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(key))
69
+ throw new TasraError('Invalid state key');
70
+ return join(root, key + suffix);
71
+ };
72
+ async function ready() {
73
+ await mkdir(root, { recursive: true, mode: 0o700 });
74
+ const stat = await lstat(root);
75
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())
76
+ throw new TasraError('State directory must be owned by this user with mode 0700');
77
+ }
78
+ async function syncDirectory() {
79
+ const dir = await open(root, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
80
+ try {
81
+ await dir.sync();
82
+ }
83
+ finally {
84
+ await dir.close();
85
+ }
86
+ }
87
+ return {
88
+ async load(key) {
89
+ const target = path(key);
90
+ await ready();
91
+ let file;
92
+ try {
93
+ file = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
94
+ }
95
+ catch (error) {
96
+ if (missing(error))
97
+ return undefined;
98
+ throw error;
99
+ }
100
+ try {
101
+ const stat = await file.stat();
102
+ if (!stat.isFile() || stat.nlink !== 1 || (stat.mode & 0o077) !== 0 || stat.uid !== process.getuid?.())
103
+ throw new TasraError('State file must be a private regular file');
104
+ const envelope = JSON.parse(await file.readFile('utf8'));
105
+ if (envelope.schemaVersion !== 1)
106
+ throw new TasraError('Unsupported state schema');
107
+ return decode(envelope.value);
108
+ }
109
+ finally {
110
+ await file.close();
111
+ }
112
+ },
113
+ async save(key, value) {
114
+ const target = path(key), contents = JSON.stringify({ schemaVersion: 1, value: encode(value) }) + '\n';
115
+ await ready();
116
+ const temporary = join(root, `.${randomUUID()}.tmp`);
117
+ const file = await open(temporary, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
118
+ try {
119
+ try {
120
+ await file.writeFile(contents, 'utf8');
121
+ await file.sync();
122
+ }
123
+ finally {
124
+ await file.close();
125
+ }
126
+ await rename(temporary, target);
127
+ await syncDirectory();
128
+ }
129
+ finally {
130
+ await unlink(temporary).catch(error => { if (!missing(error))
131
+ throw error; });
132
+ }
133
+ },
134
+ async withLock(key, action) {
135
+ const target = path(key, '.lock');
136
+ await ready();
137
+ let lock;
138
+ try {
139
+ lock = await open(target, constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW, 0o600);
140
+ }
141
+ catch (error) {
142
+ if (error.code === 'EEXIST')
143
+ throw new StoreLockedError(key);
144
+ throw error;
145
+ }
146
+ try {
147
+ await lock.writeFile(JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }));
148
+ await lock.sync();
149
+ await syncDirectory();
150
+ return await action();
151
+ }
152
+ finally {
153
+ await lock.close();
154
+ await unlink(target);
155
+ await syncDirectory();
156
+ }
157
+ },
158
+ };
159
+ }
@@ -0,0 +1,157 @@
1
+ import type { Hex } from 'viem';
2
+ import type { TasraApplication } from './client.js';
3
+ import { type SlotCreationJournal } from './creation.js';
4
+ import { type CreateSlotArgs, type WriteClientWalletConfig } from '../chain/write.js';
5
+ import { TasraError } from '../errors.js';
6
+ import type { TypedDataSigner } from '../oid4vp/verifier-agent.js';
7
+ /** Stable recovery categories for a durable named slot creation. */
8
+ export type ApplicationSlotRecoveryCode = 'SAVED_INTENT_MISMATCH' | 'SLOT_STATE_MISMATCH' | 'VERIFIER_POLICY_OUTCOME_UNKNOWN' | 'VERIFIER_POLICY_RECEIPT_PENDING' | 'VERIFIER_POLICY_REVERTED' | 'VERIFIER_POLICY_MISMATCH';
9
+ /** A creation state that requires inspection or reconciliation before resuming. */
10
+ export declare class ApplicationSlotRecoveryError extends TasraError {
11
+ /** Recovery category; never infer it from the message. */
12
+ readonly code: ApplicationSlotRecoveryCode;
13
+ /** Stable name of the private creation journal. */
14
+ readonly recoveryName: string;
15
+ /** Public slot ID, if the creation journal already contains one. */
16
+ readonly slotId?: Hex;
17
+ /** Known verifier-policy transaction hash, if available. */
18
+ readonly transactionHash?: Hex;
19
+ constructor(code: ApplicationSlotRecoveryCode, recoveryName: string, message: string, details?: {
20
+ slotId?: Hex;
21
+ transactionHash?: Hex;
22
+ cause?: unknown;
23
+ });
24
+ }
25
+ /** Implementations must save atomically and exclusively lock across processes/tabs. */
26
+ export interface ApplicationStore {
27
+ /**
28
+ * Load a saved value, or return undefined when the key does not exist.
29
+ */
30
+ load<T>(key: string): Promise<T | undefined>;
31
+ /**
32
+ * Atomically persist private state before resolving.
33
+ */
34
+ save(key: string, value: unknown): Promise<void>;
35
+ /**
36
+ * Exclusively serialize work for the key across all participating processes or tabs.
37
+ */
38
+ withLock<T>(key: string, operation: () => Promise<T>): Promise<T>;
39
+ }
40
+ /**
41
+ * Named slot intent with an authorization rule, key threshold and verifier quorum.
42
+ */
43
+ export interface CreateApplicationSlot {
44
+ /** Stable recovery name. Reusing it resumes the same intent, never creates another slot. */
45
+ name: string;
46
+ /**
47
+ * Key capability: Ethereum account, Ed25519 signing or identity encryption.
48
+ */
49
+ mode: 'ecdsa' | 'frost' | 'bls';
50
+ /** Clear authorization rule. Its salted commitment is stored on-chain. */
51
+ policy: string;
52
+ /** Authorization family; defaults to credential-wallet OID4VP. */
53
+ authType?: 'oid4vp' | 'oauth';
54
+ /**
55
+ * Minimum signing or extraction shares k out of n assigned keepers.
56
+ */
57
+ threshold: {
58
+ k: number;
59
+ n: number;
60
+ };
61
+ /**
62
+ * Verifier committee size and required authorization quorum.
63
+ */
64
+ verifiers: {
65
+ committee: number;
66
+ quorum: number;
67
+ };
68
+ /**
69
+ * Keeper selection tags; defaults to keykeeper.
70
+ */
71
+ tags?: string[];
72
+ /**
73
+ * Optional amendment authority installed atomically during creation.
74
+ */
75
+ rulePolicy?: CreateSlotArgs['rulePolicy'];
76
+ }
77
+ /**
78
+ * Private creation journal tracking rule delivery and verifier-policy installation.
79
+ */
80
+ export interface ReadySlotJournal {
81
+ /**
82
+ * Ready-slot journal schema version.
83
+ */
84
+ schemaVersion: 1;
85
+ /**
86
+ * Original named application creation request.
87
+ */
88
+ request: CreateApplicationSlot;
89
+ /**
90
+ * Private slot creation intent and its transaction history.
91
+ */
92
+ creation: SlotCreationJournal;
93
+ /**
94
+ * Whether this journal previously completed rule delivery.
95
+ */
96
+ provisioned?: boolean;
97
+ /**
98
+ * Durable verifier-policy transaction phase and hash.
99
+ */
100
+ verifierPolicy?: {
101
+ phase: 'submitting' | 'submitted' | 'confirmed';
102
+ hash?: Hex;
103
+ };
104
+ }
105
+ /** Public milestone emitted while a named slot is created or resumed. */
106
+ export interface SlotCreationProgress {
107
+ /** Creation stage. */
108
+ step: 'commit' | 'reveal' | 'key_generation' | 'rule_provisioning' | 'verifier_policy' | 'ready';
109
+ /** Current stage state. Transaction stages use submitting, submitted and confirmed. */
110
+ phase: 'waiting' | 'submitting' | 'submitted' | 'confirmed' | 'complete';
111
+ /** Public slot ID shared by every milestone. */
112
+ slotId: Hex;
113
+ /** Public transaction hash when known. */
114
+ transactionHash?: Hex;
115
+ }
116
+ /**
117
+ * Creator wallet, durable storage and network controls for creating a ready slot.
118
+ */
119
+ export interface CreateApplicationSlotOptions {
120
+ /**
121
+ * Creator wallet bound to the intended account and chain.
122
+ */
123
+ wallet: WriteClientWalletConfig['wallet'];
124
+ /**
125
+ * Creator EIP-712 signer used to authorize rule delivery.
126
+ */
127
+ signer: TypedDataSigner;
128
+ /**
129
+ * Private atomic store used to persist and lock the named creation intent.
130
+ */
131
+ store: ApplicationStore;
132
+ /**
133
+ * Explicit routing callback for registered keeper endpoints.
134
+ */
135
+ keeperUrl?: (url: string) => string;
136
+ /**
137
+ * HTTP implementation used to deliver rules to keepers.
138
+ */
139
+ fetchImpl?: typeof fetch;
140
+ /**
141
+ * Cancel pending work without reversing submitted transactions.
142
+ */
143
+ signal?: AbortSignal;
144
+ /**
145
+ * Cooperative cancellation deadline in milliseconds; defaults to 300000. Checked between stages; in-flight RPC requests and wallet prompts may outlast it. A resumed verifier-policy receipt wait uses this duration independently.
146
+ */
147
+ timeoutMs?: number;
148
+ /** Observational progress callback. Callback failures do not interrupt creation. */
149
+ onProgress?: (progress: SlotCreationProgress) => void | Promise<void>;
150
+ }
151
+ /**
152
+ * Durable creation, key readiness, rule delivery and explicit verifier policy in one operation.
153
+ * @param app Application client connected to the target deployment.
154
+ * @param input Stable named creation intent with rule and threshold policies.
155
+ * @param options Creator wallet, signer, durable store and cancellation controls.
156
+ */
157
+ export declare function createApplicationSlot(app: TasraApplication, input: CreateApplicationSlot, options: CreateApplicationSlotOptions): Promise<`0x${string}`>;
@@ -0,0 +1,199 @@
1
+ import { isOauthFormat, validate as validateRule } from '../auth/oid4vp.js';
2
+ import { prepareSlot, createPreparedSlot } from './creation.js';
3
+ import { createTasraWriteClient, ruleCommitment } from '../chain/write.js';
4
+ import { provisionRule } from '../chain/provisionRule.js';
5
+ import { requireRule } from '../chain/ruleInput.js';
6
+ import { resolveSlotKeeperUrls } from '../chain/discovery.js';
7
+ import { TasraError } from '../errors.js';
8
+ /** A creation state that requires inspection or reconciliation before resuming. */
9
+ export class ApplicationSlotRecoveryError extends TasraError {
10
+ /** Recovery category; never infer it from the message. */
11
+ code;
12
+ /** Stable name of the private creation journal. */
13
+ recoveryName;
14
+ /** Public slot ID, if the creation journal already contains one. */
15
+ slotId;
16
+ /** Known verifier-policy transaction hash, if available. */
17
+ transactionHash;
18
+ constructor(code, recoveryName, message, details = {}) {
19
+ super(message, { cause: details.cause });
20
+ this.code = code;
21
+ this.recoveryName = recoveryName;
22
+ this.slotId = details.slotId;
23
+ this.transactionHash = details.transactionHash;
24
+ }
25
+ }
26
+ function validate(request) {
27
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,79}$/.test(request.name))
28
+ throw new Error('Invalid slot recovery name');
29
+ if (!['ecdsa', 'frost', 'bls'].includes(request.mode))
30
+ throw new Error('Unsupported application slot mode');
31
+ const { committee, quorum } = request.verifiers;
32
+ if (!Number.isSafeInteger(committee) || !Number.isSafeInteger(quorum) || quorum < 1 || committee < quorum || committee > 65535)
33
+ throw new Error('Invalid verifier threshold');
34
+ const authType = request.authType === undefined ? 'oid4vp' : request.authType;
35
+ if (authType !== 'oid4vp' && authType !== 'oauth')
36
+ throw new Error('Unsupported slot authorization family');
37
+ const query = validateRule(request.policy);
38
+ if (query.credentials.some(credential => isOauthFormat(credential.format) !== (authType === 'oauth'))) {
39
+ throw new Error('Every policy query must match the slot authorization family');
40
+ }
41
+ }
42
+ function sameRequest(a, b) {
43
+ return a.name === b.name && a.mode === b.mode && a.policy === b.policy &&
44
+ (a.authType ?? 'oid4vp') === (b.authType ?? 'oid4vp') &&
45
+ a.threshold.k === b.threshold.k && a.threshold.n === b.threshold.n &&
46
+ a.verifiers.committee === b.verifiers.committee && a.verifiers.quorum === b.verifiers.quorum &&
47
+ JSON.stringify(a.tags ?? ['keykeeper']) === JSON.stringify(b.tags ?? ['keykeeper']) &&
48
+ JSON.stringify(a.rulePolicy) === JSON.stringify(b.rulePolicy);
49
+ }
50
+ function pause(ms, signal) {
51
+ signal.throwIfAborted();
52
+ return new Promise((resolve, reject) => {
53
+ const aborted = () => { clearTimeout(timer); reject(signal.reason); };
54
+ const timer = setTimeout(() => { signal.removeEventListener('abort', aborted); resolve(); }, ms);
55
+ signal.addEventListener('abort', aborted, { once: true });
56
+ });
57
+ }
58
+ /**
59
+ * Durable creation, key readiness, rule delivery and explicit verifier policy in one operation.
60
+ * @param app Application client connected to the target deployment.
61
+ * @param input Stable named creation intent with rule and threshold policies.
62
+ * @param options Creator wallet, signer, durable store and cancellation controls.
63
+ */
64
+ export async function createApplicationSlot(app, input, options) {
65
+ options = { ...options };
66
+ const request = structuredClone(input);
67
+ validate(request);
68
+ const authType = request.authType ?? 'oid4vp';
69
+ if (options.signer.address.toLowerCase() !== options.wallet.account.address.toLowerCase())
70
+ throw new Error('Provisioning signer differs from the creation wallet');
71
+ const timeoutMs = options.timeoutMs ?? 300_000;
72
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1)
73
+ throw new Error('Invalid slot creation timeout');
74
+ const signal = AbortSignal.any([AbortSignal.timeout(timeoutMs), ...(options.signal ? [options.signal] : [])]);
75
+ signal.throwIfAborted();
76
+ const key = `slot-${request.name}`;
77
+ return options.store.withLock(key, async () => {
78
+ signal.throwIfAborted();
79
+ const { deployment, chain } = app;
80
+ const mode = request.mode === 'ecdsa' ? 'tecdsa' : request.mode;
81
+ const intent = { rule: request.policy, mode, ...request.threshold, tags: request.tags, rulePolicy: request.rulePolicy, authType };
82
+ // Validation also runs on resume, before a writer is allowed to act.
83
+ prepareSlot(deployment, options.wallet.account.address, intent);
84
+ let journal = await options.store.load(key);
85
+ if (journal) {
86
+ if (journal.schemaVersion !== 1 || !sameRequest(journal.request, request))
87
+ throw new ApplicationSlotRecoveryError('SAVED_INTENT_MISMATCH', request.name, 'Saved slot intent differs; use its original request to resume', { slotId: journal.creation?.intent?.slotId });
88
+ const saved = journal.creation;
89
+ if (saved.creator.toLowerCase() !== options.wallet.account.address.toLowerCase() ||
90
+ saved.deployment.chainId !== deployment.chainId || saved.deployment.rpcUrl !== deployment.rpcUrl ||
91
+ ['KeyRegistry', 'NodeRegistry'].some(name => saved.deployment.addresses[name]?.toLowerCase() !== deployment.addresses[name]?.toLowerCase()) ||
92
+ requireRule(saved.intent) !== request.policy || saved.intent.authType !== authType || saved.intent.mode !== mode || saved.intent.k !== request.threshold.k || saved.intent.n !== request.threshold.n) {
93
+ throw new ApplicationSlotRecoveryError('SAVED_INTENT_MISMATCH', request.name, 'Saved slot belongs to a different creator, deployment or policy', { slotId: saved.intent.slotId });
94
+ }
95
+ }
96
+ else {
97
+ journal = { schemaVersion: 1, request, creation: prepareSlot(deployment, options.wallet.account.address, intent) };
98
+ }
99
+ const state = journal;
100
+ const save = () => options.store.save(key, structuredClone(state));
101
+ const slotId = state.creation.intent.slotId;
102
+ const progress = (event) => {
103
+ try {
104
+ void Promise.resolve(options.onProgress?.(event)).catch(() => { });
105
+ }
106
+ catch { /* Progress is observational. */ }
107
+ };
108
+ await save();
109
+ if (!(await app.check()).ready)
110
+ throw new Error('Deployment registries are not ready');
111
+ if (options.wallet.chain.id !== deployment.chainId)
112
+ throw new Error('Wallet chain differs from deployment');
113
+ if (!state.creation.result) {
114
+ state.creation = await createPreparedSlot(state.creation, { wallet: options.wallet, persist: async (creation) => {
115
+ const previous = state.creation;
116
+ state.creation = creation;
117
+ await save();
118
+ for (const step of ['commit', 'reveal']) {
119
+ const transaction = creation[step];
120
+ if (transaction && (transaction.phase !== previous[step]?.phase || transaction.hash !== previous[step]?.hash)) {
121
+ progress({ step, phase: transaction.phase, slotId, ...(transaction.hash ? { transactionHash: transaction.hash } : {}) });
122
+ }
123
+ }
124
+ }, options: { signal, maxWaitMs: timeoutMs } });
125
+ await save();
126
+ }
127
+ let slot = await app.slots.get(slotId);
128
+ if (!slot.ready)
129
+ progress({ step: 'key_generation', phase: 'waiting', slotId });
130
+ while (!slot.ready) {
131
+ await pause(1000, signal);
132
+ slot = await app.slots.get(slotId);
133
+ }
134
+ if (slot.mode !== ({ ecdsa: 2, frost: 0, bls: 1 }[request.mode]))
135
+ throw new ApplicationSlotRecoveryError('SLOT_STATE_MISMATCH', request.name, 'Created slot has an unexpected mode', { slotId });
136
+ const assertIntent = async () => {
137
+ const current = await chain.readers.keyRegistry.getKeySlot(slotId);
138
+ if (!current.exists || current.cancelled || current.creator.toLowerCase() !== state.creation.creator.toLowerCase() ||
139
+ current.ruleCommitment.toLowerCase() !== ruleCommitment(state.creation.intent.ruleSalt, request.policy).toLowerCase() ||
140
+ Number(current.threshold.k) !== request.threshold.k || Number(current.threshold.n) !== request.threshold.n ||
141
+ Number(current.auth) !== (authType === 'oauth' ? 2 : 1) || Number(current.mode) !== slot.mode || Number(current.epoch) !== slot.epoch || current.publicKey !== slot.publicKey) {
142
+ throw new ApplicationSlotRecoveryError('SLOT_STATE_MISMATCH', request.name, 'On-chain slot changed or differs from the saved creation intent', { slotId });
143
+ }
144
+ };
145
+ await assertIntent();
146
+ progress({ step: 'key_generation', phase: 'complete', slotId });
147
+ // Rule delivery is idempotent and covers the current committee, including after resharing.
148
+ {
149
+ progress({ step: 'rule_provisioning', phase: 'waiting', slotId });
150
+ const keeperUrls = (await resolveSlotKeeperUrls(chain, slotId)).map(options.keeperUrl ?? (url => url));
151
+ await provisionRule(chain, { slotId, rule: requireRule(state.creation.intent), ruleSalt: state.creation.intent.ruleSalt,
152
+ signer: options.signer, keeperUrls, fetchImpl: options.fetchImpl, signal });
153
+ state.provisioned = true;
154
+ await save();
155
+ progress({ step: 'rule_provisioning', phase: 'complete', slotId });
156
+ }
157
+ signal.throwIfAborted();
158
+ if (state.verifierPolicy?.phase === 'submitting' && !state.verifierPolicy.hash)
159
+ throw new ApplicationSlotRecoveryError('VERIFIER_POLICY_OUTCOME_UNKNOWN', request.name, `Verifier policy outcome unknown for ${slotId}; reconcile its transaction hash before resuming`, { slotId });
160
+ if (state.verifierPolicy?.hash && state.verifierPolicy.phase !== 'confirmed') {
161
+ progress({ step: 'verifier_policy', phase: 'submitted', slotId, transactionHash: state.verifierPolicy.hash });
162
+ const receipt = await chain.client.waitForTransactionReceipt({ hash: state.verifierPolicy.hash, timeout: timeoutMs });
163
+ if (receipt.status !== 'success')
164
+ throw new ApplicationSlotRecoveryError('VERIFIER_POLICY_REVERTED', request.name, 'Verifier policy transaction reverted; reconcile before resuming', { slotId, transactionHash: state.verifierPolicy.hash });
165
+ state.verifierPolicy.phase = 'confirmed';
166
+ await save();
167
+ progress({ step: 'verifier_policy', phase: 'confirmed', slotId, transactionHash: state.verifierPolicy.hash });
168
+ }
169
+ if (!state.verifierPolicy) {
170
+ const writer = createTasraWriteClient({ ...deployment, wallet: options.wallet });
171
+ const currentPolicy = () => state.verifierPolicy;
172
+ try {
173
+ await writer.setVerifierPolicy(slotId, request.verifiers.committee, request.verifiers.quorum, async (event) => {
174
+ if (event.phase === 'submitting')
175
+ signal.throwIfAborted();
176
+ state.verifierPolicy = event;
177
+ await save();
178
+ progress({ step: 'verifier_policy', phase: event.phase, slotId, ...(event.hash ? { transactionHash: event.hash } : {}) });
179
+ });
180
+ }
181
+ catch (cause) {
182
+ const policy = currentPolicy();
183
+ if (policy?.phase === 'submitting' && !policy.hash) {
184
+ throw new ApplicationSlotRecoveryError('VERIFIER_POLICY_OUTCOME_UNKNOWN', request.name, `Verifier policy outcome unknown for ${slotId}; reconcile its transaction hash before resuming`, { slotId, cause });
185
+ }
186
+ if (policy?.phase === 'submitted' && policy.hash) {
187
+ throw new ApplicationSlotRecoveryError('VERIFIER_POLICY_RECEIPT_PENDING', request.name, `Verifier policy receipt pending for ${slotId}; resume the saved transaction hash`, { slotId, transactionHash: policy.hash, cause });
188
+ }
189
+ throw cause;
190
+ }
191
+ }
192
+ const [committee, quorum] = await chain.readers.keyRegistry.verifierPolicy(slotId);
193
+ if (committee !== request.verifiers.committee || quorum !== request.verifiers.quorum)
194
+ throw new ApplicationSlotRecoveryError('VERIFIER_POLICY_MISMATCH', request.name, 'On-chain verifier policy differs from the requested policy', { slotId, transactionHash: state.verifierPolicy?.hash });
195
+ await assertIntent();
196
+ progress({ step: 'ready', phase: 'complete', slotId });
197
+ return slotId;
198
+ });
199
+ }