@thruputchain/client 0.0.0-stage → 0.26.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 (186) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +953 -2
  3. package/dist/actions-CXx6qzsv.cjs +513 -0
  4. package/dist/actions-CXx6qzsv.cjs.map +1 -0
  5. package/dist/actions-QHgiCqT6.js +430 -0
  6. package/dist/actions-QHgiCqT6.js.map +1 -0
  7. package/dist/actions.cjs +23 -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/artifact-BM_MVzhL.d.cts +35 -0
  12. package/dist/artifact-BM_MVzhL.d.cts.map +1 -0
  13. package/dist/artifact-BM_MVzhL.d.ts +35 -0
  14. package/dist/artifact-BM_MVzhL.d.ts.map +1 -0
  15. package/dist/client-JixxskeH.d.cts +746 -0
  16. package/dist/client-JixxskeH.d.cts.map +1 -0
  17. package/dist/client-JixxskeH.d.ts +746 -0
  18. package/dist/client-JixxskeH.d.ts.map +1 -0
  19. package/dist/codec-BHKoSaOP.js +9506 -0
  20. package/dist/codec-BHKoSaOP.js.map +1 -0
  21. package/dist/codec-C3OlYm98.cjs +9566 -0
  22. package/dist/codec-C3OlYm98.cjs.map +1 -0
  23. package/dist/contract-C7T2H2Oi.cjs +1628 -0
  24. package/dist/contract-C7T2H2Oi.cjs.map +1 -0
  25. package/dist/contract-DzvyyFCI.js +1472 -0
  26. package/dist/contract-DzvyyFCI.js.map +1 -0
  27. package/dist/contract.cjs +63 -0
  28. package/dist/contract.d.cts +4 -0
  29. package/dist/contract.d.ts +4 -0
  30. package/dist/contract.js +2 -0
  31. package/dist/contracts.cjs +1050 -0
  32. package/dist/contracts.cjs.map +1 -0
  33. package/dist/contracts.d.cts +397 -0
  34. package/dist/contracts.d.cts.map +1 -0
  35. package/dist/contracts.d.ts +397 -0
  36. package/dist/contracts.d.ts.map +1 -0
  37. package/dist/contracts.js +1030 -0
  38. package/dist/contracts.js.map +1 -0
  39. package/dist/dev_wallet-CSMA1PCt.js +497 -0
  40. package/dist/dev_wallet-CSMA1PCt.js.map +1 -0
  41. package/dist/dev_wallet-GX-NCAFk.cjs +530 -0
  42. package/dist/dev_wallet-GX-NCAFk.cjs.map +1 -0
  43. package/dist/domainSeparator-B_vU_zUD.cjs +102 -0
  44. package/dist/domainSeparator-B_vU_zUD.cjs.map +1 -0
  45. package/dist/domainSeparator-CBCvxIj-.js +79 -0
  46. package/dist/domainSeparator-CBCvxIj-.js.map +1 -0
  47. package/dist/execution-DYqPDn4O.d.cts +227 -0
  48. package/dist/execution-DYqPDn4O.d.cts.map +1 -0
  49. package/dist/execution-Dj6E4B_b.d.ts +227 -0
  50. package/dist/execution-Dj6E4B_b.d.ts.map +1 -0
  51. package/dist/hex-DIcaALXL.js +112 -0
  52. package/dist/hex-DIcaALXL.js.map +1 -0
  53. package/dist/hex-DkGpiZ5e.cjs +189 -0
  54. package/dist/hex-DkGpiZ5e.cjs.map +1 -0
  55. package/dist/index--5LsCotr.d.ts +192 -0
  56. package/dist/index--5LsCotr.d.ts.map +1 -0
  57. package/dist/index-1-rFirYe.d.cts +90 -0
  58. package/dist/index-1-rFirYe.d.cts.map +1 -0
  59. package/dist/index-B5KqSHeL.d.cts +192 -0
  60. package/dist/index-B5KqSHeL.d.cts.map +1 -0
  61. package/dist/index-BraLWObY.d.cts +164 -0
  62. package/dist/index-BraLWObY.d.cts.map +1 -0
  63. package/dist/index-ByNNqY7S.d.cts +83 -0
  64. package/dist/index-ByNNqY7S.d.cts.map +1 -0
  65. package/dist/index-ByvV2UF6.d.ts +164 -0
  66. package/dist/index-ByvV2UF6.d.ts.map +1 -0
  67. package/dist/index-CG2WRtGa.d.cts +164 -0
  68. package/dist/index-CG2WRtGa.d.cts.map +1 -0
  69. package/dist/index-CIHK7Ew9.d.cts +303 -0
  70. package/dist/index-CIHK7Ew9.d.cts.map +1 -0
  71. package/dist/index-CIHK7Ew9.d.ts +303 -0
  72. package/dist/index-CIHK7Ew9.d.ts.map +1 -0
  73. package/dist/index-CVrhB9Dr.d.cts +263 -0
  74. package/dist/index-CVrhB9Dr.d.cts.map +1 -0
  75. package/dist/index-D89ur7mO.d.ts +164 -0
  76. package/dist/index-D89ur7mO.d.ts.map +1 -0
  77. package/dist/index-DzrLv3EA.d.cts +82 -0
  78. package/dist/index-DzrLv3EA.d.cts.map +1 -0
  79. package/dist/index-DzrLv3EA.d.ts +82 -0
  80. package/dist/index-DzrLv3EA.d.ts.map +1 -0
  81. package/dist/index-SV-inhhO.d.ts +90 -0
  82. package/dist/index-SV-inhhO.d.ts.map +1 -0
  83. package/dist/index-dJ65V8se.d.ts +263 -0
  84. package/dist/index-dJ65V8se.d.ts.map +1 -0
  85. package/dist/index-fdTURpBk.d.ts +83 -0
  86. package/dist/index-fdTURpBk.d.ts.map +1 -0
  87. package/dist/index.cjs +445 -0
  88. package/dist/index.cjs.map +1 -0
  89. package/dist/index.d.cts +174 -0
  90. package/dist/index.d.cts.map +1 -0
  91. package/dist/index.d.ts +174 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +189 -0
  94. package/dist/index.js.map +1 -0
  95. package/dist/provider.cjs +101 -0
  96. package/dist/provider.cjs.map +1 -0
  97. package/dist/provider.d.cts +2 -0
  98. package/dist/provider.d.ts +2 -0
  99. package/dist/provider.js +76 -0
  100. package/dist/provider.js.map +1 -0
  101. package/dist/readError-AoNjzW75.cjs +604 -0
  102. package/dist/readError-AoNjzW75.cjs.map +1 -0
  103. package/dist/readError-CZPYcW__.js +551 -0
  104. package/dist/readError-CZPYcW__.js.map +1 -0
  105. package/dist/readViews-DJyqc7im.d.cts +604 -0
  106. package/dist/readViews-DJyqc7im.d.cts.map +1 -0
  107. package/dist/readViews-DQoaUORa.d.ts +604 -0
  108. package/dist/readViews-DQoaUORa.d.ts.map +1 -0
  109. package/dist/rolldown-runtime-D6vf50IK.cjs +28 -0
  110. package/dist/sendInvocation-BwabRa2N.js +505 -0
  111. package/dist/sendInvocation-BwabRa2N.js.map +1 -0
  112. package/dist/sendInvocation-qO8AZcmU.cjs +661 -0
  113. package/dist/sendInvocation-qO8AZcmU.cjs.map +1 -0
  114. package/dist/sign-BewmV_EL.cjs +139 -0
  115. package/dist/sign-BewmV_EL.cjs.map +1 -0
  116. package/dist/sign-DVIRyW8Y.js +122 -0
  117. package/dist/sign-DVIRyW8Y.js.map +1 -0
  118. package/dist/sign-Ve0eetRO.d.ts +48 -0
  119. package/dist/sign-Ve0eetRO.d.ts.map +1 -0
  120. package/dist/sign-eUT0iGQG.d.cts +48 -0
  121. package/dist/sign-eUT0iGQG.d.cts.map +1 -0
  122. package/dist/signed-op.cjs +9 -0
  123. package/dist/signed-op.d.cts +3 -0
  124. package/dist/signed-op.d.ts +3 -0
  125. package/dist/signed-op.js +3 -0
  126. package/dist/signedOp-C52gOgpR.js +166 -0
  127. package/dist/signedOp-C52gOgpR.js.map +1 -0
  128. package/dist/signedOp-oqAXEqmE.cjs +183 -0
  129. package/dist/signedOp-oqAXEqmE.cjs.map +1 -0
  130. package/dist/signed_op-BokEDWr-.js +154 -0
  131. package/dist/signed_op-BokEDWr-.js.map +1 -0
  132. package/dist/signed_op-C4lY_TCc.d.ts +58 -0
  133. package/dist/signed_op-C4lY_TCc.d.ts.map +1 -0
  134. package/dist/signed_op-DX5WuyEh.d.cts +58 -0
  135. package/dist/signed_op-DX5WuyEh.d.cts.map +1 -0
  136. package/dist/signed_op-q8KKSm5e.cjs +175 -0
  137. package/dist/signed_op-q8KKSm5e.cjs.map +1 -0
  138. package/dist/signers-BFP84wJP.cjs +137 -0
  139. package/dist/signers-BFP84wJP.cjs.map +1 -0
  140. package/dist/signers-CzOSedwJ.js +120 -0
  141. package/dist/signers-CzOSedwJ.js.map +1 -0
  142. package/dist/signers.cjs +5 -0
  143. package/dist/signers.d.cts +3 -0
  144. package/dist/signers.d.ts +3 -0
  145. package/dist/signers.js +2 -0
  146. package/dist/size-506oTE28.js +91 -0
  147. package/dist/size-506oTE28.js.map +1 -0
  148. package/dist/size-OAFfOthl.cjs +108 -0
  149. package/dist/size-OAFfOthl.cjs.map +1 -0
  150. package/dist/transaction-CwkQxQOx.js +24 -0
  151. package/dist/transaction-CwkQxQOx.js.map +1 -0
  152. package/dist/transaction-DrSrCJ5y.cjs +47 -0
  153. package/dist/transaction-DrSrCJ5y.cjs.map +1 -0
  154. package/dist/transaction.cjs +13 -0
  155. package/dist/transaction.d.cts +3 -0
  156. package/dist/transaction.d.ts +3 -0
  157. package/dist/transaction.js +4 -0
  158. package/dist/transactionHash-CO9ajbvU.js +24 -0
  159. package/dist/transactionHash-CO9ajbvU.js.map +1 -0
  160. package/dist/transactionHash-D5yf4KoL.cjs +29 -0
  161. package/dist/transactionHash-D5yf4KoL.cjs.map +1 -0
  162. package/dist/transport-CBFwAIIv.js +261 -0
  163. package/dist/transport-CBFwAIIv.js.map +1 -0
  164. package/dist/transport-tWxKhXUt.cjs +279 -0
  165. package/dist/transport-tWxKhXUt.cjs.map +1 -0
  166. package/dist/transport.cjs +19 -0
  167. package/dist/transport.d.cts +3 -0
  168. package/dist/transport.d.ts +3 -0
  169. package/dist/transport.js +4 -0
  170. package/dist/types-BE40oD_Q.d.cts +18 -0
  171. package/dist/types-BE40oD_Q.d.cts.map +1 -0
  172. package/dist/types-BE40oD_Q.d.ts +18 -0
  173. package/dist/types-BE40oD_Q.d.ts.map +1 -0
  174. package/dist/validation-4w-vDGAi.cjs +543 -0
  175. package/dist/validation-4w-vDGAi.cjs.map +1 -0
  176. package/dist/validation-eXATmgO0.js +411 -0
  177. package/dist/validation-eXATmgO0.js.map +1 -0
  178. package/dist/wallet-7RELuTkf.js +667 -0
  179. package/dist/wallet-7RELuTkf.js.map +1 -0
  180. package/dist/wallet-T_JazXRc.cjs +709 -0
  181. package/dist/wallet-T_JazXRc.cjs.map +1 -0
  182. package/dist/wallet.cjs +27 -0
  183. package/dist/wallet.d.cts +3 -0
  184. package/dist/wallet.d.ts +3 -0
  185. package/dist/wallet.js +3 -0
  186. package/package.json +122 -4
