@thruputchain/client 0.0.0-stage → 0.25.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 (182) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +935 -2
  3. package/dist/actions-CdFSUTO2.js +298 -0
  4. package/dist/actions-CdFSUTO2.js.map +1 -0
  5. package/dist/actions-DxJZ3yIv.cjs +357 -0
  6. package/dist/actions-DxJZ3yIv.cjs.map +1 -0
  7. package/dist/actions.cjs +19 -0
  8. package/dist/actions.d.cts +4 -0
  9. package/dist/actions.d.ts +4 -0
  10. package/dist/actions.js +3 -0
  11. package/dist/client-BxB6ktQd.d.cts +690 -0
  12. package/dist/client-BxB6ktQd.d.cts.map +1 -0
  13. package/dist/client-BxB6ktQd.d.ts +690 -0
  14. package/dist/client-BxB6ktQd.d.ts.map +1 -0
  15. package/dist/codec-B7HJjMzI.cjs +8190 -0
  16. package/dist/codec-B7HJjMzI.cjs.map +1 -0
  17. package/dist/codec-CX-19jac.js +8130 -0
  18. package/dist/codec-CX-19jac.js.map +1 -0
  19. package/dist/contract-BpxjDMHw.js +1105 -0
  20. package/dist/contract-BpxjDMHw.js.map +1 -0
  21. package/dist/contract-D0wCFcAN.cjs +1219 -0
  22. package/dist/contract-D0wCFcAN.cjs.map +1 -0
  23. package/dist/contract.cjs +58 -0
  24. package/dist/contract.d.cts +3 -0
  25. package/dist/contract.d.ts +3 -0
  26. package/dist/contract.js +2 -0
  27. package/dist/contracts.cjs +1050 -0
  28. package/dist/contracts.cjs.map +1 -0
  29. package/dist/contracts.d.cts +397 -0
  30. package/dist/contracts.d.cts.map +1 -0
  31. package/dist/contracts.d.ts +397 -0
  32. package/dist/contracts.d.ts.map +1 -0
  33. package/dist/contracts.js +1030 -0
  34. package/dist/contracts.js.map +1 -0
  35. package/dist/dev_wallet-BXWK5KR6.cjs +530 -0
  36. package/dist/dev_wallet-BXWK5KR6.cjs.map +1 -0
  37. package/dist/dev_wallet-C9eMQROk.js +497 -0
  38. package/dist/dev_wallet-C9eMQROk.js.map +1 -0
  39. package/dist/domainSeparator-B_vU_zUD.cjs +102 -0
  40. package/dist/domainSeparator-B_vU_zUD.cjs.map +1 -0
  41. package/dist/domainSeparator-CBCvxIj-.js +79 -0
  42. package/dist/domainSeparator-CBCvxIj-.js.map +1 -0
  43. package/dist/execution-CRDyKu45.d.ts +227 -0
  44. package/dist/execution-CRDyKu45.d.ts.map +1 -0
  45. package/dist/execution-DyxaIG4v.d.cts +227 -0
  46. package/dist/execution-DyxaIG4v.d.cts.map +1 -0
  47. package/dist/hex-DIcaALXL.js +112 -0
  48. package/dist/hex-DIcaALXL.js.map +1 -0
  49. package/dist/hex-DkGpiZ5e.cjs +189 -0
  50. package/dist/hex-DkGpiZ5e.cjs.map +1 -0
  51. package/dist/index--5LsCotr.d.ts +192 -0
  52. package/dist/index--5LsCotr.d.ts.map +1 -0
  53. package/dist/index-B5KqSHeL.d.cts +192 -0
  54. package/dist/index-B5KqSHeL.d.cts.map +1 -0
  55. package/dist/index-BZ0O5jZG.d.cts +163 -0
  56. package/dist/index-BZ0O5jZG.d.cts.map +1 -0
  57. package/dist/index-BuPQcAK2.d.ts +23 -0
  58. package/dist/index-BuPQcAK2.d.ts.map +1 -0
  59. package/dist/index-ByNNqY7S.d.cts +83 -0
  60. package/dist/index-ByNNqY7S.d.cts.map +1 -0
  61. package/dist/index-C-M-4jMR.d.cts +263 -0
  62. package/dist/index-C-M-4jMR.d.cts.map +1 -0
  63. package/dist/index-C97zw2rk.d.ts +137 -0
  64. package/dist/index-C97zw2rk.d.ts.map +1 -0
  65. package/dist/index-CIHK7Ew9.d.cts +303 -0
  66. package/dist/index-CIHK7Ew9.d.cts.map +1 -0
  67. package/dist/index-CIHK7Ew9.d.ts +303 -0
  68. package/dist/index-CIHK7Ew9.d.ts.map +1 -0
  69. package/dist/index-CXuO2Zjx.d.ts +263 -0
  70. package/dist/index-CXuO2Zjx.d.ts.map +1 -0
  71. package/dist/index-DOEBWXY2.d.cts +137 -0
  72. package/dist/index-DOEBWXY2.d.cts.map +1 -0
  73. package/dist/index-DzrLv3EA.d.cts +82 -0
  74. package/dist/index-DzrLv3EA.d.cts.map +1 -0
  75. package/dist/index-DzrLv3EA.d.ts +82 -0
  76. package/dist/index-DzrLv3EA.d.ts.map +1 -0
  77. package/dist/index-fdTURpBk.d.ts +83 -0
  78. package/dist/index-fdTURpBk.d.ts.map +1 -0
  79. package/dist/index-sAzHHayu.d.ts +163 -0
  80. package/dist/index-sAzHHayu.d.ts.map +1 -0
  81. package/dist/index-uQqRk9Ww.d.cts +23 -0
  82. package/dist/index-uQqRk9Ww.d.cts.map +1 -0
  83. package/dist/index.cjs +478 -0
  84. package/dist/index.cjs.map +1 -0
  85. package/dist/index.d.cts +173 -0
  86. package/dist/index.d.cts.map +1 -0
  87. package/dist/index.d.ts +173 -0
  88. package/dist/index.d.ts.map +1 -0
  89. package/dist/index.js +231 -0
  90. package/dist/index.js.map +1 -0
  91. package/dist/provider.cjs +101 -0
  92. package/dist/provider.cjs.map +1 -0
  93. package/dist/provider.d.cts +2 -0
  94. package/dist/provider.d.ts +2 -0
  95. package/dist/provider.js +76 -0
  96. package/dist/provider.js.map +1 -0
  97. package/dist/readError-BVbfTMLv.cjs +604 -0
  98. package/dist/readError-BVbfTMLv.cjs.map +1 -0
  99. package/dist/readError-Dn_XN98x.js +551 -0
  100. package/dist/readError-Dn_XN98x.js.map +1 -0
  101. package/dist/readViews-BKJtE5J3.d.cts +594 -0
  102. package/dist/readViews-BKJtE5J3.d.cts.map +1 -0
  103. package/dist/readViews-C_FX8wby.d.ts +594 -0
  104. package/dist/readViews-C_FX8wby.d.ts.map +1 -0
  105. package/dist/rolldown-runtime-D6vf50IK.cjs +28 -0
  106. package/dist/sendInvocation-2EZanZZr.cjs +661 -0
  107. package/dist/sendInvocation-2EZanZZr.cjs.map +1 -0
  108. package/dist/sendInvocation-C4ruTC-9.js +505 -0
  109. package/dist/sendInvocation-C4ruTC-9.js.map +1 -0
  110. package/dist/sign-BewmV_EL.cjs +139 -0
  111. package/dist/sign-BewmV_EL.cjs.map +1 -0
  112. package/dist/sign-DVIRyW8Y.js +122 -0
  113. package/dist/sign-DVIRyW8Y.js.map +1 -0
  114. package/dist/sign-Ve0eetRO.d.ts +48 -0
  115. package/dist/sign-Ve0eetRO.d.ts.map +1 -0
  116. package/dist/sign-eUT0iGQG.d.cts +48 -0
  117. package/dist/sign-eUT0iGQG.d.cts.map +1 -0
  118. package/dist/signed-op.cjs +9 -0
  119. package/dist/signed-op.d.cts +3 -0
  120. package/dist/signed-op.d.ts +3 -0
  121. package/dist/signed-op.js +3 -0
  122. package/dist/signedOp-Bluo0OAd.cjs +183 -0
  123. package/dist/signedOp-Bluo0OAd.cjs.map +1 -0
  124. package/dist/signedOp-x4fakrr4.js +166 -0
  125. package/dist/signedOp-x4fakrr4.js.map +1 -0
  126. package/dist/signed_op-BzVbBgv4.js +154 -0
  127. package/dist/signed_op-BzVbBgv4.js.map +1 -0
  128. package/dist/signed_op-DFgQ2yFj.d.ts +58 -0
  129. package/dist/signed_op-DFgQ2yFj.d.ts.map +1 -0
  130. package/dist/signed_op-LwxrDud8.d.cts +58 -0
  131. package/dist/signed_op-LwxrDud8.d.cts.map +1 -0
  132. package/dist/signed_op-z_8fqAi1.cjs +175 -0
  133. package/dist/signed_op-z_8fqAi1.cjs.map +1 -0
  134. package/dist/signers-BFP84wJP.cjs +137 -0
  135. package/dist/signers-BFP84wJP.cjs.map +1 -0
  136. package/dist/signers-CzOSedwJ.js +120 -0
  137. package/dist/signers-CzOSedwJ.js.map +1 -0
  138. package/dist/signers.cjs +5 -0
  139. package/dist/signers.d.cts +3 -0
  140. package/dist/signers.d.ts +3 -0
  141. package/dist/signers.js +2 -0
  142. package/dist/size-506oTE28.js +91 -0
  143. package/dist/size-506oTE28.js.map +1 -0
  144. package/dist/size-OAFfOthl.cjs +108 -0
  145. package/dist/size-OAFfOthl.cjs.map +1 -0
  146. package/dist/transaction-CwkQxQOx.js +24 -0
  147. package/dist/transaction-CwkQxQOx.js.map +1 -0
  148. package/dist/transaction-DrSrCJ5y.cjs +47 -0
  149. package/dist/transaction-DrSrCJ5y.cjs.map +1 -0
  150. package/dist/transaction.cjs +13 -0
  151. package/dist/transaction.d.cts +3 -0
  152. package/dist/transaction.d.ts +3 -0
  153. package/dist/transaction.js +4 -0
  154. package/dist/transactionHash-CO9ajbvU.js +24 -0
  155. package/dist/transactionHash-CO9ajbvU.js.map +1 -0
  156. package/dist/transactionHash-D5yf4KoL.cjs +29 -0
  157. package/dist/transactionHash-D5yf4KoL.cjs.map +1 -0
  158. package/dist/transport-B-P16rs6.cjs +252 -0
  159. package/dist/transport-B-P16rs6.cjs.map +1 -0
  160. package/dist/transport-DqyoNtUy.js +234 -0
  161. package/dist/transport-DqyoNtUy.js.map +1 -0
  162. package/dist/transport.cjs +19 -0
  163. package/dist/transport.d.cts +3 -0
  164. package/dist/transport.d.ts +3 -0
  165. package/dist/transport.js +4 -0
  166. package/dist/types-BE40oD_Q.d.cts +18 -0
  167. package/dist/types-BE40oD_Q.d.cts.map +1 -0
  168. package/dist/types-BE40oD_Q.d.ts +18 -0
  169. package/dist/types-BE40oD_Q.d.ts.map +1 -0
  170. package/dist/validation-4w-vDGAi.cjs +543 -0
  171. package/dist/validation-4w-vDGAi.cjs.map +1 -0
  172. package/dist/validation-eXATmgO0.js +411 -0
  173. package/dist/validation-eXATmgO0.js.map +1 -0
  174. package/dist/wallet-Bthapk8i.cjs +709 -0
  175. package/dist/wallet-Bthapk8i.cjs.map +1 -0
  176. package/dist/wallet-CwWPYoHF.js +667 -0
  177. package/dist/wallet-CwWPYoHF.js.map +1 -0
  178. package/dist/wallet.cjs +27 -0
  179. package/dist/wallet.d.cts +3 -0
  180. package/dist/wallet.d.ts +3 -0
  181. package/dist/wallet.js +3 -0
  182. package/package.json +122 -4
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sendInvocation-C4ruTC-9.js","names":["bytesEqual","sign"],"sources":["../src/actions/deadline.ts","../src/actions/public/waitForTransactionReceipt.ts","../src/wallet/invocationAdapter.ts","../src/wallet/execution.ts","../src/actions/wallet/prepareTransaction.ts","../src/actions/wallet/sendInvocation.ts"],"sourcesContent":["/** Run one operation within the caller's wall-clock budget and cancellation signal. */\nexport async function beforeDeadline<T>(\n operation: (signal: AbortSignal) => Promise<T>,\n deadline: number,\n caller: AbortSignal | undefined,\n timeout: () => Error,\n): Promise<T> {\n caller?.throwIfAborted();\n if (performance.now() >= deadline) throw timeout();\n const controller = new AbortController();\n const signal = caller\n ? AbortSignal.any([caller, controller.signal])\n : controller.signal;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let onAbort = () => {};\n try {\n return await Promise.race([\n new Promise<T>((_, reject) => {\n onAbort = () => reject(signal.reason);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n timer = setTimeout(\n () => controller.abort(timeout()),\n Math.ceil(Math.max(0, deadline - performance.now())),\n );\n }),\n operation(signal),\n ]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n signal.removeEventListener(\"abort\", onAbort);\n controller.abort();\n }\n}\nexport function validateTimer(value: number, field: string): void {\n if (!Number.isFinite(value) || value < 0 || value > 2147483647)\n throw new RangeError(`${field} must be between 0 and 2147483647`);\n}\nexport function waitDelay(delay: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n signal.throwIfAborted();\n const finish = () => {\n signal.removeEventListener(\"abort\", abort);\n resolve();\n };\n const timer = setTimeout(finish, delay);\n const abort = () => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", abort);\n reject(signal.reason);\n };\n signal.addEventListener(\"abort\", abort, { once: true });\n });\n}\n","import { toBase58 } from \"../../encoding.js\";\nimport type { RpcClient } from \"../../rpc/client.js\";\nimport { RpcCompatibilityError } from \"../../rpc/client.js\";\nimport { NativeRpcError } from \"../../rpc/errorReader.js\";\nimport {\n UnsupportedRpcValue,\n RpcDecodingError,\n RpcRequestValidationError,\n} from \"../../rpc/codec.js\";\nimport type { TransactionReceipt, TransactionStatus } from \"../../types/rpc.js\";\nimport { classifyReadError } from \"../../transport/readError.js\";\nimport { beforeDeadline, validateTimer, waitDelay } from \"../deadline.js\";\n\nexport interface KnownCommitment {\n readonly networkHash: Uint8Array;\n readonly transactionHash: Uint8Array;\n readonly blockHeight: bigint;\n}\nexport interface WaitForTransactionReceiptOptions {\n signal?: AbortSignal;\n /** Verified before each observation; omission uses discovery's validated network. */\n expectedNetworkHash?: Uint8Array;\n knownCommitment?: KnownCommitment;\n /** Observed status, including optional advisory attempt diagnostics. Never retry permission. */\n onStatus?: (status: TransactionStatus) => void;\n timeoutMs?: number;\n pollingIntervalMs?: number;\n}\n/** Observation stopped; neither timeout nor cancellation proves nonexecution. */\nexport class TransactionReceiptObservationError extends Error {\n constructor(\n readonly transactionHash: Uint8Array,\n readonly knownCommitment: KnownCommitment | undefined,\n readonly lastStatus: TransactionStatus | undefined,\n cause: unknown,\n ) {\n super(`Could not observe transaction ${toBase58(transactionHash)}`, {\n cause,\n });\n this.name = \"TransactionReceiptObservationError\";\n }\n}\nexport class TransactionReceiptTimeoutError extends TransactionReceiptObservationError {\n constructor(\n transactionHash: Uint8Array,\n knownCommitment: KnownCommitment | undefined,\n lastStatus: TransactionStatus | undefined,\n cause?: unknown,\n ) {\n super(transactionHash, knownCommitment, lastStatus, cause);\n this.name = \"TransactionReceiptTimeoutError\";\n this.message = `Timed out waiting for transaction ${toBase58(transactionHash)}`;\n }\n}\nconst equal = (a: Uint8Array, b: Uint8Array) =>\n a.length === b.length && a.every((v, i) => v === b[i]);\n/** Read-only capabilities used by commitment and receipt observation. */\nexport type ReceiptObserver = Pick<\n RpcClient,\n | \"getNetworkInfo\"\n | \"getTransactionReceipt\"\n | \"getTransactionStatus\"\n | \"discovery\"\n | \"requireMethods\"\n>;\n\n/** Return any committed receipt, including failed execution. Never sign or resubmit. */\nexport async function waitForTransactionReceipt(\n client: ReceiptObserver,\n transactionHash: Uint8Array,\n options: WaitForTransactionReceiptOptions = {},\n): Promise<TransactionReceipt> {\n return (await observe(\n client,\n transactionHash,\n options,\n false,\n )) as TransactionReceipt;\n}\n/** Observe commitment independently of receipt availability or execution success. */\nexport async function waitForCommitment(\n client: ReceiptObserver,\n transactionHash: Uint8Array,\n options: WaitForTransactionReceiptOptions = {},\n): Promise<KnownCommitment> {\n return (await observe(\n client,\n transactionHash,\n options,\n true,\n )) as KnownCommitment;\n}\n// Status evidence includes extensible values at arbitrary nested schema positions.\n// structuredClone alone drops their UnsupportedRpcValue class identity.\nfunction snapshotStatus(status: TransactionStatus): TransactionStatus {\n const copy = (value: unknown): unknown => {\n if (value instanceof UnsupportedRpcValue)\n return new UnsupportedRpcValue(structuredClone(value.raw));\n if (Array.isArray(value)) return value.map(copy);\n if (ArrayBuffer.isView(value)) return structuredClone(value);\n if (value !== null && typeof value === \"object\")\n return Object.fromEntries(\n Object.entries(value).map(([key, entry]) => [key, copy(entry)]),\n );\n return value;\n };\n return copy(status) as TransactionStatus;\n}\n\nasync function observe(\n client: ReceiptObserver,\n hash: Uint8Array,\n options: WaitForTransactionReceiptOptions,\n commitmentOnly: boolean,\n): Promise<TransactionReceipt | KnownCommitment> {\n const timeoutMs = options.timeoutMs ?? 30000;\n const interval = options.pollingIntervalMs ?? 250;\n validateTimer(timeoutMs, \"timeoutMs\");\n validateTimer(interval, \"pollingIntervalMs\");\n const transactionHash = new Uint8Array(hash);\n const networkHash = new Uint8Array(\n options.expectedNetworkHash ?? client.discovery.network.networkHash,\n );\n if (transactionHash.length !== 32 || networkHash.length !== 32)\n throw new RangeError(\n \"Transaction and network hashes must contain 32 bytes\",\n );\n let commitment: KnownCommitment | undefined;\n let lastStatus: TransactionStatus | undefined;\n if (options.knownCommitment) {\n const known = options.knownCommitment;\n if (\n !equal(known.transactionHash, transactionHash) ||\n !equal(known.networkHash, networkHash) ||\n typeof known.blockHeight !== \"bigint\" ||\n known.blockHeight < 0n ||\n known.blockHeight > 9223372036854775807n\n )\n throw new RpcCompatibilityError(\n \"Known commitment does not match the transaction/network context\",\n );\n commitment = {\n transactionHash: transactionHash.slice(),\n networkHash: networkHash.slice(),\n blockHeight: known.blockHeight,\n };\n lastStatus = { status: \"committed\", blockHeight: known.blockHeight };\n }\n client.requireMethods([\n \"getNetworkInfo\",\n \"getTransactionReceipt\",\n \"getTransactionStatus\",\n ]);\n const deadline = performance.now() + timeoutMs;\n let lastFailure: unknown;\n let failures = 0;\n const timeout = () =>\n new TransactionReceiptTimeoutError(\n transactionHash.slice(),\n commitment && structuredClone(commitment),\n lastStatus,\n lastFailure,\n );\n const run = <T>(operation: (signal: AbortSignal) => Promise<T>) =>\n beforeDeadline(operation, deadline, options.signal, timeout);\n const retain = (blockHeight: bigint) => {\n if (commitment && commitment.blockHeight !== blockHeight)\n throw new RpcCompatibilityError(\n \"Conflicting commitment heights for the same transaction\",\n );\n commitment = {\n transactionHash: transactionHash.slice(),\n networkHash: networkHash.slice(),\n blockHeight,\n };\n lastStatus = { status: \"committed\", blockHeight };\n };\n try {\n while (true) {\n let retryAfterMs: bigint | undefined;\n let networkVerified = false;\n let failed = false;\n try {\n const network = await run((signal) =>\n client.getNetworkInfo({}, { signal }),\n );\n if (!equal(network.networkHash, networkHash))\n throw new RpcCompatibilityError(\n \"Observation endpoint network changed\",\n );\n networkVerified = true;\n if (commitmentOnly && commitment) return structuredClone(commitment);\n const receipt = await run((signal) =>\n client.getTransactionReceipt({ transactionHash }, { signal }),\n );\n if (receipt) {\n retain(receipt.blockHeight);\n return commitmentOnly ? structuredClone(commitment!) : receipt;\n }\n } catch (cause) {\n lastFailure = cause;\n failed = true;\n if (\n cause instanceof NativeRpcError &&\n cause.decoded.classification === \"known\"\n ) {\n const data = cause.decoded.data;\n if (data.kind === \"backendDataInvalid\" && data.observation) {\n retain(data.observation.blockHeight);\n if (commitmentOnly) return structuredClone(commitment!);\n }\n if (\"retryAfterMs\" in data) retryAfterMs = data.retryAfterMs;\n }\n if (\n options.signal?.aborted ||\n classifyReadError(cause, options) !== \"transient\"\n )\n throw cause;\n }\n // Status failures cannot erase a previously validated commitment.\n let observedStatus: TransactionStatus | undefined;\n if (networkVerified)\n try {\n const status = await run((signal) =>\n client.getTransactionStatus({ transactionHash }, { signal }),\n );\n if (\n !(status instanceof UnsupportedRpcValue) &&\n status.status === \"committed\"\n )\n retain(status.blockHeight);\n else if (!commitment) lastStatus = snapshotStatus(status);\n observedStatus = status;\n } catch (cause) {\n if (\n cause instanceof RpcCompatibilityError ||\n cause instanceof RpcDecodingError ||\n cause instanceof RpcRequestValidationError ||\n classifyReadError(cause, options) === \"permanent\"\n )\n throw cause;\n options.signal?.throwIfAborted();\n lastFailure = cause;\n failed = true;\n if (\n cause instanceof NativeRpcError &&\n cause.decoded.classification === \"known\" &&\n \"retryAfterMs\" in cause.decoded.data\n ) {\n const hint = cause.decoded.data.retryAfterMs;\n if (\n hint !== undefined &&\n (retryAfterMs === undefined || hint > retryAfterMs)\n )\n retryAfterMs = hint;\n }\n }\n if (observedStatus !== undefined) options.onStatus?.(observedStatus);\n if (failed) failures++;\n else {\n failures = 0;\n lastFailure = undefined;\n }\n if (commitmentOnly && commitment) return structuredClone(commitment);\n const backoff = failures\n ? Math.min(\n 5000,\n Math.max(1, interval) * 2 ** Math.min(failures - 1, 8),\n ) *\n (0.5 + Math.random() / 2)\n : interval;\n const remaining = deadline - performance.now();\n if (\n retryAfterMs !== undefined &&\n retryAfterMs > BigInt(Math.max(0, Math.floor(remaining)))\n )\n throw timeout();\n const delay = Math.max(backoff, Number(retryAfterMs ?? 0n));\n await run((signal) =>\n waitDelay(Math.min(delay, Math.max(0, remaining)), signal),\n );\n }\n } catch (cause) {\n if (cause instanceof TransactionReceiptTimeoutError) throw cause;\n throw new TransactionReceiptObservationError(\n transactionHash,\n commitment && structuredClone(commitment),\n lastStatus,\n cause,\n );\n }\n}\n","import {\n codec,\n contractAddress,\n serialize,\n type ContractAddress,\n type GasAmount,\n type Invocation,\n} from \"@thruputchain/protocol\";\nimport { fixedBytes } from \"@thruputchain/xdr\";\nimport { bytesEqual } from \"../contract/event.js\";\nimport { DefaultWallet } from \"../contracts/default_wallet.js\";\nimport { DevWallet } from \"../contracts/dev_wallet.js\";\nimport { MAX_DEFAULT_WALLET_CALLS } from \"../provider/validation.js\";\nimport type { ContractDeployment, DeploymentOptions } from \"./deployment.js\";\nimport type { TransactionReceipt } from \"../types/rpc.js\";\n\n/** Common inputs for wrapping one inner invocation through a wallet contract. */\nexport interface WalletExecutionRequest {\n readonly invocation: Invocation;\n /** Gas available to the wallet's root invocation. */\n readonly gasLimit: GasAmount;\n}\n\n/** Ordered inner calls for one atomic DefaultWallet execution. */\nexport interface WalletBatchExecutionRequest {\n readonly invocations: readonly Invocation[];\n /** Gas available to the complete wallet root, including all calls. */\n readonly gasLimit: GasAmount;\n}\n\n/** Build a root batch directly, copying call bytes before asynchronous work. */\nexport function createDefaultWalletBatchInvocation(\n accountAddress: ContractAddress,\n request: WalletBatchExecutionRequest,\n): Invocation {\n if (\n !Array.isArray(request.invocations) ||\n request.invocations.length < 1 ||\n request.invocations.length > MAX_DEFAULT_WALLET_CALLS\n )\n throw new RangeError(\"DefaultWallet requires 1 to 16 calls\");\n return DefaultWallet.v0_1.execute.invocation(\n contractAddress(new Uint8Array(accountAddress)),\n request.gasLimit,\n {\n calls: request.invocations.map((inner) => ({\n target: contractAddress(new Uint8Array(inner.invoked_address)),\n entrypoint: fixedBytes(new Uint8Array(inner.entrypoint), 8),\n gas_limit: inner.gas_limit,\n calldata: new Uint8Array(inner.calldata),\n })),\n },\n );\n}\n\n/** Converts a wallet-specific execution request into a root invocation. */\nexport interface WalletInvocationAdapter<\n TRequest extends WalletExecutionRequest = WalletExecutionRequest,\n> {\n /** Build a root deployment when supported by this wallet. */\n createDeploymentInvocation?(\n account: ContractAddress,\n deployment: ContractDeployment,\n options: DeploymentOptions,\n ): Invocation;\n /** Decode the address returned by a root deployment. */\n decodeDeploymentReceipt?(receipt: TransactionReceipt): ContractAddress;\n /** Child return buffers in call order, or null when this wallet discards them. */\n decodeExecutionReturns?(\n receipt: TransactionReceipt,\n ): readonly Uint8Array[] | null;\n /** Build one atomic root for multiple calls when this wallet supports it. */\n createBatchRootInvocation?(\n account: ContractAddress,\n request: WalletBatchExecutionRequest,\n ): Invocation;\n createRootInvocation(\n accountAddress: ContractAddress,\n request: TRequest,\n ): Invocation;\n}\n\n/** Define an invocation adapter while preserving its request type. */\nexport function defineWalletInvocationAdapter<\n TRequest extends WalletExecutionRequest,\n>(\n adapter: WalletInvocationAdapter<TRequest>,\n): WalletInvocationAdapter<TRequest> {\n return adapter;\n}\n\n/** Wrap one call through the native-compatible DefaultWallet interface. */\nexport const defaultWalletAdapter = defineWalletInvocationAdapter({\n createBatchRootInvocation: createDefaultWalletBatchInvocation,\n decodeExecutionReturns: (receipt) =>\n DefaultWallet.v0_1.execute.decodeReceipt(receipt).value,\n createDeploymentInvocation(account, deployment, options) {\n if (\n options.initializer &&\n !bytesEqual(options.initializer.invoked_address, deployment.address)\n )\n throw new Error(\n \"Initializer must target the predicted deployment address\",\n );\n // The wallet takes an i128, but a deployment never funds a negative amount.\n if (options.amount < 0n)\n throw new RangeError(\"Deployment amount must not be negative\");\n return DefaultWallet.v0_1.deploy.invocation(account, options.gasLimit, {\n nonce: fixedBytes(deployment.deploymentNonce, 32),\n contractHash: fixedBytes(deployment.contractHash, 32),\n amount: options.amount,\n initializer: options.initializer\n ? {\n entrypoint: fixedBytes(options.initializer.entrypoint, 8),\n gas_limit: options.initializer.gas_limit,\n calldata: options.initializer.calldata,\n }\n : null,\n });\n },\n decodeDeploymentReceipt: (receipt) =>\n DefaultWallet.v0_1.deploy.decodeReceipt(receipt).value,\n createRootInvocation(\n accountAddress: ContractAddress,\n request: WalletExecutionRequest,\n ): Invocation {\n return createDefaultWalletBatchInvocation(accountAddress, {\n invocations: [request.invocation],\n gasLimit: request.gasLimit,\n });\n },\n});\n\n/** Wrap one call through the legacy DevWallet. Unified deployment is unsupported. */\nexport const devWalletAdapter = defineWalletInvocationAdapter({\n decodeExecutionReturns: () => null,\n createRootInvocation(\n accountAddress: ContractAddress,\n request: WalletExecutionRequest,\n ): Invocation {\n return DevWallet.v0_1.doAction.invocation(\n contractAddress(new Uint8Array(accountAddress)),\n request.gasLimit,\n {\n invocationBytes: serialize(request.invocation, codec.Invocation),\n },\n );\n },\n});\n","import { codec, deserialize } from \"@thruputchain/protocol\";\nimport { hashSignedTransaction } from \"../derivation/transactionHash.js\";\nimport { RpcCompatibilityError } from \"../rpc/client.js\";\nimport {\n RpcRequestValidationError,\n UnsupportedRpcValue,\n} from \"../rpc/codec.js\";\nimport { NativeRpcError } from \"../rpc/errorReader.js\";\nimport {\n TransactionReceiptObservationError,\n type KnownCommitment,\n} from \"../actions/public/waitForTransactionReceipt.js\";\nimport { gasAmount, type GasAmount } from \"@thruputchain/protocol\";\nimport type { CoreThruputClient } from \"../client.js\";\nimport type { TransactionReceipt } from \"../types/rpc.js\";\nimport type { WaitForTransactionReceiptOptions } from \"../actions/public/waitForTransactionReceipt.js\";\nimport type { ContractCall } from \"../contract/method.js\";\nimport {\n defaultWalletAdapter,\n type WalletInvocationAdapter,\n} from \"./invocationAdapter.js\";\nimport { beforeDeadline, validateTimer } from \"../actions/deadline.js\";\nimport { toBase58 } from \"../encoding.js\";\nimport type { RpcSendTransactionResult } from \"../rpc/generated.js\";\n\n/** A committed execution failure, retaining the complete native receipt. */\nexport class TransactionExecutionError extends Error {\n constructor(\n readonly receipt: TransactionReceipt,\n readonly submission?: SubmissionEvidence,\n ) {\n super(\n receipt.execution instanceof UnsupportedRpcValue\n ? `Transaction ${toBase58(receipt.transactionHash)} has an unsupported execution outcome`\n : `Transaction ${toBase58(receipt.transactionHash)} execution failed (${receipt.execution.result})`,\n );\n this.name = \"TransactionExecutionError\";\n }\n}\n/** A future execution variant is unsupported, never inferred to be success or failure. */\nexport class UnsupportedTransactionOutcomeError extends TransactionExecutionError {\n constructor(receipt: TransactionReceipt, submission?: SubmissionEvidence) {\n super(receipt, submission);\n this.name = \"UnsupportedTransactionOutcomeError\";\n }\n}\nexport function assertTransactionSuccess(\n receipt: TransactionReceipt,\n submission?: SubmissionEvidence,\n): asserts receipt is TransactionReceipt & {\n execution: { result: \"return\"; returnData: Uint8Array };\n} {\n if (receipt.execution instanceof UnsupportedRpcValue)\n throw new UnsupportedTransactionOutcomeError(receipt, submission);\n if (receipt.execution.result !== \"return\")\n throw new TransactionExecutionError(receipt, submission);\n}\n\n/** A submit response that does not establish the currently supported admission outcome. */\nexport class UnsupportedTransactionAdmissionError extends Error {\n constructor(readonly response: RpcSendTransactionResult) {\n super(\"Transaction submission returned an unsupported admission outcome\");\n this.name = \"UnsupportedTransactionAdmissionError\";\n }\n}\n\n/** Keep low-level future values intact, but never project them into an admitted hash. */\nexport function assertTransactionAdmission(\n response: RpcSendTransactionResult,\n): void {\n if (response.admission !== \"accepted\")\n throw new UnsupportedTransactionAdmissionError(response);\n}\nexport interface SubmissionEvidence {\n readonly signedTransaction: Uint8Array;\n readonly transactionHash: Uint8Array;\n readonly networkHash: Uint8Array;\n}\n/** Snapshot approved bytes before submission; accessor copies protect the retained record. */\nexport function createSubmissionEvidence(\n bytes: Uint8Array,\n network: Uint8Array,\n): SubmissionEvidence {\n const signedTransaction = new Uint8Array(bytes);\n const networkHash = new Uint8Array(network);\n if (networkHash.length !== 32)\n throw new RangeError(\"networkHash must contain 32 bytes\");\n const transactionHash = hashSignedTransaction(\n deserialize(signedTransaction, codec.SignedTransaction),\n );\n return Object.freeze({\n get signedTransaction() {\n return signedTransaction.slice();\n },\n get transactionHash() {\n return transactionHash.slice();\n },\n get networkHash() {\n return networkHash.slice();\n },\n });\n}\nexport interface ExecutionResult {\n transactionHash: Uint8Array;\n receipt: TransactionReceipt;\n submission?: SubmissionEvidence;\n}\n/** Submission or observation stopped, preserving exact approved bytes and commitment. */\nexport class TransactionObservationError extends Error {\n constructor(\n readonly submission: SubmissionEvidence,\n cause: unknown,\n readonly submissionCause?: unknown,\n readonly knownCommitment?: KnownCommitment,\n readonly phase:\n | \"beforeSubmission\"\n | \"submission\"\n | \"observation\" = \"observation\",\n ) {\n super(\n `Could not complete transaction ${toBase58(submission.transactionHash)}`,\n { cause },\n );\n this.name = \"TransactionObservationError\";\n }\n get transactionHash(): Uint8Array {\n return this.submission.transactionHash;\n }\n}\n/** Submit once, then reconcile only by reads. No path replaces or repeats signed bytes. */\nexport async function submitAndObserve(\n client: Pick<CoreThruputClient, \"waitForTransactionReceipt\">,\n evidence: SubmissionEvidence,\n submit: (signal: AbortSignal) => Promise<void>,\n options?: WaitForTransactionReceiptOptions,\n wasDispatched?: () => boolean,\n): Promise<ExecutionResult> {\n const submission = createSubmissionEvidence(\n evidence.signedTransaction,\n evidence.networkHash,\n );\n const timeoutMs = options?.timeoutMs ?? 30000;\n validateTimer(timeoutMs, \"timeoutMs\");\n const deadline = performance.now() + timeoutMs;\n let submissionCause: unknown;\n try {\n options?.signal?.throwIfAborted();\n if (timeoutMs === 0)\n throw new Error(\"Transaction submission timed out before dispatch\");\n } catch (cause) {\n throw new TransactionObservationError(\n submission,\n cause,\n undefined,\n undefined,\n \"beforeSubmission\",\n );\n }\n try {\n await beforeDeadline(\n submit,\n deadline,\n options?.signal,\n () => new Error(\"Transaction submission timed out\"),\n );\n } catch (cause) {\n if (\n wasDispatched?.() === false ||\n cause instanceof RpcRequestValidationError ||\n cause instanceof RpcCompatibilityError\n )\n throw new TransactionObservationError(\n submission,\n cause,\n undefined,\n undefined,\n \"beforeSubmission\",\n );\n if (\n cause instanceof NativeRpcError &&\n cause.decoded.classification === \"known\" &&\n (cause.decoded.data.kind === \"invalidParams\" ||\n cause.decoded.data.kind === \"transactionInvalid\" ||\n cause.decoded.data.kind === \"transactionRejected\")\n )\n throw new TransactionObservationError(\n submission,\n cause,\n undefined,\n undefined,\n \"submission\",\n );\n submissionCause = cause;\n if (options?.signal?.aborted || performance.now() >= deadline)\n throw new TransactionObservationError(\n submission,\n cause,\n submissionCause,\n undefined,\n \"submission\",\n );\n }\n try {\n const receipt = await client.waitForTransactionReceipt(\n submission.transactionHash,\n {\n ...options,\n expectedNetworkHash: submission.networkHash,\n timeoutMs: Math.max(0, deadline - performance.now()),\n },\n );\n return { transactionHash: receipt.transactionHash, receipt, submission };\n } catch (cause) {\n throw new TransactionObservationError(\n submission,\n cause,\n submissionCause,\n cause instanceof TransactionReceiptObservationError\n ? cause.knownCommitment\n : undefined,\n );\n }\n}\n/** Wait for a committed receipt, then require execution success. */\nexport async function waitForExecution(\n client: Pick<CoreThruputClient, \"waitForTransactionReceipt\">,\n hash: Uint8Array,\n options?: WaitForTransactionReceiptOptions,\n): Promise<ExecutionResult> {\n const receipt = await client.waitForTransactionReceipt(hash, options);\n assertTransactionSuccess(receipt);\n return { transactionHash: receipt.transactionHash, receipt };\n}\n\n/** Ordered result types for a tuple of calls. */\nexport type CallResults<T extends readonly ContractCall[]> = {\n [K in keyof T]: T[K] extends ContractCall<infer R> ? R : never;\n};\n\n/**\n * Decode DefaultWallet child returns without modifying the root receipt.\n * Works after disconnect and preserves call order. Supply an adapter for other\n * wallets. Wallets such as DevWallet that discard child return data report\n * unavailable results. Failed wallet receipts are not decoded with a child ABI:\n * even a single child call does not establish where an abort originated.\n */\nexport function decodeExecution<T extends readonly ContractCall[]>(\n receipt: TransactionReceipt,\n calls: T,\n adapter: WalletInvocationAdapter = defaultWalletAdapter,\n submission?: SubmissionEvidence,\n): CallResults<T> {\n // Even one child call can fail in the wallet root; its abort bytes are not a child receipt.\n assertTransactionSuccess(receipt, submission);\n try {\n const buffers = adapter.decodeExecutionReturns?.(receipt);\n if (buffers == null)\n throw new ExecutionReturnUnavailableError(receipt, submission);\n if (buffers.length !== calls.length)\n throw new Error(\n `Returned ${buffers.length} child results; expected ${calls.length}`,\n );\n return calls.map((call, index) =>\n call.method.decodeReturn(buffers[index]!),\n ) as CallResults<T>;\n } catch (cause) {\n if (cause instanceof ExecutionReturnUnavailableError) throw cause;\n throw new ExecutionDecodeError(receipt, cause, submission);\n }\n}\n\n/** A committed successful execution whose return data could not be decoded. */\nexport class ExecutionDecodeError extends Error {\n constructor(\n readonly receipt: TransactionReceipt,\n cause: unknown,\n readonly submission?: SubmissionEvidence,\n ) {\n super(\n `Transaction ${toBase58(receipt.transactionHash)} committed, but result decoding failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n { cause },\n );\n this.name = \"ExecutionDecodeError\";\n }\n}\n\n/** Execution succeeded, but this wallet does not preserve child return buffers. */\nexport class ExecutionReturnUnavailableError extends Error {\n constructor(\n readonly receipt: TransactionReceipt,\n readonly submission?: SubmissionEvidence,\n ) {\n super(\n `Transaction ${toBase58(receipt.transactionHash)} committed successfully, but its wallet does not expose child return data`,\n );\n this.name = \"ExecutionReturnUnavailableError\";\n }\n}\n\n/**\n * Sum explicit child budgets and a calibrated wallet overhead, checking u64 bounds.\n * This is not gas estimation. Calibrate budgets against the target runtime and\n * workload; there is no universally safe wallet overhead. Root gas reserves\n * scheduling capacity against the sender's free native-token balance. Storage\n * deposits are a separate requirement, and funding a target contract does not\n * sponsor root gas.\n */\nexport function walletGasLimit(\n calls: readonly { gas_limit: GasAmount }[],\n overhead: GasAmount,\n): GasAmount {\n const limits = [overhead, ...calls.map((call) => call.gas_limit)];\n if (limits.some((limit) => typeof limit !== \"bigint\" || limit < 0n))\n throw new RangeError(\"Gas budgets must be nonnegative bigint values\");\n const total = limits.reduce((sum, limit) => sum + limit, 0n);\n if (total > 0xffff_ffff_ffff_ffffn)\n throw new RangeError(\"Root gas budget exceeds u64\");\n return gasAmount(total);\n}\n","import {\n blockHeight,\n codec,\n deserialize,\n serialize,\n type BlockHeight,\n type Contract,\n type Invocation,\n type Transaction,\n} from \"@thruputchain/protocol\";\nimport type { CoreThruputClient } from \"../../client.js\";\nimport type { WalletAccount } from \"../../wallet/account.js\";\nimport { createTransaction } from \"../../transaction/build.js\";\n\nconst int64Max = 0x7fff_ffff_ffff_ffffn;\nconst uint64Max = 0xffff_ffff_ffff_ffffn;\nconst defaultExpiryBlocks = 100n;\n\n/** Inputs for preparing one wallet-authorized transaction. */\nexport interface PrepareTransactionRequest {\n /** Explicit root invocation. Smart-wallet wrapping is caller-controlled. */\n readonly invocation: Invocation;\n readonly contractsToDeploy?: readonly Contract[];\n readonly nonce?: bigint;\n readonly blockExpiryHeight?: BlockHeight;\n readonly expiryBlocks?: bigint;\n}\n\n/** Prepare an unsigned transaction for a wallet account. */\nexport async function prepareTransaction(\n client: Pick<CoreThruputClient, \"getChainTip\">,\n account: Pick<WalletAccount, \"address\" | \"authClaim\">,\n request: PrepareTransactionRequest,\n): Promise<Transaction> {\n const invocation = deserialize(\n serialize(request.invocation, codec.Invocation),\n codec.Invocation,\n );\n const contractsToDeploy = (request.contractsToDeploy ?? []).map((contract) =>\n deserialize(serialize(contract, codec.Contract), codec.Contract),\n );\n const authClaim = deserialize(\n serialize(account.authClaim, codec.AuthClaim),\n codec.AuthClaim,\n );\n\n if (!bytesEqual(invocation.invoked_address, account.address)) {\n throw new Error(\"Root invocation address must match the wallet account\");\n }\n if (\n request.blockExpiryHeight !== undefined &&\n request.expiryBlocks !== undefined\n ) {\n throw new Error(\n \"blockExpiryHeight and expiryBlocks are mutually exclusive\",\n );\n }\n\n const nonce = request.nonce ?? randomUint64();\n validateRange(nonce, 0n, uint64Max, \"nonce\");\n\n let expiry: bigint;\n if (request.blockExpiryHeight !== undefined) {\n expiry = request.blockExpiryHeight;\n validateRange(expiry, 0n, int64Max, \"blockExpiryHeight\");\n } else {\n const expiryBlocks = request.expiryBlocks ?? defaultExpiryBlocks;\n validateRange(expiryBlocks, 1n, int64Max, \"expiryBlocks\");\n const tip = await client.getChainTip();\n expiry = tip.blockHeight + expiryBlocks;\n validateRange(expiry, 0n, int64Max, \"blockExpiryHeight\");\n }\n\n return createTransaction({\n invocation,\n uniquifier: {\n block_expiry_height: blockHeight(expiry),\n nonce,\n },\n contracts_to_deploy: contractsToDeploy,\n auth_claim: authClaim,\n });\n}\n\nfunction randomUint64(): bigint {\n const bytes = crypto.getRandomValues(new Uint8Array(8));\n return new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n ).getBigUint64(0);\n}\n\nfunction validateRange(\n value: bigint,\n min: bigint,\n max: bigint,\n name: string,\n): void {\n if (typeof value !== \"bigint\" || value < min || value > max) {\n throw new RangeError(`${name} must be between ${min} and ${max}`);\n }\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n if (left.length !== right.length) return false;\n return left.every((byte, index) => byte === right[index]);\n}\n","import type {\n SHA256Hash,\n SignedTransaction,\n Transaction,\n NetworkHash,\n} from \"@thruputchain/protocol\";\nimport { codec, serialize, sha256Hash } from \"@thruputchain/protocol\";\nimport {\n createSubmissionEvidence,\n assertTransactionAdmission,\n TransactionObservationError,\n type SubmissionEvidence,\n} from \"../../wallet/execution.js\";\nimport { RpcRequestValidationError } from \"../../rpc/codec.js\";\nimport { RpcCompatibilityError } from \"../../rpc/client.js\";\nimport type { CoreThruputClient } from \"../../client.js\";\nimport type { WalletAccount } from \"../../wallet/account.js\";\nimport { signTransaction as sign } from \"../../transaction/sign.js\";\nimport {\n prepareTransaction,\n type PrepareTransactionRequest,\n} from \"./prepareTransaction.js\";\n\n/** Sign a transaction with a wallet account's configured signers. */\nexport function signWalletTransaction(\n account: WalletAccount,\n transaction: Transaction,\n networkHash: NetworkHash,\n): Promise<SignedTransaction> {\n return sign(transaction, account.signers, networkHash);\n}\n\n/** Prepare, sign, and submit one explicit root invocation. */\nexport async function sendInvocation(\n client: Pick<\n CoreThruputClient,\n \"getChainTip\" | \"sendTransaction\" | \"requireMethods\" | \"discovery\"\n >,\n account: WalletAccount,\n networkHash: NetworkHash,\n request: PrepareTransactionRequest,\n controls: {\n signal?: AbortSignal;\n onSigned?: (evidence: SubmissionEvidence) => void | Promise<void>;\n } = {},\n): Promise<SHA256Hash> {\n controls.signal?.throwIfAborted();\n client.requireMethods([\"getChainTip\", \"sendTransaction\"]);\n const signingNetwork = new Uint8Array(networkHash) as NetworkHash;\n const checkNetwork = () => {\n const discovered = client.discovery.network.networkHash;\n if (\n signingNetwork.length !== 32 ||\n discovered.length !== 32 ||\n signingNetwork.some((value, index) => value !== discovered[index])\n )\n throw new RpcCompatibilityError(\n \"Signing network does not match endpoint discovery\",\n );\n };\n checkNetwork();\n const signers = account.signers.map(({ signer, publicKeyId }) => ({\n signer,\n publicKeyId,\n }));\n const transaction = await prepareTransaction(client, account, request);\n checkNetwork();\n const signed = await sign(transaction, signers, signingNetwork);\n const evidence = createSubmissionEvidence(\n serialize(signed, codec.SignedTransaction),\n signingNetwork,\n );\n let phase: \"beforeSubmission\" | \"submission\" = \"beforeSubmission\";\n try {\n await controls.onSigned?.(evidence);\n controls.signal?.throwIfAborted();\n checkNetwork();\n phase = \"submission\";\n const result = await client.sendTransaction(\n { signedTransaction: evidence.signedTransaction },\n { signal: controls.signal },\n );\n assertTransactionAdmission(result);\n return sha256Hash(result.transactionHash);\n } catch (cause) {\n throw new TransactionObservationError(\n evidence,\n cause,\n undefined,\n undefined,\n cause instanceof RpcRequestValidationError ||\n cause instanceof RpcCompatibilityError\n ? \"beforeSubmission\"\n : phase,\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;AACA,eAAsB,eACpB,WACA,UACA,QACA,SACY;CACZ,QAAQ,eAAe;CACvB,IAAI,YAAY,IAAI,KAAK,UAAU,MAAM,QAAQ;CACjD,MAAM,aAAa,IAAI,gBAAgB;CACvC,MAAM,SAAS,SACX,YAAY,IAAI,CAAC,QAAQ,WAAW,MAAM,CAAC,IAC3C,WAAW;CACf,IAAI;CACJ,IAAI,gBAAgB,CAAC;CACrB,IAAI;EACF,OAAO,MAAM,QAAQ,KAAK,CACxB,IAAI,SAAY,GAAG,WAAW;GAC5B,gBAAgB,OAAO,OAAO,MAAM;GACpC,OAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;GACxD,QAAQ,iBACA,WAAW,MAAM,Q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+1,139 @@
1
+ const require_size = require("./size-OAFfOthl.cjs");
2
+ let _thruputchain_protocol = require("@thruputchain/protocol");
3
+ //#region src/transaction/build.ts
4
+ /**
5
+ * Build an invocation object from already-typed protocol values.
6
+ *
7
+ * Generated contract bindings usually call this helper for you. Use it directly
8
+ * when constructing a low-level invocation without generated bindings.
9
+ */
10
+ function createInvocation(params) {
11
+ return {
12
+ invoked_address: params.invoked_address,
13
+ entrypoint: params.entrypoint,
14
+ gas_limit: params.gas_limit,
15
+ calldata: params.calldata
16
+ };
17
+ }
18
+ /**
19
+ * Build an unsigned transaction from an invocation and authorization metadata.
20
+ *
21
+ * The returned transaction must be signed with {@link signTransaction} before it
22
+ * can be submitted to a Thruput JSON-RPC gateway.
23
+ */
24
+ function createTransaction(params) {
25
+ return {
26
+ invocation: params.invocation,
27
+ uniquifier: params.uniquifier,
28
+ contracts_to_deploy: params.contracts_to_deploy,
29
+ auth_claim: params.auth_claim
30
+ };
31
+ }
32
+ //#endregion
33
+ //#region src/transaction/sign.ts
34
+ /**
35
+ * Sign a transaction with one or more signers.
36
+ *
37
+ * The signature preimage is built once and each signer signs the same canonical
38
+ * bytes. The result can be passed to `sendTransaction` or serialized with
39
+ * `serializeSignedTransaction`.
40
+ *
41
+ * For a `kPubkeySignature` claim there must be exactly one signer, with
42
+ * public-key ID zero, whose key hashes to the claim's `pubkey_hash`; its key is
43
+ * attached as `pubkey_claim_key` and its signature must use the key's scheme.
44
+ * Other claims carry no `pubkey_claim_key`. Neither the key nor the signatures
45
+ * are part of the signed `Transaction`, so re-signing never changes the
46
+ * transaction hash.
47
+ *
48
+ * `networkHash` identifies the network the transaction is for. It is part of
49
+ * what gets signed, so a transaction signed for one chain will be rejected by
50
+ * another — see {@link transactionSignaturePreimage}. Local development can
51
+ * read it from the public `getNetworkInfo` response; elsewhere it
52
+ * comes from whoever operates the network.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { signTransaction } from "@thruputchain/client/transaction";
57
+ * import { Ed25519Signer } from "@thruputchain/client/signers";
58
+ *
59
+ * const signer = Ed25519Signer.fromSeed(secretKey);
60
+ * const signedTx = await signTransaction(
61
+ * tx,
62
+ * [{ signer, publicKeyId: 0n }],
63
+ * networkHash,
64
+ * );
65
+ * ```
66
+ */
67
+ async function signTransaction(tx, signers, networkHash) {
68
+ const transaction = (0, _thruputchain_protocol.deserialize)((0, _thruputchain_protocol.serialize)(tx, _thruputchain_protocol.codec.Transaction), _thruputchain_protocol.codec.Transaction);
69
+ const signerEntries = signers.map(({ signer, publicKeyId }) => ({
70
+ signer,
71
+ publicKeyId
72
+ }));
73
+ const pubkeyClaimKey = validateSignerEntries(transaction, signerEntries);
74
+ const preimage = require_size.transactionSignaturePreimage(networkHash, transaction);
75
+ return {
76
+ tx: transaction,
77
+ signatures: await Promise.all(signerEntries.map(async (entry) => {
78
+ const signature = await entry.signer.sign(preimage);
79
+ if (pubkeyClaimKey && signature.scheme !== pubkeyClaimKey.scheme) throw new Error("Signer returned a signature whose scheme does not match its public key");
80
+ return {
81
+ public_key_id: entry.publicKeyId,
82
+ signature
83
+ };
84
+ })),
85
+ pubkey_claim_key: pubkeyClaimKey
86
+ };
87
+ }
88
+ /** Validates the signer set and returns the key a pubkey claim must carry. */
89
+ function validateSignerEntries(transaction, signers) {
90
+ if (signers.length > _thruputchain_protocol.kMaxSigners) throw new RangeError(`signers must contain at most ${_thruputchain_protocol.kMaxSigners} entries`);
91
+ let previousId = -1n;
92
+ for (const entry of signers) {
93
+ if (typeof entry.publicKeyId !== "bigint" || entry.publicKeyId < 0n || entry.publicKeyId >= _thruputchain_protocol.kMaxSigners) throw new RangeError(`publicKeyId must be between 0 and ${_thruputchain_protocol.kMaxSigners - 1n}`);
94
+ if (entry.publicKeyId <= previousId) throw new Error("Signer publicKeyIds must be strictly increasing");
95
+ if (!entry.signer || typeof entry.signer.sign !== "function") throw new Error("Invalid signer");
96
+ previousId = entry.publicKeyId;
97
+ }
98
+ if (transaction.auth_claim.claim_type === _thruputchain_protocol.AuthClaimType.kPubkeySignature) {
99
+ if (signers.length !== 1 || signers[0].publicKeyId !== 0n) throw new Error("Pubkey authorization requires only publicKeyId 0");
100
+ const publicKey = copyPublicKey(signers[0].signer.publicKey);
101
+ if (!bytesEqual(require_size.derivePublicKeyHash(publicKey), transaction.auth_claim.pubkey_preimage.pubkey_hash)) throw new Error("Signer public key does not match the auth claim's pubkey_hash");
102
+ return publicKey;
103
+ }
104
+ const allowedKeys = transaction.auth_claim.source_address_claim.allowed_keys;
105
+ for (const { publicKeyId } of signers) if ((allowedKeys & 1n << publicKeyId) === 0n) throw new Error(`publicKeyId ${publicKeyId} is not selected by authClaim`);
106
+ return null;
107
+ }
108
+ /** Copy and re-validate a signer's key through the protocol codec. */
109
+ function copyPublicKey(publicKey) {
110
+ try {
111
+ return (0, _thruputchain_protocol.deserialize)((0, _thruputchain_protocol.serialize)(publicKey, _thruputchain_protocol.codec.PublicKey), _thruputchain_protocol.codec.PublicKey);
112
+ } catch {
113
+ throw new Error("Invalid signer public key");
114
+ }
115
+ }
116
+ function bytesEqual(left, right) {
117
+ return left.length === right.length && left.every((byte, index) => byte === right[index]);
118
+ }
119
+ //#endregion
120
+ Object.defineProperty(exports, "createInvocation", {
121
+ enumerable: true,
122
+ get: function() {
123
+ return createInvocation;
124
+ }
125
+ });
126
+ Object.defineProperty(exports, "createTransaction", {
127
+ enumerable: true,
128
+ get: function() {
129
+ return createTransaction;
130
+ }
131
+ });
132
+ Object.defineProperty(exports, "signTransaction", {
133
+ enumerable: true,
134
+ get: function() {
135
+ return signTransaction;
136
+ }
137
+ });
138
+
139
+ //# sourceMappingURL=sign-BewmV_EL.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-BewmV_EL.cjs","names":["codec","transactionSignaturePreimage","kMaxSigners","AuthClaimType","derivePublicKeyHash"],"sources":["../src/transaction/build.ts","../src/transaction/sign.ts"],"sourcesContent":["import type {\n Invocation,\n Transaction,\n ContractAddress,\n ContractEntrypointID,\n GasAmount,\n Calldata,\n Uniquifier,\n AuthClaim,\n Contract,\n} from \"@thruputchain/protocol\";\n\n/**\n * Build an invocation object from already-typed protocol values.\n *\n * Generated contract bindings usually call this helper for you. Use it directly\n * when constructing a low-level invocation without generated bindings.\n */\nexport function createInvocation(params: {\n invoked_address: ContractAddress;\n entrypoint: ContractEntrypointID;\n gas_limit: GasAmount;\n calldata: Calldata;\n}): Invocation {\n return {\n invoked_address: params.invoked_address,\n entrypoint: params.entrypoint,\n gas_limit: params.gas_limit,\n calldata: params.calldata,\n };\n}\n\n/**\n * Build an unsigned transaction from an invocation and authorization metadata.\n *\n * The returned transaction must be signed with {@link signTransaction} before it\n * can be submitted to a Thruput JSON-RPC gateway.\n */\nexport function createTransaction(params: {\n invocation: Invocation;\n uniquifier: Uniquifier;\n contracts_to_deploy: Contract[];\n auth_claim: AuthClaim;\n}): Transaction {\n return {\n invocation: params.invocation,\n uniquifier: params.uniquifier,\n contracts_to_deploy: params.contracts_to_deploy,\n auth_claim: params.auth_claim,\n };\n}\n","import type {\n Transaction,\n SignedTransaction,\n DecoratedSignature,\n NetworkHash,\n PublicKey,\n} from \"@thruputchain/protocol\";\nimport {\n AuthClaimType,\n codec,\n deserialize,\n kMaxSigners,\n serialize,\n} from \"@thruputchain/protocol\";\nimport type { Signer } from \"../signers/types.js\";\nimport { derivePublicKeyHash } from \"../derivation/publicKeyHash.js\";\nimport { transactionSignaturePreimage } from \"./preimage.js\";\n\n/** A signer plus the protocol public-key ID to attach to its signature. */\nexport interface SignerEntry {\n /** Signer implementation that produces a protocol signature. */\n readonly signer: Signer;\n\n /** Public-key ID expected by the chain for this signer. */\n readonly publicKeyId: bigint;\n}\n\n/**\n * Sign a transaction with one or more signers.\n *\n * The signature preimage is built once and each signer signs the same canonical\n * bytes. The result can be passed to `sendTransaction` or serialized with\n * `serializeSignedTransaction`.\n *\n * For a `kPubkeySignature` claim there must be exactly one signer, with\n * public-key ID zero, whose key hashes to the claim's `pubkey_hash`; its key is\n * attached as `pubkey_claim_key` and its signature must use the key's scheme.\n * Other claims carry no `pubkey_claim_key`. Neither the key nor the signatures\n * are part of the signed `Transaction`, so re-signing never changes the\n * transaction hash.\n *\n * `networkHash` identifies the network the transaction is for. It is part of\n * what gets signed, so a transaction signed for one chain will be rejected by\n * another — see {@link transactionSignaturePreimage}. Local development can\n * read it from the public `getNetworkInfo` response; elsewhere it\n * comes from whoever operates the network.\n *\n * @example\n * ```ts\n * import { signTransaction } from \"@thruputchain/client/transaction\";\n * import { Ed25519Signer } from \"@thruputchain/client/signers\";\n *\n * const signer = Ed25519Signer.fromSeed(secretKey);\n * const signedTx = await signTransaction(\n * tx,\n * [{ signer, publicKeyId: 0n }],\n * networkHash,\n * );\n * ```\n */\nexport async function signTransaction(\n tx: Transaction,\n signers: readonly SignerEntry[],\n networkHash: NetworkHash,\n): Promise<SignedTransaction> {\n const txBytes = serialize(tx, codec.Transaction);\n const transaction = deserialize(txBytes, codec.Transaction);\n const signerEntries = signers.map(({ signer, publicKeyId }) => ({\n signer,\n publicKeyId,\n }));\n const pubkeyClaimKey = validateSignerEntries(transaction, signerEntries);\n const preimage = transactionSignaturePreimage(networkHash, transaction);\n\n const signatures: DecoratedSignature[] = await Promise.all(\n signerEntries.map(async (entry) => {\n const signature = await entry.signer.sign(preimage);\n if (pubkeyClaimKey && signature.scheme !== pubkeyClaimKey.scheme) {\n throw new Error(\n \"Signer returned a signature whose scheme does not match its public key\",\n );\n }\n return {\n public_key_id: entry.publicKeyId,\n signature,\n };\n }),\n );\n\n return { tx: transaction, signatures, pubkey_claim_key: pubkeyClaimKey };\n}\n\n/** Validates the signer set and returns the key a pubkey claim must carry. */\nfunction validateSignerEntries(\n transaction: Transaction,\n signers: readonly SignerEntry[],\n): PublicKey | null {\n if (signers.length > kMaxSigners) {\n throw new RangeError(`signers must contain at most ${kMaxSigners} entries`);\n }\n\n let previousId = -1n;\n for (const entry of signers) {\n if (\n typeof entry.publicKeyId !== \"bigint\" ||\n entry.publicKeyId < 0n ||\n entry.publicKeyId >= kMaxSigners\n ) {\n throw new RangeError(\n `publicKeyId must be between 0 and ${kMaxSigners - 1n}`,\n );\n }\n if (entry.publicKeyId <= previousId) {\n throw new Error(\"Signer publicKeyIds must be strictly increasing\");\n }\n if (!entry.signer || typeof entry.signer.sign !== \"function\") {\n throw new Error(\"Invalid signer\");\n }\n previousId = entry.publicKeyId;\n }\n\n if (transaction.auth_claim.claim_type === AuthClaimType.kPubkeySignature) {\n if (signers.length !== 1 || signers[0]!.publicKeyId !== 0n) {\n throw new Error(\"Pubkey authorization requires only publicKeyId 0\");\n }\n const publicKey = copyPublicKey(signers[0]!.signer.publicKey);\n if (\n !bytesEqual(\n derivePublicKeyHash(publicKey),\n transaction.auth_claim.pubkey_preimage.pubkey_hash,\n )\n ) {\n throw new Error(\n \"Signer public key does not match the auth claim's pubkey_hash\",\n );\n }\n return publicKey;\n }\n\n const allowedKeys = transaction.auth_claim.source_address_claim.allowed_keys;\n for (const { publicKeyId } of signers) {\n if ((allowedKeys & (1n << publicKeyId)) === 0n) {\n throw new Error(\n `publicKeyId ${publicKeyId} is not selected by authClaim`,\n );\n }\n }\n return null;\n}\n\n/** Copy and re-validate a signer's key through the protocol codec. */\nfunction copyPublicKey(publicKey: PublicKey): PublicKey {\n try {\n return deserialize(serialize(publicKey, codec.PublicKey), codec.PublicKey);\n } catch {\n throw new Error(\"Invalid signer public key\");\n }\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n return (\n left.length === right.length &&\n left.every((byte, index) => byte === right[index])\n );\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAgB,iBAAiB,QAKlB;CACb,OAAO;EACL,iBAAiB,OAAO;EACxB,YAAY,OAAO;EACnB,WAAW,OAAO;EAClB,UAAU,OAAO;CACnB;AACF;;;;;;;AAQA,SAAgB,kBAAkB,QAKlB;CACd,OAAO;EACL,YAAY,OAAO;EACnB,YAAY,OAAO;EACnB,qBAAqB,OAAO;EAC5B,YAAY,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Q,EAAE,CAAE,gBAAgB,IACtD,MAAM,IAAI,MAAM,kDAAkD;EAEpE,MAAM,YAAY,cAAc,QAAQ,EAAE,CAAE,OAAO,SAAS;EAC5D,IACE,CAAC,WACCC,aAAAA,oBAAoB,SAAS,GAC7B,YAAY,WAAW,gBAAgB,WACzC,GAEA,MAAM,IAAI,MACR,+DACF;EAEF,OAAO;CACT;CAEA,MAAM,cAAc,YAAY,WAAW,qBAAqB;CAChE,KAAK,MAAM,EAAE,iBAAiB,SAC5B,KAAK,cAAe,MAAM,iBAAkB,IAC1C,MAAM,IAAI,MACR,eAAe,YAAY,8BAC7B;CAGJ,OAAO;AACT;;AAGA,SAAS,cAAc,WAAiC;CACtD,IAAI;EACF,QAAA,GAAA,uBAAA,YAAA,EAAA,GAAA,uBAAA,UAAA,CAA6B,WAAWJ,uBAAAA,MAAM,SAAS,GAAGA,uBAAAA,MAAM,SAAS;CAC3E,QAAQ;EACN,MAAM,IAAI,MAAM,2BAA2B;CAC7C;AACF;AAEA,SAAS,WAAW,MAAkB,OAA4B;CAChE,OACE,KAAK,WAAW,MAAM,UACtB,KAAK,OAAO,MAAM,UAAU,SAAS,MAAM,MAAM;AAErD"}
@@ -0,0 +1,122 @@
1
+ import { n as transactionSignaturePreimage, r as derivePublicKeyHash } from "./size-506oTE28.js";
2
+ import { AuthClaimType, codec, deserialize, kMaxSigners, serialize } from "@thruputchain/protocol";
3
+ //#region src/transaction/build.ts
4
+ /**
5
+ * Build an invocation object from already-typed protocol values.
6
+ *
7
+ * Generated contract bindings usually call this helper for you. Use it directly
8
+ * when constructing a low-level invocation without generated bindings.
9
+ */
10
+ function createInvocation(params) {
11
+ return {
12
+ invoked_address: params.invoked_address,
13
+ entrypoint: params.entrypoint,
14
+ gas_limit: params.gas_limit,
15
+ calldata: params.calldata
16
+ };
17
+ }
18
+ /**
19
+ * Build an unsigned transaction from an invocation and authorization metadata.
20
+ *
21
+ * The returned transaction must be signed with {@link signTransaction} before it
22
+ * can be submitted to a Thruput JSON-RPC gateway.
23
+ */
24
+ function createTransaction(params) {
25
+ return {
26
+ invocation: params.invocation,
27
+ uniquifier: params.uniquifier,
28
+ contracts_to_deploy: params.contracts_to_deploy,
29
+ auth_claim: params.auth_claim
30
+ };
31
+ }
32
+ //#endregion
33
+ //#region src/transaction/sign.ts
34
+ /**
35
+ * Sign a transaction with one or more signers.
36
+ *
37
+ * The signature preimage is built once and each signer signs the same canonical
38
+ * bytes. The result can be passed to `sendTransaction` or serialized with
39
+ * `serializeSignedTransaction`.
40
+ *
41
+ * For a `kPubkeySignature` claim there must be exactly one signer, with
42
+ * public-key ID zero, whose key hashes to the claim's `pubkey_hash`; its key is
43
+ * attached as `pubkey_claim_key` and its signature must use the key's scheme.
44
+ * Other claims carry no `pubkey_claim_key`. Neither the key nor the signatures
45
+ * are part of the signed `Transaction`, so re-signing never changes the
46
+ * transaction hash.
47
+ *
48
+ * `networkHash` identifies the network the transaction is for. It is part of
49
+ * what gets signed, so a transaction signed for one chain will be rejected by
50
+ * another — see {@link transactionSignaturePreimage}. Local development can
51
+ * read it from the public `getNetworkInfo` response; elsewhere it
52
+ * comes from whoever operates the network.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import { signTransaction } from "@thruputchain/client/transaction";
57
+ * import { Ed25519Signer } from "@thruputchain/client/signers";
58
+ *
59
+ * const signer = Ed25519Signer.fromSeed(secretKey);
60
+ * const signedTx = await signTransaction(
61
+ * tx,
62
+ * [{ signer, publicKeyId: 0n }],
63
+ * networkHash,
64
+ * );
65
+ * ```
66
+ */
67
+ async function signTransaction(tx, signers, networkHash) {
68
+ const transaction = deserialize(serialize(tx, codec.Transaction), codec.Transaction);
69
+ const signerEntries = signers.map(({ signer, publicKeyId }) => ({
70
+ signer,
71
+ publicKeyId
72
+ }));
73
+ const pubkeyClaimKey = validateSignerEntries(transaction, signerEntries);
74
+ const preimage = transactionSignaturePreimage(networkHash, transaction);
75
+ return {
76
+ tx: transaction,
77
+ signatures: await Promise.all(signerEntries.map(async (entry) => {
78
+ const signature = await entry.signer.sign(preimage);
79
+ if (pubkeyClaimKey && signature.scheme !== pubkeyClaimKey.scheme) throw new Error("Signer returned a signature whose scheme does not match its public key");
80
+ return {
81
+ public_key_id: entry.publicKeyId,
82
+ signature
83
+ };
84
+ })),
85
+ pubkey_claim_key: pubkeyClaimKey
86
+ };
87
+ }
88
+ /** Validates the signer set and returns the key a pubkey claim must carry. */
89
+ function validateSignerEntries(transaction, signers) {
90
+ if (signers.length > kMaxSigners) throw new RangeError(`signers must contain at most ${kMaxSigners} entries`);
91
+ let previousId = -1n;
92
+ for (const entry of signers) {
93
+ if (typeof entry.publicKeyId !== "bigint" || entry.publicKeyId < 0n || entry.publicKeyId >= kMaxSigners) throw new RangeError(`publicKeyId must be between 0 and ${kMaxSigners - 1n}`);
94
+ if (entry.publicKeyId <= previousId) throw new Error("Signer publicKeyIds must be strictly increasing");
95
+ if (!entry.signer || typeof entry.signer.sign !== "function") throw new Error("Invalid signer");
96
+ previousId = entry.publicKeyId;
97
+ }
98
+ if (transaction.auth_claim.claim_type === AuthClaimType.kPubkeySignature) {
99
+ if (signers.length !== 1 || signers[0].publicKeyId !== 0n) throw new Error("Pubkey authorization requires only publicKeyId 0");
100
+ const publicKey = copyPublicKey(signers[0].signer.publicKey);
101
+ if (!bytesEqual(derivePublicKeyHash(publicKey), transaction.auth_claim.pubkey_preimage.pubkey_hash)) throw new Error("Signer public key does not match the auth claim's pubkey_hash");
102
+ return publicKey;
103
+ }
104
+ const allowedKeys = transaction.auth_claim.source_address_claim.allowed_keys;
105
+ for (const { publicKeyId } of signers) if ((allowedKeys & 1n << publicKeyId) === 0n) throw new Error(`publicKeyId ${publicKeyId} is not selected by authClaim`);
106
+ return null;
107
+ }
108
+ /** Copy and re-validate a signer's key through the protocol codec. */
109
+ function copyPublicKey(publicKey) {
110
+ try {
111
+ return deserialize(serialize(publicKey, codec.PublicKey), codec.PublicKey);
112
+ } catch {
113
+ throw new Error("Invalid signer public key");
114
+ }
115
+ }
116
+ function bytesEqual(left, right) {
117
+ return left.length === right.length && left.every((byte, index) => byte === right[index]);
118
+ }
119
+ //#endregion
120
+ export { createInvocation as n, createTransaction as r, signTransaction as t };
121
+
122
+ //# sourceMappingURL=sign-DVIRyW8Y.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-DVIRyW8Y.js","names":[],"sources":["../src/transaction/build.ts","../src/transaction/sign.ts"],"sourcesContent":["import type {\n Invocation,\n Transaction,\n ContractAddress,\n ContractEntrypointID,\n GasAmount,\n Calldata,\n Uniquifier,\n AuthClaim,\n Contract,\n} from \"@thruputchain/protocol\";\n\n/**\n * Build an invocation object from already-typed protocol values.\n *\n * Generated contract bindings usually call this helper for you. Use it directly\n * when constructing a low-level invocation without generated bindings.\n */\nexport function createInvocation(params: {\n invoked_address: ContractAddress;\n entrypoint: ContractEntrypointID;\n gas_limit: GasAmount;\n calldata: Calldata;\n}): Invocation {\n return {\n invoked_address: params.invoked_address,\n entrypoint: params.entrypoint,\n gas_limit: params.gas_limit,\n calldata: params.calldata,\n };\n}\n\n/**\n * Build an unsigned transaction from an invocation and authorization metadata.\n *\n * The returned transaction must be signed with {@link signTransaction} before it\n * can be submitted to a Thruput JSON-RPC gateway.\n */\nexport function createTransaction(params: {\n invocation: Invocation;\n uniquifier: Uniquifier;\n contracts_to_deploy: Contract[];\n auth_claim: AuthClaim;\n}): Transaction {\n return {\n invocation: params.invocation,\n uniquifier: params.uniquifier,\n contracts_to_deploy: params.contracts_to_deploy,\n auth_claim: params.auth_claim,\n };\n}\n","import type {\n Transaction,\n SignedTransaction,\n DecoratedSignature,\n NetworkHash,\n PublicKey,\n} from \"@thruputchain/protocol\";\nimport {\n AuthClaimType,\n codec,\n deserialize,\n kMaxSigners,\n serialize,\n} from \"@thruputchain/protocol\";\nimport type { Signer } from \"../signers/types.js\";\nimport { derivePublicKeyHash } from \"../derivation/publicKeyHash.js\";\nimport { transactionSignaturePreimage } from \"./preimage.js\";\n\n/** A signer plus the protocol public-key ID to attach to its signature. */\nexport interface SignerEntry {\n /** Signer implementation that produces a protocol signature. */\n readonly signer: Signer;\n\n /** Public-key ID expected by the chain for this signer. */\n readonly publicKeyId: bigint;\n}\n\n/**\n * Sign a transaction with one or more signers.\n *\n * The signature preimage is built once and each signer signs the same canonical\n * bytes. The result can be passed to `sendTransaction` or serialized with\n * `serializeSignedTransaction`.\n *\n * For a `kPubkeySignature` claim there must be exactly one signer, with\n * public-key ID zero, whose key hashes to the claim's `pubkey_hash`; its key is\n * attached as `pubkey_claim_key` and its signature must use the key's scheme.\n * Other claims carry no `pubkey_claim_key`. Neither the key nor the signatures\n * are part of the signed `Transaction`, so re-signing never changes the\n * transaction hash.\n *\n * `networkHash` identifies the network the transaction is for. It is part of\n * what gets signed, so a transaction signed for one chain will be rejected by\n * another — see {@link transactionSignaturePreimage}. Local development can\n * read it from the public `getNetworkInfo` response; elsewhere it\n * comes from whoever operates the network.\n *\n * @example\n * ```ts\n * import { signTransaction } from \"@thruputchain/client/transaction\";\n * import { Ed25519Signer } from \"@thruputchain/client/signers\";\n *\n * const signer = Ed25519Signer.fromSeed(secretKey);\n * const signedTx = await signTransaction(\n * tx,\n * [{ signer, publicKeyId: 0n }],\n * networkHash,\n * );\n * ```\n */\nexport async function signTransaction(\n tx: Transaction,\n signers: readonly SignerEntry[],\n networkHash: NetworkHash,\n): Promise<SignedTransaction> {\n const txBytes = serialize(tx, codec.Transaction);\n const transaction = deserialize(txBytes, codec.Transaction);\n const signerEntries = signers.map(({ signer, publicKeyId }) => ({\n signer,\n publicKeyId,\n }));\n const pubkeyClaimKey = validateSignerEntries(transaction, signerEntries);\n const preimage = transactionSignaturePreimage(networkHash, transaction);\n\n const signatures: DecoratedSignature[] = await Promise.all(\n signerEntries.map(async (entry) => {\n const signature = await entry.signer.sign(preimage);\n if (pubkeyClaimKey && signature.scheme !== pubkeyClaimKey.scheme) {\n throw new Error(\n \"Signer returned a signature whose scheme does not match its public key\",\n );\n }\n return {\n public_key_id: entry.publicKeyId,\n signature,\n };\n }),\n );\n\n return { tx: transaction, signatures, pubkey_claim_key: pubkeyClaimKey };\n}\n\n/** Validates the signer set and returns the key a pubkey claim must carry. */\nfunction validateSignerEntries(\n transaction: Transaction,\n signers: readonly SignerEntry[],\n): PublicKey | null {\n if (signers.length > kMaxSigners) {\n throw new RangeError(`signers must contain at most ${kMaxSigners} entries`);\n }\n\n let previousId = -1n;\n for (const entry of signers) {\n if (\n typeof entry.publicKeyId !== \"bigint\" ||\n entry.publicKeyId < 0n ||\n entry.publicKeyId >= kMaxSigners\n ) {\n throw new RangeError(\n `publicKeyId must be between 0 and ${kMaxSigners - 1n}`,\n );\n }\n if (entry.publicKeyId <= previousId) {\n throw new Error(\"Signer publicKeyIds must be strictly increasing\");\n }\n if (!entry.signer || typeof entry.signer.sign !== \"function\") {\n throw new Error(\"Invalid signer\");\n }\n previousId = entry.publicKeyId;\n }\n\n if (transaction.auth_claim.claim_type === AuthClaimType.kPubkeySignature) {\n if (signers.length !== 1 || signers[0]!.publicKeyId !== 0n) {\n throw new Error(\"Pubkey authorization requires only publicKeyId 0\");\n }\n const publicKey = copyPublicKey(signers[0]!.signer.publicKey);\n if (\n !bytesEqual(\n derivePublicKeyHash(publicKey),\n transaction.auth_claim.pubkey_preimage.pubkey_hash,\n )\n ) {\n throw new Error(\n \"Signer public key does not match the auth claim's pubkey_hash\",\n );\n }\n return publicKey;\n }\n\n const allowedKeys = transaction.auth_claim.source_address_claim.allowed_keys;\n for (const { publicKeyId } of signers) {\n if ((allowedKeys & (1n << publicKeyId)) === 0n) {\n throw new Error(\n `publicKeyId ${publicKeyId} is not selected by authClaim`,\n );\n }\n }\n return null;\n}\n\n/** Copy and re-validate a signer's key through the protocol codec. */\nfunction copyPublicKey(publicKey: PublicKey): PublicKey {\n try {\n return deserialize(serialize(publicKey, codec.PublicKey), codec.PublicKey);\n } catch {\n throw new Error(\"Invalid signer public key\");\n }\n}\n\nfunction bytesEqual(left: Uint8Array, right: Uint8Array): boolean {\n return (\n left.length === right.length &&\n left.every((byte, index) => byte === right[index])\n );\n}\n"],"mappings":";;;;;;;;;AAkBA,SAAgB,iBAAiB,QAKlB;CACb,OAAO;EACL,iBAAiB,OAAO;EACxB,YAAY,OAAO;EACnB,WAAW,OAAO;EAClB,UAAU,OAAO;CACnB;AACF;;;;;;;AAQA,SAAgB,kBAAkB,QAKlB;CACd,OAAO;EACL,YAAY,OAAO;EACnB,YAAY,OAAO;EACnB,qBAAqB,OAAO;EAC5B,YAAY,OAAO;CACrB;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACUA,eAAsB,gBACpB,IACA,SACA,aAC4B;CAE5B,MAAM,cAAc,YADJ,UAAU,IAAI,MAAM,WACE,GAAG,MAAM,WAAW;CAC1D,MAAM,gBAAgB,QAAQ,KAAK,EAAE,QAAQ,mBAAmB;EAC9D;EACA;CACF,EAAE;CACF,MAAM,iBAAiB,sBAAsB,aAAa,aAAa;CACvE,MAAM,WAAW,6BAA6B,aAAa,WAAW;CAiBtE,OAAO;EAAE,IAAI;EAAa,YAAA,MAfqB,QAAQ,IACrD,cAAc,IAAI,OAAO,UAAU;GACjC,MAAM,YAAY,MAAM,MAAM,OAAO,KAAK,QAAQ;GAClD,IAAI,kBAAkB,UAAU,WAAW,eAAe,QACxD,MAAM,IAAI,MACR,wEACF;GAEF,OAAO;IACL,eAAe,MAAM;IACrB;GACF;EACF,CAAC,CACH;EAEsC,kBAAkB;CAAe;AACzE;;AAGA,SAAS,sBACP,aACA,SACkB;CAClB,IAAI,QAAQ,SAAS,aACnB,MAAM,IAAI,WAAW,gCAAgC,YAAY,SAAS;CAG5E,IAAI,aAAa,CAAC;CAClB,KAAK,MAAM,SAAS,SAAS;EAC3B,IACE,OAAO,MAAM,gBAAgB,YAC7B,MAAM,cAAc,MACpB,MAAM,eAAe,aAErB,MAAM,IAAI,WACR,qCAAqC,cAAc,IACrD;EAEF,IAAI,MAAM,eAAe,YACvB,MAAM,IAAI,MAAM,iDAAiD;EAEnE,IAAI,CAAC,MAAM,UAAU,OAAO,MAAM,OAAO,SAAS,YAChD,MAAM,IAAI,MAAM,gBAAgB;EAElC,aAAa,MAAM;CACrB;CAEA,IAAI,YAAY,WAAW,eAAe,cAAc,kBAAkB;EACxE,IAAI,QAAQ,WAAW,KAAK,QAAQ,EAAE,CAAE,gBAAgB,IACtD,MAAM,IAAI,MAAM,kDAAkD;EAEpE,MAAM,YAAY,cAAc,QAAQ,EAAE,CAAE,OAAO,SAAS;EAC5D,IACE,CAAC,WACC,oBAAoB,SAAS,GAC7B,YAAY,WAAW,gBAAgB,WACzC,GAEA,MAAM,IAAI,MACR,+DACF;EAEF,OAAO;CACT;CAEA,MAAM,cAAc,YAAY,WAAW,qBAAqB;CAChE,KAAK,MAAM,EAAE,iBAAiB,SAC5B,KAAK,cAAe,MAAM,iBAAkB,IAC1C,MAAM,IAAI,MACR,eAAe,YAAY,8BAC7B;CAGJ,OAAO;AACT;;AAGA,SAAS,cAAc,WAAiC;CACtD,IAAI;EACF,OAAO,YAAY,UAAU,WAAW,MAAM,SAAS,GAAG,MAAM,SAAS;CAC3E,QAAQ;EACN,MAAM,IAAI,MAAM,2BAA2B;CAC7C;AACF;AAEA,SAAS,WAAW,MAAkB,OAA4B;CAChE,OACE,KAAK,WAAW,MAAM,UACtB,KAAK,OAAO,MAAM,UAAU,SAAS,MAAM,MAAM;AAErD"}
@@ -0,0 +1,48 @@
1
+ import { t as Signer } from "./types-BE40oD_Q.js";
2
+ import { NetworkHash, SignedTransaction, Transaction } from "@thruputchain/protocol";
3
+
4
+ //#region src/transaction/sign.d.ts
5
+ /** A signer plus the protocol public-key ID to attach to its signature. */
6
+ interface SignerEntry {
7
+ /** Signer implementation that produces a protocol signature. */
8
+ readonly signer: Signer;
9
+ /** Public-key ID expected by the chain for this signer. */
10
+ readonly publicKeyId: bigint;
11
+ }
12
+ /**
13
+ * Sign a transaction with one or more signers.
14
+ *
15
+ * The signature preimage is built once and each signer signs the same canonical
16
+ * bytes. The result can be passed to `sendTransaction` or serialized with
17
+ * `serializeSignedTransaction`.
18
+ *
19
+ * For a `kPubkeySignature` claim there must be exactly one signer, with
20
+ * public-key ID zero, whose key hashes to the claim's `pubkey_hash`; its key is
21
+ * attached as `pubkey_claim_key` and its signature must use the key's scheme.
22
+ * Other claims carry no `pubkey_claim_key`. Neither the key nor the signatures
23
+ * are part of the signed `Transaction`, so re-signing never changes the
24
+ * transaction hash.
25
+ *
26
+ * `networkHash` identifies the network the transaction is for. It is part of
27
+ * what gets signed, so a transaction signed for one chain will be rejected by
28
+ * another — see {@link transactionSignaturePreimage}. Local development can
29
+ * read it from the public `getNetworkInfo` response; elsewhere it
30
+ * comes from whoever operates the network.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { signTransaction } from "@thruputchain/client/transaction";
35
+ * import { Ed25519Signer } from "@thruputchain/client/signers";
36
+ *
37
+ * const signer = Ed25519Signer.fromSeed(secretKey);
38
+ * const signedTx = await signTransaction(
39
+ * tx,
40
+ * [{ signer, publicKeyId: 0n }],
41
+ * networkHash,
42
+ * );
43
+ * ```
44
+ */
45
+ declare function signTransaction(tx: Transaction, signers: readonly SignerEntry[], networkHash: NetworkHash): Promise<SignedTransaction>;
46
+ //#endregion
47
+ export { signTransaction as n, SignerEntry as t };
48
+ //# sourceMappingURL=sign-Ve0eetRO.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-Ve0eetRO.d.ts","names":[],"sources":["../src/transaction/sign.ts"],"mappings":";;;;;UAmBiB,WAAA;EAAA;EAAA,SAEN,MAAA,EAAQ,MAAM;;WAGd,WAAA;AAAA;;;;AAAW;AAoCtB;;;;;;;;;;;;;;;;;;;AAI4B;;;;;;;;;;iBAJN,eAAA,CACpB,EAAA,EAAI,WAAA,EACJ,OAAA,WAAkB,WAAA,IAClB,WAAA,EAAa,WAAA,GACZ,OAAA,CAAQ,iBAAA"}
@@ -0,0 +1,48 @@
1
+ import { t as Signer } from "./types-BE40oD_Q.cjs";
2
+ import { NetworkHash, SignedTransaction, Transaction } from "@thruputchain/protocol";
3
+
4
+ //#region src/transaction/sign.d.ts
5
+ /** A signer plus the protocol public-key ID to attach to its signature. */
6
+ interface SignerEntry {
7
+ /** Signer implementation that produces a protocol signature. */
8
+ readonly signer: Signer;
9
+ /** Public-key ID expected by the chain for this signer. */
10
+ readonly publicKeyId: bigint;
11
+ }
12
+ /**
13
+ * Sign a transaction with one or more signers.
14
+ *
15
+ * The signature preimage is built once and each signer signs the same canonical
16
+ * bytes. The result can be passed to `sendTransaction` or serialized with
17
+ * `serializeSignedTransaction`.
18
+ *
19
+ * For a `kPubkeySignature` claim there must be exactly one signer, with
20
+ * public-key ID zero, whose key hashes to the claim's `pubkey_hash`; its key is
21
+ * attached as `pubkey_claim_key` and its signature must use the key's scheme.
22
+ * Other claims carry no `pubkey_claim_key`. Neither the key nor the signatures
23
+ * are part of the signed `Transaction`, so re-signing never changes the
24
+ * transaction hash.
25
+ *
26
+ * `networkHash` identifies the network the transaction is for. It is part of
27
+ * what gets signed, so a transaction signed for one chain will be rejected by
28
+ * another — see {@link transactionSignaturePreimage}. Local development can
29
+ * read it from the public `getNetworkInfo` response; elsewhere it
30
+ * comes from whoever operates the network.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { signTransaction } from "@thruputchain/client/transaction";
35
+ * import { Ed25519Signer } from "@thruputchain/client/signers";
36
+ *
37
+ * const signer = Ed25519Signer.fromSeed(secretKey);
38
+ * const signedTx = await signTransaction(
39
+ * tx,
40
+ * [{ signer, publicKeyId: 0n }],
41
+ * networkHash,
42
+ * );
43
+ * ```
44
+ */
45
+ declare function signTransaction(tx: Transaction, signers: readonly SignerEntry[], networkHash: NetworkHash): Promise<SignedTransaction>;
46
+ //#endregion
47
+ export { signTransaction as n, SignerEntry as t };
48
+ //# sourceMappingURL=sign-eUT0iGQG.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sign-eUT0iGQG.d.cts","names":[],"sources":["../src/transaction/sign.ts"],"mappings":";;;;;UAmBiB,WAAA;EAAA;EAAA,SAEN,MAAA,EAAQ,MAAM;;WAGd,WAAA;AAAA;;;;AAAW;AAoCtB;;;;;;;;;;;;;;;;;;;AAI4B;;;;;;;;;;iBAJN,eAAA,CACpB,EAAA,EAAI,WAAA,EACJ,OAAA,WAAkB,WAAA,IAClB,WAAA,EAAa,WAAA,GACZ,OAAA,CAAQ,iBAAA"}
@@ -0,0 +1,9 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_signedOp = require("./signedOp-Bluo0OAd.cjs");
3
+ const require_signed_op = require("./signed_op-z_8fqAi1.cjs");
4
+ exports.SignedOp = require_signed_op.SignedOp;
5
+ exports.SignedOpSpec = require_signed_op.spec;
6
+ exports.defineSignedOperation = require_signedOp.defineSignedOperation;
7
+ exports.randomNonce = require_signedOp.randomNonce;
8
+ exports.signedOperationPreimage = require_signedOp.signedOperationPreimage;
9
+ exports.thruput_signed_op_if = require_signed_op.thruput_signed_op_if;
@@ -0,0 +1,3 @@
1
+ import { n as spec, r as thruput_signed_op_if, t as SignedOp } from "./signed_op-LwxrDud8.cjs";
2
+ import { a as Operation, c as SignedOperationType, i as DefineSignedOperationOptions, l as defineSignedOperation, n as signedOperationPreimage, o as SignedOperation, r as ContractTypeSelector, s as SignedOperationRequest, t as SignedOperationPreimage, u as randomNonce } from "./index-B5KqSHeL.cjs";
3
+ export { type ContractTypeSelector, type DefineSignedOperationOptions, type Operation, SignedOp, spec as SignedOpSpec, type SignedOperation, type SignedOperationPreimage, type SignedOperationRequest, type SignedOperationType, defineSignedOperation, randomNonce, signedOperationPreimage, thruput_signed_op_if };
@@ -0,0 +1,3 @@
1
+ import { n as spec, r as thruput_signed_op_if, t as SignedOp } from "./signed_op-DFgQ2yFj.js";
2
+ import { a as Operation, c as SignedOperationType, i as DefineSignedOperationOptions, l as defineSignedOperation, n as signedOperationPreimage, o as SignedOperation, r as ContractTypeSelector, s as SignedOperationRequest, t as SignedOperationPreimage, u as randomNonce } from "./index--5LsCotr.js";
3
+ export { type ContractTypeSelector, type DefineSignedOperationOptions, type Operation, SignedOp, spec as SignedOpSpec, type SignedOperation, type SignedOperationPreimage, type SignedOperationRequest, type SignedOperationType, defineSignedOperation, randomNonce, signedOperationPreimage, thruput_signed_op_if };
@@ -0,0 +1,3 @@
1
+ import { n as randomNonce, r as signedOperationPreimage, t as defineSignedOperation } from "./signedOp-x4fakrr4.js";
2
+ import { n as spec, r as thruput_signed_op_if, t as SignedOp } from "./signed_op-BzVbBgv4.js";
3
+ export { SignedOp, spec as SignedOpSpec, defineSignedOperation, randomNonce, signedOperationPreimage, thruput_signed_op_if };