@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,204 @@
1
+ // Sign Ethereum transactions with a Tasra threshold-ECDSA (tECDSA) slot,
2
+ // via an ethers v6 Signer — drop it into ethers or Hardhat like any other signer.
3
+ //
4
+ // npx tsx examples/ethers-signer.ts # runs the offline self-test below
5
+ //
6
+ // This example imports the published '@t3foundry/tasra-sdk' entry point. The private key never exists anywhere: each
7
+ // signature is produced by the k-of-n keykeeper-node fleet via signEoaDigest();
8
+ // this Signer just turns ethers' transaction/message/typed-data hashes into that
9
+ // 32-byte digest call and re-assembles the {r,s,v} result.
10
+ //
11
+ // NOTE: the node's /v1/sign/eoa-digest path may be feature-gated in your
12
+ // deployment. The offline self-test at the bottom substitutes a LOCAL secp256k1
13
+ // key for the fleet to prove the assembly end-to-end without a live backend.
14
+ //
15
+ // ── Usage (ethers) ────────────────────────────────────────────────────────────
16
+ // import {redeemRenewalToken} from '@t3foundry/tasra-sdk'
17
+ // const signer = new TasraSigner({
18
+ // nodes: ['https://node-1', 'https://node-2', 'https://node-3'],
19
+ // slotId: '0x…', // a tECDSA signing slot
20
+ // getJwt: async () => (await redeemRenewalToken(verifier, renewalToken)).token,
21
+ // }).connect(provider)
22
+ // await signer.getAddress()
23
+ // await signer.sendTransaction({to, value}) // signs + broadcasts via provider
24
+ //
25
+ // ── Usage (Hardhat) ───────────────────────────────────────────────────────────
26
+ // const signer = new TasraSigner({nodes, slotId, getJwt}).connect(ethers.provider)
27
+ // const erc20 = await ethers.getContractAt('IERC20', tokenAddr, signer)
28
+ // await erc20.transfer(to, amount) // signed by the threshold fleet
29
+
30
+ import {
31
+ AbstractSigner,
32
+ Transaction,
33
+ Signature,
34
+ getBytes,
35
+ hexlify,
36
+ hashMessage,
37
+ TypedDataEncoder,
38
+ verifyMessage,
39
+ verifyTypedData,
40
+ type Provider,
41
+ type TransactionRequest,
42
+ type TransactionLike,
43
+ type TypedDataDomain,
44
+ type TypedDataField,
45
+ } from 'ethers'
46
+ import {secp256k1} from '@noble/curves/secp256k1'
47
+ import {signEoaDigest, addressFromEoaPubkey, fetchMpk} from '@t3foundry/tasra-sdk'
48
+
49
+ /** Raw Ethereum ECDSA components as returned by the threshold network. */
50
+ export interface RawEcdsaSig {
51
+ r: Uint8Array // 32-byte big-endian
52
+ s: Uint8Array // 32-byte big-endian (low-s)
53
+ yParity: number // 0 | 1
54
+ }
55
+
56
+ export interface TasraSignerConfig {
57
+ /** k-of-n keykeeper-node base URLs. */
58
+ nodes: string[]
59
+ /** 0x-prefixed bytes32 tECDSA slot id. */
60
+ slotId: string
61
+ /** Supply a fresh DCQL-gated JWT (e.g. via redeemRenewalToken / redeemCredential). */
62
+ getJwt: () => Promise<string>
63
+ /** ethers provider — needed to populate nonce/gas/chainId and to broadcast. */
64
+ provider?: Provider | null
65
+ /** The EOA address, if already known — skips the getAddress() key fetch. */
66
+ address?: string
67
+ /** Override the digest signer (used by the offline self-test); defaults to signEoaDigest. */
68
+ signDigest?: (digest: Uint8Array) => Promise<RawEcdsaSig>
69
+ }
70
+
71
+ export class TasraSigner extends AbstractSigner {
72
+ readonly cfg: TasraSignerConfig
73
+ #address?: string
74
+ readonly #signDigest: (digest: Uint8Array) => Promise<RawEcdsaSig>
75
+
76
+ constructor(cfg: TasraSignerConfig) {
77
+ super(cfg.provider ?? null)
78
+ this.cfg = cfg
79
+ this.#address = cfg.address
80
+ this.#signDigest =
81
+ cfg.signDigest ??
82
+ (async digest => {
83
+ const sig = await signEoaDigest({
84
+ nodeUrl: cfg.nodes[0]!,
85
+ jwt: await cfg.getJwt(),
86
+ slotId: cfg.slotId,
87
+ digest,
88
+ })
89
+ return {r: sig.r, s: sig.s, yParity: sig.yParity}
90
+ })
91
+ }
92
+
93
+ /** The threshold EOA address — derived from the slot's secp256k1 group key, or the configured one. */
94
+ async getAddress(): Promise<string> {
95
+ if (this.#address) return this.#address
96
+ // Assumes /v1/keys/{slot}/public serves the secp256k1 key for a tECDSA slot;
97
+ // pass `address` in the config to skip this.
98
+ const {mpkBytes} = await fetchMpk(this.cfg.nodes[0]!, this.cfg.slotId)
99
+ return (this.#address = addressFromEoaPubkey(mpkBytes))
100
+ }
101
+
102
+ connect(provider: Provider | null): TasraSigner {
103
+ return new TasraSigner({...this.cfg, provider})
104
+ }
105
+
106
+ /** Sign an arbitrary 32-byte digest via the threshold network → an ethers Signature. */
107
+ async ethSignature(digest: Uint8Array): Promise<Signature> {
108
+ const {r, s, yParity} = await this.#signDigest(digest)
109
+ return Signature.from({r: hexlify(r), s: hexlify(s), yParity: (yParity ? 1 : 0) as 0 | 1})
110
+ }
111
+
112
+ async signTransaction(tx: TransactionRequest): Promise<string> {
113
+ const pop = await this.populateTransaction(tx)
114
+ delete (pop as {from?: unknown}).from // a Transaction has no `from` (it's recovered)
115
+ const t = Transaction.from(pop as unknown as TransactionLike<string>)
116
+ t.signature = await this.ethSignature(getBytes(t.unsignedHash))
117
+ return t.serialized
118
+ }
119
+
120
+ async signMessage(message: string | Uint8Array): Promise<string> {
121
+ return (await this.ethSignature(getBytes(hashMessage(message)))).serialized
122
+ }
123
+
124
+ async signTypedData(
125
+ domain: TypedDataDomain,
126
+ types: Record<string, Array<TypedDataField>>,
127
+ value: Record<string, unknown>,
128
+ ): Promise<string> {
129
+ return (await this.ethSignature(getBytes(TypedDataEncoder.hash(domain, types, value)))).serialized
130
+ }
131
+ }
132
+
133
+ // ── Offline self-test: a LOCAL secp256k1 key stands in for the threshold fleet ──
134
+ // Proves the adapter assembles signatures that ethers recovers back to the right
135
+ // address — for messages, EIP-712 typed data, and an EIP-1559 transaction —
136
+ // without any running node (the live tECDSA path is the default in production).
137
+
138
+ async function selfTest(): Promise<void> {
139
+ const priv = getBytes('0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d')
140
+ const pub = secp256k1.getPublicKey(priv, true)
141
+ const addr = addressFromEoaPubkey(pub)
142
+
143
+ const localSignDigest = async (digest: Uint8Array): Promise<RawEcdsaSig> => {
144
+ const sig = secp256k1.sign(digest, priv) // low-s by default; carries .recovery
145
+ const compact = sig.toCompactRawBytes() // r‖s, 64 bytes
146
+ return {r: compact.slice(0, 32), s: compact.slice(32, 64), yParity: sig.recovery!}
147
+ }
148
+
149
+ const signer = new TasraSigner({
150
+ nodes: ['http://node'],
151
+ slotId: '0x' + 'cd'.repeat(32),
152
+ getJwt: async () => 'unused-offline',
153
+ address: addr,
154
+ signDigest: localSignDigest,
155
+ })
156
+
157
+ let pass = 0
158
+ const fails: string[] = []
159
+ const ok = (name: string, cond: boolean): void => {
160
+ if (cond) {
161
+ pass++
162
+ console.log(` ✓ ${name}`)
163
+ } else fails.push(name)
164
+ }
165
+
166
+ ok('getAddress() returns the threshold EOA address', (await signer.getAddress()) === addr)
167
+
168
+ const msg = 'hello from a Tasra threshold EOA'
169
+ ok('signMessage → verifyMessage recovers the address', verifyMessage(msg, await signer.signMessage(msg)) === addr)
170
+
171
+ const domain: TypedDataDomain = {name: 'Demo', version: '1', chainId: 1, verifyingContract: '0x' + '11'.repeat(20)}
172
+ const types = {Mail: [{name: 'note', type: 'string'}]}
173
+ const value = {note: 'gm'}
174
+ ok(
175
+ 'signTypedData → verifyTypedData recovers the address',
176
+ verifyTypedData(domain, types, value, await signer.signTypedData(domain, types, value)) === addr,
177
+ )
178
+
179
+ const t = Transaction.from({
180
+ to: '0x' + '22'.repeat(20),
181
+ value: 10n ** 18n,
182
+ nonce: 7,
183
+ gasLimit: 21000,
184
+ maxFeePerGas: 10n ** 9n,
185
+ maxPriorityFeePerGas: 10n ** 9n,
186
+ chainId: 1,
187
+ type: 2,
188
+ })
189
+ t.signature = await signer.ethSignature(getBytes(t.unsignedHash))
190
+ ok('signed EIP-1559 tx recovers the sender', Transaction.from(t.serialized).from === addr)
191
+
192
+ if (fails.length > 0) {
193
+ console.error(`\n✗ ethers-signer self-test: ${fails.length} failed:`)
194
+ for (const f of fails) console.error(' - ' + f)
195
+ process.exit(1)
196
+ }
197
+ console.log(`\n✓ ethers-signer self-test: ${pass} checks passed (offline, local-key stand-in)`)
198
+ }
199
+
200
+ // Surface a failure as a non-zero exit rather than an unhandled rejection.
201
+ selfTest().catch((error: unknown) => {
202
+ console.error(error)
203
+ process.exitCode = 1
204
+ })
@@ -0,0 +1,73 @@
1
+ /** Explicit purchases and usage deposits for a saved tutorial creator. */
2
+ import {TasraClient} from '@t3foundry/tasra-sdk/app'
3
+ import {createFileStore} from '@t3foundry/tasra-sdk/app/node'
4
+ import {bondingCurveAbi, createTasraWriteClient} from '@t3foundry/tasra-sdk/chain'
5
+ import {loadNetwork} from './network.js'
6
+
7
+ // Amounts are positive integer base units: EURC has 6 decimals; TSRA has 18.
8
+ const args = process.argv.slice(2)
9
+ const slotFlag = args.indexOf('--slot')
10
+ const explicitSlot = slotFlag < 0 ? undefined : args.splice(slotFlag, 2)[1]
11
+ if (slotFlag >= 0 && !explicitSlot) throw new Error('--slot requires a full slot ID')
12
+ const [directory, action = 'status', amountText, minimumText] = args
13
+ if (!directory || !['status', 'buy', 'fund', 'mint-test-eurc'].includes(action) || args.length > 4) {
14
+ throw new Error('Usage: npx tsx fund-slot.ts <state-directory> status|buy|fund|mint-test-eurc [amount] [minimum-TSRA-for-buy] [--slot 0x...]')
15
+ }
16
+ function positive(value: string | undefined, label: string): bigint {
17
+ if (!value || !/^[1-9][0-9]*$/.test(value) || value.length > 78) throw new Error(label + ' must be positive integer base units')
18
+ const amount = BigInt(value)
19
+ if (amount >= 2n ** 256n) throw new Error(label + ' exceeds uint256')
20
+ return amount
21
+ }
22
+ const amount = action === 'status' ? undefined : positive(amountText, 'Amount')
23
+ const minimum = action === 'buy' ? positive(minimumText, 'Minimum TSRA output') : undefined
24
+ if (action === 'status' && (amountText || minimumText) || action !== 'buy' && minimumText) throw new Error('Unexpected amount argument')
25
+
26
+ // Restore the same account and verified manifest; never generate a replacement key.
27
+ const network = loadNetwork()
28
+ const tasra = new TasraClient({manifest: network.deployment})
29
+ const store = createFileStore(directory)
30
+ const pin = await store.load<string>('network-pin')
31
+ if (!pin || pin !== network.deployment.provenance?.manifestSha256) throw new Error('State does not match this downloaded network manifest')
32
+ const privateKey = await store.load<`0x${string}`>('creator-key')
33
+ if (!privateKey) throw new Error('Saved creator key missing; run the tutorial setup first')
34
+ const creator = tasra.wallets.create({privateKey})
35
+ // The release manifest may omit the EURC token. Read it from the pinned curve.
36
+ const curve = tasra.deployment.addresses.BondingCurve
37
+ if (!curve) throw new Error('Network manifest has no BondingCurve')
38
+ const eurc = await tasra.chain.client.readContract({address: curve, abi: bondingCurveAbi, functionName: 'eurc'})
39
+ if (tasra.deployment.addresses.MockEurc && tasra.deployment.addresses.MockEurc.toLowerCase() !== eurc.toLowerCase()) {
40
+ throw new Error('Manifest EURC address does not match BondingCurve')
41
+ }
42
+ const writer = createTasraWriteClient({...tasra.deployment,
43
+ addresses: {...tasra.deployment.addresses, MockEurc: eurc}, wallet: creator.wallet})
44
+ const slotId = explicitSlot ?? await store.load<string>('slot-id')
45
+ if (!slotId || !/^0x[0-9a-fA-F]{64}$/.test(slotId)) throw new Error('Saved slot missing; use the slot ID printed by the tutorial with --slot')
46
+ const slot = slotId as `0x${string}`
47
+ await tasra.slots.get(slot) // Settlement accepts arbitrary IDs, so validate before depositing.
48
+
49
+ async function status() {
50
+ console.log('Creator:', creator.address, 'Chain:', tasra.deployment.chainId)
51
+ console.log('AVAX (wei):', (await writer.ethBalance()).toString())
52
+ console.log('EURC (base units):', (await writer.eurcBalance(creator.address)).toString())
53
+ console.log('Wallet TSRA (base units):', (await writer.tsraBalance()).toString())
54
+ console.log('Slot:', slot, 'TSRA credit (base units):', (await writer.settlementBalance(slot)).toString())
55
+ }
56
+ await status()
57
+ if (action !== 'status') {
58
+ // A repeated explicit command spends again. Never retry an uncertain outcome blindly.
59
+ await store.withLock('funding', async () => {
60
+ console.log('Submitting:', action, amount!.toString())
61
+ if (action === 'mint-test-eurc') {
62
+ console.log('Mint confirmed:', await writer.mintMockEurc(creator.address, amount!))
63
+ } else if (action === 'buy') {
64
+ console.log('EURC approval confirmed:', await writer.approveEurcForCurve(amount!))
65
+ console.log('Purchase confirmed:', await writer.buyTsra(amount!, minimum!))
66
+ } else {
67
+ const receipt = await writer.fundSlot(slot, amount!)
68
+ console.log('TSRA approval confirmed:', receipt.approveTx)
69
+ console.log('Slot funding confirmed:', receipt.fundTx)
70
+ }
71
+ })
72
+ await status()
73
+ }
@@ -0,0 +1,25 @@
1
+ // A provisioned, non-exportable BLS slot and an issuer credential are prerequisites.
2
+ // No operator/admin credentials are used in this application example.
3
+ import {fromBytes} from '@t3foundry/tasra-sdk'
4
+ import {committeeClient, decryptPeers, loadHolder, loadNetwork, slotId} from './live-config.ts'
5
+
6
+ const network = await loadNetwork()
7
+ const slot = slotId()
8
+ const identity = loadHolder()
9
+ try {
10
+ const client = committeeClient(network.chain, slot, identity, 'decrypt')
11
+ const peers = await decryptPeers(network.chain, slot)
12
+ // UTF-8 AAD is required by the threshold HTTP protocol.
13
+ const envelope = fromBytes(await client.encrypt(slot, new TextEncoder().encode('Hello Tasra'), {
14
+ identity: new TextEncoder().encode(slot),
15
+ }))
16
+ const plaintext = await client.decrypt(slot, {
17
+ ciphertext: envelope.ciphertext, identity: envelope.identity,
18
+ ciphertextEpoch: envelope.epoch === null ? undefined : Number(envelope.epoch),
19
+ decryptingSet: peers.map(p => p.id), blsPeers: peers,
20
+ })
21
+ if (new TextDecoder().decode(plaintext) !== 'Hello Tasra') throw new Error('Threshold round trip failed')
22
+ console.log('Threshold decrypt succeeded; the master key was not exported.')
23
+ } finally {
24
+ identity.secretKey.fill(0)
25
+ }
@@ -0,0 +1,23 @@
1
+ import {savedCreator, store, tasra} from './learning-context.js'
2
+
3
+ // Restore the issuer whose rule was committed when this slot was created.
4
+ const issuerKey = await store.load<Uint8Array>('issuer-key')
5
+ if (!issuerKey) throw new Error('Complete the create-slot lesson first')
6
+ const issuer = tasra.identities.create({seed: issuerKey})
7
+ const alice = await store.withLock('alice', async () => {
8
+ const identity = tasra.identities.create({seed: await store.load<Uint8Array>('alice-key')})
9
+ await store.save('alice-key', identity.exportPrivateKey())
10
+ return identity
11
+ })
12
+ const credential = tasra.credentials.issue({
13
+ issuer, holder: alice, type: 'urn:my-app:member', claims: {name: 'Alice'},
14
+ })
15
+ const creator = await savedCreator()
16
+ if (!tasra.verifierAgentUrl) throw new Error('The network manifest must advertise a verifier agent')
17
+
18
+ // Prepare the callback; credentials are presented only when an operation calls it.
19
+ export const authorize = tasra.credentials.authorize({
20
+ verifierAgentUrl: tasra.verifierAgentUrl, signer: creator.signer,
21
+ identity: alice, credentials: [credential],
22
+ })
23
+ console.log('Alice has a membership credential ready for the signing lesson.')
@@ -0,0 +1,11 @@
1
+ import {createTasraWriteClient} from '@t3foundry/tasra-sdk/chain'
2
+ import {savedCreator, savedSlotId, tasra} from './learning-context.js'
3
+
4
+ if (!process.argv.includes('--confirm-cancel')) throw new Error('Cancellation is final. Add --confirm-cancel only when finished with this slot.')
5
+ const slotId = await savedSlotId()
6
+ const creator = await savedCreator()
7
+ const lifecycle = createTasraWriteClient({...tasra.deployment, wallet: creator.wallet})
8
+ console.log('Confirmed transaction:', await lifecycle.cancelSlot(slotId))
9
+ // Cancelled slots remain visible in the registry's historical record.
10
+ const record = await tasra.chain.readers.keyRegistry.getKeySlot(slotId)
11
+ console.log('Cancelled:', record.cancelled)
@@ -0,0 +1,28 @@
1
+ import {TasraClient} from '@t3foundry/tasra-sdk/app'
2
+ import {createFileStore} from '@t3foundry/tasra-sdk/app/node'
3
+ import {loadNetwork} from './network.js'
4
+
5
+ const network = loadNetwork()
6
+ export const store = createFileStore('.tasra/first-slot')
7
+ export const tasra = new TasraClient({manifest: network.deployment, verifierAgentUrl: network.verifierAgentUrl, store})
8
+
9
+ // Keep this lesson's saved accounts and slot on their original network snapshot.
10
+ await store.withLock('network', async () => {
11
+ const pin = network.deployment.provenance?.manifestSha256
12
+ if (!pin) throw new Error('Download the network manifest first')
13
+ const saved = await store.load<string>('network-pin')
14
+ if (saved && saved !== pin) throw new Error('Network changed; preserve the original lesson state and manifest')
15
+ if (!saved) await store.save('network-pin', pin)
16
+ })
17
+
18
+ export async function savedSlotId() {
19
+ const slotId = await store.load<`0x${string}`>('slot-id')
20
+ if (!slotId) throw new Error('Complete the create-slot lesson first')
21
+ return slotId
22
+ }
23
+
24
+ export async function savedCreator() {
25
+ const privateKey = await store.load<`0x${string}`>('creator-key')
26
+ if (!privateKey) throw new Error('Complete the create-slot lesson first')
27
+ return tasra.wallets.create({privateKey})
28
+ }
@@ -0,0 +1,25 @@
1
+ import {store, tasra} from './learning-context.js'
2
+
3
+ // Save fresh keys before the first network write; later runs reuse them.
4
+ await store.withLock('lesson', async () => {
5
+ const creator = tasra.wallets.create({privateKey: await store.load<`0x${string}`>('creator-key')})
6
+ await store.save('creator-key', creator.exportPrivateKey())
7
+ console.log('Creator address:', creator.address)
8
+ if (await tasra.chain.client.getBalance({address: creator.address}) === 0n) {
9
+ console.log('Fund this creator address with AVAX on the selected network, then run again.')
10
+ return
11
+ }
12
+
13
+ const issuer = tasra.identities.create({seed: await store.load<Uint8Array>('issuer-key')})
14
+ await store.save('issuer-key', issuer.exportPrivateKey())
15
+ const policy = tasra.credentials.policy({issuer, type: 'urn:my-app:member'})
16
+
17
+ // One named signing slot, ready for later document-signing lessons.
18
+ const slot = await tasra.slots.create({
19
+ name: 'first-document-signer', mode: 'frost', policy,
20
+ threshold: {k: 2, n: 3}, verifiers: {committee: 3, quorum: 2},
21
+ }, {wallet: creator, onProgress: ({step, phase}) => console.log('Slot creation:', step, phase)})
22
+ await store.save('slot-id', slot.slotId)
23
+ console.log('Slot ready:', slot.slotId)
24
+ console.log('Before signing: buy TSRA with EURC and fund this slot. Follow node_modules/@t3foundry/tasra-sdk/docs/funding.md.')
25
+ })
@@ -0,0 +1,8 @@
1
+ import {savedSlotId, tasra} from './learning-context.js'
2
+
3
+ const slotId = await savedSlotId()
4
+ const slot = await tasra.slots.get(slotId)
5
+ console.log('Slot:', slot.slotId)
6
+ console.log('Key ready:', slot.ready)
7
+ console.log('Key epoch:', slot.epoch)
8
+ console.log('Threshold:', slot.threshold)
@@ -0,0 +1,12 @@
1
+ import {createTasraWriteClient} from '@t3foundry/tasra-sdk/chain'
2
+ import {savedCreator, savedSlotId, tasra} from './learning-context.js'
3
+
4
+ const slotId = await savedSlotId()
5
+ const creator = await savedCreator()
6
+ const lifecycle = createTasraWriteClient({...tasra.deployment, wallet: creator.wallet})
7
+ const before = await tasra.chain.readers.keyRegistry.getKeySlot(slotId)
8
+ const transaction = await lifecycle.renewSlot(slotId)
9
+ const after = await tasra.chain.readers.keyRegistry.getKeySlot(slotId)
10
+ console.log('Confirmed transaction:', transaction)
11
+ console.log('Previous lease expiry:', before.expiry)
12
+ console.log('Current lease expiry:', after.expiry)
@@ -0,0 +1,8 @@
1
+ import {authorize} from './learning-authorize.js'
2
+ import {savedSlotId, tasra} from './learning-context.js'
3
+
4
+ const signer = await tasra.slots.frost(await savedSlotId())
5
+ const message = new TextEncoder().encode('I approve this first TASRA example.')
6
+ const result = await signer.sign(message, {authorize})
7
+ console.log('Signature verified:', result.signature)
8
+ console.log('Key epoch:', result.epoch)
@@ -0,0 +1,71 @@
1
+ // Node example utilities, not part of the SDK's public API.
2
+ import {readFileSync} from 'node:fs'
3
+ import {ed25519DidKey, hexToBytes, type HolderSigner} from '@t3foundry/tasra-sdk'
4
+ import {
5
+ addressBookFromManifest, createTasraChainClient, parsePinnedNetworkManifest,
6
+ observeNetworkManifest, resolveSlotKeeperUrls, nodeApi,
7
+ createCommitteeSlotClient, type TasraChainClient,
8
+ } from '@t3foundry/tasra-sdk/chain'
9
+ import {ed25519ClientSigner, holderProofPerVerifier} from '@t3foundry/tasra-sdk/committee'
10
+
11
+ export function required(name: string, env: NodeJS.ProcessEnv = process.env): string {
12
+ const value = env[name]?.trim()
13
+ if (!value) throw new Error(`Missing ${name}. See docs/prerequisites.md and https://github.com/t3foundry/tasra-releases for Fuji deployment records.`)
14
+ return value
15
+ }
16
+
17
+ export function slotId(name = 'KK_SLOT_ID'): `0x${string}` {
18
+ const value = required(name)
19
+ if (!/^0x[0-9a-fA-F]{64}$/.test(value)) throw new Error(`${name} must be a 0x-prefixed bytes32`)
20
+ return value as `0x${string}`
21
+ }
22
+
23
+ export async function loadNetwork() {
24
+ const digest = required('KK_MANIFEST_SHA256')
25
+ const manifest = parsePinnedNetworkManifest(readFileSync(required('KK_MANIFEST_FILE'), 'utf8'), digest)
26
+ const addresses = addressBookFromManifest(manifest)
27
+ const rpcUrl = required('KK_RPC_URL')
28
+ const observation = await observeNetworkManifest(manifest, rpcUrl)
29
+ if (!observation.matches) throw new Error('Deployment code does not match the pinned manifest')
30
+ return {manifest, digest, rpcUrl, addresses,
31
+ chain: createTasraChainClient({rpcUrl, addresses, chainId: manifest.chainId})}
32
+ }
33
+
34
+ export function loadHolder(prefix = 'KK') {
35
+ const secretKey = hexToBytes(readFileSync(required(`${prefix}_HOLDER_KEY_FILE`), 'utf8').trim())
36
+ try {
37
+ if (secretKey.length !== 32) throw new Error('Holder key must contain exactly 32 bytes of hex')
38
+ const credentials: unknown = JSON.parse(readFileSync(required(`${prefix}_CREDENTIALS_FILE`), 'utf8'))
39
+ if (!Array.isArray(credentials) || !credentials.length || !credentials.every(v => typeof v === 'string' && v.length > 0)) {
40
+ throw new Error('Credentials file must be a nonempty JSON array of compact-JWS credentials')
41
+ }
42
+ const holder = ed25519DidKey(ed25519ClientSigner(secretKey).publicKey)
43
+ const signer: HolderSigner = {alg: 'EdDSA', did: holder, secretKey}
44
+ return {holder, signer, secretKey, credentials: credentials as string[]}
45
+ } catch (error) {
46
+ secretKey.fill(0)
47
+ throw error
48
+ }
49
+ }
50
+
51
+ export function committeeClient(chain: TasraChainClient, slot: string, identity: ReturnType<typeof loadHolder>, action: 'sign' | 'decrypt') {
52
+ return createCommitteeSlotClient({chain, holder: identity.holder, credentials: identity.credentials,
53
+ clientSigner: ed25519ClientSigner(identity.secretKey),
54
+ holderProof: holderProofPerVerifier({signer: identity.signer, credentials: identity.credentials,
55
+ audience: required('KK_VERIFIER_AUDIENCE'), slotId: slot, action}),
56
+ })
57
+ }
58
+
59
+ export async function decryptPeers(chain: TasraChainClient, slot: `0x${string}`) {
60
+ const urls = await resolveSlotKeeperUrls(chain, slot)
61
+ if (!urls.length) throw new Error('Slot has no assigned keeper endpoints')
62
+ const peers = await Promise.all(urls.map(async url => {
63
+ const info = await nodeApi.info(url)
64
+ if (!Number.isSafeInteger(info.node_identifier) || Number(info.node_identifier) <= 0 || !info.peer_id) {
65
+ throw new Error('Keeper did not publish its BLS identifier and peer ID')
66
+ }
67
+ return {id: info.node_identifier!, peerId: info.peer_id}
68
+ }))
69
+ if (new Set(peers.map(p => p.id)).size !== peers.length) throw new Error('Duplicate BLS identifiers')
70
+ return peers.sort((a, b) => a.id - b.id)
71
+ }
@@ -0,0 +1,6 @@
1
+ // No deployment needed. These public demo keys must never protect real data.
2
+ import {offlineRoundTrip} from './offline.ts'
3
+
4
+ const message = offlineRoundTrip()
5
+ if (message !== 'Hello Tasra') throw new Error('Offline round trip failed')
6
+ console.log(message)
@@ -0,0 +1,57 @@
1
+ /** Two distinct people approve one threshold signature; duplicate and replay checks follow. */
2
+ import {setApprovalPolicy, identityApprover, type ReadySlotJournal} from '@t3foundry/tasra-sdk/app'
3
+ import {dualSignApprovalPayload} from '@t3foundry/tasra-sdk/committee'
4
+ import {createTutorial, stopped} from './tutorial-support.js'
5
+ const hex = (bytes: Uint8Array) => `0x${Buffer.from(bytes).toString('hex')}` as `0x${string}`
6
+
7
+ async function main() {
8
+ // 1. Fresh local development identities and a manifest-based client.
9
+ const {tasra, awaitUsageCredit, wallet, users, store, directory, save, policy: accessPolicy} =
10
+ await createTutorial('native-approvals', 'DocumentSigner', 'document-signer')
11
+ const policy = accessPolicy(['alice', 'bob'])
12
+ // 2. Create and provision a FROST slot through the SDK.
13
+ const slot = await tasra.slots.create({name: 'document-approvals', mode: 'frost', policy,
14
+ threshold: {k: 2, n: 3}, verifiers: {committee: 3, quorum: 2}})
15
+ await awaitUsageCredit(slot.slotId)
16
+ const creation = (await store.load<ReadySlotJournal>('slot-document-approvals'))!.creation.result!
17
+ const {commitTx, revealTx, targetEpoch, seeded} = creation
18
+ // 3. Two distinct identity keys must approve the same invoice request.
19
+ const signers = [identityApprover(users.alice!.identity), identityApprover(users.bob!.identity)]
20
+ const policyTransaction = await setApprovalPolicy(tasra, slot.slotId, {quorum: 2, approvers: signers.map(s => s.publicKey)}, {wallet, store})
21
+ // Allow the network's event watchers to observe the confirmed policy.
22
+ await new Promise(resolve => setTimeout(resolve, 4000))
23
+ const approvals = await slot.approvals({quorum: 2, credentialGated: false})
24
+ const message = new TextEncoder().encode('Approve synthetic invoice 42, version 1'), request = await approvals.create(message)
25
+ save('request.json', {requestId: request.requestId, coordinator: request.nodeUrl, slotId: slot.slotId, message: hex(message), quorum: 2})
26
+ const first = await request.approve({signer: signers[0]!})
27
+ if (first.status !== 'pending' || first.have !== 1) throw new Error('First approver did not leave request pending')
28
+ try { await request.approve({signer: signers[0]!}) } catch (error) {
29
+ if (!(error instanceof Error) || !('status' in error) || ![400, 403, 409].includes(Number(error.status))) throw error
30
+ }
31
+ const duplicate = await request.status()
32
+ if (duplicate.status !== 'pending' || duplicate.have !== 1) throw new Error('Duplicate approver changed quorum')
33
+ await request.approve({signer: signers[1]!})
34
+ const result = await request.wait({timeoutMs: 120_000})
35
+
36
+ // 4. A protocol negative check replays the first approval against a new request.
37
+ const next = await approvals.create(message)
38
+ const replay = await fetch(`${next.nodeUrl}/v1/dual-sign/${next.requestId}/approve`, {method: 'POST', headers: {'content-type': 'application/json'},
39
+ body: JSON.stringify({approver_pubkey: hex(signers[0]!.publicKey), signature: hex(await signers[0]!.sign(dualSignApprovalPayload(slot.slotId, message, request.requestId)))})})
40
+ if (![400, 403].includes(replay.status)) throw new Error('Cross-request approval replay was not refused')
41
+ const afterReplay = await next.status()
42
+ if (afterReplay.status !== 'pending' || afterReplay.have !== 0) throw new Error('Replay added a vote')
43
+ let changedRejected = false
44
+ try { await approvals.resume(next.requestId, new Uint8Array([1])).status() } catch (error) {
45
+ if (error instanceof Error && /message or slot/.test(error.message)) changedRejected = true; else throw error
46
+ }
47
+ if (!changedRejected) throw new Error('Changed message accepted')
48
+ const evidence = {chainId: tasra.deployment.chainId, addresses: tasra.deployment.addresses, createdAt: new Date().toISOString(), slotId: slot.slotId,
49
+ creation: {slotId: slot.slotId, commitTx, revealTx, targetEpoch, seeded}, policyHash: policyTransaction.hash,
50
+ requestId: request.requestId, quorum: 2, duplicateHave: duplicate.have, replayHttpStatus: replay.status, replayHave: afterReplay.have,
51
+ changedMessageRejected: changedRejected, verifiedSignature: {r: hex(result.signature.r), z: hex(result.signature.z), groupPublicKey: hex(result.groupPublicKey)},
52
+ mode: 'static-approver-keys', receipt: result.receipt ? 'present-unverified' : 'absent'}
53
+ save('evidence.json', evidence)
54
+ console.log(`PASS: two distinct approvals, duplicate vote prevented, replay refused. Evidence: ${directory}/evidence.json`)
55
+ }
56
+
57
+ main().catch(stopped)
@@ -0,0 +1,58 @@
1
+ /** Download and validate the public testnet manifest used by these examples. */
2
+ import {readFileSync, writeFileSync} from 'node:fs'
3
+ import {resolve} from 'node:path'
4
+ import {fileURLToPath} from 'node:url'
5
+ import {parsePinnedNetworkManifest} from '@t3foundry/tasra-sdk/chain'
6
+ import {resolveApplicationManifest} from '@t3foundry/tasra-sdk/app'
7
+
8
+ const base = 'https://raw.githubusercontent.com/t3foundry/tasra-releases/main/networks/testnet/'
9
+ type Pin = {sha256: string; manifestUrl: string}
10
+
11
+ /** Fetch the pointer and its checksum-verified manifest, then save the original bytes. */
12
+ export async function downloadNetwork(fetchImpl: typeof fetch = fetch, directory = '.') {
13
+ const download = async (url: string) => {
14
+ const response = await fetchImpl(url, {signal: AbortSignal.timeout(15_000), redirect: 'error'})
15
+ if (!response.ok) throw new Error(`Network manifest download failed: HTTP ${response.status}`)
16
+ return response.text()
17
+ }
18
+ const pointer = JSON.parse(await download(base + 'current.json')) as Record<string, unknown>
19
+ if (pointer.schemaVersion !== 1 || pointer.network !== 'testnet' || pointer.chainId !== 43113 ||
20
+ pointer.status !== 'active' || typeof pointer.manifest !== 'string' ||
21
+ !/^deployments\/[a-z0-9.-]+\.json$/.test(pointer.manifest) ||
22
+ typeof pointer.sha256 !== 'string' || !/^[a-f0-9]{64}$/.test(pointer.sha256)) {
23
+ throw new Error('Expected an active testnet pointer with a manifest path and SHA-256')
24
+ }
25
+ const pin = {sha256: pointer.sha256, manifestUrl: base + pointer.manifest}
26
+ const text = await download(pin.manifestUrl)
27
+ checkedManifest(text, pin)
28
+ writeFileSync(resolve(directory, 'network.json'), text)
29
+ writeFileSync(resolve(directory, 'network-pin.json'), JSON.stringify(pin, null, 2) + '\n')
30
+ }
31
+
32
+ function checkedManifest(text: string, pin: Pin) {
33
+ if (!pin || typeof pin.sha256 !== 'string' || typeof pin.manifestUrl !== 'string' ||
34
+ !pin.manifestUrl.startsWith(base + 'deployments/')) throw new Error('Invalid downloaded manifest pin')
35
+ const manifest = parsePinnedNetworkManifest(text, pin.sha256)
36
+ if (manifest.network !== 'testnet' || manifest.chainId !== 43113 || manifest.status !== 'active') {
37
+ throw new Error('Expected an active testnet manifest')
38
+ }
39
+ return manifest
40
+ }
41
+
42
+ /** Read the saved manifest and verify its bytes before configuring any client. */
43
+ export function loadNetwork(directory = '.') {
44
+ const text = readFileSync(resolve(directory, 'network.json'), 'utf8')
45
+ const pin = JSON.parse(readFileSync(resolve(directory, 'network-pin.json'), 'utf8')) as Pin
46
+ const manifest = checkedManifest(text, pin)
47
+ // Coordinator selection is an explicit application setting, absent from the manifest schema.
48
+ const resolved = resolveApplicationManifest(manifest, {coordinator: 'lowest-operator-id'})
49
+ resolved.deployment = {...resolved.deployment, provenance: {
50
+ networkRevision: `${manifest.deploymentId}@${manifest.revision}`, manifestSha256: pin.sha256,
51
+ }}
52
+ return resolved
53
+ }
54
+
55
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
56
+ await downloadNetwork()
57
+ console.log('Saved checksum-verified network.json and network-pin.json from tasra-releases.')
58
+ }
@@ -0,0 +1,16 @@
1
+ import {encryptEnvelope, decryptWithMasterKey, hexToBytes} from '@t3foundry/tasra-sdk'
2
+
3
+ /** Public, fixed DEMO keys. Never encrypt a real secret with these. */
4
+ export function offlineRoundTrip(): string {
5
+ const msk = new Uint8Array(32)
6
+ msk[0] = 1
7
+ const mpk = hexToBytes('93e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8')
8
+ const identity = new TextEncoder().encode('demo')
9
+ try {
10
+ const envelope = encryptEnvelope(new Uint8Array(32), mpk, identity,
11
+ new TextEncoder().encode('Hello Tasra'), 0n)
12
+ return new TextDecoder().decode(decryptWithMasterKey(msk, envelope.ciphertext, identity))
13
+ } finally {
14
+ msk.fill(0)
15
+ }
16
+ }