@t3foundry/tasra-sdk 0.3.1 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/CHANGELOG.md +1067 -28
  2. package/README.md +15 -0
  3. package/dist/app/approvals.d.ts +66 -4
  4. package/dist/app/approvals.js +153 -16
  5. package/dist/app/authorization.d.ts +1 -1
  6. package/dist/app/authorization.js +1 -1
  7. package/dist/app/browser.d.ts +63 -0
  8. package/dist/app/browser.js +242 -0
  9. package/dist/app/client.d.ts +114 -13
  10. package/dist/app/client.js +302 -76
  11. package/dist/app/identity.js +21 -9
  12. package/dist/app/index.d.ts +28 -3
  13. package/dist/app/index.js +16 -1
  14. package/dist/app/memory-store.d.ts +7 -0
  15. package/dist/app/memory-store.js +55 -0
  16. package/dist/app/node.d.ts +34 -6
  17. package/dist/app/node.js +387 -64
  18. package/dist/app/paid-allowance.d.ts +325 -0
  19. package/dist/app/paid-allowance.js +1290 -0
  20. package/dist/app/paid-approval.d.ts +122 -0
  21. package/dist/app/paid-approval.js +379 -0
  22. package/dist/app/paid-journal.d.ts +51 -0
  23. package/dist/app/paid-journal.js +117 -0
  24. package/dist/app/paid-keys.d.ts +12 -0
  25. package/dist/app/paid-keys.js +20 -0
  26. package/dist/app/paid-operation.d.ts +821 -0
  27. package/dist/app/paid-operation.js +1720 -0
  28. package/dist/app/paid-reservation.d.ts +157 -0
  29. package/dist/app/paid-reservation.js +323 -0
  30. package/dist/app/paid-session.d.ts +147 -0
  31. package/dist/app/paid-session.js +578 -0
  32. package/dist/app/payer-queue.d.ts +11 -0
  33. package/dist/app/payer-queue.js +27 -0
  34. package/dist/app/policy-bootstrap.d.ts +342 -0
  35. package/dist/app/policy-bootstrap.js +365 -0
  36. package/dist/app/policy-operation.d.ts +47 -0
  37. package/dist/app/policy-operation.js +101 -0
  38. package/dist/app/ready-slot.d.ts +12 -0
  39. package/dist/app/ready-slot.js +5 -2
  40. package/dist/app/rotation-lock.d.ts +38 -0
  41. package/dist/app/rotation-lock.js +42 -0
  42. package/dist/app/session-decrypt.d.ts +135 -0
  43. package/dist/app/session-decrypt.js +335 -0
  44. package/dist/app/session-grants.d.ts +349 -0
  45. package/dist/app/session-grants.js +811 -0
  46. package/dist/app/signing-intents.d.ts +78 -0
  47. package/dist/app/signing-intents.js +95 -0
  48. package/dist/app/store-commit.d.ts +63 -0
  49. package/dist/app/store-commit.js +126 -0
  50. package/dist/app/store-errors.d.ts +8 -0
  51. package/dist/app/store-errors.js +11 -0
  52. package/dist/app/tasra-client.d.ts +2 -0
  53. package/dist/app/tasra-client.js +1 -1
  54. package/dist/app/wallet.js +4 -1
  55. package/dist/auth/holderProof.d.ts +3 -0
  56. package/dist/auth/holderProof.js +8 -7
  57. package/dist/auth/verifier.d.ts +4 -2
  58. package/dist/auth/verifier.js +5 -2
  59. package/dist/chain/abis/index.d.ts +6178 -4101
  60. package/dist/chain/abis/index.js +3 -0
  61. package/dist/chain/abis/keyRegistry.d.ts +256 -0
  62. package/dist/chain/abis/keyRegistry.js +333 -0
  63. package/dist/chain/abis/prepaidFaultOracle.d.ts +321 -0
  64. package/dist/chain/abis/prepaidFaultOracle.js +413 -0
  65. package/dist/chain/abis/settlement.d.ts +2203 -703
  66. package/dist/chain/abis/settlement.js +2685 -764
  67. package/dist/chain/allowance.d.ts +358 -0
  68. package/dist/chain/allowance.js +800 -0
  69. package/dist/chain/billing.d.ts +85 -0
  70. package/dist/chain/billing.js +197 -0
  71. package/dist/chain/chainId.d.ts +13 -0
  72. package/dist/chain/chainId.js +26 -0
  73. package/dist/chain/client.d.ts +15 -1
  74. package/dist/chain/client.js +57 -1
  75. package/dist/chain/commitmentRecovery.d.ts +51 -0
  76. package/dist/chain/commitmentRecovery.js +38 -0
  77. package/dist/chain/committeeClient.d.ts +17 -10
  78. package/dist/chain/committeeClient.js +64 -16
  79. package/dist/chain/committeeDraw.d.ts +12 -0
  80. package/dist/chain/committeeDraw.js +56 -0
  81. package/dist/chain/custodyHealth.d.ts +212 -0
  82. package/dist/chain/custodyHealth.js +365 -0
  83. package/dist/chain/deployments.js +2 -0
  84. package/dist/chain/events.js +2 -0
  85. package/dist/chain/headFollower.d.ts +77 -0
  86. package/dist/chain/headFollower.js +219 -0
  87. package/dist/chain/headPrefetch.d.ts +23 -0
  88. package/dist/chain/headPrefetch.js +67 -0
  89. package/dist/chain/index.d.ts +50 -8
  90. package/dist/chain/index.js +28 -3
  91. package/dist/chain/keeperExecution.d.ts +44 -0
  92. package/dist/chain/keeperExecution.js +127 -0
  93. package/dist/chain/keeperRecovery.d.ts +78 -0
  94. package/dist/chain/keeperRecovery.js +91 -0
  95. package/dist/chain/node.d.ts +24 -1
  96. package/dist/chain/node.js +88 -43
  97. package/dist/chain/offchain.d.ts +2 -0
  98. package/dist/chain/paidAgentTransport.d.ts +38 -0
  99. package/dist/chain/paidAgentTransport.js +1 -0
  100. package/dist/chain/paidEpoch.d.ts +66 -0
  101. package/dist/chain/paidEpoch.js +139 -0
  102. package/dist/chain/paidPacing.d.ts +81 -0
  103. package/dist/chain/paidPacing.js +136 -0
  104. package/dist/chain/pinnedReads.d.ts +49 -0
  105. package/dist/chain/pinnedReads.js +218 -0
  106. package/dist/chain/prepaid.d.ts +383 -0
  107. package/dist/chain/prepaid.js +1046 -0
  108. package/dist/chain/prepaidEscape.d.ts +274 -0
  109. package/dist/chain/prepaidEscape.js +432 -0
  110. package/dist/chain/prepaidFault.d.ts +94 -0
  111. package/dist/chain/prepaidFault.js +148 -0
  112. package/dist/chain/receipt.d.ts +24 -0
  113. package/dist/chain/receipt.js +82 -0
  114. package/dist/chain/registeredAgent.d.ts +68 -3
  115. package/dist/chain/registeredAgent.js +143 -42
  116. package/dist/chain/registeredOperation.d.ts +10 -1
  117. package/dist/chain/registeredOperation.js +18 -3
  118. package/dist/chain/registeredPaidAgent.d.ts +254 -0
  119. package/dist/chain/registeredPaidAgent.js +889 -0
  120. package/dist/chain/registeredRelay.d.ts +31 -1
  121. package/dist/chain/registeredRelay.js +164 -43
  122. package/dist/chain/relayVoucher.d.ts +64 -0
  123. package/dist/chain/relayVoucher.js +69 -0
  124. package/dist/chain/reservation.d.ts +239 -0
  125. package/dist/chain/reservation.js +746 -0
  126. package/dist/chain/reshareRoster.d.ts +64 -0
  127. package/dist/chain/reshareRoster.js +85 -0
  128. package/dist/chain/revertReason.d.ts +8 -0
  129. package/dist/chain/revertReason.js +2 -1
  130. package/dist/chain/rotationLock.d.ts +130 -0
  131. package/dist/chain/rotationLock.js +168 -0
  132. package/dist/chain/serviceRequestPolicy.d.ts +47 -0
  133. package/dist/chain/serviceRequestPolicy.js +86 -0
  134. package/dist/chain/services.d.ts +7 -0
  135. package/dist/chain/services.js +44 -4
  136. package/dist/chain/slotClient.js +11 -2
  137. package/dist/chain/slotHandoff.d.ts +81 -0
  138. package/dist/chain/slotHandoff.js +166 -0
  139. package/dist/chain/slotSeed.d.ts +47 -5
  140. package/dist/chain/slotSeed.js +173 -42
  141. package/dist/chain/verifierSnapshot.d.ts +36 -0
  142. package/dist/chain/verifierSnapshot.js +197 -0
  143. package/dist/chain/write.d.ts +111 -21
  144. package/dist/chain/write.js +378 -146
  145. package/dist/committee/blsSharing.d.ts +53 -0
  146. package/dist/committee/blsSharing.js +90 -0
  147. package/dist/committee/client.d.ts +62 -23
  148. package/dist/committee/client.js +288 -72
  149. package/dist/committee/dual-operation.d.ts +165 -0
  150. package/dist/committee/dual-operation.js +229 -0
  151. package/dist/committee/dual-sign.d.ts +26 -1
  152. package/dist/committee/dual-sign.js +85 -7
  153. package/dist/committee/ecdsa.d.ts +38 -0
  154. package/dist/committee/ecdsa.js +87 -15
  155. package/dist/committee/evidence.d.ts +30 -0
  156. package/dist/committee/evidence.js +65 -0
  157. package/dist/committee/execution.d.ts +414 -0
  158. package/dist/committee/execution.js +446 -0
  159. package/dist/committee/extraction.js +33 -26
  160. package/dist/committee/index.d.ts +30 -7
  161. package/dist/committee/index.js +18 -6
  162. package/dist/committee/keeperExecution.d.ts +37 -0
  163. package/dist/committee/keeperExecution.js +141 -0
  164. package/dist/committee/oauth.d.ts +14 -4
  165. package/dist/committee/oauth.js +17 -5
  166. package/dist/committee/payment.d.ts +369 -0
  167. package/dist/committee/payment.js +339 -0
  168. package/dist/committee/recovery.d.ts +136 -0
  169. package/dist/committee/recovery.js +204 -0
  170. package/dist/committee/recoveryJson.d.ts +2 -0
  171. package/dist/committee/recoveryJson.js +87 -0
  172. package/dist/committee/request.d.ts +63 -27
  173. package/dist/committee/request.js +77 -66
  174. package/dist/committee/session-grant.d.ts +320 -0
  175. package/dist/committee/session-grant.js +397 -0
  176. package/dist/committee/status-refresh.d.ts +257 -0
  177. package/dist/committee/status-refresh.js +619 -0
  178. package/dist/committee/token.d.ts +163 -15
  179. package/dist/committee/token.js +247 -10
  180. package/dist/crypto/bn254.d.ts +70 -0
  181. package/dist/crypto/bn254.js +222 -0
  182. package/dist/crypto/ibe.d.ts +32 -0
  183. package/dist/crypto/ibe.js +56 -8
  184. package/dist/crypto/index.d.ts +1 -1
  185. package/dist/crypto/index.js +1 -1
  186. package/dist/crypto/kem.d.ts +31 -0
  187. package/dist/crypto/kem.js +113 -7
  188. package/dist/crypto/recipient.d.ts +75 -0
  189. package/dist/crypto/recipient.js +107 -0
  190. package/dist/decryption/client.d.ts +10 -16
  191. package/dist/decryption/client.js +8 -76
  192. package/dist/decryption/index.d.ts +2 -0
  193. package/dist/decryption/index.js +2 -0
  194. package/dist/decryption/sealed.d.ts +72 -0
  195. package/dist/decryption/sealed.js +147 -0
  196. package/dist/decryption/session.d.ts +115 -0
  197. package/dist/decryption/session.js +358 -0
  198. package/dist/errors.d.ts +406 -1
  199. package/dist/errors.js +400 -5
  200. package/dist/index.d.ts +9 -2
  201. package/dist/index.js +6 -1
  202. package/dist/internal/bounded.d.ts +66 -0
  203. package/dist/internal/bounded.js +126 -0
  204. package/dist/internal/network.d.ts +4 -0
  205. package/dist/internal/network.js +40 -0
  206. package/dist/internal/retryAfter.d.ts +8 -0
  207. package/dist/internal/retryAfter.js +28 -0
  208. package/dist/internal/sleep.d.ts +6 -0
  209. package/dist/internal/sleep.js +15 -0
  210. package/dist/internal/typedData.d.ts +13 -0
  211. package/dist/internal/typedData.js +77 -0
  212. package/dist/internal/viemErrors.d.ts +26 -0
  213. package/dist/internal/viemErrors.js +49 -0
  214. package/dist/oid4vp/binding.d.ts +27 -1
  215. package/dist/oid4vp/binding.js +36 -1
  216. package/dist/oid4vp/jose.d.ts +4 -2
  217. package/dist/oid4vp/jose.js +39 -7
  218. package/dist/oid4vp/request-object.d.ts +61 -4
  219. package/dist/oid4vp/request-object.js +140 -5
  220. package/dist/oid4vp/verifier-agent.d.ts +18 -8
  221. package/dist/oid4vp/verifier-agent.js +48 -6
  222. package/dist/oid4vp/wallet.d.ts +2 -4
  223. package/dist/oid4vp/wallet.js +1 -0
  224. package/dist/retry.d.ts +78 -0
  225. package/dist/retry.js +137 -0
  226. package/dist/signing/frost.d.ts +1 -1
  227. package/dist/verifier-agent/index.d.ts +41 -5
  228. package/dist/verifier-agent/index.js +124 -9
  229. package/dist/verifier-agent/payment.d.ts +7 -0
  230. package/dist/verifier-agent/payment.js +17 -0
  231. package/docs/api.md +8 -2
  232. package/docs/application-api.md +25 -2
  233. package/docs/chain.md +155 -9
  234. package/docs/consumer-migrations.md +61 -0
  235. package/docs/encrypted-notes.md +3 -2
  236. package/docs/encryption.md +4 -2
  237. package/docs/errors.md +14 -1
  238. package/docs/flows.md +2 -2
  239. package/docs/funding.md +902 -0
  240. package/docs/native-approvals.md +63 -0
  241. package/docs/reference/README.md +9 -8
  242. package/docs/reference/app-browser.md +232 -0
  243. package/docs/reference/app-node.md +38 -8
  244. package/docs/reference/app.md +4621 -805
  245. package/docs/reference/chain-node.md +74 -16
  246. package/docs/reference/chain.md +6740 -1592
  247. package/docs/reference/committee.md +5630 -987
  248. package/docs/reference/main.md +1439 -140
  249. package/docs/reference/oid4vp.md +297 -144
  250. package/docs/reference/verifier-agent.md +77 -35
  251. package/docs/signing.md +6 -0
  252. package/examples/encrypted-notes.ts +21 -6
  253. package/examples/getting-started.ts +2 -7
  254. package/examples/live-config.ts +24 -17
  255. package/package.json +17 -5