@@ -0,0 +1,1472 @@
1
+ import { l as serializeHeight, r as UnsupportedRpcValue, u as serializeU64 } from "./codec-BHKoSaOP.js";
2
+ import { g as toBase58, i as toHex0x } from "./hex-DIcaALXL.js";
3
+ import { AuthClaimType, BoolCodec, ContractType, CxsReader, CxsWriter, FixedArrayCodec, Int128Codec, Int256Codec, Int32Codec, Int64Codec, OptionCodec, Uint128Codec, Uint256Codec, Uint32Codec, Uint64Codec, VarArrayCodec, VoidCodec, calldata, codec, contractAddress, contractEntrypointID, deserialize, kMaxEventLength, serialize, sha256Hash } from "@thruputchain/protocol";
4
+ import { sha256 } from "@noble/hashes/sha2.js";
5
+ import { CxsReader as CxsReader$1, CxsWriter as CxsWriter$1, FixedOpaqueCodec, Uint8Codec, VarOpaqueCodec, XdrReader, fixedArray, fixedArray as fixedArray$1, fixedBytes, fixedBytes as fixedBytes$1, withCodecBudget } from "@thruputchain/xdr";
6
+ import { ContractMethodEffect, ContractMethodEffect as ContractMethodEffect$1, ContractTypeDefKind, ContractTypeDefKind as ContractTypeDefKind$1, ContractTypeKind, ContractTypeKind as ContractTypeKind$1, ContractUnionCaseKind, ContractUnionCaseKind as ContractUnionCaseKind$1, codec as codec$1 } from "@thruputchain/contract-spec";
7
+ //#region src/contract/spec.ts
8
+ /**
9
+ * Lookup key for a named type: every segment of its spec id.
10
+ *
11
+ * Two types with the same declared name in different crates or modules are
12
+ * distinct, so named-codec maps from {@link buildNamedCodecs} are keyed by
13
+ * this rather than by `declared` alone. The encoding is injective; use
14
+ * {@link formatSpecId} for anything a person reads.
15
+ */
16
+ function specIdKey(id) {
17
+ return JSON.stringify([
18
+ id.crate_name,
19
+ id.major,
20
+ id.module_path,
21
+ id.declared
22
+ ]);
23
+ }
24
+ /**
25
+ * Render a spec id for diagnostics as `module_path::declared (crate@major)`,
26
+ * the shape the Thruput CLI and spec tool print.
27
+ */
28
+ function formatSpecId(id) {
29
+ return `${id.module_path}::${id.declared} (${id.crate_name}@${id.major})`;
30
+ }
31
+ //#endregion
32
+ //#region src/contract/errors.ts
33
+ /** Error raised when contract bytes do not match their declared ABI type. */
34
+ var ContractDecodeError = class extends Error {
35
+ constructor(message, options) {
36
+ super(message, options);
37
+ this.name = "ContractDecodeError";
38
+ }
39
+ };
40
+ /** Retrieved bytes or response metadata failed identity/canonical validation. */
41
+ var ContractVerificationError = class extends Error {
42
+ constructor(message, options) {
43
+ super(message, options);
44
+ this.name = "ContractVerificationError";
45
+ }
46
+ };
47
+ //#endregion
48
+ //#region src/contract/valueLimits.ts
49
+ function contractValueLimits(inputBytes) {
50
+ return {
51
+ maxDepth: 128,
52
+ maxWork: Math.min(1e5, 1024 + 16 * inputBytes)
53
+ };
54
+ }
55
+ //#endregion
56
+ //#region src/contract/signedToken.ts
57
+ const SIGNED_TOKEN = Object.freeze({ kind: "signedToken" });
58
+ /** The placeholder standing in for a signed auth token. */
59
+ function signedToken() {
60
+ return SIGNED_TOKEN;
61
+ }
62
+ /** Whether `value` is a signed-token placeholder. */
63
+ function isSignedToken(value) {
64
+ return typeof value === "object" && value !== null && value.kind === "signedToken";
65
+ }
66
+ /**
67
+ * Codec for a signed-token position: writes and reads nothing, since the
68
+ * token's handle never travels in calldata or return data.
69
+ */
70
+ const SignedTokenCodec = {
71
+ encode(_writer, value) {
72
+ if (!isSignedToken(value)) throw new TypeError("SignedToken expected a signed-token placeholder");
73
+ },
74
+ decode() {
75
+ return SIGNED_TOKEN;
76
+ }
77
+ };
78
+ //#endregion
79
+ //#region src/contract/encode.ts
80
+ const AddressCodec = requireByteArrayCodec(codec.ContractAddress, "Address");
81
+ const BytesCodec = requireByteArrayCodec(VarOpaqueCodec(4294967295), "Bytes");
82
+ const ContractBoolCodec = {
83
+ encode(writer, value) {
84
+ if (typeof value !== "boolean") throw new TypeError("Bool expected boolean");
85
+ BoolCodec.encode(writer, value);
86
+ },
87
+ decode: BoolCodec.decode
88
+ };
89
+ const ContractVoidCodec = {
90
+ encode(writer, value) {
91
+ if (value !== void 0) throw new TypeError("Void expected undefined");
92
+ VoidCodec.encode(writer, value);
93
+ },
94
+ decode: VoidCodec.decode
95
+ };
96
+ const ContractU128Codec = requireBigIntCodec("U128", Uint128Codec);
97
+ const ContractI128Codec = requireBigIntCodec("I128", Int128Codec);
98
+ const ContractU256Codec = requireBigIntCodec("U256", Uint256Codec);
99
+ const ContractI256Codec = requireBigIntCodec("I256", Int256Codec);
100
+ const ContractU64Codec = requireBigIntCodec("U64", Uint64Codec);
101
+ const ContractI64Codec = requireBigIntCodec("I64", Int64Codec);
102
+ const ContractU32Codec = requireBigIntCodec("U32", Uint32Codec);
103
+ const ContractI32Codec = requireBigIntCodec("I32", Int32Codec);
104
+ const StringCodec = {
105
+ encode(w, val) {
106
+ assertWellFormedString(val);
107
+ w.writeString(val, 4294967295);
108
+ },
109
+ decode(r) {
110
+ return new TextDecoder("utf-8", { fatal: true }).decode(r.readVarOpaque(4294967295));
111
+ }
112
+ };
113
+ const resolvedCodecCaches = /* @__PURE__ */ new WeakMap();
114
+ /** @internal Enable identity caching for an immutable named-codec map. */
115
+ function enableResolvedCodecCache(namedCodecs, cacheableTypes) {
116
+ resolvedCodecCaches.set(namedCodecs, {
117
+ cacheableTypes: new WeakSet(cacheableTypes),
118
+ codecs: /* @__PURE__ */ new WeakMap()
119
+ });
120
+ }
121
+ function assertWellFormedString(value) {
122
+ if (typeof value !== "string") throw new TypeError("Expected string");
123
+ for (let index = 0; index < value.length; index++) {
124
+ const codeUnit = value.charCodeAt(index);
125
+ if (codeUnit >= 55296 && codeUnit <= 56319) {
126
+ const next = value.charCodeAt(index + 1);
127
+ if (!Number.isInteger(next) || next < 56320 || next > 57343) throw new TypeError("String contains an unpaired UTF-16 surrogate");
128
+ index++;
129
+ } else if (codeUnit >= 56320 && codeUnit <= 57343) throw new TypeError("String contains an unpaired UTF-16 surrogate");
130
+ }
131
+ }
132
+ function requireByteArrayCodec(codec, label = "U8 container") {
133
+ return {
134
+ ...codec,
135
+ encode(writer, value) {
136
+ if (!(value instanceof Uint8Array)) throw new TypeError(`Expected Uint8Array for ${label}`);
137
+ codec.encode(writer, value);
138
+ },
139
+ decode: codec.decode
140
+ };
141
+ }
142
+ function requireBigIntCodec(label, codec) {
143
+ return {
144
+ ...codec,
145
+ encode(writer, value) {
146
+ if (typeof value !== "bigint") throw new TypeError(`${label} expected bigint`);
147
+ codec.encode(writer, value);
148
+ },
149
+ decode: codec.decode
150
+ };
151
+ }
152
+ function requireArrayCodec(codec) {
153
+ return {
154
+ ...codec,
155
+ encode(writer, value) {
156
+ if (!Array.isArray(value)) throw new TypeError("Expected array");
157
+ assertOwnArrayElements(value);
158
+ codec.encode(writer, value);
159
+ },
160
+ decode: codec.decode
161
+ };
162
+ }
163
+ /**
164
+ * Resolve a contract-spec type into the XDR/CXS codec used to encode values.
165
+ *
166
+ * Pass `namedCodecs` when resolving named structs, enums, or unions from a
167
+ * contract spec. Build that map with {@link buildNamedCodecs}.
168
+ */
169
+ function resolveCodec(ty, namedCodecs) {
170
+ if (ty.v === ContractTypeKind$1.Named) return resolveUncachedCodec(ty, namedCodecs);
171
+ if (!namedCodecs) return withCodecBudget(resolveUncachedCodec(ty));
172
+ const resolvedCache = resolvedCodecCaches.get(namedCodecs);
173
+ if (!resolvedCache?.cacheableTypes.has(ty)) return withCodecBudget(resolveUncachedCodec(ty, namedCodecs));
174
+ const cached = resolvedCache.codecs.get(ty);
175
+ if (cached) return cached;
176
+ const codec = withCodecBudget(resolveUncachedCodec(ty, namedCodecs));
177
+ resolvedCache.codecs.set(ty, codec);
178
+ return codec;
179
+ }
180
+ function resolveUncachedCodec(ty, namedCodecs) {
181
+ switch (ty.v) {
182
+ case ContractTypeKind$1.Address: return AddressCodec;
183
+ case ContractTypeKind$1.U128: return ContractU128Codec;
184
+ case ContractTypeKind$1.I128: return ContractI128Codec;
185
+ case ContractTypeKind$1.U256: return ContractU256Codec;
186
+ case ContractTypeKind$1.I256: return ContractI256Codec;
187
+ case ContractTypeKind$1.U64: return ContractU64Codec;
188
+ case ContractTypeKind$1.I64: return ContractI64Codec;
189
+ case ContractTypeKind$1.U32: return ContractU32Codec;
190
+ case ContractTypeKind$1.I32: return ContractI32Codec;
191
+ case ContractTypeKind$1.U8: return Uint8Codec;
192
+ case ContractTypeKind$1.Bool: return ContractBoolCodec;
193
+ case ContractTypeKind$1.Void: return ContractVoidCodec;
194
+ case ContractTypeKind$1.Bytes: return BytesCodec;
195
+ case ContractTypeKind$1.String: return StringCodec;
196
+ case ContractTypeKind$1.Option: return OptionCodec(resolveCodec(ty.option_inner, namedCodecs));
197
+ case ContractTypeKind$1.Vector:
198
+ if (ty.vector.element?.v === ContractTypeKind$1.U8) return requireByteArrayCodec(VarOpaqueCodec(Number(ty.vector.max_len)));
199
+ return requireArrayCodec(VarArrayCodec(resolveCodec(ty.vector.element, namedCodecs), Number(ty.vector.max_len)));
200
+ case ContractTypeKind$1.Array:
201
+ if (ty.array.element?.v === ContractTypeKind$1.U8) return requireByteArrayCodec(FixedOpaqueCodec(Number(ty.array.len)));
202
+ const arrayLength = Number(ty.array.len);
203
+ const arrayCodec = requireArrayCodec(FixedArrayCodec(resolveCodec(ty.array.element, namedCodecs), arrayLength));
204
+ return {
205
+ ...arrayCodec,
206
+ decode(reader) {
207
+ return fixedArray(arrayCodec.decode(reader), arrayLength);
208
+ }
209
+ };
210
+ case ContractTypeKind$1.Tuple: {
211
+ const innerCodecs = ty.tuple.map((t) => resolveCodec(t, namedCodecs));
212
+ return {
213
+ encode(w, val) {
214
+ if (!Array.isArray(val) || val.length !== innerCodecs.length) throw new TypeError(`Tuple expected ${innerCodecs.length} values, got ${Array.isArray(val) ? val.length : "non-array"}`);
215
+ const arr = val;
216
+ assertOwnArrayElements(arr);
217
+ for (const [i, codec] of innerCodecs.entries()) codec.encode(w, arr[i]);
218
+ },
219
+ decode(r) {
220
+ return innerCodecs.map((c) => c.decode(r));
221
+ }
222
+ };
223
+ }
224
+ case ContractTypeKind$1.Named: {
225
+ const key = specIdKey(ty.named);
226
+ const codec = namedCodecs && Object.hasOwn(namedCodecs, key) ? namedCodecs[key] : void 0;
227
+ if (codec === void 0) throw new Error(`No codec for named type "${formatSpecId(ty.named)}".`);
228
+ return codec;
229
+ }
230
+ case ContractTypeKind$1.SignedToken: return SignedTokenCodec;
231
+ default: throw new Error(`Unsupported ContractType kind: ${ty.v}`);
232
+ }
233
+ }
234
+ function lookupMethod(spec, interfaceName, methodName) {
235
+ const iface = spec.interfaces.find((i) => i.name === interfaceName);
236
+ if (!iface) throw new Error(`Interface "${interfaceName}" not found in spec`);
237
+ const method = iface.methods.find((m) => m.name === methodName);
238
+ if (!method) throw new Error(`Method "${methodName}" not found in interface "${interfaceName}"`);
239
+ return method;
240
+ }
241
+ /**
242
+ * Encode method arguments into contract calldata using a contract spec.
243
+ *
244
+ * Use this when constructing invocations from a spec without generated
245
+ * TypeScript bindings. Generated descriptors use their own resolved codecs.
246
+ *
247
+ * @example
248
+ * ```ts
249
+ * const namedCodecs = buildNamedCodecs(spec.type_defs);
250
+ * const calldata = encodeCalldata(
251
+ * spec,
252
+ * "Counter",
253
+ * "increment",
254
+ * [1n],
255
+ * namedCodecs,
256
+ * );
257
+ * ```
258
+ */
259
+ function encodeCalldata(spec, interfaceName, methodName, args, namedCodecs) {
260
+ const method = lookupMethod(spec, interfaceName, methodName);
261
+ if (args.length !== method.args.length) throw new Error(`Expected ${method.args.length} args for "${methodName}", got ${args.length}`);
262
+ assertOwnArrayElements(args);
263
+ const w = new CxsWriter();
264
+ for (const [i, arg] of method.args.entries()) resolveCodec(arg.ty, namedCodecs).encode(w, args[i]);
265
+ return calldata(w.finish());
266
+ }
267
+ /**
268
+ * Decode contract calldata into an object keyed by argument name.
269
+ *
270
+ * This is primarily useful for tooling, tests, and debugging generated
271
+ * invocations.
272
+ */
273
+ function decodeCalldata(spec, interfaceName, methodName, data, namedCodecs) {
274
+ const method = lookupMethod(spec, interfaceName, methodName);
275
+ try {
276
+ const r = new CxsReader(data, contractValueLimits(data.length));
277
+ const result = {};
278
+ for (const arg of method.args) {
279
+ const argCodec = resolveCodec(arg.ty, namedCodecs);
280
+ defineRecordValue$2(result, arg.name, argCodec.decode(r));
281
+ }
282
+ if (r.remaining !== 0) throw new Error(`Trailing data after decoding "${methodName}": ${r.remaining} bytes remaining`);
283
+ return result;
284
+ } catch (cause) {
285
+ throw new ContractDecodeError(`Failed to decode calldata for "${interfaceName}.${methodName}"${cause instanceof Error ? `: ${cause.message}` : ""}`, { cause });
286
+ }
287
+ }
288
+ function assertOwnArrayElements(value) {
289
+ for (let index = 0; index < value.length; index++) if (!Object.hasOwn(value, index)) throw new TypeError(`Array requires own value at index ${index}`);
290
+ }
291
+ function defineRecordValue$2(record, name, value) {
292
+ Object.defineProperty(record, name, {
293
+ configurable: true,
294
+ enumerable: true,
295
+ value,
296
+ writable: true
297
+ });
298
+ }
299
+ //#endregion
300
+ //#region src/derivation/entrypointId.ts
301
+ /**
302
+ * The major-version domain a semver string belongs to.
303
+ *
304
+ * Mirrors the Rust SDK's `major_version_from_string`: a zero major or minor is
305
+ * not a stable domain on its own, so the domain widens until it is.
306
+ *
307
+ * - `1.2.3` → `1`
308
+ * - `0.9.2` → `0.9`
309
+ * - `0.0.2` → `0.0.2`
310
+ *
311
+ * @throws If `versionStr` has fewer than three dot-separated components.
312
+ */
313
+ function majorVersionFromSemver(versionStr) {
314
+ const [majorPart, minorPart, patchPart] = versionStr.split(".");
315
+ if (majorPart === void 0 || minorPart === void 0 || patchPart === void 0) throw new Error(`Invalid semver: ${versionStr}`);
316
+ const major = parseInt(majorPart, 10);
317
+ const minor = parseInt(minorPart, 10);
318
+ const patch = parseInt(patchPart, 10);
319
+ if (major > 0) return `${major}`;
320
+ if (minor > 0) return `${major}.${minor}`;
321
+ if (patch > 0) return `${major}.${minor}.${patch}`;
322
+ return versionStr;
323
+ }
324
+ /**
325
+ * The 8-byte entrypoint ID for a contract method:
326
+ * `sha256(interface :: majorVersion :: method)[0..8]`.
327
+ *
328
+ * A null `interfaceName` uses the `_unnamed_interface` domain. The literal `::`
329
+ * separators are what keep field boundaries unambiguous — without them
330
+ * interface `Foo1` with major `2` and interface `Foo` with major `12` would
331
+ * hash identically. Fields are raw UTF-8, not XDR-encoded.
332
+ *
333
+ * Matches the Rust SDK's `contract_entrypoint_id`.
334
+ */
335
+ function deriveEntrypointID(interfaceName, versionStr, methodName) {
336
+ const name = interfaceName ?? "_unnamed_interface";
337
+ const majorVersion = majorVersionFromSemver(versionStr);
338
+ return contractEntrypointID(sha256(new TextEncoder().encode(`${name}::${majorVersion}::${methodName}`)).slice(0, 8));
339
+ }
340
+ //#endregion
341
+ //#region src/contract/codegen.ts
342
+ /**
343
+ * Build codecs for named contract-spec types.
344
+ *
345
+ * The returned map is required by {@link encodeCalldata},
346
+ * {@link decodeCalldata}, and {@link resolveCodec} whenever a method argument
347
+ * references a named struct, enum, or union. It is keyed by
348
+ * {@link specIdKey} of each type's spec id.
349
+ *
350
+ * @throws If two definitions share a spec id.
351
+ */
352
+ function buildNamedCodecs(typeDefs) {
353
+ const codecs = Object.create(null);
354
+ const define = (id, codec) => {
355
+ const key = specIdKey(id);
356
+ if (Object.hasOwn(codecs, key)) throw new Error(`Contract spec defines "${formatSpecId(id)}" twice`);
357
+ codecs[key] = withCodecBudget(codec);
358
+ };
359
+ for (const def of typeDefs) switch (def.v) {
360
+ case ContractTypeDefKind$1.TypeDefEnum:
361
+ define(def.enum_def.name, enumCodec(formatSpecId(def.enum_def.name), def.enum_def.variants.map((variant) => variant.value)));
362
+ break;
363
+ case ContractTypeDefKind$1.TypeDefStruct: {
364
+ const structDef = def.struct_def;
365
+ const name = formatSpecId(structDef.name);
366
+ define(structDef.name, {
367
+ encode(w, val) {
368
+ if (!val || typeof val !== "object" || Array.isArray(val)) throw new TypeError(`Expected object for struct "${name}"`);
369
+ const obj = val;
370
+ for (const field of structDef.fields) resolveCodec(field.ty, codecs).encode(w, ownProperty(obj, field.name, `Struct "${name}"`));
371
+ },
372
+ decode(r) {
373
+ const obj = {};
374
+ for (const field of structDef.fields) {
375
+ const fieldCodec = resolveCodec(field.ty, codecs);
376
+ defineRecordValue$1(obj, field.name, fieldCodec.decode(r));
377
+ }
378
+ return obj;
379
+ }
380
+ });
381
+ break;
382
+ }
383
+ case ContractTypeDefKind$1.TypeDefUnion: {
384
+ const unionDef = def.union_def;
385
+ const name = formatSpecId(unionDef.name);
386
+ define(unionDef.name, {
387
+ encode(w, val) {
388
+ if (!val || typeof val !== "object" || Array.isArray(val)) throw new TypeError(`Expected case object for union "${name}"`);
389
+ const obj = val;
390
+ const caseName = ownProperty(obj, "case", `Union "${name}"`);
391
+ const caseSpec = unionDef.cases.find((candidate) => candidate.name === caseName);
392
+ if (!caseSpec) throw new Error(`Unknown case ${String(caseName)} for union "${name}"`);
393
+ w.writeInt32(caseSpec.discriminant);
394
+ encodeUnionCase(caseSpec.case_type, Object.hasOwn(obj, "value") ? obj.value : void 0, w, codecs);
395
+ },
396
+ decode(r) {
397
+ const discriminant = r.readInt32();
398
+ const caseSpec = unionDef.cases.find((c) => c.discriminant === discriminant);
399
+ if (!caseSpec) throw new Error(`Unknown discriminant ${discriminant} for union "${name}"`);
400
+ return decodeUnionCase(caseSpec.case_type, caseSpec.name, r, codecs);
401
+ }
402
+ });
403
+ break;
404
+ }
405
+ default: throw new Error(`Unsupported ContractTypeDefKind: ${def.v}`);
406
+ }
407
+ return codecs;
408
+ }
409
+ function enumCodec(name, values) {
410
+ const declared = new Set(values);
411
+ return {
412
+ encode(writer, value) {
413
+ if (typeof value !== "bigint" || !declared.has(value)) throw new Error(`Unknown value ${String(value)} for enum "${name}"`);
414
+ Int32Codec.encode(writer, value);
415
+ },
416
+ decode(reader) {
417
+ const value = Int32Codec.decode(reader);
418
+ if (!declared.has(value)) throw new Error(`Unknown value ${value} for enum "${name}"`);
419
+ return value;
420
+ }
421
+ };
422
+ }
423
+ function encodeUnionCase(caseType, value, w, codecs) {
424
+ switch (caseType.v) {
425
+ case ContractUnionCaseKind$1.UnionCaseVoid:
426
+ if (value !== void 0) throw new TypeError("Void union case must not contain a value");
427
+ break;
428
+ case ContractUnionCaseKind$1.UnionCaseTuple: {
429
+ if (!Array.isArray(value) || value.length !== caseType.tuple.length) throw new TypeError(`Tuple union case expected ${caseType.tuple.length} values`);
430
+ const arr = value;
431
+ for (const [i, type] of caseType.tuple.entries()) {
432
+ if (!Object.hasOwn(arr, i)) throw new TypeError(`Tuple union case requires own value at index ${i}`);
433
+ resolveCodec(type, codecs).encode(w, arr[i]);
434
+ }
435
+ break;
436
+ }
437
+ case ContractUnionCaseKind$1.UnionCaseStruct: {
438
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new TypeError("Struct union case requires an object value");
439
+ const fields = value;
440
+ for (const field of caseType.struct_fields) resolveCodec(field.ty, codecs).encode(w, ownProperty(fields, field.name, "Struct union case"));
441
+ break;
442
+ }
443
+ default: throw new Error(`Unsupported ContractUnionCaseKind: ${caseType.v}`);
444
+ }
445
+ }
446
+ function decodeUnionCase(caseType, caseName, r, codecs) {
447
+ switch (caseType.v) {
448
+ case ContractUnionCaseKind$1.UnionCaseVoid: return { case: caseName };
449
+ case ContractUnionCaseKind$1.UnionCaseTuple: return {
450
+ case: caseName,
451
+ value: caseType.tuple.map((ty) => {
452
+ return resolveCodec(ty, codecs).decode(r);
453
+ })
454
+ };
455
+ case ContractUnionCaseKind$1.UnionCaseStruct: {
456
+ const value = {};
457
+ for (const field of caseType.struct_fields) {
458
+ const c = resolveCodec(field.ty, codecs);
459
+ defineRecordValue$1(value, field.name, c.decode(r));
460
+ }
461
+ return {
462
+ case: caseName,
463
+ value
464
+ };
465
+ }
466
+ default: throw new Error(`Unsupported ContractUnionCaseKind: ${caseType.v}`);
467
+ }
468
+ }
469
+ function ownProperty(value, name, context) {
470
+ if (!Object.hasOwn(value, name)) throw new TypeError(`${context} requires own property "${name}"`);
471
+ return value[name];
472
+ }
473
+ function defineRecordValue$1(record, name, value) {
474
+ Object.defineProperty(record, name, {
475
+ configurable: true,
476
+ enumerable: true,
477
+ value,
478
+ writable: true
479
+ });
480
+ }
481
+ //#endregion
482
+ //#region src/contract/codec.ts
483
+ const contextCodecs = /* @__PURE__ */ new WeakMap();
484
+ const contextEnums = /* @__PURE__ */ new WeakMap();
485
+ /** Build the shared codec context for a generated binding module. */
486
+ function createContractCodecContext(typeDefs) {
487
+ const context = Object.freeze({});
488
+ const typeDefsSnapshot = structuredClone([...typeDefs]);
489
+ const namedCodecs = buildNamedCodecs(typeDefsSnapshot);
490
+ enableResolvedCodecCache(namedCodecs, collectTypeNodes(typeDefsSnapshot));
491
+ contextCodecs.set(context, namedCodecs);
492
+ const enums = /* @__PURE__ */ new Map();
493
+ for (const definition of typeDefsSnapshot) if (definition.v === ContractTypeDefKind$1.TypeDefEnum) enums.set(specIdKey(definition.enum_def.name), new Map(definition.enum_def.variants.map((variant) => [variant.value, variant.name])));
494
+ contextEnums.set(context, enums);
495
+ return context;
496
+ }
497
+ /** @internal */
498
+ function contextEnumVariant(context, type, value) {
499
+ return type.v === ContractTypeKind$1.Named && typeof value === "bigint" ? contextEnums.get(context)?.get(specIdKey(type.named))?.get(value) : void 0;
500
+ }
501
+ function collectTypeNodes(typeDefs) {
502
+ const types = /* @__PURE__ */ new Set();
503
+ const visit = (type) => {
504
+ if (types.has(type)) return;
505
+ types.add(type);
506
+ switch (type.v) {
507
+ case ContractTypeKind$1.Option:
508
+ visit(type.option_inner);
509
+ break;
510
+ case ContractTypeKind$1.Vector:
511
+ visit(type.vector.element);
512
+ break;
513
+ case ContractTypeKind$1.Tuple:
514
+ type.tuple.forEach(visit);
515
+ break;
516
+ case ContractTypeKind$1.Array:
517
+ visit(type.array.element);
518
+ break;
519
+ case ContractTypeKind$1.SignedToken:
520
+ if (type.signed_token_preimage.preimage_type) visit(type.signed_token_preimage.preimage_type);
521
+ break;
522
+ }
523
+ };
524
+ for (const definition of typeDefs) if (definition.v === ContractTypeDefKind$1.TypeDefStruct) definition.struct_def.fields.forEach((field) => visit(field.ty));
525
+ else if (definition.v === ContractTypeDefKind$1.TypeDefUnion) {
526
+ for (const unionCase of definition.union_def.cases) if (unionCase.case_type.v === ContractUnionCaseKind$1.UnionCaseTuple) unionCase.case_type.tuple.forEach(visit);
527
+ else if (unionCase.case_type.v === ContractUnionCaseKind$1.UnionCaseStruct) unionCase.case_type.struct_fields.forEach((field) => visit(field.ty));
528
+ }
529
+ return types;
530
+ }
531
+ /** @internal */
532
+ function resolveContextCodec(context, type) {
533
+ const namedCodecs = contextCodecs.get(context);
534
+ if (!namedCodecs) throw new TypeError("Invalid ContractCodecContext");
535
+ return resolveCodec(type, namedCodecs);
536
+ }
537
+ /** @internal */
538
+ function createContractCodec(context, type, label = "contract value") {
539
+ const valueCodec = resolveContextCodec(context, type);
540
+ return {
541
+ encode(value) {
542
+ const writer = new CxsWriter$1();
543
+ valueCodec.encode(writer, value);
544
+ return writer.finish();
545
+ },
546
+ decode(data) {
547
+ return decodeComplete(valueCodec, data, label);
548
+ }
549
+ };
550
+ }
551
+ /** @internal */
552
+ function decodeComplete(valueCodec, data, label) {
553
+ try {
554
+ const reader = new CxsReader$1(data, contractValueLimits(data.length));
555
+ const value = valueCodec.decode(reader);
556
+ if (reader.remaining !== 0) throw new Error(`${reader.remaining} trailing bytes`);
557
+ return value;
558
+ } catch (cause) {
559
+ if (cause instanceof ContractDecodeError) throw cause;
560
+ throw new ContractDecodeError(`Failed to decode ${label}${cause instanceof Error ? `: ${cause.message}` : ""}`, { cause });
561
+ }
562
+ }
563
+ //#endregion
564
+ //#region src/actions/viewFreshness.ts
565
+ /** Reject a successful view that violates the caller's snapshot constraint. */
566
+ function assertViewFreshness(height, minHeight) {
567
+ if (minHeight !== void 0 && height < minHeight) throw new Error(`View response height ${height} is below the requested minimum ${minHeight}`);
568
+ }
569
+ //#endregion
570
+ //#region src/actions/viewAuthClaim.ts
571
+ function u32(value, name) {
572
+ serializeU64(value, name);
573
+ if (value > 4294967295n) throw new RangeError(`${name} must fit uint32`);
574
+ return Number(value);
575
+ }
576
+ /** Project public authorization assumptions; this neither signs nor verifies authorization. */
577
+ function toAssumedAuth(claim) {
578
+ switch (claim.claim_type) {
579
+ case AuthClaimType.kSourceAddressAuthData: return {
580
+ kind: "sourceAddress",
581
+ allowedKeys: u32(claim.source_address_claim.allowed_keys, "allowedKeys"),
582
+ requiredWeight: u32(claim.source_address_claim.required_weight, "requiredWeight")
583
+ };
584
+ case AuthClaimType.kPubkeySignature: {
585
+ const { pubkey_hash, nonce } = claim.pubkey_preimage;
586
+ if (!(pubkey_hash instanceof Uint8Array) || pubkey_hash.length !== 32) throw new TypeError("Assumed pubkey hash must contain 32 bytes");
587
+ serializeU64(nonce, "accountNonce");
588
+ return {
589
+ kind: "pubkeySignature",
590
+ pubkeyHash: pubkey_hash.slice(),
591
+ accountNonce: nonce
592
+ };
593
+ }
594
+ default: throw new TypeError("Unsupported authorization assumption");
595
+ }
596
+ }
597
+ //#endregion
598
+ //#region src/contract/method.ts
599
+ /** Error thrown by the view API for aborts, faults, or unsupported outcomes. */
600
+ var ContractViewError = class extends Error {
601
+ outcome;
602
+ constructor(outcome) {
603
+ const selector = outcome.kind === "abort" ? exceptionSelector(outcome.exception) : void 0;
604
+ super(outcome.kind === "abort" ? `Contract view aborted with ${formatException(outcome.exception, selector)}` : outcome.kind === "unsupported" ? "Unsupported contract simulation outcome" : "Contract view faulted");
605
+ this.name = "ContractViewError";
606
+ this.outcome = outcome;
607
+ }
608
+ };
609
+ /** Error thrown when a root contract receipt does not produce a typed return. */
610
+ var ContractReceiptError = class extends Error {
611
+ outcome;
612
+ constructor(outcome) {
613
+ const selector = outcome.kind === "abort" ? exceptionSelector(outcome.exception) : void 0;
614
+ super(outcome.kind === "abort" ? `Contract transaction ${toBase58(outcome.transactionHash)} aborted with ${formatException(outcome.exception, selector)}` : `Contract transaction ${toBase58(outcome.transactionHash)} did not return a supported successful result`);
615
+ this.name = "ContractReceiptError";
616
+ this.outcome = outcome;
617
+ }
618
+ };
619
+ function formatException(exception, selector) {
620
+ if (exception && typeof exception === "object" && "name" in exception && typeof exception.name === "string" && "value" in exception) {
621
+ const value = typeof exception.value === "bigint" ? `${exception.value}n` : JSON.stringify(exception.value, (_, v) => typeof v === "bigint" ? `${v}n` : v);
622
+ const variant = "variant" in exception && typeof exception.variant === "string" ? `.${exception.variant}` : "";
623
+ return `${exception.name}${variant} (${value})`;
624
+ }
625
+ return `unknown selector ${selector === void 0 ? "unknown" : `0x${selector.toString(16)}`}`;
626
+ }
627
+ function exceptionSelector(exception) {
628
+ if (!exception || typeof exception !== "object" || !("selector" in exception)) return;
629
+ return typeof exception.selector === "bigint" ? exception.selector : void 0;
630
+ }
631
+ /** Build one generated method descriptor from direct ABI metadata. */
632
+ function defineContractMethod(definition) {
633
+ return defineContractMethodWithExceptions(definition, resolveContractExceptions(definition));
634
+ }
635
+ function resolveContractExceptions(definition) {
636
+ const exceptions = /* @__PURE__ */ new Map();
637
+ for (const metadata of definition.throws) {
638
+ if (exceptions.has(metadata.selector)) throw new Error(`Duplicate contract exception selector ${metadata.selector}`);
639
+ exceptions.set(metadata.selector, {
640
+ name: metadata.name,
641
+ codec: resolveContextCodec(definition.codecs, metadata.type),
642
+ variant: (value) => contextEnumVariant(definition.codecs, metadata.type, value)
643
+ });
644
+ }
645
+ return exceptions;
646
+ }
647
+ function defineContractMethodWithExceptions(definition, exceptionBySelector) {
648
+ const entrypoint = copyEntrypoint(definition.entrypoint);
649
+ const effect = definition.effect ?? null;
650
+ if (effect !== null && ![
651
+ ContractMethodEffect.EffectPure,
652
+ ContractMethodEffect.EffectReadOnly,
653
+ ContractMethodEffect.EffectStateChanging
654
+ ].includes(effect)) throw new TypeError(`Unsupported contract method effect ${effect}`);
655
+ const name = definition.interfaceName && definition.publicName ? `${definition.interfaceName}.${definition.publicName}` : toHex0x(entrypoint);
656
+ const encode = (args) => {
657
+ try {
658
+ return encodeArguments(argumentCodecs, args);
659
+ } catch (cause) {
660
+ throw new TypeError(`${name}: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
661
+ }
662
+ };
663
+ const argumentCodecs = definition.args.map((argument) => ({
664
+ publicName: argument.publicName,
665
+ codec: resolveContextCodec(definition.codecs, argument.type)
666
+ }));
667
+ const returnCodec = resolveContextCodec(definition.codecs, definition.returnType);
668
+ const method = {
669
+ name,
670
+ effect,
671
+ viewRequest(options) {
672
+ if ("minStateBlockHeight" in options) throw new TypeError("Set minStateBlockHeight on readViews, not on a prepared call");
673
+ return {
674
+ request: {
675
+ address: contractAddress(new Uint8Array(options.address)),
676
+ entrypoint: copyEntrypoint(entrypoint),
677
+ calldata: encode("args" in options ? options.args : void 0),
678
+ ...options.assumedAuth === void 0 ? {} : { assumedAuth: toAssumedAuth(options.assumedAuth) },
679
+ ...options.caller ? { caller: contractAddress(new Uint8Array(options.caller)) } : {}
680
+ },
681
+ method
682
+ };
683
+ },
684
+ call(options) {
685
+ if ("minStateBlockHeight" in options) throw new TypeError("minStateBlockHeight is a read constraint, not a transaction option");
686
+ return {
687
+ invocation: {
688
+ invoked_address: contractAddress(new Uint8Array(options.address)),
689
+ entrypoint: copyEntrypoint(entrypoint),
690
+ gas_limit: options.gasLimit,
691
+ calldata: encode("args" in options ? options.args : void 0)
692
+ },
693
+ method
694
+ };
695
+ },
696
+ get entrypoint() {
697
+ return copyEntrypoint(entrypoint);
698
+ },
699
+ invocation(contract, gasLimit, ...args) {
700
+ return {
701
+ invoked_address: contract,
702
+ entrypoint: copyEntrypoint(entrypoint),
703
+ gas_limit: gasLimit,
704
+ calldata: encode(args[0])
705
+ };
706
+ },
707
+ decodeArgs(data) {
708
+ const reader = new CxsReader$1(data, contractValueLimits(data.length));
709
+ const args = Object.fromEntries(argumentCodecs.map((argument) => {
710
+ try {
711
+ return [argument.publicName, argument.codec.decode(reader)];
712
+ } catch (cause) {
713
+ const detail = cause instanceof Error ? `: ${cause.message}` : "";
714
+ throw new ContractDecodeError(`${name}: argument "${argument.publicName}"${detail}`, { cause });
715
+ }
716
+ }));
717
+ if (reader.remaining !== 0) throw new ContractDecodeError(`${name}: ${reader.remaining} trailing calldata bytes`);
718
+ return argumentCodecs.length === 0 ? void 0 : args;
719
+ },
720
+ decodeReturn(data) {
721
+ return decodeComplete(returnCodec, data, `${name} contract return value`);
722
+ },
723
+ decodeException(data) {
724
+ return decodeException(data, exceptionBySelector);
725
+ },
726
+ decodeReceiptOutcome(receipt) {
727
+ const metadata = {
728
+ transactionHash: receipt.transactionHash,
729
+ blockHeight: receipt.blockHeight,
730
+ events: receipt.events
731
+ };
732
+ const execution = receipt.execution;
733
+ if (execution instanceof UnsupportedRpcValue) return {
734
+ kind: "unsupported",
735
+ raw: receipt,
736
+ ...metadata
737
+ };
738
+ if (execution.result === "return") return {
739
+ kind: "return",
740
+ value: method.decodeReturn(execution.returnData),
741
+ ...metadata
742
+ };
743
+ if (execution.result === "abort") return {
744
+ kind: "abort",
745
+ exception: method.decodeException(execution.abortData),
746
+ abortData: execution.abortData,
747
+ ...metadata
748
+ };
749
+ return {
750
+ kind: "failure",
751
+ execution,
752
+ ...metadata
753
+ };
754
+ },
755
+ decodeReceipt(receipt) {
756
+ const outcome = method.decodeReceiptOutcome(receipt);
757
+ if (outcome.kind === "return") return {
758
+ value: outcome.value,
759
+ transactionHash: outcome.transactionHash,
760
+ blockHeight: outcome.blockHeight,
761
+ events: outcome.events
762
+ };
763
+ throw new ContractReceiptError(outcome);
764
+ },
765
+ decodeView(response) {
766
+ const outcome = method.decodeViewOutcome(response);
767
+ if (outcome.kind !== "return") throw new ContractViewError(outcome);
768
+ return {
769
+ value: outcome.value,
770
+ stateBlockHeight: outcome.stateBlockHeight,
771
+ gasUsed: outcome.gasUsed,
772
+ events: outcome.events
773
+ };
774
+ },
775
+ async viewOutcome(options) {
776
+ options.signal?.throwIfAborted();
777
+ const minStateBlockHeight = options.minStateBlockHeight;
778
+ if (minStateBlockHeight !== void 0) serializeHeight(minStateBlockHeight);
779
+ const request = {
780
+ ...options.assumedAuth === void 0 ? {} : { assumedAuth: toAssumedAuth(options.assumedAuth) },
781
+ address: options.address,
782
+ entrypoint: copyEntrypoint(entrypoint),
783
+ calldata: encode("args" in options ? options.args : void 0),
784
+ ...options.caller ? { caller: options.caller } : {},
785
+ ...minStateBlockHeight === void 0 ? {} : { minStateBlockHeight }
786
+ };
787
+ const response = await (options.signal ? options.client.simulateInvocation(request, { signal: options.signal }) : options.client.simulateInvocation(request));
788
+ assertViewFreshness(response.stateBlockHeight, minStateBlockHeight);
789
+ return method.decodeViewOutcome(response);
790
+ },
791
+ decodeViewOutcome(response) {
792
+ if (response.output instanceof UnsupportedRpcValue) return {
793
+ kind: "unsupported",
794
+ raw: response,
795
+ stateBlockHeight: response.stateBlockHeight,
796
+ gasUsed: response.gasUsed,
797
+ events: response.events
798
+ };
799
+ switch (response.output.result) {
800
+ case "return": return {
801
+ kind: "return",
802
+ value: method.decodeReturn(response.output.returnData),
803
+ stateBlockHeight: response.stateBlockHeight,
804
+ gasUsed: response.gasUsed,
805
+ events: response.events
806
+ };
807
+ case "abort": return {
808
+ kind: "abort",
809
+ exception: method.decodeException(response.output.abortData),
810
+ abortData: response.output.abortData,
811
+ stateBlockHeight: response.stateBlockHeight,
812
+ gasUsed: response.gasUsed,
813
+ events: response.events
814
+ };
815
+ case "fault": return {
816
+ kind: "fault",
817
+ stateBlockHeight: response.stateBlockHeight,
818
+ gasUsed: response.gasUsed,
819
+ events: response.events
820
+ };
821
+ }
822
+ },
823
+ async view(options) {
824
+ const outcome = await method.viewOutcome(options);
825
+ if (outcome.kind === "return") return {
826
+ value: outcome.value,
827
+ stateBlockHeight: outcome.stateBlockHeight,
828
+ gasUsed: outcome.gasUsed,
829
+ events: outcome.events
830
+ };
831
+ throw new ContractViewError(outcome);
832
+ }
833
+ };
834
+ return method;
835
+ }
836
+ function copyEntrypoint(value) {
837
+ return contractEntrypointID(Uint8Array.from(value));
838
+ }
839
+ function encodeArguments(argumentsAndCodecs, args) {
840
+ if (argumentsAndCodecs.length > 0 && (!args || typeof args !== "object")) throw new TypeError("Contract method arguments must be an object");
841
+ const values = args;
842
+ const writer = new CxsWriter$1();
843
+ for (const argument of argumentsAndCodecs) {
844
+ if (!values || !Object.hasOwn(values, argument.publicName)) throw new TypeError(`Contract method arguments require own property "${argument.publicName}"`);
845
+ try {
846
+ argument.codec.encode(writer, values[argument.publicName]);
847
+ } catch (cause) {
848
+ throw new TypeError(`argument "${argument.publicName}": ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
849
+ }
850
+ }
851
+ return calldata(writer.finish());
852
+ }
853
+ function decodeException(data, exceptionBySelector) {
854
+ try {
855
+ const reader = new CxsReader$1(data, contractValueLimits(data.length));
856
+ const selector = reader.readUint64();
857
+ const declared = exceptionBySelector.get(selector);
858
+ if (!declared) return {
859
+ kind: "unknown",
860
+ selector,
861
+ data
862
+ };
863
+ const value = declared.codec.decode(reader);
864
+ const variant = declared.variant(value);
865
+ if (reader.remaining !== 0) throw new Error(`${reader.remaining} trailing bytes`);
866
+ return {
867
+ kind: "declared",
868
+ selector,
869
+ name: declared.name,
870
+ value,
871
+ ...variant === void 0 ? {} : { variant }
872
+ };
873
+ } catch (cause) {
874
+ throw new ContractDecodeError(`Failed to decode contract exception${cause instanceof Error ? `: ${cause.message}` : ""}`, { cause });
875
+ }
876
+ }
877
+ //#endregion
878
+ //#region src/contract/specMethod.ts
879
+ /**
880
+ * Decode a selector and arguments with the generated-binding codecs.
881
+ * Unknown selectors return null; malformed known inputs throw. The caller must
882
+ * establish the spec's identity. A current spec does not prove historical code.
883
+ */
884
+ function createContractCallDecoder(spec) {
885
+ const snapshot = structuredClone(spec);
886
+ const codecs = createContractCodecContext(snapshot.type_defs);
887
+ const methods = /* @__PURE__ */ new Map();
888
+ for (const iface of snapshot.interfaces) {
889
+ const throws = iface.throws.map((exception) => ({
890
+ selector: exception.selector,
891
+ name: null,
892
+ type: exception.ty
893
+ }));
894
+ const exceptions = resolveContractExceptions({
895
+ throws,
896
+ codecs
897
+ });
898
+ for (const method of iface.methods) {
899
+ const key = deriveEntrypointID(iface.name, iface.vers, method.name).join(",");
900
+ if (methods.has(key)) throw new ContractDecodeError("Duplicate method selector in contract spec");
901
+ if (new Set(method.args.map((arg) => arg.name)).size !== method.args.length) throw new ContractDecodeError("Duplicate argument name in contract spec");
902
+ const descriptor = defineContractMethodWithExceptions({
903
+ interfaceName: iface.name,
904
+ interfaceVersion: iface.vers,
905
+ publicName: method.name,
906
+ abiName: method.name,
907
+ entrypoint: deriveEntrypointID(iface.name, iface.vers, method.name),
908
+ effect: method.effect,
909
+ args: method.args.map((arg) => ({
910
+ abiName: arg.name,
911
+ publicName: arg.name,
912
+ type: arg.ty
913
+ })),
914
+ returnType: method.return_type,
915
+ throws,
916
+ codecs
917
+ }, exceptions);
918
+ methods.set(key, {
919
+ interfaceName: iface.name,
920
+ interfaceVersion: iface.vers,
921
+ methodName: method.name,
922
+ method: descriptor
923
+ });
924
+ }
925
+ }
926
+ return (invocation) => {
927
+ const found = methods.get(invocation.entrypoint.join(","));
928
+ if (!found) return null;
929
+ return {
930
+ ...found,
931
+ args: found.method.decodeArgs(invocation.calldata) || void 0
932
+ };
933
+ };
934
+ }
935
+ //#endregion
936
+ //#region src/contract/hash.ts
937
+ /**
938
+ * Return the network identity of a protocol contract.
939
+ *
940
+ * The hash covers the canonical encoded `Contract`, including its type and
941
+ * payload framing. Hashing only the raw artifact bytes produces a different
942
+ * value and therefore a different derived address.
943
+ *
944
+ * @example
945
+ * ```ts
946
+ * import {
947
+ * deriveContractAddress,
948
+ * hashContract,
949
+ * } from "@thruputchain/client";
950
+ *
951
+ * const contractHash = hashContract(contract);
952
+ * const address = deriveContractAddress(wallet, deploymentNonce, contractHash);
953
+ * ```
954
+ */
955
+ function hashContract(contract) {
956
+ return sha256Hash(sha256(serialize(contract, codec.Contract)));
957
+ }
958
+ //#endregion
959
+ //#region src/contract/event.ts
960
+ /**
961
+ * Build a decoder from a parsed spec using the same codecs as generated bindings.
962
+ * Unknown signatures return null; malformed known events throw. The caller must
963
+ * establish that this spec belongs to the contract that emitted the event.
964
+ */
965
+ function createContractEventDecoder(spec) {
966
+ const codecs = createContractCodecContext(spec.type_defs);
967
+ const signatures = /* @__PURE__ */ new Set();
968
+ const events = spec.events.map((event) => {
969
+ const key = event.signature.join(",");
970
+ if (signatures.has(key)) throw new ContractDecodeError("Duplicate event signature in contract spec");
971
+ signatures.add(key);
972
+ return defineContractEvent({
973
+ name: formatSpecId(event.name),
974
+ signature: event.signature,
975
+ topics: event.topics.map((field) => ({
976
+ name: field.name,
977
+ type: field.ty,
978
+ representation: topicRepresentation(field.ty)
979
+ })),
980
+ fields: event.fields.map((field) => ({
981
+ name: field.name,
982
+ type: field.ty
983
+ })),
984
+ codecs
985
+ });
986
+ });
987
+ return (event) => {
988
+ for (const descriptor of events) {
989
+ const decoded = descriptor.decode(event);
990
+ if (decoded !== null) return decoded;
991
+ }
992
+ return null;
993
+ };
994
+ }
995
+ const maxFilterContractAddresses = 5;
996
+ const maxFilterTopicValues = 16;
997
+ /** Build one generated event descriptor from direct ABI metadata. */
998
+ function defineContractEvent(definition) {
999
+ const eventName = definition.name;
1000
+ const signature = fixedBytes(Uint8Array.from(definition.signature), 32);
1001
+ if (definition.topics.length > 2) throw new Error(`${eventName} declares ${definition.topics.length + 1} topics; protocol maximum is 3`);
1002
+ assertUniqueNames(definition.topics, `${eventName} topic`);
1003
+ assertUniqueNames(definition.fields, `${eventName} field`);
1004
+ const resolvedTopics = definition.topics.map((metadata) => {
1005
+ const expected = topicRepresentation(metadata.type);
1006
+ if (metadata.representation !== expected) throw new Error(`${eventName} topic "${metadata.name}" representation "${metadata.representation}" does not match its declared type; expected "${expected}"`);
1007
+ if (metadata.representation !== "address" && metadata.representation !== "fixedBytes32" && metadata.representation !== "hash") {
1008
+ const signed = metadata.representation.startsWith("i");
1009
+ const bits = metadata.representation === "bool" ? 1 : Number(metadata.representation.slice(1));
1010
+ const bound = 1n << BigInt(signed ? bits - 1 : bits);
1011
+ return {
1012
+ name: metadata.name,
1013
+ representation: metadata.representation,
1014
+ codec: resolveContextCodec(definition.codecs, { v: signed ? ContractTypeKind$1.I256 : ContractTypeKind$1.U256 }),
1015
+ min: signed ? -bound : 0n,
1016
+ max: bound - 1n
1017
+ };
1018
+ }
1019
+ return {
1020
+ name: metadata.name,
1021
+ representation: metadata.representation
1022
+ };
1023
+ });
1024
+ const fields = definition.fields.map((metadata) => ({
1025
+ metadata: { ...metadata },
1026
+ codec: resolveContextCodec(definition.codecs, metadata.type)
1027
+ }));
1028
+ const descriptor = {
1029
+ get signature() {
1030
+ return Uint8Array.from(signature);
1031
+ },
1032
+ decode(event) {
1033
+ if (!bytesEqual(event.topics[0], signature)) return null;
1034
+ try {
1035
+ const expectedTopicCount = resolvedTopics.length + 1;
1036
+ if (event.topics.length !== expectedTopicCount) throw new Error(`expected ${expectedTopicCount} topics, got ${event.topics.length}`);
1037
+ assertEventSize(event.topics, event.data);
1038
+ const decodedTopics = {};
1039
+ for (const [index, metadata] of resolvedTopics.entries()) {
1040
+ const rawTopic = event.topics[index + 1];
1041
+ if (rawTopic === void 0) throw new Error(`missing topic "${metadata.name}"`);
1042
+ const value = decodeTopic(metadata, fixedBytes(rawTopic, 32));
1043
+ defineRecordValue(decodedTopics, metadata.name, value);
1044
+ }
1045
+ const reader = new CxsReader$1(event.data, contractValueLimits(event.data.length));
1046
+ const decodedFields = {};
1047
+ for (const field of fields) defineRecordValue(decodedFields, field.metadata.name, field.codec.decode(reader));
1048
+ if (reader.remaining !== 0) throw new Error(`${reader.remaining} trailing payload bytes`);
1049
+ return {
1050
+ name: eventName,
1051
+ topics: decodedTopics,
1052
+ fields: decodedFields
1053
+ };
1054
+ } catch (cause) {
1055
+ if (cause instanceof ContractDecodeError) throw cause;
1056
+ throw new ContractDecodeError(`Failed to decode ${eventName}${cause instanceof Error ? `: ${cause.message}` : ""}`, { cause });
1057
+ }
1058
+ },
1059
+ filter(input) {
1060
+ if (input.addresses.length === 0) throw new Error(`${eventName} filter requires a contract address`);
1061
+ if (input.addresses.length > maxFilterContractAddresses) throw new Error(`${eventName} filter supports at most ${maxFilterContractAddresses} contract addresses`);
1062
+ for (const address of input.addresses) fixedBytes(address, 32);
1063
+ const filterTopics = { topic0: [Uint8Array.from(signature)] };
1064
+ const constraints = input.topics;
1065
+ if (constraints) {
1066
+ const directTopics = new Map(resolvedTopics.map((metadata, index) => ({
1067
+ metadata,
1068
+ index
1069
+ })).filter(({ metadata }) => metadata.representation !== "hash").map((topic) => [topic.metadata.name, topic]));
1070
+ for (const [name, constraint] of Object.entries(constraints)) {
1071
+ const topic = directTopics.get(name);
1072
+ if (topic === void 0) throw new Error(`${eventName} topic "${name}" is not directly filterable`);
1073
+ const { metadata, index } = topic;
1074
+ const values = filterValues(constraint, eventName, metadata);
1075
+ const key = `topic${index + 1}`;
1076
+ filterTopics[key] = values.map((value) => encodeTopic(metadata, value, eventName));
1077
+ }
1078
+ }
1079
+ return {
1080
+ addresses: [...input.addresses],
1081
+ topics: filterTopics
1082
+ };
1083
+ },
1084
+ allFromReceipt(receipt, options) {
1085
+ const matches = [];
1086
+ for (const event of receipt.events) {
1087
+ if (!bytesEqual(event.address, options.address)) continue;
1088
+ const decoded = descriptor.decode(event);
1089
+ if (decoded !== null) matches.push({
1090
+ ...decoded,
1091
+ address: contractAddress(event.address.slice())
1092
+ });
1093
+ }
1094
+ return matches;
1095
+ },
1096
+ singleFromReceipt(receipt, options) {
1097
+ const matches = descriptor.allFromReceipt(receipt, options);
1098
+ const match = matches[0];
1099
+ if (matches.length !== 1 || match === void 0) throw new Error(`Expected exactly one ${eventName} event, got ${matches.length}`);
1100
+ return match;
1101
+ }
1102
+ };
1103
+ return descriptor;
1104
+ }
1105
+ /** Distinguish directly encoded indexed values from irreversible topic hashes. */
1106
+ function topicRepresentation(type) {
1107
+ if (type.v === ContractTypeKind$1.Address) return "address";
1108
+ if (type.v === ContractTypeKind$1.U32) return "u32";
1109
+ if (type.v === ContractTypeKind$1.U64) return "u64";
1110
+ if (type.v === ContractTypeKind$1.U128) return "u128";
1111
+ if (type.v === ContractTypeKind$1.U256) return "u256";
1112
+ if (type.v === ContractTypeKind$1.I32) return "i32";
1113
+ if (type.v === ContractTypeKind$1.I64) return "i64";
1114
+ if (type.v === ContractTypeKind$1.I128) return "i128";
1115
+ if (type.v === ContractTypeKind$1.I256) return "i256";
1116
+ if (type.v === ContractTypeKind$1.Bool) return "bool";
1117
+ if (type.v === ContractTypeKind$1.Array && type.array.len === 32n && type.array.element?.v === ContractTypeKind$1.U8) return "fixedBytes32";
1118
+ return "hash";
1119
+ }
1120
+ /** Compare public byte identifiers. This function is not constant-time. */
1121
+ function bytesEqual(left, right) {
1122
+ if (!left || left.length !== right.length) return false;
1123
+ for (let index = 0; index < left.length; index++) if (left[index] !== right[index]) return false;
1124
+ return true;
1125
+ }
1126
+ function filterValues(constraint, eventName, topic) {
1127
+ if (constraint && typeof constraint === "object" && !Array.isArray(constraint) && !(constraint instanceof Uint8Array) && "oneOf" in constraint) {
1128
+ const values = constraint.oneOf;
1129
+ if (!Array.isArray(values) || values.length === 0) throw new Error(`${eventName} topic "${topic.name}" oneOf must not be empty`);
1130
+ if (values.length > maxFilterTopicValues) throw new Error(`${eventName} topic "${topic.name}" oneOf supports at most ${maxFilterTopicValues} values`);
1131
+ return values;
1132
+ }
1133
+ return [constraint];
1134
+ }
1135
+ function decodeTopic(topic, bytes) {
1136
+ switch (topic.representation) {
1137
+ case "address": return contractAddress(bytes);
1138
+ case "fixedBytes32":
1139
+ case "hash": return bytes;
1140
+ default: {
1141
+ const value = topic.codec.decode(new CxsReader$1(bytes, contractValueLimits(bytes.length)));
1142
+ assertScalarRange(topic, value);
1143
+ return topic.representation === "bool" ? value === 1n : value;
1144
+ }
1145
+ }
1146
+ }
1147
+ function encodeTopic(topic, value, eventName) {
1148
+ switch (topic.representation) {
1149
+ case "address":
1150
+ case "fixedBytes32": return fixedBytes(requireBytes(value, eventName, topic.name), 32);
1151
+ case "hash": throw new Error(`${eventName} topic "${topic.name}" is not directly filterable`);
1152
+ default: {
1153
+ const writer = new CxsWriter$1();
1154
+ try {
1155
+ if (topic.representation === "bool") {
1156
+ if (typeof value !== "boolean") throw new TypeError("Bool expected boolean");
1157
+ value = value ? 1n : 0n;
1158
+ }
1159
+ topic.codec.encode(writer, value);
1160
+ assertScalarRange(topic, value);
1161
+ } catch (cause) {
1162
+ const detail = cause instanceof Error ? `: ${cause.message}` : "";
1163
+ throw new Error(`${eventName} topic "${topic.name}" failed to encode${detail}`, { cause });
1164
+ }
1165
+ return fixedBytes(writer.finish(), 32);
1166
+ }
1167
+ }
1168
+ }
1169
+ function assertScalarRange(topic, value) {
1170
+ if (value < topic.min || value > topic.max) throw new RangeError(`topic "${topic.name}" is outside the ${topic.representation} range`);
1171
+ }
1172
+ function requireBytes(value, eventName, topicName) {
1173
+ if (!(value instanceof Uint8Array)) throw new TypeError(`${eventName} topic "${topicName}" must be bytes`);
1174
+ return value;
1175
+ }
1176
+ function assertEventSize(topics, data) {
1177
+ const size = topics.reduce((total, topic) => total + topic.length, data.length);
1178
+ const limit = Number(kMaxEventLength);
1179
+ if (size > limit) throw new Error(`serialized event size ${size} exceeds ${limit} bytes`);
1180
+ }
1181
+ function assertUniqueNames(values, label) {
1182
+ const names = /* @__PURE__ */ new Set();
1183
+ for (const value of values) {
1184
+ if (names.has(value.name)) throw new Error(`Duplicate ${label} name "${value.name}"`);
1185
+ names.add(value.name);
1186
+ }
1187
+ }
1188
+ function defineRecordValue(record, name, value) {
1189
+ Object.defineProperty(record, name, {
1190
+ configurable: true,
1191
+ enumerable: true,
1192
+ value,
1193
+ writable: true
1194
+ });
1195
+ }
1196
+ //#endregion
1197
+ //#region src/contract/specValidation.ts
1198
+ /** Validate references after schema-1 wire preflight has bounded the structure. */
1199
+ function validateArtifactSpec(spec) {
1200
+ createContractCallDecoder(spec);
1201
+ createContractEventDecoder(spec);
1202
+ }
1203
+ //#endregion
1204
+ //#region src/contract/specPreflight.ts
1205
+ const contractSpecCodecLimits = {
1206
+ maxDepth: 256,
1207
+ maxWork: 1e6
1208
+ };
1209
+ /**
1210
+ * Schema-1 tooling limits, mirrored by tools' contract_spec/bounded.rs.
1211
+ * Count collection entries and type nodes (tuple elements count in both).
1212
+ * Type depth starts at one; named references are leaves, not expansions.
1213
+ * This bounds the generated decoder before it recurses or allocates lists.
1214
+ */
1215
+ function preflightContractSpec(bytes) {
1216
+ if (bytes.length > 16 * 1024 * 1024) throw new ContractDecodeError("Contract spec exceeds byte limit (16777216)");
1217
+ const reader = new XdrReader(bytes);
1218
+ let work = 1e5;
1219
+ const spend = (count) => {
1220
+ work -= count;
1221
+ if (work < 0) throw new ContractDecodeError("Contract spec exceeds work limit (100000)");
1222
+ };
1223
+ const list = (item) => {
1224
+ const count = Number(reader.readUint32());
1225
+ if (count > Math.floor(reader.remaining / 4)) throw new ContractDecodeError("Truncated contract spec collection");
1226
+ spend(count);
1227
+ for (let i = 0; i < count; i++) item();
1228
+ };
1229
+ const string = () => {
1230
+ codec$1.ContractSpecString.decode(reader);
1231
+ };
1232
+ const id = () => {
1233
+ codec$1.ContractSpecId.decode(reader);
1234
+ };
1235
+ const type = (depth = 1) => {
1236
+ if (depth > 64) throw new ContractDecodeError("Contract spec exceeds type nesting limit (64)");
1237
+ spend(1);
1238
+ const kind = Number(reader.readInt32());
1239
+ switch (kind) {
1240
+ case ContractTypeKind.Void:
1241
+ case ContractTypeKind.Bool:
1242
+ case ContractTypeKind.U8:
1243
+ case ContractTypeKind.U32:
1244
+ case ContractTypeKind.I32:
1245
+ case ContractTypeKind.U64:
1246
+ case ContractTypeKind.I64:
1247
+ case ContractTypeKind.U128:
1248
+ case ContractTypeKind.I128:
1249
+ case ContractTypeKind.U256:
1250
+ case ContractTypeKind.I256:
1251
+ case ContractTypeKind.String:
1252
+ case ContractTypeKind.Bytes:
1253
+ case ContractTypeKind.Address: return;
1254
+ case ContractTypeKind.Option:
1255
+ type(depth + 1);
1256
+ return;
1257
+ case ContractTypeKind.Vector:
1258
+ case ContractTypeKind.Array:
1259
+ type(depth + 1);
1260
+ reader.readUint32();
1261
+ return;
1262
+ case ContractTypeKind.Tuple:
1263
+ list(() => type(depth + 1));
1264
+ return;
1265
+ case ContractTypeKind.Named:
1266
+ id();
1267
+ return;
1268
+ case ContractTypeKind.SignedToken:
1269
+ if (reader.readBool()) type(depth + 1);
1270
+ return;
1271
+ default: throw new ContractDecodeError(`Unknown contract spec type ${kind}`);
1272
+ }
1273
+ };
1274
+ const field = () => {
1275
+ string();
1276
+ type();
1277
+ };
1278
+ try {
1279
+ list(() => {
1280
+ string();
1281
+ string();
1282
+ list(() => {
1283
+ reader.readUint64();
1284
+ type();
1285
+ });
1286
+ list(() => {
1287
+ string();
1288
+ list(field);
1289
+ type();
1290
+ if (reader.readBool()) codec$1.ContractMethodEffect.decode(reader);
1291
+ });
1292
+ });
1293
+ list(() => {
1294
+ const kind = Number(reader.readInt32());
1295
+ id();
1296
+ switch (kind) {
1297
+ case ContractTypeDefKind.TypeDefStruct:
1298
+ list(field);
1299
+ break;
1300
+ case ContractTypeDefKind.TypeDefEnum:
1301
+ list(() => {
1302
+ codec$1.ContractEnumVariant.decode(reader);
1303
+ });
1304
+ break;
1305
+ case ContractTypeDefKind.TypeDefUnion:
1306
+ list(() => {
1307
+ string();
1308
+ reader.readInt32();
1309
+ const kind = Number(reader.readInt32());
1310
+ switch (kind) {
1311
+ case ContractUnionCaseKind.UnionCaseVoid: break;
1312
+ case ContractUnionCaseKind.UnionCaseTuple:
1313
+ list(() => type());
1314
+ break;
1315
+ case ContractUnionCaseKind.UnionCaseStruct:
1316
+ list(field);
1317
+ break;
1318
+ default: throw new ContractDecodeError(`Unknown contract spec union case ${kind}`);
1319
+ }
1320
+ });
1321
+ break;
1322
+ default: throw new ContractDecodeError(`Unknown contract spec definition ${kind}`);
1323
+ }
1324
+ });
1325
+ list(() => {
1326
+ id();
1327
+ reader.readFixedOpaque(32);
1328
+ list(field);
1329
+ list(field);
1330
+ });
1331
+ if (reader.remaining !== 0) throw new ContractDecodeError("Trailing contract spec bytes");
1332
+ } catch (cause) {
1333
+ if (cause instanceof ContractDecodeError) throw cause;
1334
+ throw new ContractDecodeError("Invalid contract spec XDR", { cause });
1335
+ }
1336
+ }
1337
+ //#endregion
1338
+ //#region src/contract/artifact.ts
1339
+ /**
1340
+ * Verify complete Contract XDR against the requested hash, then read its spec.
1341
+ * Rejects malformed known envelopes. Unknown versions remain explicit results.
1342
+ * Reads v5 as having no spec. In v6, validates all extension framing and skips
1343
+ * unknown kinds. Only the contract-spec extension body is interpreted.
1344
+ * This proves byte identity, not deployment, executable validity, or spec truth.
1345
+ */
1346
+ function readContractArtifactSpec(contractXdr, expectedHash) {
1347
+ try {
1348
+ return readArtifact(contractXdr, expectedHash);
1349
+ } catch (cause) {
1350
+ throw new ContractVerificationError(cause instanceof Error ? cause.message : "Invalid contract artifact", { cause });
1351
+ }
1352
+ }
1353
+ function readArtifact(contractXdr, expectedHash) {
1354
+ const bytes = contractXdr.slice();
1355
+ if (!bytesEqual(sha256(bytes), expectedHash)) throw new Error("Contract artifact hash mismatch");
1356
+ const contract = deserialize(bytes, codec.Contract);
1357
+ if (!bytesEqual(serialize(contract, codec.Contract), bytes)) throw new Error("Noncanonical Contract XDR");
1358
+ if (contract.contract_type === ContractType.kNative) return { kind: "native" };
1359
+ if (contract.contract_type !== ContractType.kRv32) return {
1360
+ kind: "unsupportedContract",
1361
+ contractType: contract.contract_type
1362
+ };
1363
+ const artifact = contract.rv32_contract.data;
1364
+ if (artifact.length < 12 || !bytesEqual(artifact.subarray(0, 8), new TextEncoder().encode("GHRV32A1"))) throw new Error("Invalid RV32 artifact header");
1365
+ const header = new DataView(artifact.buffer, artifact.byteOffset, artifact.byteLength);
1366
+ const formatVersion = header.getUint32(8, true);
1367
+ if (formatVersion !== 5 && formatVersion !== 6) return {
1368
+ kind: "unsupportedFormat",
1369
+ formatVersion
1370
+ };
1371
+ if (artifact.length < 128 || header.getUint32(12, true) !== 128) throw new Error("Invalid RV32 header size");
1372
+ const codeSize = header.getUint32(52, true);
1373
+ const memorySize = header.getUint32(56, true);
1374
+ const sectionsEnd = 128 + codeSize + memorySize;
1375
+ if (sectionsEnd > artifact.length) throw new Error("Invalid RV32 section layout");
1376
+ if (formatVersion === 5) {
1377
+ if (sectionsEnd !== artifact.length) throw new Error("Invalid RV32 v5 section layout");
1378
+ return { kind: "absent" };
1379
+ }
1380
+ const body = readSpecExtension(artifact.subarray(sectionsEnd));
1381
+ if (body === void 0) return { kind: "absent" };
1382
+ const reader = new XdrReader(body);
1383
+ const schemaVersion = Number(reader.readUint32());
1384
+ const specBytes = reader.readVarOpaque(reader.remaining);
1385
+ if (reader.remaining !== 0) throw new Error("Trailing bytes in contract spec extension");
1386
+ if (schemaVersion !== 1) return {
1387
+ kind: "unsupportedSchema",
1388
+ schemaVersion,
1389
+ bytes: specBytes
1390
+ };
1391
+ preflightContractSpec(specBytes);
1392
+ const spec = deserialize(specBytes, codec$1.ContractSpec, contractSpecCodecLimits);
1393
+ validateArtifactSpec(spec);
1394
+ if (!bytesEqual(serialize(spec, codec$1.ContractSpec, contractSpecCodecLimits), specBytes)) throw new Error("Noncanonical contract spec XDR");
1395
+ return {
1396
+ kind: "spec",
1397
+ schemaVersion,
1398
+ spec
1399
+ };
1400
+ }
1401
+ function readSpecExtension(bytes) {
1402
+ const reader = new XdrReader(bytes);
1403
+ const count = Number(reader.readUint32());
1404
+ if (count > Math.floor(reader.remaining / 8)) throw new Error("Truncated RV32 extension list");
1405
+ let previousKind = 0;
1406
+ let spec;
1407
+ for (let i = 0; i < count; i++) {
1408
+ const kind = Number(reader.readUint32());
1409
+ if (kind <= previousKind) throw new Error("RV32 extension kinds must be nonzero and strictly ascending");
1410
+ previousKind = kind;
1411
+ const body = reader.readVarOpaque(reader.remaining);
1412
+ if (kind === 1) spec = body;
1413
+ }
1414
+ if (reader.remaining !== 0) throw new Error("Trailing bytes in RV32 extension list");
1415
+ return spec;
1416
+ }
1417
+ //#endregion
1418
+ //#region src/derivation/contractAddress.ts
1419
+ /**
1420
+ * The on-chain address a deployment produces:
1421
+ * `sha256(txs(ContractDeploymentHashPreimage))` over the deployer, nonce, and
1422
+ * contract hash.
1423
+ */
1424
+ function deriveContractAddress(deployer, nonce, contractHash) {
1425
+ return contractAddress(sha256(serialize({
1426
+ deployer_address: deployer,
1427
+ nonce,
1428
+ contract_hash: contractHash
1429
+ }, codec.ContractDeploymentHashPreimage)));
1430
+ }
1431
+ //#endregion
1432
+ //#region src/contract/instance.ts
1433
+ /**
1434
+ * Bind a generated interface to an address and public client.
1435
+ * Views preserve heights and events and accept cancellation and minimum-height
1436
+ * constraints. A minimum height is a freshness floor; use readViews when several
1437
+ * results must come from the same snapshot.
1438
+ *
1439
+ * @example
1440
+ * ```ts
1441
+ * const token = getContract({ binding: ERC20.v0_1, address, client });
1442
+ * const balance = await token.getBalanceOf.view({ args: { addr: owner }, signal });
1443
+ * ```
1444
+ */
1445
+ function getContract(options) {
1446
+ const address = options.address.slice();
1447
+ return Object.fromEntries(Object.entries(options.binding).map(([key, method]) => [key, {
1448
+ ...method,
1449
+ viewRequest: (input) => method.viewRequest({
1450
+ ...input,
1451
+ address
1452
+ }),
1453
+ view: (input) => method.view({
1454
+ ...input,
1455
+ address,
1456
+ client: options.client
1457
+ }),
1458
+ viewOutcome: (input) => method.viewOutcome({
1459
+ ...input,
1460
+ address,
1461
+ client: options.client
1462
+ }),
1463
+ call: (input) => method.call({
1464
+ ...input,
1465
+ address
1466
+ })
1467
+ }]));
1468
+ }
1469
+ //#endregion
1470
+ export { ContractUnionCaseKind$1 as A, isSignedToken as C, ContractMethodEffect$1 as D, ContractVerificationError as E, specIdKey as M, ContractTypeDefKind$1 as O, resolveCodec as S, ContractDecodeError as T, buildNamedCodecs as _, readContractArtifactSpec as a, decodeCalldata as b, defineContractEvent as c, createContractCallDecoder as d, ContractReceiptError as f, createContractCodecContext as g, createContractCodec as h, deriveContractAddress as i, formatSpecId as j, ContractTypeKind$1 as k, topicRepresentation as l, defineContractMethod as m, fixedBytes$1 as n, bytesEqual as o, ContractViewError as p, getContract as r, createContractEventDecoder as s, fixedArray$1 as t, hashContract as u, deriveEntrypointID as v, signedToken as w, encodeCalldata as x, majorVersionFromSemver as y };
1471
+
1472
+ //# sourceMappingURL=contract-DzvyyFCI.js.map