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