@@ -0,0 +1,78 @@
1
+ import { type TransactionSerializable, type TypedDataDefinition } from 'viem';
2
+ import { type DualOperationApprovalRecord, type DualOperationApprover, type PreparedDualOperation } from '../committee/dual-operation.js';
3
+ import type { CompoundTokenWire } from '../committee/token.js';
4
+ import type { VerifierProof } from '../committee/client.js';
5
+ import { type PaymentIntentWire } from '../committee/payment.js';
6
+ /** Largest serialized transaction, typed-data document or message an intent may carry, in bytes. */
7
+ export declare const SIGNING_INTENT_MAX_BYTES = 65536;
8
+ /** An EIP-155 or typed transaction; the digest is keccak256 of its unsigned serialization. */
9
+ export interface TransactionSigningIntent {
10
+ /** Intent kind. */
11
+ kind: 'transaction';
12
+ /** The transaction; it must name its `chainId`. */
13
+ transaction: TransactionSerializable;
14
+ }
15
+ /** EIP-712 typed data; the digest is its EIP-712 hash. */
16
+ export interface TypedDataSigningIntent {
17
+ /** Intent kind. */
18
+ kind: 'typed-data';
19
+ /** The typed data; its domain must name a `chainId`. */
20
+ typedData: TypedDataDefinition;
21
+ }
22
+ /** An EIP-191 personal message; the digest is its `personal_sign` hash. */
23
+ export interface MessageSigningIntent {
24
+ /** Intent kind. */
25
+ kind: 'message';
26
+ /** The message text or bytes, at most 64 KiB. */
27
+ message: string | Uint8Array;
28
+ }
29
+ /** What a secp256k1 slot signs, from which the SDK derives the Ethereum digest itself. */
30
+ export type EthereumSigningIntent = TransactionSigningIntent | TypedDataSigningIntent | MessageSigningIntent;
31
+ /** What a P-256 slot signs: the SHA-256 of exactly these bytes. */
32
+ export interface P256SigningIntent {
33
+ /** Intent kind. */
34
+ kind: 'sha256';
35
+ /** The bytes, at most 64 KiB. */
36
+ data: Uint8Array;
37
+ }
38
+ /** Either curve's structured intent. */
39
+ export type SigningIntent = EthereumSigningIntent | P256SigningIntent;
40
+ /**
41
+ * The 32-byte digest a slot signs for a structured intent. A transaction and typed data must name
42
+ * a chain, and that chain must be `expectChainId` when given; every input is size-bounded.
43
+ * @param intent Structured intent.
44
+ * @param options Chain the transaction or typed data must name.
45
+ */
46
+ export declare function signingIntentDigest(intent: SigningIntent, options?: {
47
+ expectChainId?: number;
48
+ }): Uint8Array;
49
+ /**
50
+ * The curve an intent belongs to.
51
+ * @param intent Structured intent.
52
+ */
53
+ export declare function signingIntentCurve(intent: SigningIntent): 'secp256k1' | 'p256';
54
+ /**
55
+ * Check that a final `eoa-sign` payment pays for exactly this intent (its payload digest is the
56
+ * SHA-256 of the intent's digest). Returns the digest.
57
+ * @param payment The final payment intent.
58
+ * @param intent Structured intent.
59
+ */
60
+ export declare function requireIntentPayment(payment: PaymentIntentWire, intent: SigningIntent): Uint8Array;
61
+ /**
62
+ * An approver's side of a native approval for a structured intent: recompute the digest from the
63
+ * intent it reviewed, check the final payment pays for exactly it and the statement names it,
64
+ * then sign the statement. Refuses before signing on any difference.
65
+ * @param input Prepared statement, final payment, the reviewed intent, the approver and its optional holder-bound grant.
66
+ */
67
+ export declare function approveSigningIntent(input: {
68
+ prepared: PreparedDualOperation;
69
+ payment: PaymentIntentWire;
70
+ intent: SigningIntent;
71
+ approver: DualOperationApprover;
72
+ authorization?: {
73
+ compound_token: CompoundTokenWire;
74
+ verifier_proofs: VerifierProof[];
75
+ evidence_ct?: string;
76
+ };
77
+ nowSecs?: number;
78
+ }): Promise<DualOperationApprovalRecord>;
@@ -0,0 +1,95 @@
1
+ // Structured signing intents for threshold ECDSA slots: the SDK builds the 32-byte digest from a
2
+ // transaction, EIP-712 typed data, a personal message or (P-256) the exact bytes, so callers,
3
+ // approvers and the keeper request all derive the digest from the same reviewed input instead of
4
+ // passing an opaque one around.
5
+ import { sha256 } from '@noble/hashes/sha256';
6
+ import { hashMessage, hashTypedData, hexToBytes, keccak256, serializeTransaction, toHex } from 'viem';
7
+ import { approveDualOperation } from '../committee/dual-operation.js';
8
+ import { assertPaymentIntentWire } from '../committee/payment.js';
9
+ import { TasraError } from '../errors.js';
10
+ /** Largest serialized transaction, typed-data document or message an intent may carry, in bytes. */
11
+ export const SIGNING_INTENT_MAX_BYTES = 65_536;
12
+ const json = (value) => JSON.stringify(value, (_key, v) => typeof v === 'bigint' ? v.toString() : v);
13
+ function bounded(size, what) {
14
+ if (size > SIGNING_INTENT_MAX_BYTES)
15
+ throw new TasraError(`${what} exceeds ${SIGNING_INTENT_MAX_BYTES} bytes`);
16
+ }
17
+ /**
18
+ * The 32-byte digest a slot signs for a structured intent. A transaction and typed data must name
19
+ * a chain, and that chain must be `expectChainId` when given; every input is size-bounded.
20
+ * @param intent Structured intent.
21
+ * @param options Chain the transaction or typed data must name.
22
+ */
23
+ export function signingIntentDigest(intent, options = {}) {
24
+ const chain = (id, what) => {
25
+ const n = typeof id === 'bigint' ? Number(id) : id;
26
+ if (!Number.isSafeInteger(n) || n <= 0)
27
+ throw new TasraError(`${what} must name its chain`);
28
+ if (options.expectChainId !== undefined && n !== options.expectChainId)
29
+ throw new TasraError(`${what} names chain ${String(n)}, not ${options.expectChainId}`);
30
+ };
31
+ switch (intent?.kind) {
32
+ case 'transaction': {
33
+ chain(intent.transaction?.chainId, 'Transaction');
34
+ const unsigned = serializeTransaction(intent.transaction);
35
+ bounded((unsigned.length - 2) / 2, 'Transaction');
36
+ return hexToBytes(keccak256(unsigned));
37
+ }
38
+ case 'typed-data': {
39
+ chain(intent.typedData?.domain?.chainId, 'Typed data');
40
+ bounded(new TextEncoder().encode(json(intent.typedData)).length, 'Typed data');
41
+ return hexToBytes(hashTypedData(intent.typedData));
42
+ }
43
+ case 'message': {
44
+ const size = typeof intent.message === 'string' ? new TextEncoder().encode(intent.message).length : intent.message?.length;
45
+ if (typeof size !== 'number')
46
+ throw new TasraError('Message must be a string or bytes');
47
+ bounded(size, 'Message');
48
+ return hexToBytes(hashMessage(typeof intent.message === 'string' ? intent.message : { raw: intent.message }));
49
+ }
50
+ case 'sha256': {
51
+ if (!(intent.data instanceof Uint8Array))
52
+ throw new TasraError('P-256 intent data must be bytes');
53
+ bounded(intent.data.length, 'P-256 intent data');
54
+ return sha256(intent.data);
55
+ }
56
+ default:
57
+ throw new TasraError('Unknown signing intent kind');
58
+ }
59
+ }
60
+ /**
61
+ * The curve an intent belongs to.
62
+ * @param intent Structured intent.
63
+ */
64
+ export function signingIntentCurve(intent) {
65
+ return intent.kind === 'sha256' ? 'p256' : 'secp256k1';
66
+ }
67
+ /**
68
+ * Check that a final `eoa-sign` payment pays for exactly this intent (its payload digest is the
69
+ * SHA-256 of the intent's digest). Returns the digest.
70
+ * @param payment The final payment intent.
71
+ * @param intent Structured intent.
72
+ */
73
+ export function requireIntentPayment(payment, intent) {
74
+ assertPaymentIntentWire(payment);
75
+ // The intent's own chain is where the account acts; the payment's is where the slot lives.
76
+ const digest = signingIntentDigest(intent);
77
+ if (payment.action !== 'eoa-sign' || payment.payload_digest.toLowerCase() !== toHex(sha256(digest)).toLowerCase()) {
78
+ throw new TasraError('Payment does not pay for this signing intent');
79
+ }
80
+ return digest;
81
+ }
82
+ /**
83
+ * An approver's side of a native approval for a structured intent: recompute the digest from the
84
+ * intent it reviewed, check the final payment pays for exactly it and the statement names it,
85
+ * then sign the statement. Refuses before signing on any difference.
86
+ * @param input Prepared statement, final payment, the reviewed intent, the approver and its optional holder-bound grant.
87
+ */
88
+ export async function approveSigningIntent(input) {
89
+ const digest = requireIntentPayment(input.payment, input.intent);
90
+ const operation = signingIntentCurve(input.intent) === 'p256' ? 'p256-sign' : 'secp256k1-sign';
91
+ if (input.prepared?.statement?.operation !== operation)
92
+ throw new TasraError(`Approval statement names ${String(input.prepared?.statement?.operation)}, not ${operation}`);
93
+ return approveDualOperation({ prepared: input.prepared, payment: input.payment, expectSlot: input.payment.slot, expectPayloadDigest: toHex(sha256(digest)),
94
+ approver: input.approver, ...(input.authorization ? { authorization: input.authorization } : {}), ...(input.nowSecs !== undefined ? { nowSecs: input.nowSecs } : {}) });
95
+ }
@@ -0,0 +1,63 @@
1
+ import type { ApplicationStore } from './ready-slot.js';
2
+ /** Writes staged by a {@link withCommit} action, published with the lock's release. */
3
+ export interface LockedCommit {
4
+ /** Publish `value` under `key` when the action returns normally (never when it throws). A later stage of one key replaces an earlier one. */
5
+ stage(key: string, value: unknown): void;
6
+ }
7
+ /** The commit steps a store implements natively (the file store). */
8
+ export interface StoreCommitSteps {
9
+ withCommit<T>(keys: string | readonly string[], action: (commit: LockedCommit) => Promise<T>): Promise<T>;
10
+ saveAll(entries: readonly (readonly [string, unknown])[]): Promise<void>;
11
+ saveRederivable(key: string, value: unknown): Promise<void>;
12
+ /**
13
+ * The durable state this store object is a view of, equal for every store object of this process
14
+ * on the same state with the same behaviour (the file store: its resolved directory and lock
15
+ * wait). In-process coalescing that would otherwise be per store object is shared by all of them:
16
+ * an application that opens one store object per call on one directory still batches its journal
17
+ * commits. Absent, the store object itself is the identity.
18
+ */
19
+ readonly identity?: string;
20
+ }
21
+ /** Where a store carries its native commit steps. */
22
+ export declare const STORE_COMMIT: unique symbol;
23
+ /** What in-process coalescing keys a store by: its native {@link StoreCommitSteps.identity}, else the store object itself. */
24
+ export declare function storeIdentity(store: ApplicationStore): string | ApplicationStore;
25
+ /**
26
+ * Exclusively run `action` under the lock of `keys` (several: all of them, taken in sorted order),
27
+ * then publish what it staged with the release. Without native steps: `withLock` on each key in
28
+ * sorted order, and each staged value saved, in stage order, before the release.
29
+ */
30
+ export declare function withCommit<T>(store: ApplicationStore, keys: string | readonly string[], action: (commit: LockedCommit) => Promise<T>): Promise<T>;
31
+ /** Save every entry durably before resolving; without native steps, one at a time in order. */
32
+ export declare function saveAll(store: ApplicationStore, entries: readonly (readonly [string, unknown])[]): Promise<void>;
33
+ /** Save a value its recovery re-derives; without native steps, an ordinary save. */
34
+ export declare function saveRederivable(store: ApplicationStore, key: string, value: unknown): Promise<void>;
35
+ /**
36
+ * Re-derivable writes of one flow, published with its next durable commit instead of on their own
37
+ * (or by {@link Rederivable.flush} at its end). Only for values the flow's own recovery re-derives
38
+ * from what it reads anyway: a crash may leave each one unwritten.
39
+ *
40
+ * An OWED entry ({@link Rederivable.put} with `owed`) is a confirmation a recovery does NOT
41
+ * re-derive: the `confirmed` of a sent write whose `prepared` is already durable. A crash before it
42
+ * is durable leaves the write `prepared`, which a recovery refuses (never resent; the caller
43
+ * reconciles), so it may ride on a later commit only when that commit follows the send at once: the
44
+ * flow calls {@link Rederivable.flushOwed} before any wait or poll that follows a send.
45
+ * {@link Rederivable.flush} publishes owed entries durably.
46
+ */
47
+ export declare class Rederivable {
48
+ #private;
49
+ /** Write `value` under `key` with the next commit (a later put of one key replaces an earlier one). */
50
+ put(key: string, value: unknown, options?: {
51
+ owed?: boolean;
52
+ }): void;
53
+ /** The value `key` will be published with, or undefined when none is pending (a detached copy). */
54
+ peek<T>(key: string): T | undefined;
55
+ /** The entries for the commit about to run; give them back with {@link Rederivable.restore} if it failed. */
56
+ take(): [string, unknown][];
57
+ /** Return entries a failed commit did not publish (a newer put of a key wins). */
58
+ restore(entries: readonly (readonly [string, unknown])[]): void;
59
+ /** Publish everything pending in one durable commit when any of it is owed; nothing otherwise. */
60
+ flushOwed(store: ApplicationStore): Promise<void>;
61
+ /** Publish whatever is left: each as {@link saveRederivable}, or all in one durable commit when any is owed. */
62
+ flush(store: ApplicationStore): Promise<void>;
63
+ }
@@ -0,0 +1,126 @@
1
+ // Internal durable-commit steps of the SDK's own stores. Not part of the public ApplicationStore
2
+ // contract: an application store without them gets the same calls as before, one save at a time.
3
+ //
4
+ // The paid paths journal several values per transition, and on the Node file store every durable
5
+ // save costs two device flushes (data barrier, directory sync) and every lock three. These steps let
6
+ // one transition pay once:
7
+ //
8
+ // - `withCommit`: a lock whose entry is not flushed on its own, and whose last writes are published
9
+ // with the unlock in ONE commit (their data flushed once, renamed, the lock removed, the
10
+ // directory synced once). The lock is still exclusive across processes at once (O_EXCL). It is
11
+ // durable no later than the first durable write the action makes, because that write's directory
12
+ // sync covers every entry created before it in the same directory. An action that sends anything
13
+ // journals it durably first, so at every external step the lock is exactly as durable as before;
14
+ // before that step it guards nothing a recovery reads. (The browser store's Web Locks are never
15
+ // durable at all, so no recovery path can depend on finding a lock after a crash.)
16
+ // - `saveAll`: several keys in one commit. A crash before it resolves may leave ANY subset of them;
17
+ // each caller states why every subset is safe.
18
+ // - `saveRederivable`: a complete value (flushed before it is renamed into place, never torn) whose
19
+ // directory entry becomes durable with the next directory sync. A crash may leave the previous
20
+ // value; only for values a recovery re-derives from what it reads anyway.
21
+ /** Where a store carries its native commit steps. */
22
+ export const STORE_COMMIT = Symbol.for('@t3foundry/tasra-sdk/store-commit');
23
+ function steps(store) {
24
+ // Only the store object's OWN property counts: an object inheriting from a native store (or
25
+ // spreading one, which the file store prevents by making the property non-enumerable) may
26
+ // override `load`/`save` and is therefore not the state the steps commit to.
27
+ if (!Object.hasOwn(store, STORE_COMMIT))
28
+ return undefined;
29
+ const found = store[STORE_COMMIT];
30
+ return found && typeof found.withCommit === 'function' ? found : undefined;
31
+ }
32
+ /** What in-process coalescing keys a store by: its native {@link StoreCommitSteps.identity}, else the store object itself. */
33
+ export function storeIdentity(store) {
34
+ const identity = steps(store)?.identity;
35
+ return typeof identity === 'string' && identity.length > 0 ? identity : store;
36
+ }
37
+ /**
38
+ * Exclusively run `action` under the lock of `keys` (several: all of them, taken in sorted order),
39
+ * then publish what it staged with the release. Without native steps: `withLock` on each key in
40
+ * sorted order, and each staged value saved, in stage order, before the release.
41
+ */
42
+ export function withCommit(store, keys, action) {
43
+ const native = steps(store);
44
+ if (native)
45
+ return native.withCommit(keys, action);
46
+ const sorted = [...new Set(typeof keys === 'string' ? [keys] : keys)].sort();
47
+ const run = async () => {
48
+ const staged = new Map();
49
+ const result = await action({ stage: (k, v) => { staged.delete(k); staged.set(k, structuredClone(v)); } });
50
+ for (const [k, v] of staged)
51
+ await store.save(k, v);
52
+ return result;
53
+ };
54
+ return sorted.reduceRight((inner, key) => () => store.withLock(key, inner), run)();
55
+ }
56
+ /** Save every entry durably before resolving; without native steps, one at a time in order. */
57
+ export async function saveAll(store, entries) {
58
+ const native = steps(store);
59
+ if (native)
60
+ return native.saveAll(entries);
61
+ for (const [key, value] of entries)
62
+ await store.save(key, value);
63
+ }
64
+ /** Save a value its recovery re-derives; without native steps, an ordinary save. */
65
+ export function saveRederivable(store, key, value) {
66
+ const native = steps(store);
67
+ return native ? native.saveRederivable(key, value) : store.save(key, value);
68
+ }
69
+ /**
70
+ * Re-derivable writes of one flow, published with its next durable commit instead of on their own
71
+ * (or by {@link Rederivable.flush} at its end). Only for values the flow's own recovery re-derives
72
+ * from what it reads anyway: a crash may leave each one unwritten.
73
+ *
74
+ * An OWED entry ({@link Rederivable.put} with `owed`) is a confirmation a recovery does NOT
75
+ * re-derive: the `confirmed` of a sent write whose `prepared` is already durable. A crash before it
76
+ * is durable leaves the write `prepared`, which a recovery refuses (never resent; the caller
77
+ * reconciles), so it may ride on a later commit only when that commit follows the send at once: the
78
+ * flow calls {@link Rederivable.flushOwed} before any wait or poll that follows a send.
79
+ * {@link Rederivable.flush} publishes owed entries durably.
80
+ */
81
+ export class Rederivable {
82
+ #pending = new Map();
83
+ #owed = new Set();
84
+ /** Write `value` under `key` with the next commit (a later put of one key replaces an earlier one). */
85
+ put(key, value, options = {}) {
86
+ this.#pending.delete(key);
87
+ this.#pending.set(key, structuredClone(value));
88
+ if (options.owed === true)
89
+ this.#owed.add(key);
90
+ else
91
+ this.#owed.delete(key);
92
+ }
93
+ /** The value `key` will be published with, or undefined when none is pending (a detached copy). */
94
+ peek(key) { return this.#pending.has(key) ? structuredClone(this.#pending.get(key)) : undefined; }
95
+ /** The entries for the commit about to run; give them back with {@link Rederivable.restore} if it failed. */
96
+ take() { const out = [...this.#pending]; this.#pending.clear(); return out; }
97
+ /** Return entries a failed commit did not publish (a newer put of a key wins). */
98
+ restore(entries) { for (const [key, value] of entries)
99
+ if (!this.#pending.has(key))
100
+ this.#pending.set(key, value); }
101
+ /** Publish everything pending in one durable commit when any of it is owed; nothing otherwise. */
102
+ async flushOwed(store) {
103
+ for (const key of this.#pending.keys())
104
+ if (this.#owed.has(key))
105
+ return this.flush(store);
106
+ }
107
+ /** Publish whatever is left: each as {@link saveRederivable}, or all in one durable commit when any is owed. */
108
+ async flush(store) {
109
+ const out = this.take();
110
+ if (out.length === 0)
111
+ return;
112
+ try {
113
+ if (out.some(([key]) => this.#owed.has(key)))
114
+ await saveAll(store, out);
115
+ else
116
+ await Promise.all(out.map(([key, value]) => saveRederivable(store, key, value)));
117
+ }
118
+ catch (error) {
119
+ this.restore(out);
120
+ throw error;
121
+ }
122
+ for (const [key] of out)
123
+ if (!this.#pending.has(key))
124
+ this.#owed.delete(key);
125
+ }
126
+ }
@@ -0,0 +1,8 @@
1
+ import { TasraError } from '../errors.js';
2
+ /**
3
+ * A state lock is already held and requires reconciliation before manual removal.
4
+ */
5
+ export declare class StoreLockedError extends TasraError {
6
+ readonly key: string;
7
+ constructor(/** Store entry whose exclusive lock could not be acquired. */ key: string);
8
+ }
@@ -0,0 +1,11 @@
1
+ import { TasraError } from '../errors.js';
2
+ /**
3
+ * A state lock is already held and requires reconciliation before manual removal.
4
+ */
5
+ export class StoreLockedError extends TasraError {
6
+ key;
7
+ constructor(/** Store entry whose exclusive lock could not be acquired. */ key) {
8
+ super(`State ${key} is locked; reconcile any interrupted operation before removing its lock`);
9
+ this.key = key;
10
+ }
11
+ }
@@ -8,6 +8,8 @@ import { createIdentity, issueCredential, verifyCredential, credentialPolicy, cr
8
8
  * Network manifest and optional wallet, storage and transport adapters for an application.
9
9
  */
10
10
  export interface TasraClientOptions extends ResolveApplicationManifestOptions {
11
+ /** Permit paid keeper HTTP only on the explicitly selected local chain43112. */
12
+ allowLocalPaidHttp?: boolean;
11
13
  /**
12
14
  * Network manifest downloaded from tasra-releases, or approved application settings.
13
15
  */
@@ -45,7 +45,7 @@ export class TasraClient {
45
45
  options = { ...options };
46
46
  const resolved = resolveApplicationManifest(options.manifest, options);
47
47
  const keeperUrl = options.keeperUrl ?? resolved.keeperUrl;
48
- const app = createTasra({ ...resolved, keeperUrl, chain: options.chain, fetchImpl: options.fetchImpl });
48
+ const app = createTasra({ ...resolved, keeperUrl, chain: options.chain, fetchImpl: options.fetchImpl, allowLocalPaidHttp: options.allowLocalPaidHttp });
49
49
  this.deployment = app.deployment;
50
50
  this.chain = app.chain;
51
51
  this.verifierAgentUrl = options.verifierAgentUrl ?? resolved.verifierAgentUrl;
@@ -1,8 +1,10 @@
1
1
  import { createPublicClient, createWalletClient, custom, defineChain, http, keccak256, toHex, parseTransaction, recoverTransactionAddress } from 'viem';
2
+ import { headFollowerOf } from '../chain/headFollower.js';
2
3
  import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';
3
4
  import { TasraError } from '../errors.js';
4
5
  import { defineDeployment } from './deployment.js';
5
6
  import { toViemAccount } from './viem.js';
7
+ import { WRITE_POLL_INTERVAL_MS } from '../chain/receipt.js';
6
8
  function chainFor(deployment) {
7
9
  return defineChain({ id: deployment.chainId, name: deployment.name, nativeCurrency: { name: 'Native token', symbol: 'NATIVE', decimals: 18 }, rpcUrls: { default: { http: [deployment.rpcUrl] } } });
8
10
  }
@@ -21,7 +23,7 @@ async function verifySignedTransaction(journal) {
21
23
  }
22
24
  function wrap(deployment, wallet, local) {
23
25
  const config = defineDeployment(deployment), address = wallet.account.address;
24
- const pub = createPublicClient({ chain: chainFor(config), transport: http(config.rpcUrl, { retryCount: 0 }) });
26
+ const pub = createPublicClient({ chain: chainFor(config), transport: http(config.rpcUrl, { retryCount: 0 }), pollingInterval: WRITE_POLL_INTERVAL_MS, cacheTime: 4_000 });
25
27
  async function assertChain() {
26
28
  if (await pub.getChainId() !== config.chainId || await wallet.getChainId() !== config.chainId)
27
29
  throw new TasraError('Wallet or RPC chain differs from the deployment');
@@ -88,6 +90,7 @@ function wrap(deployment, wallet, local) {
88
90
  await verifySignedTransaction(journal);
89
91
  await assertChain();
90
92
  const receipt = await pub.waitForTransactionReceipt({ hash: journal.hash, timeout: timeoutMs, checkReplacement: false });
93
+ headFollowerOf(pub)?.noteMinedBlock(receipt.blockNumber);
91
94
  journal.phase = 'confirmed';
92
95
  journal.receipt = receipt;
93
96
  await persist?.(structuredClone(journal));
@@ -1,3 +1,4 @@
1
+ import { type RetryPolicy } from '../retry.js';
1
2
  /**
2
3
  * `base64url(sha256(credentials joined by "\n"))`.
3
4
  *
@@ -32,6 +33,8 @@ export interface HolderNonce {
32
33
  export declare function fetchHolderNonce(verifierUrl: string, opts?: {
33
34
  slotId?: string;
34
35
  action?: string;
36
+ /** Waits on a capacity refusal (429/503 + `Retry-After`); `false` fails at once. A refused mint stores nothing. */
37
+ retry?: RetryPolicy | false;
35
38
  }): Promise<HolderNonce>;
36
39
  /**
37
40
  * A signer for the holder DID's `authentication` key. Either the SDK holds the raw
@@ -13,6 +13,7 @@
13
13
  import { ed25519 } from '@noble/curves/ed25519';
14
14
  import { sha256 } from '@noble/hashes/sha256';
15
15
  import { httpError } from '../errors.js';
16
+ import { classifyRefusal, retryIdempotent } from '../retry.js';
16
17
  function base(url) {
17
18
  return url.replace(/\/$/, '');
18
19
  }
@@ -48,13 +49,13 @@ export function credentialsCommitment(credentials) {
48
49
  */
49
50
  export async function fetchHolderNonce(verifierUrl, opts) {
50
51
  const url = `${base(verifierUrl)}/v1/nonce`;
51
- const res = await fetch(url, {
52
- method: 'POST',
53
- headers: { 'Content-Type': 'application/json' },
54
- body: JSON.stringify({ slot_id: opts?.slotId, action: opts?.action }),
55
- });
56
- if (!res.ok)
57
- throw await httpError(res, url, 'v1/nonce');
52
+ const body = JSON.stringify({ slot_id: opts?.slotId, action: opts?.action });
53
+ const res = await retryIdempotent(async () => {
54
+ const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body });
55
+ if (!response.ok)
56
+ throw await httpError(response, url, 'v1/nonce');
57
+ return response;
58
+ }, { policy: opts?.retry === false ? { maxAttempts: 1 } : opts?.retry, classify: classifyRefusal });
58
59
  const b = (await res.json());
59
60
  const out = { nonce: b.nonce, expiresAt: b.expires_at };
60
61
  if (b.dcql_rule !== undefined)
@@ -1,3 +1,4 @@
1
+ import { type RetryPolicy } from '../retry.js';
1
2
  /** Verifier-issued bearer JWT with its holder identifier and expiry in Unix seconds. */
2
3
  export interface IssuedToken {
3
4
  /** The signed JWT (EdDSA) to present to keykeeper-nodes as a Bearer token. */
@@ -33,7 +34,9 @@ export declare function createRenewal(verifierUrl: string, body: {
33
34
  presentation: unknown;
34
35
  credentials?: string[];
35
36
  slot_ids?: string[];
36
- }): Promise<RenewalGrant>;
37
+ },
38
+ /** Waits on an SP-11 capacity refusal (HTTP 429, nothing stored); `false` fails at once. Other failures are never retried. */
39
+ retry?: RetryPolicy | false): Promise<RenewalGrant>;
37
40
  /**
38
41
  * Revoke a renewal token - future redeems are denied, and any bound slots get a
39
42
  * rotation webhook. POST {verifier}/v1/renewals/revoke {renewal_token}
@@ -109,7 +112,6 @@ export declare function revokeSlotUser(verifierUrl: string, adminSecret: string,
109
112
  export declare function verifyPresentation(verifierUrl: string, body: {
110
113
  dcql_rule: string;
111
114
  presentation: unknown;
112
- credentials?: unknown;
113
115
  }): Promise<IssuedToken>;
114
116
  /**
115
117
  * The PRODUCTION credential path: present signed JWT-VCs + holder proof for a
@@ -6,6 +6,7 @@
6
6
  // token(s). These cover the "(obtain, refresh) a DCQL-gated JWT" lifecycle that
7
7
  // every product on top of a Tasra Network needs.
8
8
  import { httpError } from '../errors.js';
9
+ import { classifyRefusedWrite, retryIdempotent } from '../retry.js';
9
10
  function base(url) {
10
11
  return url.replace(/\/$/, '');
11
12
  }
@@ -29,8 +30,10 @@ async function postJson(url, body) {
29
30
  * @param verifierUrl - Verifier HTTP base URL.
30
31
  * @param body - Policy, presentation and optional signed credentials or revocation-bound slots.
31
32
  */
32
- export async function createRenewal(verifierUrl, body) {
33
- const b = (await postJson(`${base(verifierUrl)}/v1/renewals`, body));
33
+ export async function createRenewal(verifierUrl, body,
34
+ /** Waits on an SP-11 capacity refusal (HTTP 429, nothing stored); `false` fails at once. Other failures are never retried. */
35
+ retry) {
36
+ const b = (await retryIdempotent(() => postJson(`${base(verifierUrl)}/v1/renewals`, body), { policy: retry === false ? { maxAttempts: 1 } : retry, classify: classifyRefusedWrite }));
34
37
  return { renewalToken: b.renewal_token, holder: b.holder, expiresAt: b.expires_at, scopes: b.scopes };
35
38
  }
36
39
  /**