@stellar/stellar-sdk 16.0.1 → 16.1.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/README.md +2 -2
- package/dist/stellar-sdk-axios.js +5608 -4598
- package/dist/stellar-sdk-axios.js.map +1 -1
- package/dist/stellar-sdk-axios.min.js +12 -11
- package/dist/stellar-sdk-axios.min.js.map +1 -1
- package/dist/stellar-sdk.js +3902 -3434
- package/dist/stellar-sdk.js.map +1 -1
- package/dist/stellar-sdk.min.js +17 -17
- package/dist/stellar-sdk.min.js.map +1 -1
- package/lib/axios/cjs/base/auth.js +107 -0
- package/lib/axios/cjs/base/auth.js.map +1 -1
- package/lib/axios/cjs/base/keypair.js +39 -0
- package/lib/axios/cjs/base/keypair.js.map +1 -1
- package/lib/axios/cjs/base/scval.js +34 -0
- package/lib/axios/cjs/base/scval.js.map +1 -1
- package/lib/axios/cjs/bindings/config.js +1 -1
- package/lib/axios/cjs/cli/index.js +1 -1
- package/lib/axios/cjs/cli/index.js.map +1 -1
- package/lib/axios/cjs/contract/assembled_transaction.js +8 -7
- package/lib/axios/cjs/contract/assembled_transaction.js.map +1 -1
- package/lib/axios/cjs/contract/client.js +56 -3
- package/lib/axios/cjs/contract/client.js.map +1 -1
- package/lib/axios/cjs/contract/spec.js +7 -3
- package/lib/axios/cjs/contract/spec.js.map +1 -1
- package/lib/axios/cjs/errors/transaction_failed.js +62 -0
- package/lib/axios/cjs/errors/transaction_failed.js.map +1 -0
- package/lib/axios/cjs/errors/wrap_http_error.js +20 -0
- package/lib/axios/cjs/errors/wrap_http_error.js.map +1 -0
- package/lib/axios/cjs/federation/server.js +14 -15
- package/lib/axios/cjs/federation/server.js.map +1 -1
- package/lib/axios/cjs/horizon/call_builder.js +20 -0
- package/lib/axios/cjs/horizon/call_builder.js.map +1 -1
- package/lib/axios/cjs/horizon/horizon_api.js +5 -0
- package/lib/axios/cjs/horizon/horizon_api.js.map +1 -1
- package/lib/axios/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/cjs/horizon/server.js +20 -26
- package/lib/axios/cjs/horizon/server.js.map +1 -1
- package/lib/axios/cjs/horizon/trade_aggregation_call_builder.js +20 -0
- package/lib/axios/cjs/horizon/trade_aggregation_call_builder.js.map +1 -1
- package/lib/axios/cjs/index.js +4 -0
- package/lib/axios/cjs/index.js.map +1 -1
- package/lib/axios/cjs/rpc/api.js.map +1 -1
- package/lib/axios/cjs/rpc/axios.js +1 -1
- package/lib/axios/cjs/rpc/server.js +163 -8
- package/lib/axios/cjs/rpc/server.js.map +1 -1
- package/lib/axios/esm/base/auth.d.ts +141 -0
- package/lib/axios/esm/base/auth.js +106 -1
- package/lib/axios/esm/base/auth.js.map +1 -1
- package/lib/axios/esm/base/index.d.ts +2 -2
- package/lib/axios/esm/base/keypair.d.ts +27 -0
- package/lib/axios/esm/base/keypair.js +39 -0
- package/lib/axios/esm/base/keypair.js.map +1 -1
- package/lib/axios/esm/base/scval.d.ts +4 -0
- package/lib/axios/esm/base/scval.js +34 -0
- package/lib/axios/esm/base/scval.js.map +1 -1
- package/lib/axios/esm/bindings/config.js +1 -1
- package/lib/axios/esm/cli/index.js +1 -1
- package/lib/axios/esm/cli/index.js.map +1 -1
- package/lib/axios/esm/contract/assembled_transaction.d.ts +1 -1
- package/lib/axios/esm/contract/assembled_transaction.js +9 -8
- package/lib/axios/esm/contract/assembled_transaction.js.map +1 -1
- package/lib/axios/esm/contract/client.d.ts +49 -3
- package/lib/axios/esm/contract/client.js +56 -3
- package/lib/axios/esm/contract/client.js.map +1 -1
- package/lib/axios/esm/contract/spec.js +7 -3
- package/lib/axios/esm/contract/spec.js.map +1 -1
- package/lib/axios/esm/errors/index.d.ts +1 -0
- package/lib/axios/esm/errors/transaction_failed.d.ts +55 -0
- package/lib/axios/esm/errors/transaction_failed.js +60 -0
- package/lib/axios/esm/errors/transaction_failed.js.map +1 -0
- package/lib/axios/esm/errors/wrap_http_error.d.ts +20 -0
- package/lib/axios/esm/errors/wrap_http_error.js +18 -0
- package/lib/axios/esm/errors/wrap_http_error.js.map +1 -0
- package/lib/axios/esm/federation/server.js +14 -15
- package/lib/axios/esm/federation/server.js.map +1 -1
- package/lib/axios/esm/horizon/call_builder.js +20 -0
- package/lib/axios/esm/horizon/call_builder.js.map +1 -1
- package/lib/axios/esm/horizon/horizon_api.d.ts +12 -1
- package/lib/axios/esm/horizon/horizon_api.js +5 -0
- package/lib/axios/esm/horizon/horizon_api.js.map +1 -1
- package/lib/axios/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/esm/horizon/server.d.ts +10 -4
- package/lib/axios/esm/horizon/server.js +20 -26
- package/lib/axios/esm/horizon/server.js.map +1 -1
- package/lib/axios/esm/horizon/trade_aggregation_call_builder.js +20 -0
- package/lib/axios/esm/horizon/trade_aggregation_call_builder.js.map +1 -1
- package/lib/axios/esm/index.js +2 -1
- package/lib/axios/esm/index.js.map +1 -1
- package/lib/axios/esm/rpc/api.d.ts +21 -0
- package/lib/axios/esm/rpc/api.js.map +1 -1
- package/lib/axios/esm/rpc/axios.js +1 -1
- package/lib/axios/esm/rpc/server.d.ts +104 -1
- package/lib/axios/esm/rpc/server.js +163 -8
- package/lib/axios/esm/rpc/server.js.map +1 -1
- package/lib/cjs/base/auth.js +107 -0
- package/lib/cjs/base/auth.js.map +1 -1
- package/lib/cjs/base/keypair.js +39 -0
- package/lib/cjs/base/keypair.js.map +1 -1
- package/lib/cjs/base/scval.js +34 -0
- package/lib/cjs/base/scval.js.map +1 -1
- package/lib/cjs/bindings/config.js +1 -1
- package/lib/cjs/cli/index.js +1 -1
- package/lib/cjs/cli/index.js.map +1 -1
- package/lib/cjs/contract/assembled_transaction.js +8 -7
- package/lib/cjs/contract/assembled_transaction.js.map +1 -1
- package/lib/cjs/contract/client.js +56 -3
- package/lib/cjs/contract/client.js.map +1 -1
- package/lib/cjs/contract/spec.js +7 -3
- package/lib/cjs/contract/spec.js.map +1 -1
- package/lib/cjs/errors/transaction_failed.js +62 -0
- package/lib/cjs/errors/transaction_failed.js.map +1 -0
- package/lib/cjs/errors/wrap_http_error.js +20 -0
- package/lib/cjs/errors/wrap_http_error.js.map +1 -0
- package/lib/cjs/federation/server.js +14 -15
- package/lib/cjs/federation/server.js.map +1 -1
- package/lib/cjs/horizon/call_builder.js +20 -0
- package/lib/cjs/horizon/call_builder.js.map +1 -1
- package/lib/cjs/horizon/horizon_api.js +5 -0
- package/lib/cjs/horizon/horizon_api.js.map +1 -1
- package/lib/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/cjs/horizon/server.js +20 -26
- package/lib/cjs/horizon/server.js.map +1 -1
- package/lib/cjs/horizon/trade_aggregation_call_builder.js +20 -0
- package/lib/cjs/horizon/trade_aggregation_call_builder.js.map +1 -1
- package/lib/cjs/index.js +4 -0
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/rpc/api.js.map +1 -1
- package/lib/cjs/rpc/axios.js +1 -1
- package/lib/cjs/rpc/server.js +163 -8
- package/lib/cjs/rpc/server.js.map +1 -1
- package/lib/esm/base/auth.d.ts +141 -0
- package/lib/esm/base/auth.js +106 -1
- package/lib/esm/base/auth.js.map +1 -1
- package/lib/esm/base/index.d.ts +2 -2
- package/lib/esm/base/keypair.d.ts +27 -0
- package/lib/esm/base/keypair.js +39 -0
- package/lib/esm/base/keypair.js.map +1 -1
- package/lib/esm/base/scval.d.ts +4 -0
- package/lib/esm/base/scval.js +34 -0
- package/lib/esm/base/scval.js.map +1 -1
- package/lib/esm/bindings/config.js +1 -1
- package/lib/esm/cli/index.js +1 -1
- package/lib/esm/cli/index.js.map +1 -1
- package/lib/esm/contract/assembled_transaction.d.ts +1 -1
- package/lib/esm/contract/assembled_transaction.js +9 -8
- package/lib/esm/contract/assembled_transaction.js.map +1 -1
- package/lib/esm/contract/client.d.ts +49 -3
- package/lib/esm/contract/client.js +56 -3
- package/lib/esm/contract/client.js.map +1 -1
- package/lib/esm/contract/spec.js +7 -3
- package/lib/esm/contract/spec.js.map +1 -1
- package/lib/esm/errors/index.d.ts +1 -0
- package/lib/esm/errors/transaction_failed.d.ts +55 -0
- package/lib/esm/errors/transaction_failed.js +60 -0
- package/lib/esm/errors/transaction_failed.js.map +1 -0
- package/lib/esm/errors/wrap_http_error.d.ts +20 -0
- package/lib/esm/errors/wrap_http_error.js +18 -0
- package/lib/esm/errors/wrap_http_error.js.map +1 -0
- package/lib/esm/federation/server.js +14 -15
- package/lib/esm/federation/server.js.map +1 -1
- package/lib/esm/horizon/call_builder.js +20 -0
- package/lib/esm/horizon/call_builder.js.map +1 -1
- package/lib/esm/horizon/horizon_api.d.ts +12 -1
- package/lib/esm/horizon/horizon_api.js +5 -0
- package/lib/esm/horizon/horizon_api.js.map +1 -1
- package/lib/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/esm/horizon/server.d.ts +10 -4
- package/lib/esm/horizon/server.js +20 -26
- package/lib/esm/horizon/server.js.map +1 -1
- package/lib/esm/horizon/trade_aggregation_call_builder.js +20 -0
- package/lib/esm/horizon/trade_aggregation_call_builder.js.map +1 -1
- package/lib/esm/index.js +2 -1
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/rpc/api.d.ts +21 -0
- package/lib/esm/rpc/api.js.map +1 -1
- package/lib/esm/rpc/axios.js +1 -1
- package/lib/esm/rpc/server.d.ts +104 -1
- package/lib/esm/rpc/server.js +163 -8
- package/lib/esm/rpc/server.js.map +1 -1
- package/package.json +27 -30
|
@@ -61,6 +61,10 @@ export interface NativeToScValOpts {
|
|
|
61
61
|
* for the key and the value), where `null` (or a missing entry) indicates
|
|
62
62
|
* the default interpretation(s) (refer to the examples, below)
|
|
63
63
|
*
|
|
64
|
+
* - when `val` is a `Map`, this can be a `[keyType, valType]` pair applied
|
|
65
|
+
* to every entry, or (when all keys are strings) the same per-key spec
|
|
66
|
+
* object used for plain objects
|
|
67
|
+
*
|
|
64
68
|
* - when `val` is a string type, this can be 'string' or 'symbol' to force
|
|
65
69
|
* a particular interpretation of `val`.
|
|
66
70
|
*
|
|
@@ -59,6 +59,40 @@ function nativeToScVal(val, opts = {}) {
|
|
|
59
59
|
})
|
|
60
60
|
);
|
|
61
61
|
}
|
|
62
|
+
if (val instanceof Map) {
|
|
63
|
+
let uniformKeyType = null;
|
|
64
|
+
let uniformValType = null;
|
|
65
|
+
let perKeySpec = null;
|
|
66
|
+
if (Array.isArray(opts.type)) {
|
|
67
|
+
if (opts.type.length > 2) {
|
|
68
|
+
throw new TypeError(
|
|
69
|
+
`expected a [keyType, valType] pair for a Map, got ${JSON.stringify(opts.type)}`
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
[uniformKeyType = null, uniformValType = null] = opts.type;
|
|
73
|
+
} else if (typeof opts.type === "object" && opts.type !== null) {
|
|
74
|
+
perKeySpec = opts.type;
|
|
75
|
+
} else if (opts.type !== void 0) {
|
|
76
|
+
throw new TypeError(
|
|
77
|
+
`invalid type (${JSON.stringify(opts.type)}) specified for a Map`
|
|
78
|
+
);
|
|
79
|
+
}
|
|
80
|
+
const entries = [];
|
|
81
|
+
for (const [k, v] of val) {
|
|
82
|
+
let keyType = uniformKeyType;
|
|
83
|
+
let valType = uniformValType;
|
|
84
|
+
if (perKeySpec && typeof k === "string" && Object.hasOwn(perKeySpec, k)) {
|
|
85
|
+
[keyType = null, valType = null] = perKeySpec[k] ?? [];
|
|
86
|
+
}
|
|
87
|
+
entries.push(
|
|
88
|
+
new types.ScMapEntry({
|
|
89
|
+
key: nativeToScVal(k, keyType ? { type: keyType } : {}),
|
|
90
|
+
val: nativeToScVal(v, valType ? { type: valType } : {})
|
|
91
|
+
})
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
return types.scvSortedMap(entries);
|
|
95
|
+
}
|
|
62
96
|
if (Object.getPrototypeOf(val) !== Object.prototype) {
|
|
63
97
|
throw new TypeError(
|
|
64
98
|
`cannot interpret ${val.constructor?.name} value as ScVal (${JSON.stringify(val)})`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scval.js","sources":["../../../../src/base/scval.ts"],"sourcesContent":["import xdr from \"./xdr.js\";\nimport { Keypair } from \"./keypair.js\";\nimport { Address } from \"./address.js\";\nimport { Contract } from \"./contract.js\";\nimport { ScInt, XdrLargeInt, scValToBigInt } from \"./numbers/index.js\";\nimport type { ScIntType } from \"./numbers/index.js\";\n\ntype ScValIntType = ScIntType | \"i32\" | \"u32\";\ntype ScValStringType = ScValIntType | \"address\" | \"string\" | \"symbol\";\ntype ScValBytesType = \"bytes\" | \"string\" | \"symbol\";\ntype ScValType = ScValBytesType | ScValIntType | ScValStringType;\n\ntype ScValMapTypeSpec = Record<\n string,\n [(ScValType | null)?, (ScValType | null)?]\n>;\n\nexport interface NativeToScValOpts {\n type?: (ScValType | null)[] | ScValMapTypeSpec | ScValType | undefined;\n}\n\n/**\n * Attempts to convert native types into smart contract values\n * ({@link xdr.ScVal}).\n *\n * Provides conversions from smart contract XDR values ({@link xdr.ScVal}) to\n * native JavaScript types.\n *\n * The conversions are as follows:\n *\n * - `xdr.ScVal` → passthrough\n * - `null` / `undefined` → `scvVoid`\n * - `string` → `scvString` (a copy is made)\n * - `UintArray8` → `scvBytes` (a copy is made)\n * - `boolean` → `scvBool`\n *\n * - `number` / `bigint` → the smallest possible XDR integer type that will fit\n * the input value (if you want a specific type, use {@link ScInt})\n *\n * - {@link Address} or {@link Contract} → `scvAddress` (for contracts and\n * public keys)\n *\n * - `Array<T>` → `scvVec` after attempting to convert each item of type `T` to\n * an `xdr.ScVal` (recursively). note that all values must be the same type!\n *\n * - `object` → `scvMap` after attempting to convert each key and value to an\n * `xdr.ScVal` (recursively). note that there is no restriction on types\n * matching anywhere (unlike arrays)\n *\n * When passing an integer-like native value, you can also optionally specify a\n * type which will force a particular interpretation of that value.\n *\n * Note that not all type specifications are compatible with all `ScVal`s, e.g.\n * `toScVal(\"a string\", {type: \"i256\"})` will throw.\n *\n * @param val - a native (or convertible) input value to wrap\n * @param opts - an optional set of hints around the type of\n * conversion you'd like to see\n * - `type`: there is different behavior for different input\n * types for `val`:\n *\n * - when `val` is an integer-like type (i.e. number|bigint), this will be\n * forwarded to {@link ScInt} or forced to be u32/i32.\n *\n * - when `val` is an array type, this is forwarded to the recursion\n *\n * - when `val` is an object type (key-value entries), this should be an\n * object in which each key has a pair of types (to represent forced types\n * for the key and the value), where `null` (or a missing entry) indicates\n * the default interpretation(s) (refer to the examples, below)\n *\n * - when `val` is a string type, this can be 'string' or 'symbol' to force\n * a particular interpretation of `val`.\n *\n * - when `val` is a bytes-like type, this can be 'string', 'symbol', or\n * 'bytes' to force a particular interpretation\n *\n * As a simple example, `nativeToScVal(\"hello\", {type: 'symbol'})` will\n * return an `scvSymbol`, whereas without the type it would have been an\n * `scvString`.\n *\n * @throws if...\n * - there are arrays with more than one type in them\n * - there are values that do not have a sensible conversion (e.g. random XDR\n * types, custom classes)\n * - the type of the input object (or some inner value of said object) cannot\n * be determined (via `typeof`)\n * - the type you specified (via `opts.type`) is incompatible with the value\n * you passed in (`val`), e.g. `nativeToScVal(\"a string\", { type: 'i128' })`,\n * though this does not apply for types that ignore `opts` (e.g. addresses).\n * @see scValToNative\n *\n * @example\n * ```ts\n * nativeToScVal(1000); // gives ScValType === scvU64\n * nativeToScVal(1000n); // gives ScValType === scvU64\n * nativeToScVal(1n << 100n); // gives ScValType === scvU128\n * nativeToScVal(1000, { type: 'u32' }); // gives ScValType === scvU32\n * nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256\n * nativeToScVal(\"a string\"); // gives ScValType === scvString\n * nativeToScVal(\"a string\", { type: 'symbol' }); // gives scvSymbol\n * nativeToScVal(new Uint8Array(5)); // scvBytes\n * nativeToScVal(new Uint8Array(5), { type: 'symbol' }); // scvSymbol\n * nativeToScVal(null); // scvVoid\n * nativeToScVal(true); // scvBool\n * nativeToScVal([1, 2, 3]); // gives scvVec with each element as scvU64\n * nativeToScVal([1, 2, 3], { type: 'i128' }); // scvVec<scvI128>\n * nativeToScVal([1, '2'], { type: ['i128', 'symbol'] }); // scvVec with diff types\n * nativeToScVal([1, '2', 3], { type: ['i128', 'symbol'] });\n * // scvVec with diff types, using the default when omitted\n * nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, {\n * type: {\n * 'hello': [ 'symbol', 'i128' ],\n * }\n * })\n * // gives scvMap with entries: [\n * // [ scvSymbol, scvI128 ],\n * // [ scvString, scvArray<scvBool> ]\n * // ]\n * ```\n *\n * @example\n * ```ts\n * import {\n * nativeToScVal,\n * scValToNative,\n * ScInt,\n * xdr\n * } from '@stellar/stellar-base';\n *\n * let gigaMap = {\n * bool: true,\n * void: null,\n * u32: xdr.ScVal.scvU32(1),\n * i32: xdr.ScVal.scvI32(1),\n * u64: 1n,\n * i64: -1n,\n * u128: new ScInt(1).toU128(),\n * i128: new ScInt(1).toI128(),\n * u256: new ScInt(1).toU256(),\n * i256: new ScInt(1).toI256(),\n * map: {\n * arbitrary: 1n,\n * nested: 'values',\n * etc: false\n * },\n * vec: ['same', 'type', 'list'],\n * vec: ['diff', 1, 'type', 2, 'list'],\n * };\n *\n * // then, simply:\n * let scv = nativeToScVal(gigaMap); // scv.switch() == xdr.ScValType.scvMap()\n *\n * // then...\n * someContract.call(\"method\", scv);\n *\n * // Similarly, the inverse should work:\n * scValToNative(scv) == gigaMap; // true\n * ```\n */\nexport function nativeToScVal(\n val: unknown,\n opts: NativeToScValOpts = {},\n): xdr.ScVal {\n switch (typeof val) {\n case \"object\": {\n if (val === null) {\n return xdr.ScVal.scvVoid();\n }\n\n if (val instanceof xdr.ScVal) {\n return val; // should we copy?\n }\n\n if (val instanceof Address) {\n return val.toScVal();\n }\n\n if (val instanceof Keypair) {\n return nativeToScVal(val.publicKey(), { type: \"address\" });\n }\n\n if (val instanceof Contract) {\n return val.address().toScVal();\n }\n\n if (val instanceof Uint8Array || Buffer.isBuffer(val)) {\n const copy = Buffer.from(val);\n switch ((opts?.type as string) ?? \"bytes\") {\n case \"bytes\":\n return xdr.ScVal.scvBytes(copy);\n case \"symbol\":\n return xdr.ScVal.scvSymbol(copy);\n case \"string\":\n return xdr.ScVal.scvString(copy);\n default:\n throw new TypeError(\n `invalid type (${JSON.stringify(opts.type)}) specified for bytes-like value`,\n );\n }\n }\n\n if (Array.isArray(val)) {\n return xdr.ScVal.scvVec(\n val.map((v: unknown, idx: number) => {\n // There may be different type specifications for each element in\n // the array, so we need to apply those accordingly.\n if (Array.isArray(opts.type)) {\n return nativeToScVal(\n v,\n // only include a `{ type: ... }` if it's present (safer than\n // `{type: undefined}`)\n {\n ...(opts.type.length > idx && {\n type: opts.type[idx] as ScValType,\n }),\n },\n );\n }\n\n // Otherwise apply a generic (or missing) type specifier on it.\n return nativeToScVal(v, opts);\n }),\n );\n }\n\n if (Object.getPrototypeOf(val) !== Object.prototype) {\n throw new TypeError(\n `cannot interpret ${\n val.constructor?.name\n } value as ScVal (${JSON.stringify(val)})`,\n );\n }\n\n const mapTypeSpec = (opts?.type ?? {}) as ScValMapTypeSpec;\n\n return xdr.ScVal.scvMap(\n Object.entries(val as Record<string, unknown>)\n // The Soroban runtime expects maps to have their keys in sorted\n // order, so let's do that here as part of the conversion to prevent\n // confusing error messages on execution.\n .sort(([key1], [key2]) => (key1 < key2 ? -1 : key1 > key2 ? 1 : 0))\n .map(([k, v]) => {\n // the type can be specified with an entry for the key and the value,\n // e.g. val = { 'hello': 1 } and opts.type = { hello: [ 'symbol',\n // 'u128' ]} or you can use `null` for the default interpretation\n const [keyType, valType] = Object.hasOwn(mapTypeSpec, k)\n ? (mapTypeSpec[k] ?? [null, null])\n : [null, null];\n const keyOpts: NativeToScValOpts = keyType ? { type: keyType } : {};\n const valOpts: NativeToScValOpts = valType ? { type: valType } : {};\n\n return new xdr.ScMapEntry({\n key: nativeToScVal(k, keyOpts),\n val: nativeToScVal(v, valOpts),\n });\n }),\n );\n }\n\n case \"number\":\n case \"bigint\": {\n const bigintVal = BigInt(val);\n switch (opts?.type) {\n case \"u32\":\n if (\n bigintVal < BigInt(xdr.Uint32.MIN_VALUE) ||\n bigintVal > BigInt(xdr.Uint32.MAX_VALUE)\n ) {\n throw new TypeError(`invalid value (${val}) for type u32`);\n }\n return xdr.ScVal.scvU32(Number(val));\n case \"i32\":\n if (\n bigintVal < -BigInt(xdr.Int32.MIN_VALUE) ||\n bigintVal > BigInt(xdr.Int32.MAX_VALUE)\n ) {\n throw new TypeError(`invalid value (${val}) for type i32`);\n }\n return xdr.ScVal.scvI32(Number(val));\n\n default:\n break;\n }\n\n return new ScInt(val, { type: opts?.type as ScIntType }).toScVal();\n }\n case \"string\": {\n const optType = (opts?.type as string) ?? \"string\";\n switch (optType) {\n case \"string\":\n return xdr.ScVal.scvString(val);\n\n case \"symbol\":\n return xdr.ScVal.scvSymbol(val);\n\n case \"address\":\n return new Address(val).toScVal();\n\n case \"u32\": {\n const bigintVal = BigInt(val);\n if (\n bigintVal < BigInt(xdr.Uint32.MIN_VALUE) ||\n bigintVal > BigInt(xdr.Uint32.MAX_VALUE)\n ) {\n throw new TypeError(`invalid value (${val}) for type u32`);\n }\n return xdr.ScVal.scvU32(Number(bigintVal));\n }\n\n case \"i32\": {\n const bigintVal = BigInt(val);\n // TODO: Update this check once xdr.Int32.MIN_VALUE in XDR is properly\n // set to negative. Check this globally.\n if (\n bigintVal < -BigInt(xdr.Int32.MIN_VALUE) ||\n bigintVal > BigInt(xdr.Int32.MAX_VALUE)\n ) {\n throw new TypeError(`invalid value (${val}) for type i32`);\n }\n return xdr.ScVal.scvI32(Number(bigintVal));\n }\n\n default:\n if (XdrLargeInt.isType(optType)) {\n return new XdrLargeInt(optType, val).toScVal();\n }\n\n throw new TypeError(\n `invalid type (${JSON.stringify(opts.type)}) specified for string value`,\n );\n }\n }\n\n case \"boolean\":\n return xdr.ScVal.scvBool(val);\n\n case \"undefined\":\n return xdr.ScVal.scvVoid();\n\n case \"function\": // FIXME: Is this too helpful?\n return nativeToScVal((val as () => unknown)());\n\n default:\n throw new TypeError(\n `failed to convert typeof ${typeof val} (${JSON.stringify(val)})`,\n );\n }\n}\n\n/**\n * Given a smart contract value, attempt to convert it to a native type.\n * Possible conversions include:\n *\n * - `void` → `null`\n * - `u32`, `i32` → `number`\n * - `u64`, `i64`, `u128`, `i128`, `u256`, `i256`, `timepoint`, `duration` →\n * `bigint`\n * - `vec` → `Array` of any of the above (via recursion)\n * - `map` → key-value object of any of the above (via recursion)\n * - `bool` → `boolean`\n * - `bytes` → `Uint8Array`\n * - `symbol` → `string`\n * - `string` → `string` IF the underlying buffer can be decoded as ascii/utf8,\n * `Uint8Array` of the raw contents in any error case\n *\n * If no viable conversion can be determined, this just \"unwraps\" the smart\n * value to return its underlying XDR value.\n *\n * @param scv - the input smart contract value\n *\n * @see nativeToScVal\n */\n\nexport function scValToNative(scv: xdr.ScVal): any {\n // we use the verbose xdr.ScValType.<type>.value form here because it's faster\n // than string comparisons and the underlying constants never need to be\n // updated\n switch (scv.switch().value) {\n case xdr.ScValType.scvVoid().value:\n return null;\n\n // these can be converted to bigints directly\n case xdr.ScValType.scvU64().value:\n case xdr.ScValType.scvI64().value:\n return (scv.value() as xdr.Int64 | xdr.Uint64).toBigInt();\n\n // these can be parsed by internal abstractions note that this can also\n // handle the above two cases, but it's not as efficient (another\n // type-check, parsing, etc.)\n case xdr.ScValType.scvU128().value:\n case xdr.ScValType.scvI128().value:\n case xdr.ScValType.scvU256().value:\n case xdr.ScValType.scvI256().value:\n return scValToBigInt(scv);\n\n case xdr.ScValType.scvVec().value:\n return (scv.vec() ?? []).map(scValToNative);\n\n case xdr.ScValType.scvAddress().value:\n return Address.fromScVal(scv).toString();\n\n case xdr.ScValType.scvMap().value:\n return Object.fromEntries(\n (scv.map() ?? []).map((entry: xdr.ScMapEntry) => [\n scValToNative(entry.key()),\n scValToNative(entry.val()),\n ]),\n );\n\n // these return the primitive type directly\n case xdr.ScValType.scvBool().value:\n case xdr.ScValType.scvU32().value:\n case xdr.ScValType.scvI32().value:\n case xdr.ScValType.scvBytes().value:\n return scv.value();\n\n // Symbols are limited to [a-zA-Z0-9_]+, so we can safely make ascii strings\n //\n // Strings, however, are \"presented\" as strings and we treat them as such\n // (in other words, string = bytes with a hint that it's text). If the user\n // encoded non-printable bytes in their string value, that's on them.\n //\n // Note that we assume a utf8 encoding (ascii-compatible). For other\n // encodings, you should probably use bytes anyway. If it cannot be decoded,\n // the raw bytes are returned.\n case xdr.ScValType.scvSymbol().value: {\n const v = scv.sym();\n if (\n Buffer.isBuffer(v) ||\n (ArrayBuffer.isView(v) && typeof v !== \"string\")\n ) {\n try {\n return new TextDecoder().decode(v);\n } catch {\n return new Uint8Array((v as ArrayBufferView).buffer); // copy of bytes\n }\n }\n return v; // string already\n }\n case xdr.ScValType.scvString().value: {\n const v = scv.str();\n if (\n Buffer.isBuffer(v) ||\n (ArrayBuffer.isView(v) && typeof v !== \"string\")\n ) {\n try {\n return new TextDecoder().decode(v);\n } catch {\n return new Uint8Array((v as ArrayBufferView).buffer); // copy of bytes\n }\n }\n return v; // string already\n }\n\n // these can be converted to bigint\n case xdr.ScValType.scvTimepoint().value:\n case xdr.ScValType.scvDuration().value:\n return (scv.value() as xdr.Uint64).toBigInt();\n\n case xdr.ScValType.scvError().value:\n switch (scv.error().switch().value) {\n // Distinguish errors from the user contract.\n case xdr.ScErrorType.sceContract().value:\n return { type: \"contract\", code: scv.error().contractCode() };\n default: {\n const err = scv.error();\n return {\n type: \"system\",\n code: err.code().value,\n value: err.code().name,\n };\n }\n }\n\n // in the fallthrough case, just return the underlying value directly\n default:\n return scv.value();\n }\n}\n\n/**\n * Build a sorted ScVal map from unsorted entries, sorted by key.\n *\n * @param items - the unsorted map entries\n */\nexport function scvSortedMap(items: xdr.ScMapEntry[]): xdr.ScVal {\n const sorted = Array.from(items).sort((a, b) => {\n // Both a and b are `ScMapEntry`s, so we need to sort by underlying key.\n //\n // We couldn't possibly handle every combination of keys since Soroban\n // maps don't enforce consistent types, so we do a best-effort and try\n // sorting by \"number-like\" or \"string-like.\"\n const nativeA = scValToNative(a.key()) as bigint | number | string;\n const nativeB = scValToNative(b.key()) as bigint | number | string;\n\n switch (typeof nativeA) {\n case \"number\":\n case \"bigint\":\n if (nativeA === nativeB) return 0;\n return nativeA < (nativeB as bigint | number) ? -1 : 1;\n\n default: {\n const strA = nativeA.toString();\n const strB = nativeB.toString();\n return strA < strB ? -1 : strA > strB ? 1 : 0;\n }\n }\n });\n\n return xdr.ScVal.scvMap(sorted);\n}\n\n// Inject a sortable map builder into the xdr module for backwards compatibility.\nxdr.scvSortedMap = scvSortedMap;\n"],"names":["xdr"],"mappings":";;;;;;;;;AAgKO,SAAS,aAAA,CACd,GAAA,EACA,IAAA,GAA0B,EAAC,EAChB;AACX,EAAA,QAAQ,OAAO,GAAA;AAAK,IAClB,KAAK,QAAA,EAAU;AACb,MAAA,IAAI,QAAQ,IAAA,EAAM;AAChB,QAAA,OAAOA,KAAA,CAAI,MAAM,OAAA,EAAQ;AAAA,MAC3B;AAEA,MAAA,IAAI,GAAA,YAAeA,MAAI,KAAA,EAAO;AAC5B,QAAA,OAAO,GAAA;AAAA,MACT;AAEA,MAAA,IAAI,eAAe,OAAA,EAAS;AAC1B,QAAA,OAAO,IAAI,OAAA,EAAQ;AAAA,MACrB;AAEA,MAAA,IAAI,eAAe,OAAA,EAAS;AAC1B,QAAA,OAAO,cAAc,GAAA,CAAI,SAAA,IAAa,EAAE,IAAA,EAAM,WAAW,CAAA;AAAA,MAC3D;AAEA,MAAA,IAAI,eAAe,QAAA,EAAU;AAC3B,QAAA,OAAO,GAAA,CAAI,OAAA,EAAQ,CAAE,OAAA,EAAQ;AAAA,MAC/B;AAEA,MAAA,IAAI,GAAA,YAAe,UAAA,IAAc,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,EAAG;AACrD,QAAA,MAAM,IAAA,GAAO,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA;AAC5B,QAAA,QAAS,IAAA,EAAM,QAAmB,OAAA;AAAS,UACzC,KAAK,OAAA;AACH,YAAA,OAAOA,KAAA,C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AM,OAAA,GAAU,aAAA,CAAc,CAAA,CAAE,GAAA,EAAK,CAAA;AACrC,IAAA,MAAM,OAAA,GAAU,aAAA,CAAc,CAAA,CAAE,GAAA,EAAK,CAAA;AAErC,IAAA,QAAQ,OAAO,OAAA;AAAS,MACtB,KAAK,QAAA;AAAA,MACL,KAAK,QAAA;AACH,QAAA,IAAI,OAAA,KAAY,SAAS,OAAO,CAAA;AAChC,QAAA,OAAO,OAAA,GAAW,UAA8B,EAAA,GAAK,CAAA;AAAA,MAEvD,SAAS;AACP,QAAA,MAAM,IAAA,GAAO,QAAQ,QAAA,EAAS;AAC9B,QAAA,MAAM,IAAA,GAAO,QAAQ,QAAA,EAAS;AAC9B,QAAA,OAAO,IAAA,GAAO,IAAA,GAAO,EAAA,GAAK,IAAA,GAAO,OAAO,CAAA,GAAI,CAAA;AAAA,MAC9C;AAAA;AACF,EACF,CAAC,CAAA;AAED,EAAA,OAAOA,KAAA,CAAI,KAAA,CAAM,MAAA,CAAO,MAAM,CAAA;AAChC;AAGAA,KAAA,CAAI,YAAA,GAAe,YAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"scval.js","sources":["../../../../src/base/scval.ts"],"sourcesContent":["import xdr from \"./xdr.js\";\nimport { Keypair } from \"./keypair.js\";\nimport { Address } from \"./address.js\";\nimport { Contract } from \"./contract.js\";\nimport { ScInt, XdrLargeInt, scValToBigInt } from \"./numbers/index.js\";\nimport type { ScIntType } from \"./numbers/index.js\";\n\ntype ScValIntType = ScIntType | \"i32\" | \"u32\";\ntype ScValStringType = ScValIntType | \"address\" | \"string\" | \"symbol\";\ntype ScValBytesType = \"bytes\" | \"string\" | \"symbol\";\ntype ScValType = ScValBytesType | ScValIntType | ScValStringType;\n\ntype ScValMapTypeSpec = Record<\n string,\n [(ScValType | null)?, (ScValType | null)?]\n>;\n\nexport interface NativeToScValOpts {\n type?: (ScValType | null)[] | ScValMapTypeSpec | ScValType | undefined;\n}\n\n/**\n * Attempts to convert native types into smart contract values\n * ({@link xdr.ScVal}).\n *\n * Provides conversions from smart contract XDR values ({@link xdr.ScVal}) to\n * native JavaScript types.\n *\n * The conversions are as follows:\n *\n * - `xdr.ScVal` → passthrough\n * - `null` / `undefined` → `scvVoid`\n * - `string` → `scvString` (a copy is made)\n * - `UintArray8` → `scvBytes` (a copy is made)\n * - `boolean` → `scvBool`\n *\n * - `number` / `bigint` → the smallest possible XDR integer type that will fit\n * the input value (if you want a specific type, use {@link ScInt})\n *\n * - {@link Address} or {@link Contract} → `scvAddress` (for contracts and\n * public keys)\n *\n * - `Array<T>` → `scvVec` after attempting to convert each item of type `T` to\n * an `xdr.ScVal` (recursively). note that all values must be the same type!\n *\n * - `object` → `scvMap` after attempting to convert each key and value to an\n * `xdr.ScVal` (recursively). note that there is no restriction on types\n * matching anywhere (unlike arrays)\n *\n * When passing an integer-like native value, you can also optionally specify a\n * type which will force a particular interpretation of that value.\n *\n * Note that not all type specifications are compatible with all `ScVal`s, e.g.\n * `toScVal(\"a string\", {type: \"i256\"})` will throw.\n *\n * @param val - a native (or convertible) input value to wrap\n * @param opts - an optional set of hints around the type of\n * conversion you'd like to see\n * - `type`: there is different behavior for different input\n * types for `val`:\n *\n * - when `val` is an integer-like type (i.e. number|bigint), this will be\n * forwarded to {@link ScInt} or forced to be u32/i32.\n *\n * - when `val` is an array type, this is forwarded to the recursion\n *\n * - when `val` is an object type (key-value entries), this should be an\n * object in which each key has a pair of types (to represent forced types\n * for the key and the value), where `null` (or a missing entry) indicates\n * the default interpretation(s) (refer to the examples, below)\n *\n * - when `val` is a `Map`, this can be a `[keyType, valType]` pair applied\n * to every entry, or (when all keys are strings) the same per-key spec\n * object used for plain objects\n *\n * - when `val` is a string type, this can be 'string' or 'symbol' to force\n * a particular interpretation of `val`.\n *\n * - when `val` is a bytes-like type, this can be 'string', 'symbol', or\n * 'bytes' to force a particular interpretation\n *\n * As a simple example, `nativeToScVal(\"hello\", {type: 'symbol'})` will\n * return an `scvSymbol`, whereas without the type it would have been an\n * `scvString`.\n *\n * @throws if...\n * - there are arrays with more than one type in them\n * - there are values that do not have a sensible conversion (e.g. random XDR\n * types, custom classes)\n * - the type of the input object (or some inner value of said object) cannot\n * be determined (via `typeof`)\n * - the type you specified (via `opts.type`) is incompatible with the value\n * you passed in (`val`), e.g. `nativeToScVal(\"a string\", { type: 'i128' })`,\n * though this does not apply for types that ignore `opts` (e.g. addresses).\n * @see scValToNative\n *\n * @example\n * ```ts\n * nativeToScVal(1000); // gives ScValType === scvU64\n * nativeToScVal(1000n); // gives ScValType === scvU64\n * nativeToScVal(1n << 100n); // gives ScValType === scvU128\n * nativeToScVal(1000, { type: 'u32' }); // gives ScValType === scvU32\n * nativeToScVal(1000, { type: 'i125' }); // gives ScValType === scvI256\n * nativeToScVal(\"a string\"); // gives ScValType === scvString\n * nativeToScVal(\"a string\", { type: 'symbol' }); // gives scvSymbol\n * nativeToScVal(new Uint8Array(5)); // scvBytes\n * nativeToScVal(new Uint8Array(5), { type: 'symbol' }); // scvSymbol\n * nativeToScVal(null); // scvVoid\n * nativeToScVal(true); // scvBool\n * nativeToScVal([1, 2, 3]); // gives scvVec with each element as scvU64\n * nativeToScVal([1, 2, 3], { type: 'i128' }); // scvVec<scvI128>\n * nativeToScVal([1, '2'], { type: ['i128', 'symbol'] }); // scvVec with diff types\n * nativeToScVal([1, '2', 3], { type: ['i128', 'symbol'] });\n * // scvVec with diff types, using the default when omitted\n * nativeToScVal({ 'hello': 1, 'world': [ true, false ] }, {\n * type: {\n * 'hello': [ 'symbol', 'i128' ],\n * }\n * })\n * // gives scvMap with entries: [\n * // [ scvSymbol, scvI128 ],\n * // [ scvString, scvArray<scvBool> ]\n * // ]\n * ```\n *\n * @example\n * ```ts\n * import {\n * nativeToScVal,\n * scValToNative,\n * ScInt,\n * xdr\n * } from '@stellar/stellar-base';\n *\n * let gigaMap = {\n * bool: true,\n * void: null,\n * u32: xdr.ScVal.scvU32(1),\n * i32: xdr.ScVal.scvI32(1),\n * u64: 1n,\n * i64: -1n,\n * u128: new ScInt(1).toU128(),\n * i128: new ScInt(1).toI128(),\n * u256: new ScInt(1).toU256(),\n * i256: new ScInt(1).toI256(),\n * map: {\n * arbitrary: 1n,\n * nested: 'values',\n * etc: false\n * },\n * vec: ['same', 'type', 'list'],\n * vec: ['diff', 1, 'type', 2, 'list'],\n * };\n *\n * // then, simply:\n * let scv = nativeToScVal(gigaMap); // scv.switch() == xdr.ScValType.scvMap()\n *\n * // then...\n * someContract.call(\"method\", scv);\n *\n * // Similarly, the inverse should work:\n * scValToNative(scv) == gigaMap; // true\n * ```\n */\nexport function nativeToScVal(\n val: unknown,\n opts: NativeToScValOpts = {},\n): xdr.ScVal {\n switch (typeof val) {\n case \"object\": {\n if (val === null) {\n return xdr.ScVal.scvVoid();\n }\n\n if (val instanceof xdr.ScVal) {\n return val; // should we copy?\n }\n\n if (val instanceof Address) {\n return val.toScVal();\n }\n\n if (val instanceof Keypair) {\n return nativeToScVal(val.publicKey(), { type: \"address\" });\n }\n\n if (val instanceof Contract) {\n return val.address().toScVal();\n }\n\n if (val instanceof Uint8Array || Buffer.isBuffer(val)) {\n const copy = Buffer.from(val);\n switch ((opts?.type as string) ?? \"bytes\") {\n case \"bytes\":\n return xdr.ScVal.scvBytes(copy);\n case \"symbol\":\n return xdr.ScVal.scvSymbol(copy);\n case \"string\":\n return xdr.ScVal.scvString(copy);\n default:\n throw new TypeError(\n `invalid type (${JSON.stringify(opts.type)}) specified for bytes-like value`,\n );\n }\n }\n\n if (Array.isArray(val)) {\n return xdr.ScVal.scvVec(\n val.map((v: unknown, idx: number) => {\n // There may be different type specifications for each element in\n // the array, so we need to apply those accordingly.\n if (Array.isArray(opts.type)) {\n return nativeToScVal(\n v,\n // only include a `{ type: ... }` if it's present (safer than\n // `{type: undefined}`)\n {\n ...(opts.type.length > idx && {\n type: opts.type[idx] as ScValType,\n }),\n },\n );\n }\n\n // Otherwise apply a generic (or missing) type specifier on it.\n return nativeToScVal(v, opts);\n }),\n );\n }\n\n if (val instanceof Map) {\n // For Maps, `opts.type` can take two forms:\n // - a `[keyType, valType]` pair applied to every entry (keys need not\n // be strings, so a per-key spec can't address them), or\n // - a per-key spec object (like the plain-object form below), which\n // only makes sense when the Map's keys are strings.\n let uniformKeyType: ScValType | null = null;\n let uniformValType: ScValType | null = null;\n let perKeySpec: ScValMapTypeSpec | null = null;\n if (Array.isArray(opts.type)) {\n if (opts.type.length > 2) {\n throw new TypeError(\n `expected a [keyType, valType] pair for a Map, got ${JSON.stringify(opts.type)}`,\n );\n }\n [uniformKeyType = null, uniformValType = null] = opts.type;\n } else if (typeof opts.type === \"object\" && opts.type !== null) {\n perKeySpec = opts.type;\n } else if (opts.type !== undefined) {\n throw new TypeError(\n `invalid type (${JSON.stringify(opts.type)}) specified for a Map`,\n );\n }\n\n const entries: xdr.ScMapEntry[] = [];\n for (const [k, v] of val) {\n let keyType = uniformKeyType;\n let valType = uniformValType;\n if (\n perKeySpec &&\n typeof k === \"string\" &&\n Object.hasOwn(perKeySpec, k)\n ) {\n [keyType = null, valType = null] = perKeySpec[k] ?? [];\n }\n entries.push(\n new xdr.ScMapEntry({\n key: nativeToScVal(k, keyType ? { type: keyType } : {}),\n val: nativeToScVal(v, valType ? { type: valType } : {}),\n }),\n );\n }\n return xdr.scvSortedMap(entries);\n }\n\n if (Object.getPrototypeOf(val) !== Object.prototype) {\n throw new TypeError(\n `cannot interpret ${\n val.constructor?.name\n } value as ScVal (${JSON.stringify(val)})`,\n );\n }\n\n const mapTypeSpec = (opts?.type ?? {}) as ScValMapTypeSpec;\n\n return xdr.ScVal.scvMap(\n Object.entries(val as Record<string, unknown>)\n // The Soroban runtime expects maps to have their keys in sorted\n // order, so let's do that here as part of the conversion to prevent\n // confusing error messages on execution.\n .sort(([key1], [key2]) => (key1 < key2 ? -1 : key1 > key2 ? 1 : 0))\n .map(([k, v]) => {\n // the type can be specified with an entry for the key and the value,\n // e.g. val = { 'hello': 1 } and opts.type = { hello: [ 'symbol',\n // 'u128' ]} or you can use `null` for the default interpretation\n const [keyType, valType] = Object.hasOwn(mapTypeSpec, k)\n ? (mapTypeSpec[k] ?? [null, null])\n : [null, null];\n const keyOpts: NativeToScValOpts = keyType ? { type: keyType } : {};\n const valOpts: NativeToScValOpts = valType ? { type: valType } : {};\n\n return new xdr.ScMapEntry({\n key: nativeToScVal(k, keyOpts),\n val: nativeToScVal(v, valOpts),\n });\n }),\n );\n }\n\n case \"number\":\n case \"bigint\": {\n const bigintVal = BigInt(val);\n switch (opts?.type) {\n case \"u32\":\n if (\n bigintVal < BigInt(xdr.Uint32.MIN_VALUE) ||\n bigintVal > BigInt(xdr.Uint32.MAX_VALUE)\n ) {\n throw new TypeError(`invalid value (${val}) for type u32`);\n }\n return xdr.ScVal.scvU32(Number(val));\n case \"i32\":\n if (\n bigintVal < -BigInt(xdr.Int32.MIN_VALUE) ||\n bigintVal > BigInt(xdr.Int32.MAX_VALUE)\n ) {\n throw new TypeError(`invalid value (${val}) for type i32`);\n }\n return xdr.ScVal.scvI32(Number(val));\n\n default:\n break;\n }\n\n return new ScInt(val, { type: opts?.type as ScIntType }).toScVal();\n }\n case \"string\": {\n const optType = (opts?.type as string) ?? \"string\";\n switch (optType) {\n case \"string\":\n return xdr.ScVal.scvString(val);\n\n case \"symbol\":\n return xdr.ScVal.scvSymbol(val);\n\n case \"address\":\n return new Address(val).toScVal();\n\n case \"u32\": {\n const bigintVal = BigInt(val);\n if (\n bigintVal < BigInt(xdr.Uint32.MIN_VALUE) ||\n bigintVal > BigInt(xdr.Uint32.MAX_VALUE)\n ) {\n throw new TypeError(`invalid value (${val}) for type u32`);\n }\n return xdr.ScVal.scvU32(Number(bigintVal));\n }\n\n case \"i32\": {\n const bigintVal = BigInt(val);\n // TODO: Update this check once xdr.Int32.MIN_VALUE in XDR is properly\n // set to negative. Check this globally.\n if (\n bigintVal < -BigInt(xdr.Int32.MIN_VALUE) ||\n bigintVal > BigInt(xdr.Int32.MAX_VALUE)\n ) {\n throw new TypeError(`invalid value (${val}) for type i32`);\n }\n return xdr.ScVal.scvI32(Number(bigintVal));\n }\n\n default:\n if (XdrLargeInt.isType(optType)) {\n return new XdrLargeInt(optType, val).toScVal();\n }\n\n throw new TypeError(\n `invalid type (${JSON.stringify(opts.type)}) specified for string value`,\n );\n }\n }\n\n case \"boolean\":\n return xdr.ScVal.scvBool(val);\n\n case \"undefined\":\n return xdr.ScVal.scvVoid();\n\n case \"function\": // FIXME: Is this too helpful?\n return nativeToScVal((val as () => unknown)());\n\n default:\n throw new TypeError(\n `failed to convert typeof ${typeof val} (${JSON.stringify(val)})`,\n );\n }\n}\n\n/**\n * Given a smart contract value, attempt to convert it to a native type.\n * Possible conversions include:\n *\n * - `void` → `null`\n * - `u32`, `i32` → `number`\n * - `u64`, `i64`, `u128`, `i128`, `u256`, `i256`, `timepoint`, `duration` →\n * `bigint`\n * - `vec` → `Array` of any of the above (via recursion)\n * - `map` → key-value object of any of the above (via recursion)\n * - `bool` → `boolean`\n * - `bytes` → `Uint8Array`\n * - `symbol` → `string`\n * - `string` → `string` IF the underlying buffer can be decoded as ascii/utf8,\n * `Uint8Array` of the raw contents in any error case\n *\n * If no viable conversion can be determined, this just \"unwraps\" the smart\n * value to return its underlying XDR value.\n *\n * @param scv - the input smart contract value\n *\n * @see nativeToScVal\n */\n\nexport function scValToNative(scv: xdr.ScVal): any {\n // we use the verbose xdr.ScValType.<type>.value form here because it's faster\n // than string comparisons and the underlying constants never need to be\n // updated\n switch (scv.switch().value) {\n case xdr.ScValType.scvVoid().value:\n return null;\n\n // these can be converted to bigints directly\n case xdr.ScValType.scvU64().value:\n case xdr.ScValType.scvI64().value:\n return (scv.value() as xdr.Int64 | xdr.Uint64).toBigInt();\n\n // these can be parsed by internal abstractions note that this can also\n // handle the above two cases, but it's not as efficient (another\n // type-check, parsing, etc.)\n case xdr.ScValType.scvU128().value:\n case xdr.ScValType.scvI128().value:\n case xdr.ScValType.scvU256().value:\n case xdr.ScValType.scvI256().value:\n return scValToBigInt(scv);\n\n case xdr.ScValType.scvVec().value:\n return (scv.vec() ?? []).map(scValToNative);\n\n case xdr.ScValType.scvAddress().value:\n return Address.fromScVal(scv).toString();\n\n case xdr.ScValType.scvMap().value:\n return Object.fromEntries(\n (scv.map() ?? []).map((entry: xdr.ScMapEntry) => [\n scValToNative(entry.key()),\n scValToNative(entry.val()),\n ]),\n );\n\n // these return the primitive type directly\n case xdr.ScValType.scvBool().value:\n case xdr.ScValType.scvU32().value:\n case xdr.ScValType.scvI32().value:\n case xdr.ScValType.scvBytes().value:\n return scv.value();\n\n // Symbols are limited to [a-zA-Z0-9_]+, so we can safely make ascii strings\n //\n // Strings, however, are \"presented\" as strings and we treat them as such\n // (in other words, string = bytes with a hint that it's text). If the user\n // encoded non-printable bytes in their string value, that's on them.\n //\n // Note that we assume a utf8 encoding (ascii-compatible). For other\n // encodings, you should probably use bytes anyway. If it cannot be decoded,\n // the raw bytes are returned.\n case xdr.ScValType.scvSymbol().value: {\n const v = scv.sym();\n if (\n Buffer.isBuffer(v) ||\n (ArrayBuffer.isView(v) && typeof v !== \"string\")\n ) {\n try {\n return new TextDecoder().decode(v);\n } catch {\n return new Uint8Array((v as ArrayBufferView).buffer); // copy of bytes\n }\n }\n return v; // string already\n }\n case xdr.ScValType.scvString().value: {\n const v = scv.str();\n if (\n Buffer.isBuffer(v) ||\n (ArrayBuffer.isView(v) && typeof v !== \"string\")\n ) {\n try {\n return new TextDecoder().decode(v);\n } catch {\n return new Uint8Array((v as ArrayBufferView).buffer); // copy of bytes\n }\n }\n return v; // string already\n }\n\n // these can be converted to bigint\n case xdr.ScValType.scvTimepoint().value:\n case xdr.ScValType.scvDuration().value:\n return (scv.value() as xdr.Uint64).toBigInt();\n\n case xdr.ScValType.scvError().value:\n switch (scv.error().switch().value) {\n // Distinguish errors from the user contract.\n case xdr.ScErrorType.sceContract().value:\n return { type: \"contract\", code: scv.error().contractCode() };\n default: {\n const err = scv.error();\n return {\n type: \"system\",\n code: err.code().value,\n value: err.code().name,\n };\n }\n }\n\n // in the fallthrough case, just return the underlying value directly\n default:\n return scv.value();\n }\n}\n\n/**\n * Build a sorted ScVal map from unsorted entries, sorted by key.\n *\n * @param items - the unsorted map entries\n */\nexport function scvSortedMap(items: xdr.ScMapEntry[]): xdr.ScVal {\n const sorted = Array.from(items).sort((a, b) => {\n // Both a and b are `ScMapEntry`s, so we need to sort by underlying key.\n //\n // We couldn't possibly handle every combination of keys since Soroban\n // maps don't enforce consistent types, so we do a best-effort and try\n // sorting by \"number-like\" or \"string-like.\"\n const nativeA = scValToNative(a.key()) as bigint | number | string;\n const nativeB = scValToNative(b.key()) as bigint | number | string;\n\n switch (typeof nativeA) {\n case \"number\":\n case \"bigint\":\n if (nativeA === nativeB) return 0;\n return nativeA < (nativeB as bigint | number) ? -1 : 1;\n\n default: {\n const strA = nativeA.toString();\n const strB = nativeB.toString();\n return strA < strB ? -1 : strA > strB ? 1 : 0;\n }\n }\n });\n\n return xdr.ScVal.scvMap(sorted);\n}\n\n// Inject a sortable map builder into the xdr module for backwards compatibility.\nxdr.scvSortedMap = scvSortedMap;\n"],"names":["xdr"],"mappings":";;;;;;;;;AAoKO,SAAS,aAAA,CACd,GAAA,EACA,IAAA,GAA0B,EAAC,EAChB;AACX,EAAA,QAAQ,OAAO,GAAA;AAAK,IAClB,KAAK,QAAA,EAAU;AACb,MAAA,IAAI,QAAQ,IAAA,EAAM;AAChB,QAAA,OAAOA,KAAA,CAAI,MAAM,OAAA,EAAQ;AAAA,MAC3B;AAEA,MAAA,IAAI,GAAA,YAAeA,MAAI,KAAA,EAAO;AAC5B,QAAA,OAAO,GAAA;AAAA,MACT;AAEA,MAAA,IAAI,eAAe,OAAA,EAAS;AAC1B,QAAA,OAAO,IAAI,OAAA,EAAQ;AAAA,MACrB;AAEA,MAAA,IAAI,eAAe,OAAA,EAAS;AAC1B,QAAA,OAAO,cAAc,GAAA,CAAI,SAAA,IAAa,EAAE,IAAA,EAAM,WAAW,CAAA;AAAA,MAC3D;AAEA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AA;AAAA,MAC9C;AAAA;AACF,EACF,CAAC,CAAA;AAED,EAAA,OAAOA,KAAA,CAAI,KAAA,CAAM,MAAA,CAAO,MAAM,CAAA;AAChC;AAGAA,KAAA,CAAI,YAAA,GAAe,YAAA;;;;"}
|
|
@@ -104,7 +104,7 @@ function runCli() {
|
|
|
104
104
|
let timeout;
|
|
105
105
|
if (options.timeout) {
|
|
106
106
|
timeout = parseInt(options.timeout, 10);
|
|
107
|
-
if (
|
|
107
|
+
if (!/^\d+$/.test(options.timeout.trim()) || timeout <= 0) {
|
|
108
108
|
throw new Error(
|
|
109
109
|
`Invalid timeout value: ${options.timeout}. Must be a positive integer.`
|
|
110
110
|
);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/cli/index.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport * as path from \"path\";\n\nimport { WasmFetchError } from \"../bindings/wasm_fetcher.js\";\nimport {\n createGenerator,\n generateAndWrite,\n logSourceInfo,\n deriveContractName,\n} from \"./util.js\";\nimport { Networks } from \"../base/index.js\";\n\n// Default RPC URLs for each network\nconst NETWORK_CONFIG: Record<\n string,\n { passphrase: string; rpcUrl: string | null }\n> = {\n testnet: {\n passphrase: Networks.TESTNET,\n rpcUrl: \"https://soroban-testnet.stellar.org\",\n },\n mainnet: {\n passphrase: Networks.PUBLIC,\n rpcUrl: null, // User must provide their own\n },\n futurenet: {\n passphrase: Networks.FUTURENET,\n rpcUrl: \"https://rpc-futurenet.stellar.org\",\n },\n localnet: {\n passphrase: Networks.STANDALONE,\n rpcUrl: \"http://localhost:8000/rpc\",\n },\n};\n\nfunction runCli() {\n const program = new Command();\n\n program\n .name(\"stellar-cli\")\n .description(\"CLI for generating TypeScript bindings for Stellar contracts\")\n .version(\"1.0.0\");\n\n program\n .command(\"generate\")\n .description(\"Generate TypeScript bindings for a Stellar contract\")\n .helpOption(\"-h, --help\", \"Display help for command\")\n .option(\"--wasm <path>\", \"Path to local WASM file\")\n .option(\"--wasm-hash <hash>\", \"Hash of WASM blob on network\")\n .option(\"--contract-id <id>\", \"Contract ID on network\")\n .option(\"--rpc-url <url>\", \"RPC server URL\")\n .option(\n \"--network <network>\",\n \"Network options to use: mainnet, testnet, futurenet, or localnet\",\n )\n .option(\"--output-dir <dir>\", \"Output directory for generated bindings\")\n .option(\n \"--allow-http\",\n \"Allow insecure HTTP connections to RPC server\",\n false,\n )\n .option(\"--timeout <ms>\", \"RPC request timeout in milliseconds\")\n .option(\n \"--headers <json>\",\n 'Custom headers as JSON object (e.g., \\'{\"Authorization\": \"Bearer token\"}\\')',\n )\n .option(\n \"--contract-name <name>\",\n \"Name for the generated contract client class\",\n )\n .option(\"--overwrite\", \"Overwrite existing files\", false)\n .action(async (options) => {\n try {\n // Map network to passphrase and default RPC URL\n let networkPassphrase: string | undefined;\n let rpcUrl: string | undefined = options.rpcUrl;\n let allowHttp: boolean = options.allowHttp;\n\n if (options.network) {\n const network = options.network.toLowerCase();\n const config = NETWORK_CONFIG[network];\n\n if (!config) {\n throw new Error(\n `\\n✗ Invalid network: ${options.network}. Must be mainnet, testnet, futurenet, or localnet`,\n );\n }\n\n networkPassphrase = config.passphrase;\n\n // Use default RPC URL if not provided (only needed for network sources)\n const needsRpcUrl = options.wasmHash || options.contractId;\n if (!rpcUrl && needsRpcUrl) {\n if (config.rpcUrl) {\n rpcUrl = config.rpcUrl;\n console.log(`Using default RPC URL for ${network}: ${rpcUrl}`);\n\n // Auto-enable allowHttp for localnet when using default HTTP URL\n if (network === \"localnet\" && !options.allowHttp) {\n allowHttp = true;\n }\n } else if (network === \"mainnet\") {\n throw new Error(\n `\\n✗ --rpc-url is required for mainnet. Find RPC providers at: https://developers.stellar.org/docs/data/rpc/rpc-providers`,\n );\n }\n }\n }\n\n if (options.outputDir === undefined) {\n throw new Error(\"Output directory (--output-dir) is required\");\n }\n\n // Parse headers JSON if provided\n let headers: Record<string, string> | undefined;\n if (options.headers) {\n try {\n headers = JSON.parse(options.headers);\n } catch {\n throw new Error(`Invalid JSON for --headers: ${options.headers}`);\n }\n }\n\n // Parse timeout if provided\n let timeout: number | undefined;\n if (options.timeout) {\n timeout = parseInt(options.timeout, 10);\n if (Number.isNaN(timeout) || timeout <= 0) {\n throw new Error(\n `Invalid timeout value: ${options.timeout}. Must be a positive integer.`,\n );\n }\n }\n\n console.log(\"Fetching contract...\");\n\n const { generator, source } = await createGenerator({\n wasm: options.wasm,\n wasmHash: options.wasmHash,\n contractId: options.contractId,\n rpcUrl,\n networkPassphrase,\n serverOptions: { allowHttp, timeout, headers },\n });\n\n logSourceInfo(source);\n\n // Derive contract name from source or use provided/default\n const contractName =\n options.contractName || deriveContractName(source) || \"contract\";\n console.log(\n `\\n✓ Generating TypeScript bindings for \"${contractName}\"...`,\n );\n\n await generateAndWrite(generator, {\n contractName,\n outputDir: path.resolve(options.outputDir),\n overwrite: options.overwrite,\n });\n\n console.log(\n `\\n✓ Successfully generated bindings in ${options.outputDir}`,\n );\n console.log(`\\nUsage:`);\n console.log(\n ` import { Client } from './${path.basename(options.outputDir)}';`,\n );\n } catch (error) {\n if (error instanceof WasmFetchError) {\n console.error(`\\n✗ Error: ${error.message}`);\n if (error.cause) {\n console.error(` Caused by: ${error.cause.message}`);\n }\n } else if (error instanceof Error) {\n console.error(`\\n✗ Error: ${error.message}`);\n } else {\n console.error(`\\n✗ Unexpected error:`, error);\n }\n process.exit(1);\n }\n });\n program.parse();\n}\n\nexport { runCli };\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,cAAA,GAGF;AAAA,EACF,OAAA,EAAS;AAAA,IACP,YAAY,QAAA,CAAS,OAAA;AAAA,IACrB,MAAA,EAAQ;AAAA,GACV;AAAA,EACA,OAAA,EAAS;AAAA,IACP,YAAY,QAAA,CAAS,MAAA;AAAA,IACrB,MAAA,EAAQ;AAAA;AAAA,GACV;AAAA,EACA,SAAA,EAAW;AAAA,IACT,YAAY,QAAA,CAAS,SAAA;AAAA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AA,MAAA,CAAU,CAAA;AACtB,MAAA,OAAA,CAAQ,GAAA;AAAA,QACN,CAAA,4BAAA,EAA+B,IAAA,CAAK,QAAA,CAAS,OAAA,CAAQ,SAAS,CAAC,CAAA,EAAA;AAAA,OACjE;AAAA,IACF,SAAS,KAAA,EAAO;AACd,MAAA,IAAI,iBAAiB,cAAA,EAAgB;AACnC,QAAA,OAAA,CAAQ,KAAA,CAAM;AAAA,cAAA,EAAc,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAC3C,QAAA,IAAI,MAAM,KAAA,EAAO;AACf,UAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,aAAA,EAAgB,KAAA,CAAM,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,QACrD;AAAA,MACF,CAAA,MAAA,IAAW,iBAAiB,KAAA,EAAO;AACjC,QAAA,OAAA,CAAQ,KAAA,CAAM;AAAA,cAAA,EAAc,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,MAC7C,CAAA,MAAO;AACL,QAAA,OAAA,CAAQ,KAAA,CAAM;AAAA,wBAAA,CAAA,EAAyB,KAAK,CAAA;AAAA,MAC9C;AACA,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF,CAAC,CAAA;AACH,EAAA,OAAA,CAAQ,KAAA,EAAM;AAChB;;;;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/cli/index.ts"],"sourcesContent":["import { Command } from \"commander\";\nimport * as path from \"path\";\n\nimport { WasmFetchError } from \"../bindings/wasm_fetcher.js\";\nimport {\n createGenerator,\n generateAndWrite,\n logSourceInfo,\n deriveContractName,\n} from \"./util.js\";\nimport { Networks } from \"../base/index.js\";\n\n// Default RPC URLs for each network\nconst NETWORK_CONFIG: Record<\n string,\n { passphrase: string; rpcUrl: string | null }\n> = {\n testnet: {\n passphrase: Networks.TESTNET,\n rpcUrl: \"https://soroban-testnet.stellar.org\",\n },\n mainnet: {\n passphrase: Networks.PUBLIC,\n rpcUrl: null, // User must provide their own\n },\n futurenet: {\n passphrase: Networks.FUTURENET,\n rpcUrl: \"https://rpc-futurenet.stellar.org\",\n },\n localnet: {\n passphrase: Networks.STANDALONE,\n rpcUrl: \"http://localhost:8000/rpc\",\n },\n};\n\nfunction runCli() {\n const program = new Command();\n\n program\n .name(\"stellar-cli\")\n .description(\"CLI for generating TypeScript bindings for Stellar contracts\")\n .version(\"1.0.0\");\n\n program\n .command(\"generate\")\n .description(\"Generate TypeScript bindings for a Stellar contract\")\n .helpOption(\"-h, --help\", \"Display help for command\")\n .option(\"--wasm <path>\", \"Path to local WASM file\")\n .option(\"--wasm-hash <hash>\", \"Hash of WASM blob on network\")\n .option(\"--contract-id <id>\", \"Contract ID on network\")\n .option(\"--rpc-url <url>\", \"RPC server URL\")\n .option(\n \"--network <network>\",\n \"Network options to use: mainnet, testnet, futurenet, or localnet\",\n )\n .option(\"--output-dir <dir>\", \"Output directory for generated bindings\")\n .option(\n \"--allow-http\",\n \"Allow insecure HTTP connections to RPC server\",\n false,\n )\n .option(\"--timeout <ms>\", \"RPC request timeout in milliseconds\")\n .option(\n \"--headers <json>\",\n 'Custom headers as JSON object (e.g., \\'{\"Authorization\": \"Bearer token\"}\\')',\n )\n .option(\n \"--contract-name <name>\",\n \"Name for the generated contract client class\",\n )\n .option(\"--overwrite\", \"Overwrite existing files\", false)\n .action(async (options) => {\n try {\n // Map network to passphrase and default RPC URL\n let networkPassphrase: string | undefined;\n let rpcUrl: string | undefined = options.rpcUrl;\n let allowHttp: boolean = options.allowHttp;\n\n if (options.network) {\n const network = options.network.toLowerCase();\n const config = NETWORK_CONFIG[network];\n\n if (!config) {\n throw new Error(\n `\\n✗ Invalid network: ${options.network}. Must be mainnet, testnet, futurenet, or localnet`,\n );\n }\n\n networkPassphrase = config.passphrase;\n\n // Use default RPC URL if not provided (only needed for network sources)\n const needsRpcUrl = options.wasmHash || options.contractId;\n if (!rpcUrl && needsRpcUrl) {\n if (config.rpcUrl) {\n rpcUrl = config.rpcUrl;\n console.log(`Using default RPC URL for ${network}: ${rpcUrl}`);\n\n // Auto-enable allowHttp for localnet when using default HTTP URL\n if (network === \"localnet\" && !options.allowHttp) {\n allowHttp = true;\n }\n } else if (network === \"mainnet\") {\n throw new Error(\n `\\n✗ --rpc-url is required for mainnet. Find RPC providers at: https://developers.stellar.org/docs/data/rpc/rpc-providers`,\n );\n }\n }\n }\n\n if (options.outputDir === undefined) {\n throw new Error(\"Output directory (--output-dir) is required\");\n }\n\n // Parse headers JSON if provided\n let headers: Record<string, string> | undefined;\n if (options.headers) {\n try {\n headers = JSON.parse(options.headers);\n } catch {\n throw new Error(`Invalid JSON for --headers: ${options.headers}`);\n }\n }\n\n // Parse timeout if provided\n let timeout: number | undefined;\n if (options.timeout) {\n timeout = parseInt(options.timeout, 10);\n // require digits only, so values parseInt would otherwise silently\n // truncate (\"10abc\" -> 10, \"10.9\" -> 10) are rejected\n if (!/^\\d+$/.test(options.timeout.trim()) || timeout <= 0) {\n throw new Error(\n `Invalid timeout value: ${options.timeout}. Must be a positive integer.`,\n );\n }\n }\n\n console.log(\"Fetching contract...\");\n\n const { generator, source } = await createGenerator({\n wasm: options.wasm,\n wasmHash: options.wasmHash,\n contractId: options.contractId,\n rpcUrl,\n networkPassphrase,\n serverOptions: { allowHttp, timeout, headers },\n });\n\n logSourceInfo(source);\n\n // Derive contract name from source or use provided/default\n const contractName =\n options.contractName || deriveContractName(source) || \"contract\";\n console.log(\n `\\n✓ Generating TypeScript bindings for \"${contractName}\"...`,\n );\n\n await generateAndWrite(generator, {\n contractName,\n outputDir: path.resolve(options.outputDir),\n overwrite: options.overwrite,\n });\n\n console.log(\n `\\n✓ Successfully generated bindings in ${options.outputDir}`,\n );\n console.log(`\\nUsage:`);\n console.log(\n ` import { Client } from './${path.basename(options.outputDir)}';`,\n );\n } catch (error) {\n if (error instanceof WasmFetchError) {\n console.error(`\\n✗ Error: ${error.message}`);\n if (error.cause) {\n console.error(` Caused by: ${error.cause.message}`);\n }\n } else if (error instanceof Error) {\n console.error(`\\n✗ Error: ${error.message}`);\n } else {\n console.error(`\\n✗ Unexpected error:`, error);\n }\n process.exit(1);\n }\n });\n program.parse();\n}\n\nexport { runCli };\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,MAAM,cAAA,GAGF;AAAA,EACF,OAAA,EAAS;AAAA,IACP,YAAY,QAAA,CAAS,OAAA;AAAA,IACrB,MAAA,EAAQ;AAAA,GACV;AAAA,EACA,OAAA,EAAS;AAAA,IACP,YAAY,QAAA,CAAS,MAAA;AAAA,IACrB,MAAA,EAAQ;AAAA;AAAA,GACV;AAAA,EACA,SAAA,EAAW;AAAA,IACT,YAAY,QAAA,CAAS,SAAA;AAAA,IACrB,MAAA,EAAQ;AAAA,GACV;AAAA,EACA,QAAA,EAAU;AAAA,IACR,YAAY,QAAA,CAAS,UAAA;AAAA,IACrB,MAAA,EAAQ;AAAA;AAEZ,CAAA;AAEA,SAAS,MAAA,GAAS;AAChB,EAAA,MAAM,OAAA,GAAU,IAAI,OAAA,EAAQ;AAE5B,EAAA,OAAA,CACG,KAAK,aAAa,CAAA,CAClB,YAAY,8DAA8D,CAAA,CAC1E,QAAQ,OAAO,CAAA;AAElB,EAAA,OAAA,CACG,OAAA,CAAQ,UAAU,CAAA,CAClB,WAAA,CAAY,qDAAqD,EACjE,UAAA,CAAW,YAAA,EAAc,0BAA0B,CAAA,CACnD,MAAA,CAAO,eAAA,EAAiB,yBAAyB,CAAA,CACjD,MAAA,CAAO,oBAAA,EAAsB,8BAA8B,CAAA,CAC3D,MAAA,CAAO,oBAAA,EAAsB,wBAAwB,CAAA,CACrD,MAAA,CAAO,iBAAA,EAAmB,gBAAgB,CAAA,CAC1C,MAAA;AAAA,IACC,qBAAA;AAAA,IACA;AAAA,GACF,CACC,MAAA,CAAO,oBAAA,EAAsB,yCAAyC,CAAA,CACtE,MAAA;AAAA,IACC,cAAA;AAAA,IACA,+CA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MAC9C;AACA,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF,CAAC,CAAA;AACH,EAAA,OAAA,CAAQ,KAAA,EAAM;AAChB;;;;"}
|
|
@@ -205,7 +205,7 @@ import { ExpiredStateError, ExternalServiceError, FakeAccountError, InternalWall
|
|
|
205
205
|
*
|
|
206
206
|
* To see an even more complicated example, where Alice swaps with Bob but the
|
|
207
207
|
* transaction is invoked by yet another party, check out
|
|
208
|
-
* [test-swap.js](https://github.com/stellar/js-stellar-sdk/blob/
|
|
208
|
+
* [test-swap.js](https://github.com/stellar/js-stellar-sdk/blob/main/test/e2e/src/test-swap.js).
|
|
209
209
|
*
|
|
210
210
|
*/
|
|
211
211
|
export declare class AssembledTransaction<T> {
|
|
@@ -17,7 +17,7 @@ import { Contract } from '../base/contract.js';
|
|
|
17
17
|
import { Address } from '../base/address.js';
|
|
18
18
|
import '../base/scval.js';
|
|
19
19
|
import { SorobanDataBuilder } from '../base/sorobandata_builder.js';
|
|
20
|
-
import {
|
|
20
|
+
import { inspectAuthEntry, authorizeEntry, getAddressCredentials } from '../base/auth.js';
|
|
21
21
|
import '../base/numbers/uint128.js';
|
|
22
22
|
import '../base/numbers/uint256.js';
|
|
23
23
|
import '../base/numbers/int128.js';
|
|
@@ -564,15 +564,16 @@ You can set \`restore\` to true in the method options in order to automatically
|
|
|
564
564
|
const rawInvokeHostFunctionOp = this.built.operations[0];
|
|
565
565
|
return [
|
|
566
566
|
...new Set(
|
|
567
|
-
(rawInvokeHostFunctionOp.auth ?? []).map((entry) =>
|
|
568
|
-
(
|
|
567
|
+
(rawInvokeHostFunctionOp.auth ?? []).map((entry) => inspectAuthEntry(entry)).filter(
|
|
568
|
+
(info) => (
|
|
569
569
|
// skip source-account credentials (no address payload), which
|
|
570
|
-
// are covered by the envelope signature on the source account
|
|
571
|
-
|
|
570
|
+
// are covered by the envelope signature on the source account.
|
|
571
|
+
// Only the top-level credentials (signers[0]) matter here — this
|
|
572
|
+
// method reports (and signAuthEntries signs) the top-level
|
|
573
|
+
// address, so unsigned delegate nodes must not keep it listed.
|
|
574
|
+
info.address !== null && (includeAlreadySigned || !info.signers[0].signed)
|
|
572
575
|
)
|
|
573
|
-
).map(
|
|
574
|
-
(addrAuth) => Address.fromScAddress(addrAuth.address()).toString()
|
|
575
|
-
)
|
|
576
|
+
).map((info) => info.address)
|
|
576
577
|
)
|
|
577
578
|
];
|
|
578
579
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"assembled_transaction.js","sources":["../../../../src/contract/assembled_transaction.ts"],"sourcesContent":["/* disable max-classes rule, because extending error shouldn't count! */\n/* eslint max-classes-per-file: 0 */\nimport {\n Account,\n Address,\n BASE_FEE,\n Contract,\n Operation,\n SorobanDataBuilder,\n TransactionBuilder,\n authorizeEntry as stellarBaseAuthorizeEntry,\n xdr,\n} from \"../base/index.js\";\n// internal helper (not part of the public API), imported directly from auth.js\nimport { getAddressCredentials } from \"../base/auth.js\";\nimport type {\n AssembledTransactionOptions,\n ClientOptions,\n MethodOptions,\n Tx,\n WalletError,\n XDR_BASE64,\n} from \"./types.js\";\nimport { Server } from \"../rpc/index.js\";\nimport { Api } from \"../rpc/api.js\";\nimport { assembleTransaction } from \"../rpc/transaction.js\";\nimport type { Client } from \"./client.js\";\nimport { Err } from \"./rust_result.js\";\nimport {\n contractErrorPattern,\n implementsToString,\n getAccount,\n} from \"./utils.js\";\nimport { DEFAULT_TIMEOUT } from \"./types.js\";\nimport { SentTransaction, Watcher } from \"./sent_transaction.js\";\nimport { Spec } from \"./spec.js\";\nimport {\n ExpiredStateError,\n ExternalServiceError,\n FakeAccountError,\n InternalWalletError,\n InvalidClientRequestError,\n NeedsMoreSignaturesError,\n NoSignatureNeededError,\n NoSignerError,\n NotYetSimulatedError,\n NoUnsignedNonInvokerAuthEntriesError,\n RestoreFailureError,\n SimulationFailedError,\n UserRejectedError,\n} from \"./errors.js\";\n\n/**\n * The main workhorse of {@link Client}. This class is used to wrap a\n * transaction-under-construction and provide high-level interfaces to the most\n * common workflows, while still providing access to low-level stellar-sdk\n * transaction manipulation.\n *\n * Most of the time, you will not construct an `AssembledTransaction` directly,\n * but instead receive one as the return value of a `Client` method. If\n * you're familiar with the libraries generated by soroban-cli's\n * `contract bindings typescript` command, these also wraps `Client` and return\n * `AssembledTransaction` instances.\n *\n * Let's look at examples of how to use `AssembledTransaction` for a variety of\n * use-cases:\n *\n * #### 1. Simple read call\n *\n * Since these only require simulation, you can get the `result` of the call\n * right after constructing your `AssembledTransaction`:\n *\n * ```ts\n * const { result } = await AssembledTransaction.build({\n * method: 'myReadMethod',\n * args: spec.funcArgsToScVals('myReadMethod', {\n * args: 'for',\n * my: 'method',\n * ...\n * }),\n * contractId: 'C123…',\n * networkPassphrase: '…',\n * rpcUrl: 'https://…',\n * publicKey: undefined, // irrelevant, for simulation-only read calls\n * parseResultXdr: (result: xdr.ScVal) =>\n * spec.funcResToNative('myReadMethod', result),\n * })\n * ```\n *\n * While that looks pretty complicated, most of the time you will use this in\n * conjunction with {@link Client}, which simplifies it to:\n *\n * ```ts\n * const { result } = await client.myReadMethod({\n * args: 'for',\n * my: 'method',\n * ...\n * })\n * ```\n *\n * #### 2. Simple write call\n *\n * For write calls that will be simulated and then sent to the network without\n * further manipulation, only one more step is needed:\n *\n * ```ts\n * const assembledTx = await client.myWriteMethod({\n * args: 'for',\n * my: 'method',\n * ...\n * })\n * const sentTx = await assembledTx.signAndSend()\n * ```\n *\n * Here we're assuming that you're using a {@link Client}, rather than\n * constructing `AssembledTransaction`'s directly.\n *\n * Note that `sentTx`, the return value of `signAndSend`, is a\n * {@link SentTransaction}. `SentTransaction` is similar to\n * `AssembledTransaction`, but is missing many of the methods and fields that\n * are only relevant while assembling a transaction. It also has a few extra\n * methods and fields that are only relevant after the transaction has been\n * sent to the network.\n *\n * Like `AssembledTransaction`, `SentTransaction` also has a `result` getter,\n * which contains the parsed final return value of the contract call. Most of\n * the time, you may only be interested in this, so rather than getting the\n * whole `sentTx` you may just want to:\n *\n * ```ts\n * const tx = await client.myWriteMethod({ args: 'for', my: 'method', ... })\n * const { result } = await tx.signAndSend()\n * ```\n *\n * #### 3. More fine-grained control over transaction construction\n *\n * If you need more control over the transaction before simulating it, you can\n * set various {@link MethodOptions} when constructing your\n * `AssembledTransaction`. With a {@link Client}, this is passed as a\n * second object after the arguments (or the only object, if the method takes\n * no arguments):\n *\n * ```ts\n * const tx = await client.myWriteMethod(\n * {\n * args: 'for',\n * my: 'method',\n * ...\n * }, {\n * fee: '10000', // default: {@link BASE_FEE}\n * simulate: false,\n * timeoutInSeconds: 20, // default: {@link DEFAULT_TIMEOUT}\n * }\n * )\n * ```\n *\n * Since we've skipped simulation, we can now edit the `raw` transaction and\n * then manually call `simulate`:\n *\n * ```ts\n * tx.raw.addMemo(Memo.text('Nice memo, friend!'))\n * await tx.simulate()\n * ```\n *\n * If you need to inspect the simulation later, you can access it with\n * `tx.simulation`.\n *\n * #### 4. Multi-auth workflows\n *\n * Soroban, and Stellar in general, allows multiple parties to sign a\n * transaction.\n *\n * Let's consider an Atomic Swap contract. Alice wants to give 10 of her Token\n * A tokens to Bob for 5 of his Token B tokens.\n *\n * ```ts\n * const ALICE = 'G123...'\n * const BOB = 'G456...'\n * const TOKEN_A = 'C123…'\n * const TOKEN_B = 'C456…'\n * const AMOUNT_A = 10n\n * const AMOUNT_B = 5n\n * ```\n *\n * Let's say Alice is also going to be the one signing the final transaction\n * envelope, meaning she is the invoker. So your app, from Alice's browser,\n * simulates the `swap` call:\n *\n * ```ts\n * const tx = await swapClient.swap({\n * a: ALICE,\n * b: BOB,\n * token_a: TOKEN_A,\n * token_b: TOKEN_B,\n * amount_a: AMOUNT_A,\n * amount_b: AMOUNT_B,\n * })\n * ```\n *\n * But your app can't `signAndSend` this right away, because Bob needs to sign\n * it first. You can check this:\n *\n * ```ts\n * const whoElseNeedsToSign = tx.needsNonInvokerSigningBy()\n * ```\n *\n * You can verify that `whoElseNeedsToSign` is an array of length `1`,\n * containing only Bob's public key.\n *\n * Then, still on Alice's machine, you can serialize the\n * transaction-under-assembly:\n *\n * ```ts\n * const json = tx.toJSON()\n * ```\n *\n * And now you need to send it to Bob's browser. How you do this depends on\n * your app. Maybe you send it to a server first, maybe you use WebSockets, or\n * maybe you have Alice text the JSON blob to Bob and have him paste it into\n * your app in his browser (note: this option might be error-prone 😄).\n *\n * Once you get the JSON blob into your app on Bob's machine, you can\n * deserialize it:\n *\n * ```ts\n * const tx = swapClient.txFromJSON(json)\n * ```\n *\n * Or, if you're using a client generated with\n * `soroban contract bindings typescript`, this deserialization will look like:\n *\n * ```ts\n * const tx = swapClient.fromJSON.swap(json)\n * ```\n *\n * Then you can have Bob sign it. What Bob will actually need to sign is some\n * _auth entries_ within the transaction, not the transaction itself or the\n * transaction envelope. Your app can verify that Bob has the correct wallet\n * selected, then:\n *\n * ```ts\n * await tx.signAuthEntries()\n * ```\n *\n * Under the hood, this uses `signAuthEntry`, which you either need to inject\n * during initial construction of the `Client`/`AssembledTransaction`,\n * or which you can pass directly to `signAuthEntries`.\n *\n * Now Bob can again serialize the transaction and send back to Alice, where\n * she can finally call `signAndSend()`.\n *\n * To see an even more complicated example, where Alice swaps with Bob but the\n * transaction is invoked by yet another party, check out\n * [test-swap.js](https://github.com/stellar/js-stellar-sdk/blob/master/test/e2e/src/test-swap.js).\n *\n */\nexport class AssembledTransaction<T> {\n /**\n * The TransactionBuilder as constructed in\n * {@link AssembledTransaction}.build. Feel free set `simulate: false` to modify\n * this object before calling `tx.simulate()` manually. Example:\n *\n * ```ts\n * const tx = await myContract.myMethod(\n * { args: 'for', my: 'method', ... },\n * { simulate: false }\n * );\n * tx.raw.addMemo(Memo.text('Nice memo, friend!'))\n * await tx.simulate();\n * ```\n */\n public raw?: TransactionBuilder;\n\n /**\n * Stores the original operation from `buildWithOp` for reuse during\n * automatic state restoration rebuilds.\n */\n private originalOp?: xdr.Operation;\n\n /**\n * The Transaction as it was built with `raw.build()` right before\n * simulation. Once this is set, modifying `raw` will have no effect unless\n * you call `tx.simulate()` again.\n */\n public built?: Tx;\n\n /**\n * The result of the transaction simulation. This is set after the first call\n * to `simulate`. It is difficult to serialize and deserialize, so it is not\n * included in the `toJSON` and `fromJSON` methods. See `simulationData`\n * cached, serializable access to the data needed by AssembledTransaction\n * logic.\n */\n public simulation?: Api.SimulateTransactionResponse;\n\n /**\n * Cached simulation result. This is set after the first call to\n * {@link AssembledTransaction.simulationData}, and is used to facilitate\n * serialization and deserialization of the AssembledTransaction.\n *\n * Most of the time, if you need this data, you can call\n * `tx.simulation.result`.\n *\n * If you need access to this data after a transaction has been serialized\n * and then deserialized, you can call `simulationData.result`.\n */\n private simulationResult?: Api.SimulateHostFunctionResult;\n\n /**\n * Cached simulation transaction data. This is set after the first call to\n * {@link AssembledTransaction.simulationData}, and is used to facilitate\n * serialization and deserialization of the AssembledTransaction.\n *\n * Most of the time, if you need this data, you can call\n * `simulation.transactionData`.\n *\n * If you need access to this data after a transaction has been serialized\n * and then deserialized, you can call `simulationData.transactionData`.\n */\n private simulationTransactionData?: xdr.SorobanTransactionData;\n\n /**\n * The Soroban server to use for all RPC calls. This is constructed from the\n * `rpcUrl` in the options.\n */\n private server: Server;\n\n /**\n * The signed transaction.\n */\n public signed?: Tx;\n\n /**\n * A list of the most important errors that various AssembledTransaction\n * methods can throw. Feel free to catch specific errors in your application\n * logic.\n */\n static Errors = {\n ExpiredState: ExpiredStateError,\n RestorationFailure: RestoreFailureError,\n NeedsMoreSignatures: NeedsMoreSignaturesError,\n NoSignatureNeeded: NoSignatureNeededError,\n NoUnsignedNonInvokerAuthEntries: NoUnsignedNonInvokerAuthEntriesError,\n NoSigner: NoSignerError,\n NotYetSimulated: NotYetSimulatedError,\n FakeAccount: FakeAccountError,\n SimulationFailed: SimulationFailedError,\n InternalWalletError,\n ExternalServiceError,\n InvalidClientRequest: InvalidClientRequestError,\n UserRejected: UserRejectedError,\n };\n\n /**\n * Serialize the AssembledTransaction to a JSON string. This is useful for\n * saving the transaction to a database or sending it over the wire for\n * multi-auth workflows. `fromJSON` can be used to deserialize the\n * transaction. This only works with transactions that have been simulated.\n */\n toJSON() {\n return JSON.stringify({\n method: this.options.method,\n tx: this.built?.toXDR(),\n simulationResult: {\n auth: this.simulationData.result.auth.map((a) => a.toXDR(\"base64\")),\n retval: this.simulationData.result.retval.toXDR(\"base64\"),\n },\n simulationTransactionData:\n this.simulationData.transactionData.toXDR(\"base64\"),\n });\n }\n\n /**\n * Validate that a built transaction is a single invokeContract operation\n * targeting the expected contract, and return the parsed InvokeContractArgs.\n */\n private static validateInvokeContractOp(\n built: Tx,\n expectedContractId: string,\n ): xdr.InvokeContractArgs {\n if (built.operations.length !== 1) {\n throw new Error(\n \"Transaction envelope must contain exactly one operation.\",\n );\n }\n\n const operation = built.operations[0];\n\n if (operation.type !== \"invokeHostFunction\") {\n throw new Error(\n \"Transaction envelope does not contain an invokeHostFunction operation.\",\n );\n }\n\n const invokeOp = operation as Operation.InvokeHostFunction;\n\n if (invokeOp.func.switch().name !== \"hostFunctionTypeInvokeContract\") {\n throw new Error(\n \"Transaction envelope does not contain an invokeContract host function.\",\n );\n }\n\n const invokeContractArgs = invokeOp.func.value() as xdr.InvokeContractArgs;\n\n let contractAddress: xdr.ScAddress;\n let functionName: string;\n\n try {\n contractAddress = invokeContractArgs.contractAddress();\n functionName = invokeContractArgs.functionName().toString(\"utf-8\");\n } catch {\n throw new Error(\n \"Could not extract contract address or method name from the transaction envelope.\",\n );\n }\n\n if (!contractAddress || !functionName) {\n throw new Error(\n \"Could not extract contract address or method name from the transaction envelope.\",\n );\n }\n\n const xdrContractId = Address.fromScAddress(contractAddress).toString();\n if (xdrContractId !== expectedContractId) {\n throw new Error(\n `Transaction envelope targets contract ${xdrContractId}, but this Client is configured for ${expectedContractId}.`,\n );\n }\n\n return invokeContractArgs;\n }\n\n static fromJSON<T>(\n options: Omit<AssembledTransactionOptions<T>, \"args\">,\n {\n tx,\n simulationResult,\n simulationTransactionData,\n }: {\n tx: XDR_BASE64;\n simulationResult: {\n auth: XDR_BASE64[];\n retval: XDR_BASE64;\n };\n simulationTransactionData: XDR_BASE64;\n },\n ): AssembledTransaction<T> {\n const txn = new AssembledTransaction(options);\n txn.built = TransactionBuilder.fromXDR(tx, options.networkPassphrase) as Tx;\n\n const invokeContractArgs = AssembledTransaction.validateInvokeContractOp(\n txn.built,\n options.contractId,\n );\n\n const xdrMethod = invokeContractArgs.functionName().toString(\"utf-8\");\n\n if (xdrMethod !== options.method) {\n throw new Error(\n `Transaction envelope calls method '${xdrMethod}', but the provided method is '${options.method}'.`,\n );\n }\n\n txn.simulationResult = {\n auth: simulationResult.auth.map((a) =>\n xdr.SorobanAuthorizationEntry.fromXDR(a, \"base64\"),\n ),\n retval: xdr.ScVal.fromXDR(simulationResult.retval, \"base64\"),\n };\n txn.simulationTransactionData = xdr.SorobanTransactionData.fromXDR(\n simulationTransactionData,\n \"base64\",\n );\n return txn;\n }\n\n /**\n * Serialize the AssembledTransaction to a base64-encoded XDR string.\n */\n toXDR(): string {\n if (!this.built)\n throw new Error(\n \"Transaction has not yet been simulated; \" +\n \"call `AssembledTransaction.simulate` first.\",\n );\n return this.built?.toEnvelope().toXDR(\"base64\");\n }\n\n /**\n * Deserialize the AssembledTransaction from a base64-encoded XDR string.\n */\n static fromXDR<T>(\n options: Omit<\n AssembledTransactionOptions<T>,\n \"args\" | \"method\" | \"parseResultXdr\"\n >,\n encodedXDR: string,\n spec: Spec,\n ): AssembledTransaction<T> {\n const envelope = xdr.TransactionEnvelope.fromXDR(encodedXDR, \"base64\");\n const built = TransactionBuilder.fromXDR(\n envelope,\n options.networkPassphrase,\n ) as Tx;\n\n const invokeContractArgs = AssembledTransaction.validateInvokeContractOp(\n built,\n options.contractId,\n );\n\n const method = invokeContractArgs.functionName().toString(\"utf-8\");\n const txn = new AssembledTransaction({\n ...options,\n method,\n parseResultXdr: (result: xdr.ScVal) =>\n spec.funcResToNative(method, result),\n });\n txn.built = built;\n return txn;\n }\n\n private handleWalletError(error?: WalletError): void {\n if (!error) return;\n\n const { message, code } = error;\n const fullMessage = `${message}${error.ext ? ` (${error.ext.join(\", \")})` : \"\"}`;\n\n switch (code) {\n case -1:\n throw new AssembledTransaction.Errors.InternalWalletError(fullMessage);\n case -2:\n throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage);\n case -3:\n throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage);\n case -4:\n throw new AssembledTransaction.Errors.UserRejected(fullMessage);\n default:\n throw new Error(`Unhandled error: ${fullMessage}`);\n }\n }\n\n private constructor(public options: AssembledTransactionOptions<T>) {\n this.options.simulate = this.options.simulate ?? true;\n const { server, allowHttp, headers, rpcUrl } = this.options;\n this.server = server ?? new Server(rpcUrl, { allowHttp, headers });\n }\n\n /**\n * Construct a new AssembledTransaction. This is the main way to create a new\n * AssembledTransaction; the constructor is private.\n *\n * This is an asynchronous constructor for two reasons:\n *\n * 1. It needs to fetch the account from the network to get the current\n * sequence number.\n * 2. It needs to simulate the transaction to get the expected fee.\n *\n * If you don't want to simulate the transaction, you can set `simulate` to\n * `false` in the options.\n *\n * If you need to create an operation other than `invokeHostFunction`, you\n * can use {@link AssembledTransaction.buildWithOp} instead.\n *\n * @example\n * ```ts\n * const tx = await AssembledTransaction.build({\n * ...,\n * simulate: false,\n * })\n * ```\n */\n static build<T>(\n options: AssembledTransactionOptions<T>,\n ): Promise<AssembledTransaction<T>> {\n const contract = new Contract(options.contractId);\n return AssembledTransaction.buildWithOp(\n contract.call(options.method, ...(options.args ?? [])),\n options,\n );\n }\n\n /**\n * Construct a new AssembledTransaction, specifying an Operation other than\n * `invokeHostFunction` (the default used by {@link AssembledTransaction.build}).\n *\n * Note: `AssembledTransaction` currently assumes these operations can be\n * simulated. This is not true for classic operations; only for those used by\n * Soroban Smart Contracts like `invokeHostFunction` and `createCustomContract`.\n *\n * @example\n * ```ts\n * const tx = await AssembledTransaction.buildWithOp(\n * Operation.createCustomContract({ ... });\n * {\n * ...,\n * simulate: false,\n * }\n * )\n * ```\n */\n static async buildWithOp<T>(\n operation: xdr.Operation,\n options: AssembledTransactionOptions<T>,\n ): Promise<AssembledTransaction<T>> {\n const tx = new AssembledTransaction(options);\n tx.originalOp = operation;\n const account = await getAccount(options, tx.server);\n tx.raw = new TransactionBuilder(account, {\n fee: options.fee ?? BASE_FEE,\n networkPassphrase: options.networkPassphrase,\n })\n .setTimeout(options.timeoutInSeconds ?? DEFAULT_TIMEOUT)\n .addOperation(operation);\n\n if (options.simulate) await tx.simulate();\n\n return tx;\n }\n\n private static async buildFootprintRestoreTransaction<T>(\n options: AssembledTransactionOptions<T>,\n sorobanData: SorobanDataBuilder | xdr.SorobanTransactionData,\n account: Account,\n fee: string,\n ): Promise<AssembledTransaction<T>> {\n const tx = new AssembledTransaction(options);\n tx.raw = new TransactionBuilder(account, {\n fee,\n networkPassphrase: options.networkPassphrase,\n })\n .setSorobanData(\n sorobanData instanceof SorobanDataBuilder\n ? sorobanData.build()\n : sorobanData,\n )\n .addOperation(Operation.restoreFootprint({}))\n .setTimeout(options.timeoutInSeconds ?? DEFAULT_TIMEOUT);\n await tx.simulate({ restore: false });\n return tx;\n }\n\n simulate = async ({ restore }: { restore?: boolean } = {}): Promise<this> => {\n if (!this.built) {\n if (!this.raw) {\n throw new Error(\n \"Transaction has not yet been assembled; \" +\n \"call `AssembledTransaction.build` first.\",\n );\n }\n this.built = this.raw.build();\n }\n restore = restore ?? this.options.restore;\n\n // need to force re-calculation of simulationData for new simulation\n delete this.simulationResult;\n delete this.simulationTransactionData;\n this.simulation = await this.server.simulateTransaction(this.built);\n\n if (restore && Api.isSimulationRestore(this.simulation)) {\n const account = await getAccount(this.options, this.server);\n const result = await this.restoreFootprint(\n this.simulation.restorePreamble,\n account,\n );\n if (result.status === Api.GetTransactionStatus.SUCCESS) {\n // need to rebuild the transaction with bumped account sequence number\n const op = this.originalOp\n ? this.originalOp\n : new Contract(this.options.contractId).call(\n this.options.method,\n ...(this.options.args ?? []),\n );\n this.raw = new TransactionBuilder(account, {\n fee: this.options.fee ?? BASE_FEE,\n networkPassphrase: this.options.networkPassphrase,\n })\n .addOperation(op)\n .setTimeout(this.options.timeoutInSeconds ?? DEFAULT_TIMEOUT);\n delete this.built;\n await this.simulate();\n return this;\n }\n throw new AssembledTransaction.Errors.RestorationFailure(\n `Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\\n${JSON.stringify(result)}`,\n );\n }\n\n if (Api.isSimulationSuccess(this.simulation)) {\n this.built = assembleTransaction(this.built, this.simulation).build();\n }\n\n return this;\n };\n\n get simulationData(): {\n result: Api.SimulateHostFunctionResult;\n transactionData: xdr.SorobanTransactionData;\n } {\n if (this.simulationResult && this.simulationTransactionData) {\n return {\n result: this.simulationResult,\n transactionData: this.simulationTransactionData,\n };\n }\n const simulation = this.simulation!;\n if (!simulation) {\n throw new AssembledTransaction.Errors.NotYetSimulated(\n \"Transaction has not yet been simulated\",\n );\n }\n if (Api.isSimulationError(simulation)) {\n throw new AssembledTransaction.Errors.SimulationFailed(\n `Transaction simulation failed: \"${simulation.error}\"`,\n );\n }\n\n if (Api.isSimulationRestore(simulation)) {\n throw new AssembledTransaction.Errors.ExpiredState(\n `You need to restore some contract state before you can invoke this method.\\n` +\n \"You can set `restore` to true in the method options in order to \" +\n \"automatically restore the contract state when needed.\",\n );\n }\n\n // add to object for serialization & deserialization\n this.simulationResult = simulation.result ?? {\n auth: [],\n retval: xdr.ScVal.scvVoid(),\n };\n this.simulationTransactionData = simulation.transactionData.build();\n\n return {\n result: this.simulationResult,\n transactionData: this.simulationTransactionData!,\n };\n }\n\n get result(): T {\n try {\n if (!this.simulationData.result) {\n throw new Error(\"No simulation result!\");\n }\n return this.options.parseResultXdr(this.simulationData.result.retval);\n } catch (e) {\n if (!implementsToString(e)) throw e;\n const err = this.parseError(e.toString());\n if (err) return err as T;\n throw e;\n }\n }\n\n private parseError(errorMessage: string) {\n if (!this.options.errorTypes) return undefined;\n const match = errorMessage.match(contractErrorPattern);\n if (!match) return undefined;\n const i = parseInt(match[1], 10);\n const err = this.options.errorTypes[i];\n if (!err) return undefined;\n return new Err(err);\n }\n\n /**\n * Sign the transaction with the signTransaction function included previously.\n * If you did not previously include one, you need to include one now.\n */\n sign = async ({\n force = false,\n signTransaction = this.options.signTransaction,\n }: {\n /**\n * If `true`, sign and send the transaction even if it is a read call\n */\n force?: boolean;\n /**\n * You must provide this here if you did not provide one before\n */\n signTransaction?: ClientOptions[\"signTransaction\"];\n } = {}): Promise<void> => {\n if (!this.built) {\n throw new Error(\"Transaction has not yet been simulated\");\n }\n\n if (!force && this.isReadCall) {\n throw new AssembledTransaction.Errors.NoSignatureNeeded(\n \"This is a read call. It requires no signature or sending. \" +\n \"Use `force: true` to sign and send anyway.\",\n );\n }\n\n if (!signTransaction) {\n throw new AssembledTransaction.Errors.NoSigner(\n \"You must provide a signTransaction function, either when calling \" +\n \"`signAndSend` or when initializing your Client\",\n );\n }\n\n if (!this.options.publicKey) {\n throw new AssembledTransaction.Errors.FakeAccount(\n \"This transaction was constructed using a default account. Provide a valid publicKey in the AssembledTransactionOptions.\",\n );\n }\n\n // filter out contracts, as these are dealt with via cross contract calls\n const sigsNeeded = this.needsNonInvokerSigningBy().filter(\n (id) => !id.startsWith(\"C\"),\n );\n if (sigsNeeded.length) {\n throw new AssembledTransaction.Errors.NeedsMoreSignatures(\n `Transaction requires signatures from ${sigsNeeded}. ` +\n \"See `needsNonInvokerSigningBy` for details.\",\n );\n }\n\n const timeoutInSeconds = this.options.timeoutInSeconds ?? DEFAULT_TIMEOUT;\n this.built = TransactionBuilder.cloneFrom(this.built!, {\n fee: this.built!.fee,\n timebounds: undefined,\n sorobanData: this.simulationData.transactionData,\n })\n .setTimeout(timeoutInSeconds)\n .build();\n\n const signOpts: Parameters<\n NonNullable<ClientOptions[\"signTransaction\"]>\n >[1] = {\n networkPassphrase: this.options.networkPassphrase,\n };\n\n if (this.options.address) signOpts.address = this.options.address;\n if (this.options.submit !== undefined)\n signOpts.submit = this.options.submit;\n if (this.options.submitUrl) signOpts.submitUrl = this.options.submitUrl;\n\n const { signedTxXdr: signature, error } = await signTransaction(\n this.built.toXDR(),\n signOpts,\n );\n\n this.handleWalletError(error);\n\n this.signed = TransactionBuilder.fromXDR(\n signature,\n this.options.networkPassphrase,\n ) as Tx;\n };\n\n /**\n * Sends the transaction to the network to return a `SentTransaction` that\n * keeps track of all the attempts to fetch the transaction. Optionally pass\n * a {@link Watcher} that allows you to keep track of the progress as the\n * transaction is sent and processed.\n */\n async send(watcher?: Watcher) {\n if (!this.signed) {\n throw new Error(\n \"The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead.\",\n );\n }\n const sent = await SentTransaction.init(this, watcher);\n return sent;\n }\n\n /**\n * Sign the transaction with the `signTransaction` function included previously.\n * If you did not previously include one, you need to include one now.\n * After signing, this method will send the transaction to the network and\n * return a `SentTransaction` that keeps track of all the attempts to fetch\n * the transaction. You may pass a {@link Watcher} to keep\n * track of this progress.\n */\n signAndSend = async ({\n force = false,\n signTransaction = this.options.signTransaction,\n watcher,\n }: {\n /**\n * If `true`, sign and send the transaction even if it is a read call\n */\n force?: boolean;\n /**\n * You must provide this here if you did not provide one before\n */\n signTransaction?: ClientOptions[\"signTransaction\"];\n /**\n * A {@link Watcher} to notify after the transaction is successfully\n * submitted to the network (`onSubmitted`) and as the transaction is\n * processed (`onProgress`).\n */\n watcher?: Watcher;\n } = {}): Promise<SentTransaction<T>> => {\n if (!this.signed) {\n // Wrap signTransaction to disable submit and prevent double submission,\n // without mutating the shared this.options object\n const signer = signTransaction || this.options.signTransaction;\n const wrappedSignTransaction: typeof signTransaction =\n this.options.submit && signer\n ? (tx, opts) => signer(tx, { ...opts, submit: false })\n : signTransaction;\n\n await this.sign({ force, signTransaction: wrappedSignTransaction });\n }\n return this.send(watcher);\n };\n\n /**\n * Get a list of accounts, other than the invoker of the simulation, that\n * need to sign auth entries in this transaction.\n *\n * Soroban allows multiple people to sign a transaction. Someone needs to\n * sign the final transaction envelope; this person/account is called the\n * _invoker_, or _source_. Other accounts might need to sign individual auth\n * entries in the transaction, if they're not also the invoker.\n *\n * This function returns a list of accounts that need to sign auth entries,\n * assuming that the same invoker/source account will sign the final\n * transaction envelope as signed the initial simulation.\n *\n * One at a time, for each public key in this array, you will need to\n * serialize this transaction with `toJSON`, send to the owner of that key,\n * deserialize the transaction with `txFromJson`, and call\n * {@link AssembledTransaction.signAuthEntries}. Then re-serialize and send to\n * the next account in this list.\n */\n needsNonInvokerSigningBy = ({\n includeAlreadySigned = false,\n }: {\n /**\n * Whether or not to include auth entries that have already been signed.\n * Default: false\n */\n includeAlreadySigned?: boolean;\n } = {}): string[] => {\n if (!this.built) {\n throw new Error(\"Transaction has not yet been simulated\");\n }\n\n // We expect that any transaction constructed by these libraries has a\n // single operation, which is an InvokeHostFunction operation. The host\n // function being invoked is the contract method call.\n if (!(\"operations\" in this.built)) {\n throw new Error(\n `Unexpected Transaction type; no operations: ${JSON.stringify(\n this.built,\n )}`,\n );\n }\n const rawInvokeHostFunctionOp = this.built\n .operations[0] as Operation.InvokeHostFunction;\n\n return [\n ...new Set(\n (rawInvokeHostFunctionOp.auth ?? [])\n .map((entry) => getAddressCredentials(entry.credentials()))\n .filter(\n (addrAuth): addrAuth is xdr.SorobanAddressCredentials =>\n // skip source-account credentials (no address payload), which\n // are covered by the envelope signature on the source account\n addrAuth !== null &&\n (includeAlreadySigned ||\n addrAuth.signature().switch().name === \"scvVoid\"),\n )\n .map((addrAuth) =>\n Address.fromScAddress(addrAuth.address()).toString(),\n ),\n ),\n ];\n };\n\n /**\n * If {@link AssembledTransaction.needsNonInvokerSigningBy} returns a\n * non-empty list, you can serialize the transaction with `toJSON`, send it to\n * the owner of one of the public keys in the map, deserialize with\n * `txFromJSON`, and call this method on their machine. Internally, this will\n * use `signAuthEntry` function from connected `wallet` for each.\n *\n * Then, re-serialize the transaction and either send to the next\n * `needsNonInvokerSigningBy` owner, or send it back to the original account\n * who simulated the transaction so they can {@link AssembledTransaction.sign}\n * the transaction envelope and {@link AssembledTransaction.send} it to the\n * network.\n *\n * Sending to all `needsNonInvokerSigningBy` owners in parallel is not\n * currently supported!\n */\n signAuthEntries = async ({\n expiration = (async () =>\n (await this.server.getLatestLedger()).sequence + 100)(),\n signAuthEntry = this.options.signAuthEntry,\n address = this.options.publicKey,\n authorizeEntry = stellarBaseAuthorizeEntry,\n }: {\n /**\n * When to set each auth entry to expire. Could be any number of blocks in\n * the future. Can be supplied as a promise or a raw number. Default:\n * about 8.3 minutes from now.\n */\n expiration?: number | Promise<number>;\n /**\n * Sign all auth entries for this account. Default: the account that\n * constructed the transaction\n */\n address?: string;\n /**\n * You must provide this here if you did not provide one before and you are not passing `authorizeEntry`. Default: the `signAuthEntry` function from the `Client` options. Must sign things as the given `publicKey`.\n */\n signAuthEntry?: ClientOptions[\"signAuthEntry\"];\n\n /**\n * If you have a pro use-case and need to override the default `authorizeEntry` function, rather than using the one in `@stellar/stellar-base`, you can do that! Your function needs to take at least the first argument, `entry: xdr.SorobanAuthorizationEntry`, and return a `Promise<xdr.SorobanAuthorizationEntry>`.\n *\n * Note that you if you pass this, then `signAuthEntry` will be ignored.\n */\n authorizeEntry?: typeof stellarBaseAuthorizeEntry;\n } = {}): Promise<void> => {\n if (!this.built)\n throw new Error(\"Transaction has not yet been assembled or simulated\");\n\n // Likely if we're using a custom authorizeEntry then we know better than the `needsNonInvokerSigningBy` logic.\n if (authorizeEntry === stellarBaseAuthorizeEntry) {\n const needsNonInvokerSigningBy = this.needsNonInvokerSigningBy();\n if (needsNonInvokerSigningBy.length === 0) {\n throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries(\n \"No unsigned non-invoker auth entries; maybe you already signed?\",\n );\n }\n if (needsNonInvokerSigningBy.indexOf(address ?? \"\") === -1) {\n throw new AssembledTransaction.Errors.NoSignatureNeeded(\n `No auth entries for public key \"${address}\"`,\n );\n }\n if (!signAuthEntry) {\n throw new AssembledTransaction.Errors.NoSigner(\n \"You must provide `signAuthEntry` or a custom `authorizeEntry`\",\n );\n }\n }\n\n const rawInvokeHostFunctionOp = this.built\n .operations[0] as Operation.InvokeHostFunction;\n\n const authEntries = rawInvokeHostFunctionOp.auth ?? [];\n\n for (const [i, entry] of authEntries.entries()) {\n // workaround for https://github.com/stellar/js-stellar-sdk/issues/1070\n const credentials = xdr.SorobanCredentials.fromXDR(\n entry.credentials().toXDR(),\n );\n const addrAuth = getAddressCredentials(credentials);\n if (addrAuth === null) {\n // if the invoker/source account, then the entry doesn't need explicit\n // signature, since the tx envelope is already signed by the source\n // account, so only address-based credentials need signing here\n continue;\n }\n const authEntryAddress = Address.fromScAddress(\n addrAuth.address(),\n ).toString();\n\n // this auth entry needs to be signed by a different account\n // (or maybe already was!)\n if (authEntryAddress !== address) continue;\n\n const sign: typeof signAuthEntry = signAuthEntry ?? Promise.resolve;\n\n authEntries[i] = await authorizeEntry(\n entry,\n async (preimage) => {\n const { signedAuthEntry, error } = await sign(\n preimage.toXDR(\"base64\"),\n {\n address,\n },\n );\n this.handleWalletError(error);\n return Buffer.from(signedAuthEntry, \"base64\");\n },\n await expiration,\n this.options.networkPassphrase,\n );\n }\n };\n\n /**\n * Whether this transaction is a read call. This is determined by the\n * simulation result and the transaction data. If the transaction is a read\n * call, it will not need to be signed and sent to the network. If this\n * returns `false`, then you need to call `signAndSend` on this transaction.\n */\n get isReadCall(): boolean {\n const authsCount = this.simulationData.result.auth.length;\n const writeLength = this.simulationData.transactionData\n .resources()\n .footprint()\n .readWrite().length;\n return authsCount === 0 && writeLength === 0;\n }\n\n /**\n * Restores the footprint (resource ledger entries that can be read or written)\n * of an expired transaction.\n *\n * The method will:\n * 1. Build a new transaction aimed at restoring the necessary resources.\n * 2. Sign this new transaction if a `signTransaction` handler is provided.\n * 3. Send the signed transaction to the network.\n * 4. Await and return the response from the network.\n *\n * Preconditions:\n * - A `signTransaction` function must be provided during the Client initialization.\n * - The provided `restorePreamble` should include a minimum resource fee and valid\n * transaction data.\n *\n * @throws - Throws an error if no `signTransaction` function is provided during\n * Client initialization.\n * @throws - Throws a custom error if the\n * restore transaction fails, providing the details of the failure.\n */\n async restoreFootprint(\n /**\n * The preamble object containing data required to\n * build the restore transaction.\n */\n restorePreamble: {\n minResourceFee: string;\n transactionData: SorobanDataBuilder;\n },\n /** The account that is executing the footprint restore operation. If omitted, will use the account from the AssembledTransaction. */\n account?: Account,\n ): Promise<Api.GetTransactionResponse> {\n if (!this.options.signTransaction) {\n throw new Error(\n \"For automatic restore to work you must provide a signTransaction function when initializing your Client\",\n );\n }\n account = account ?? (await getAccount(this.options, this.server));\n // first try restoring the contract\n const restoreTx =\n await AssembledTransaction.buildFootprintRestoreTransaction(\n { ...this.options },\n restorePreamble.transactionData,\n account,\n restorePreamble.minResourceFee,\n );\n const sentTransaction = await restoreTx.signAndSend();\n if (!sentTransaction.getTransactionResponse) {\n throw new AssembledTransaction.Errors.RestorationFailure(\n `The attempt at automatic restore failed. \\n${JSON.stringify(sentTransaction)}`,\n );\n }\n return sentTransaction.getTransactionResponse;\n }\n}\n"],"names":["Server","xdr","authorizeEntry","stellarBaseAuthorizeEntry"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgQO,MAAM,oBAAA,CAAwB;AAAA,EA6R3B,YAAmB,OAAA,EAAyC;AAAzC,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACzB,IAAA,IAAA,CAAK,OAAA,CAAQ,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,QAAA,IAAY,IAAA;AACjD,IAAA,MAAM,EAAE,MAAA,EAAQ,SAAA,EAAW,OAAA,EAAS,MAAA,KAAW,IAAA,CAAK,OAAA;AACpD,IAAA,IAAA,CAAK,MAAA,GAAS,UAAU,IAAIA,SAAA,CAAO,QAAQ,EAAE,SAAA,EAAW,SAAS,CAAA;AAAA,EACnE;AAAA,EAJ2B,OAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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A,MAAM,eAAA,GAAkB,MAAM,SAAA,CAAU,WAAA,EAAY;AACpD,IAAA,IAAI,CAAC,gBAAgB,sBAAA,EAAwB;AAC3C,MAAA,MAAM,IAAI,qBAAqB,MAAA,CAAO,kBAAA;AAAA,QACpC,CAAA;AAAA,EAA8C,IAAA,CAAK,SAAA,CAAU,eAAe,CAAC,CAAA;AAAA,OAC/E;AAAA,IACF;AACA,IAAA,OAAO,eAAA,CAAgB,sBAAA;AAAA,EACzB;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"assembled_transaction.js","sources":["../../../../src/contract/assembled_transaction.ts"],"sourcesContent":["/* disable max-classes rule, because extending error shouldn't count! */\n/* eslint max-classes-per-file: 0 */\nimport {\n Account,\n Address,\n BASE_FEE,\n Contract,\n Operation,\n SorobanDataBuilder,\n TransactionBuilder,\n authorizeEntry as stellarBaseAuthorizeEntry,\n inspectAuthEntry,\n xdr,\n} from \"../base/index.js\";\n// internal helper (not part of the public API), imported directly from auth.js\nimport { getAddressCredentials } from \"../base/auth.js\";\nimport type {\n AssembledTransactionOptions,\n ClientOptions,\n MethodOptions,\n Tx,\n WalletError,\n XDR_BASE64,\n} from \"./types.js\";\nimport { Server } from \"../rpc/index.js\";\nimport { Api } from \"../rpc/api.js\";\nimport { assembleTransaction } from \"../rpc/transaction.js\";\nimport type { Client } from \"./client.js\";\nimport { Err } from \"./rust_result.js\";\nimport {\n contractErrorPattern,\n implementsToString,\n getAccount,\n} from \"./utils.js\";\nimport { DEFAULT_TIMEOUT } from \"./types.js\";\nimport { SentTransaction, Watcher } from \"./sent_transaction.js\";\nimport { Spec } from \"./spec.js\";\nimport {\n ExpiredStateError,\n ExternalServiceError,\n FakeAccountError,\n InternalWalletError,\n InvalidClientRequestError,\n NeedsMoreSignaturesError,\n NoSignatureNeededError,\n NoSignerError,\n NotYetSimulatedError,\n NoUnsignedNonInvokerAuthEntriesError,\n RestoreFailureError,\n SimulationFailedError,\n UserRejectedError,\n} from \"./errors.js\";\n\n/**\n * The main workhorse of {@link Client}. This class is used to wrap a\n * transaction-under-construction and provide high-level interfaces to the most\n * common workflows, while still providing access to low-level stellar-sdk\n * transaction manipulation.\n *\n * Most of the time, you will not construct an `AssembledTransaction` directly,\n * but instead receive one as the return value of a `Client` method. If\n * you're familiar with the libraries generated by soroban-cli's\n * `contract bindings typescript` command, these also wraps `Client` and return\n * `AssembledTransaction` instances.\n *\n * Let's look at examples of how to use `AssembledTransaction` for a variety of\n * use-cases:\n *\n * #### 1. Simple read call\n *\n * Since these only require simulation, you can get the `result` of the call\n * right after constructing your `AssembledTransaction`:\n *\n * ```ts\n * const { result } = await AssembledTransaction.build({\n * method: 'myReadMethod',\n * args: spec.funcArgsToScVals('myReadMethod', {\n * args: 'for',\n * my: 'method',\n * ...\n * }),\n * contractId: 'C123…',\n * networkPassphrase: '…',\n * rpcUrl: 'https://…',\n * publicKey: undefined, // irrelevant, for simulation-only read calls\n * parseResultXdr: (result: xdr.ScVal) =>\n * spec.funcResToNative('myReadMethod', result),\n * })\n * ```\n *\n * While that looks pretty complicated, most of the time you will use this in\n * conjunction with {@link Client}, which simplifies it to:\n *\n * ```ts\n * const { result } = await client.myReadMethod({\n * args: 'for',\n * my: 'method',\n * ...\n * })\n * ```\n *\n * #### 2. Simple write call\n *\n * For write calls that will be simulated and then sent to the network without\n * further manipulation, only one more step is needed:\n *\n * ```ts\n * const assembledTx = await client.myWriteMethod({\n * args: 'for',\n * my: 'method',\n * ...\n * })\n * const sentTx = await assembledTx.signAndSend()\n * ```\n *\n * Here we're assuming that you're using a {@link Client}, rather than\n * constructing `AssembledTransaction`'s directly.\n *\n * Note that `sentTx`, the return value of `signAndSend`, is a\n * {@link SentTransaction}. `SentTransaction` is similar to\n * `AssembledTransaction`, but is missing many of the methods and fields that\n * are only relevant while assembling a transaction. It also has a few extra\n * methods and fields that are only relevant after the transaction has been\n * sent to the network.\n *\n * Like `AssembledTransaction`, `SentTransaction` also has a `result` getter,\n * which contains the parsed final return value of the contract call. Most of\n * the time, you may only be interested in this, so rather than getting the\n * whole `sentTx` you may just want to:\n *\n * ```ts\n * const tx = await client.myWriteMethod({ args: 'for', my: 'method', ... })\n * const { result } = await tx.signAndSend()\n * ```\n *\n * #### 3. More fine-grained control over transaction construction\n *\n * If you need more control over the transaction before simulating it, you can\n * set various {@link MethodOptions} when constructing your\n * `AssembledTransaction`. With a {@link Client}, this is passed as a\n * second object after the arguments (or the only object, if the method takes\n * no arguments):\n *\n * ```ts\n * const tx = await client.myWriteMethod(\n * {\n * args: 'for',\n * my: 'method',\n * ...\n * }, {\n * fee: '10000', // default: {@link BASE_FEE}\n * simulate: false,\n * timeoutInSeconds: 20, // default: {@link DEFAULT_TIMEOUT}\n * }\n * )\n * ```\n *\n * Since we've skipped simulation, we can now edit the `raw` transaction and\n * then manually call `simulate`:\n *\n * ```ts\n * tx.raw.addMemo(Memo.text('Nice memo, friend!'))\n * await tx.simulate()\n * ```\n *\n * If you need to inspect the simulation later, you can access it with\n * `tx.simulation`.\n *\n * #### 4. Multi-auth workflows\n *\n * Soroban, and Stellar in general, allows multiple parties to sign a\n * transaction.\n *\n * Let's consider an Atomic Swap contract. Alice wants to give 10 of her Token\n * A tokens to Bob for 5 of his Token B tokens.\n *\n * ```ts\n * const ALICE = 'G123...'\n * const BOB = 'G456...'\n * const TOKEN_A = 'C123…'\n * const TOKEN_B = 'C456…'\n * const AMOUNT_A = 10n\n * const AMOUNT_B = 5n\n * ```\n *\n * Let's say Alice is also going to be the one signing the final transaction\n * envelope, meaning she is the invoker. So your app, from Alice's browser,\n * simulates the `swap` call:\n *\n * ```ts\n * const tx = await swapClient.swap({\n * a: ALICE,\n * b: BOB,\n * token_a: TOKEN_A,\n * token_b: TOKEN_B,\n * amount_a: AMOUNT_A,\n * amount_b: AMOUNT_B,\n * })\n * ```\n *\n * But your app can't `signAndSend` this right away, because Bob needs to sign\n * it first. You can check this:\n *\n * ```ts\n * const whoElseNeedsToSign = tx.needsNonInvokerSigningBy()\n * ```\n *\n * You can verify that `whoElseNeedsToSign` is an array of length `1`,\n * containing only Bob's public key.\n *\n * Then, still on Alice's machine, you can serialize the\n * transaction-under-assembly:\n *\n * ```ts\n * const json = tx.toJSON()\n * ```\n *\n * And now you need to send it to Bob's browser. How you do this depends on\n * your app. Maybe you send it to a server first, maybe you use WebSockets, or\n * maybe you have Alice text the JSON blob to Bob and have him paste it into\n * your app in his browser (note: this option might be error-prone 😄).\n *\n * Once you get the JSON blob into your app on Bob's machine, you can\n * deserialize it:\n *\n * ```ts\n * const tx = swapClient.txFromJSON(json)\n * ```\n *\n * Or, if you're using a client generated with\n * `soroban contract bindings typescript`, this deserialization will look like:\n *\n * ```ts\n * const tx = swapClient.fromJSON.swap(json)\n * ```\n *\n * Then you can have Bob sign it. What Bob will actually need to sign is some\n * _auth entries_ within the transaction, not the transaction itself or the\n * transaction envelope. Your app can verify that Bob has the correct wallet\n * selected, then:\n *\n * ```ts\n * await tx.signAuthEntries()\n * ```\n *\n * Under the hood, this uses `signAuthEntry`, which you either need to inject\n * during initial construction of the `Client`/`AssembledTransaction`,\n * or which you can pass directly to `signAuthEntries`.\n *\n * Now Bob can again serialize the transaction and send back to Alice, where\n * she can finally call `signAndSend()`.\n *\n * To see an even more complicated example, where Alice swaps with Bob but the\n * transaction is invoked by yet another party, check out\n * [test-swap.js](https://github.com/stellar/js-stellar-sdk/blob/main/test/e2e/src/test-swap.js).\n *\n */\nexport class AssembledTransaction<T> {\n /**\n * The TransactionBuilder as constructed in\n * {@link AssembledTransaction}.build. Feel free set `simulate: false` to modify\n * this object before calling `tx.simulate()` manually. Example:\n *\n * ```ts\n * const tx = await myContract.myMethod(\n * { args: 'for', my: 'method', ... },\n * { simulate: false }\n * );\n * tx.raw.addMemo(Memo.text('Nice memo, friend!'))\n * await tx.simulate();\n * ```\n */\n public raw?: TransactionBuilder;\n\n /**\n * Stores the original operation from `buildWithOp` for reuse during\n * automatic state restoration rebuilds.\n */\n private originalOp?: xdr.Operation;\n\n /**\n * The Transaction as it was built with `raw.build()` right before\n * simulation. Once this is set, modifying `raw` will have no effect unless\n * you call `tx.simulate()` again.\n */\n public built?: Tx;\n\n /**\n * The result of the transaction simulation. This is set after the first call\n * to `simulate`. It is difficult to serialize and deserialize, so it is not\n * included in the `toJSON` and `fromJSON` methods. See `simulationData`\n * cached, serializable access to the data needed by AssembledTransaction\n * logic.\n */\n public simulation?: Api.SimulateTransactionResponse;\n\n /**\n * Cached simulation result. This is set after the first call to\n * {@link AssembledTransaction.simulationData}, and is used to facilitate\n * serialization and deserialization of the AssembledTransaction.\n *\n * Most of the time, if you need this data, you can call\n * `tx.simulation.result`.\n *\n * If you need access to this data after a transaction has been serialized\n * and then deserialized, you can call `simulationData.result`.\n */\n private simulationResult?: Api.SimulateHostFunctionResult;\n\n /**\n * Cached simulation transaction data. This is set after the first call to\n * {@link AssembledTransaction.simulationData}, and is used to facilitate\n * serialization and deserialization of the AssembledTransaction.\n *\n * Most of the time, if you need this data, you can call\n * `simulation.transactionData`.\n *\n * If you need access to this data after a transaction has been serialized\n * and then deserialized, you can call `simulationData.transactionData`.\n */\n private simulationTransactionData?: xdr.SorobanTransactionData;\n\n /**\n * The Soroban server to use for all RPC calls. This is constructed from the\n * `rpcUrl` in the options.\n */\n private server: Server;\n\n /**\n * The signed transaction.\n */\n public signed?: Tx;\n\n /**\n * A list of the most important errors that various AssembledTransaction\n * methods can throw. Feel free to catch specific errors in your application\n * logic.\n */\n static Errors = {\n ExpiredState: ExpiredStateError,\n RestorationFailure: RestoreFailureError,\n NeedsMoreSignatures: NeedsMoreSignaturesError,\n NoSignatureNeeded: NoSignatureNeededError,\n NoUnsignedNonInvokerAuthEntries: NoUnsignedNonInvokerAuthEntriesError,\n NoSigner: NoSignerError,\n NotYetSimulated: NotYetSimulatedError,\n FakeAccount: FakeAccountError,\n SimulationFailed: SimulationFailedError,\n InternalWalletError,\n ExternalServiceError,\n InvalidClientRequest: InvalidClientRequestError,\n UserRejected: UserRejectedError,\n };\n\n /**\n * Serialize the AssembledTransaction to a JSON string. This is useful for\n * saving the transaction to a database or sending it over the wire for\n * multi-auth workflows. `fromJSON` can be used to deserialize the\n * transaction. This only works with transactions that have been simulated.\n */\n toJSON() {\n return JSON.stringify({\n method: this.options.method,\n tx: this.built?.toXDR(),\n simulationResult: {\n auth: this.simulationData.result.auth.map((a) => a.toXDR(\"base64\")),\n retval: this.simulationData.result.retval.toXDR(\"base64\"),\n },\n simulationTransactionData:\n this.simulationData.transactionData.toXDR(\"base64\"),\n });\n }\n\n /**\n * Validate that a built transaction is a single invokeContract operation\n * targeting the expected contract, and return the parsed InvokeContractArgs.\n */\n private static validateInvokeContractOp(\n built: Tx,\n expectedContractId: string,\n ): xdr.InvokeContractArgs {\n if (built.operations.length !== 1) {\n throw new Error(\n \"Transaction envelope must contain exactly one operation.\",\n );\n }\n\n const operation = built.operations[0];\n\n if (operation.type !== \"invokeHostFunction\") {\n throw new Error(\n \"Transaction envelope does not contain an invokeHostFunction operation.\",\n );\n }\n\n const invokeOp = operation as Operation.InvokeHostFunction;\n\n if (invokeOp.func.switch().name !== \"hostFunctionTypeInvokeContract\") {\n throw new Error(\n \"Transaction envelope does not contain an invokeContract host function.\",\n );\n }\n\n const invokeContractArgs = invokeOp.func.value() as xdr.InvokeContractArgs;\n\n let contractAddress: xdr.ScAddress;\n let functionName: string;\n\n try {\n contractAddress = invokeContractArgs.contractAddress();\n functionName = invokeContractArgs.functionName().toString(\"utf-8\");\n } catch {\n throw new Error(\n \"Could not extract contract address or method name from the transaction envelope.\",\n );\n }\n\n if (!contractAddress || !functionName) {\n throw new Error(\n \"Could not extract contract address or method name from the transaction envelope.\",\n );\n }\n\n const xdrContractId = Address.fromScAddress(contractAddress).toString();\n if (xdrContractId !== expectedContractId) {\n throw new Error(\n `Transaction envelope targets contract ${xdrContractId}, but this Client is configured for ${expectedContractId}.`,\n );\n }\n\n return invokeContractArgs;\n }\n\n static fromJSON<T>(\n options: Omit<AssembledTransactionOptions<T>, \"args\">,\n {\n tx,\n simulationResult,\n simulationTransactionData,\n }: {\n tx: XDR_BASE64;\n simulationResult: {\n auth: XDR_BASE64[];\n retval: XDR_BASE64;\n };\n simulationTransactionData: XDR_BASE64;\n },\n ): AssembledTransaction<T> {\n const txn = new AssembledTransaction(options);\n txn.built = TransactionBuilder.fromXDR(tx, options.networkPassphrase) as Tx;\n\n const invokeContractArgs = AssembledTransaction.validateInvokeContractOp(\n txn.built,\n options.contractId,\n );\n\n const xdrMethod = invokeContractArgs.functionName().toString(\"utf-8\");\n\n if (xdrMethod !== options.method) {\n throw new Error(\n `Transaction envelope calls method '${xdrMethod}', but the provided method is '${options.method}'.`,\n );\n }\n\n txn.simulationResult = {\n auth: simulationResult.auth.map((a) =>\n xdr.SorobanAuthorizationEntry.fromXDR(a, \"base64\"),\n ),\n retval: xdr.ScVal.fromXDR(simulationResult.retval, \"base64\"),\n };\n txn.simulationTransactionData = xdr.SorobanTransactionData.fromXDR(\n simulationTransactionData,\n \"base64\",\n );\n return txn;\n }\n\n /**\n * Serialize the AssembledTransaction to a base64-encoded XDR string.\n */\n toXDR(): string {\n if (!this.built)\n throw new Error(\n \"Transaction has not yet been simulated; \" +\n \"call `AssembledTransaction.simulate` first.\",\n );\n return this.built?.toEnvelope().toXDR(\"base64\");\n }\n\n /**\n * Deserialize the AssembledTransaction from a base64-encoded XDR string.\n */\n static fromXDR<T>(\n options: Omit<\n AssembledTransactionOptions<T>,\n \"args\" | \"method\" | \"parseResultXdr\"\n >,\n encodedXDR: string,\n spec: Spec,\n ): AssembledTransaction<T> {\n const envelope = xdr.TransactionEnvelope.fromXDR(encodedXDR, \"base64\");\n const built = TransactionBuilder.fromXDR(\n envelope,\n options.networkPassphrase,\n ) as Tx;\n\n const invokeContractArgs = AssembledTransaction.validateInvokeContractOp(\n built,\n options.contractId,\n );\n\n const method = invokeContractArgs.functionName().toString(\"utf-8\");\n const txn = new AssembledTransaction({\n ...options,\n method,\n parseResultXdr: (result: xdr.ScVal) =>\n spec.funcResToNative(method, result),\n });\n txn.built = built;\n return txn;\n }\n\n private handleWalletError(error?: WalletError): void {\n if (!error) return;\n\n const { message, code } = error;\n const fullMessage = `${message}${error.ext ? ` (${error.ext.join(\", \")})` : \"\"}`;\n\n switch (code) {\n case -1:\n throw new AssembledTransaction.Errors.InternalWalletError(fullMessage);\n case -2:\n throw new AssembledTransaction.Errors.ExternalServiceError(fullMessage);\n case -3:\n throw new AssembledTransaction.Errors.InvalidClientRequest(fullMessage);\n case -4:\n throw new AssembledTransaction.Errors.UserRejected(fullMessage);\n default:\n throw new Error(`Unhandled error: ${fullMessage}`);\n }\n }\n\n private constructor(public options: AssembledTransactionOptions<T>) {\n this.options.simulate = this.options.simulate ?? true;\n const { server, allowHttp, headers, rpcUrl } = this.options;\n this.server = server ?? new Server(rpcUrl, { allowHttp, headers });\n }\n\n /**\n * Construct a new AssembledTransaction. This is the main way to create a new\n * AssembledTransaction; the constructor is private.\n *\n * This is an asynchronous constructor for two reasons:\n *\n * 1. It needs to fetch the account from the network to get the current\n * sequence number.\n * 2. It needs to simulate the transaction to get the expected fee.\n *\n * If you don't want to simulate the transaction, you can set `simulate` to\n * `false` in the options.\n *\n * If you need to create an operation other than `invokeHostFunction`, you\n * can use {@link AssembledTransaction.buildWithOp} instead.\n *\n * @example\n * ```ts\n * const tx = await AssembledTransaction.build({\n * ...,\n * simulate: false,\n * })\n * ```\n */\n static build<T>(\n options: AssembledTransactionOptions<T>,\n ): Promise<AssembledTransaction<T>> {\n const contract = new Contract(options.contractId);\n return AssembledTransaction.buildWithOp(\n contract.call(options.method, ...(options.args ?? [])),\n options,\n );\n }\n\n /**\n * Construct a new AssembledTransaction, specifying an Operation other than\n * `invokeHostFunction` (the default used by {@link AssembledTransaction.build}).\n *\n * Note: `AssembledTransaction` currently assumes these operations can be\n * simulated. This is not true for classic operations; only for those used by\n * Soroban Smart Contracts like `invokeHostFunction` and `createCustomContract`.\n *\n * @example\n * ```ts\n * const tx = await AssembledTransaction.buildWithOp(\n * Operation.createCustomContract({ ... });\n * {\n * ...,\n * simulate: false,\n * }\n * )\n * ```\n */\n static async buildWithOp<T>(\n operation: xdr.Operation,\n options: AssembledTransactionOptions<T>,\n ): Promise<AssembledTransaction<T>> {\n const tx = new AssembledTransaction(options);\n tx.originalOp = operation;\n const account = await getAccount(options, tx.server);\n tx.raw = new TransactionBuilder(account, {\n fee: options.fee ?? BASE_FEE,\n networkPassphrase: options.networkPassphrase,\n })\n .setTimeout(options.timeoutInSeconds ?? DEFAULT_TIMEOUT)\n .addOperation(operation);\n\n if (options.simulate) await tx.simulate();\n\n return tx;\n }\n\n private static async buildFootprintRestoreTransaction<T>(\n options: AssembledTransactionOptions<T>,\n sorobanData: SorobanDataBuilder | xdr.SorobanTransactionData,\n account: Account,\n fee: string,\n ): Promise<AssembledTransaction<T>> {\n const tx = new AssembledTransaction(options);\n tx.raw = new TransactionBuilder(account, {\n fee,\n networkPassphrase: options.networkPassphrase,\n })\n .setSorobanData(\n sorobanData instanceof SorobanDataBuilder\n ? sorobanData.build()\n : sorobanData,\n )\n .addOperation(Operation.restoreFootprint({}))\n .setTimeout(options.timeoutInSeconds ?? DEFAULT_TIMEOUT);\n await tx.simulate({ restore: false });\n return tx;\n }\n\n simulate = async ({ restore }: { restore?: boolean } = {}): Promise<this> => {\n if (!this.built) {\n if (!this.raw) {\n throw new Error(\n \"Transaction has not yet been assembled; \" +\n \"call `AssembledTransaction.build` first.\",\n );\n }\n this.built = this.raw.build();\n }\n restore = restore ?? this.options.restore;\n\n // need to force re-calculation of simulationData for new simulation\n delete this.simulationResult;\n delete this.simulationTransactionData;\n this.simulation = await this.server.simulateTransaction(this.built);\n\n if (restore && Api.isSimulationRestore(this.simulation)) {\n const account = await getAccount(this.options, this.server);\n const result = await this.restoreFootprint(\n this.simulation.restorePreamble,\n account,\n );\n if (result.status === Api.GetTransactionStatus.SUCCESS) {\n // need to rebuild the transaction with bumped account sequence number\n const op = this.originalOp\n ? this.originalOp\n : new Contract(this.options.contractId).call(\n this.options.method,\n ...(this.options.args ?? []),\n );\n this.raw = new TransactionBuilder(account, {\n fee: this.options.fee ?? BASE_FEE,\n networkPassphrase: this.options.networkPassphrase,\n })\n .addOperation(op)\n .setTimeout(this.options.timeoutInSeconds ?? DEFAULT_TIMEOUT);\n delete this.built;\n await this.simulate();\n return this;\n }\n throw new AssembledTransaction.Errors.RestorationFailure(\n `Automatic restore failed! You set 'restore: true' but the attempted restore did not work. Result:\\n${JSON.stringify(result)}`,\n );\n }\n\n if (Api.isSimulationSuccess(this.simulation)) {\n this.built = assembleTransaction(this.built, this.simulation).build();\n }\n\n return this;\n };\n\n get simulationData(): {\n result: Api.SimulateHostFunctionResult;\n transactionData: xdr.SorobanTransactionData;\n } {\n if (this.simulationResult && this.simulationTransactionData) {\n return {\n result: this.simulationResult,\n transactionData: this.simulationTransactionData,\n };\n }\n const simulation = this.simulation!;\n if (!simulation) {\n throw new AssembledTransaction.Errors.NotYetSimulated(\n \"Transaction has not yet been simulated\",\n );\n }\n if (Api.isSimulationError(simulation)) {\n throw new AssembledTransaction.Errors.SimulationFailed(\n `Transaction simulation failed: \"${simulation.error}\"`,\n );\n }\n\n if (Api.isSimulationRestore(simulation)) {\n throw new AssembledTransaction.Errors.ExpiredState(\n `You need to restore some contract state before you can invoke this method.\\n` +\n \"You can set `restore` to true in the method options in order to \" +\n \"automatically restore the contract state when needed.\",\n );\n }\n\n // add to object for serialization & deserialization\n this.simulationResult = simulation.result ?? {\n auth: [],\n retval: xdr.ScVal.scvVoid(),\n };\n this.simulationTransactionData = simulation.transactionData.build();\n\n return {\n result: this.simulationResult,\n transactionData: this.simulationTransactionData!,\n };\n }\n\n get result(): T {\n try {\n if (!this.simulationData.result) {\n throw new Error(\"No simulation result!\");\n }\n return this.options.parseResultXdr(this.simulationData.result.retval);\n } catch (e) {\n if (!implementsToString(e)) throw e;\n const err = this.parseError(e.toString());\n if (err) return err as T;\n throw e;\n }\n }\n\n private parseError(errorMessage: string) {\n if (!this.options.errorTypes) return undefined;\n const match = errorMessage.match(contractErrorPattern);\n if (!match) return undefined;\n const i = parseInt(match[1], 10);\n const err = this.options.errorTypes[i];\n if (!err) return undefined;\n return new Err(err);\n }\n\n /**\n * Sign the transaction with the signTransaction function included previously.\n * If you did not previously include one, you need to include one now.\n */\n sign = async ({\n force = false,\n signTransaction = this.options.signTransaction,\n }: {\n /**\n * If `true`, sign and send the transaction even if it is a read call\n */\n force?: boolean;\n /**\n * You must provide this here if you did not provide one before\n */\n signTransaction?: ClientOptions[\"signTransaction\"];\n } = {}): Promise<void> => {\n if (!this.built) {\n throw new Error(\"Transaction has not yet been simulated\");\n }\n\n if (!force && this.isReadCall) {\n throw new AssembledTransaction.Errors.NoSignatureNeeded(\n \"This is a read call. It requires no signature or sending. \" +\n \"Use `force: true` to sign and send anyway.\",\n );\n }\n\n if (!signTransaction) {\n throw new AssembledTransaction.Errors.NoSigner(\n \"You must provide a signTransaction function, either when calling \" +\n \"`signAndSend` or when initializing your Client\",\n );\n }\n\n if (!this.options.publicKey) {\n throw new AssembledTransaction.Errors.FakeAccount(\n \"This transaction was constructed using a default account. Provide a valid publicKey in the AssembledTransactionOptions.\",\n );\n }\n\n // filter out contracts, as these are dealt with via cross contract calls\n const sigsNeeded = this.needsNonInvokerSigningBy().filter(\n (id) => !id.startsWith(\"C\"),\n );\n if (sigsNeeded.length) {\n throw new AssembledTransaction.Errors.NeedsMoreSignatures(\n `Transaction requires signatures from ${sigsNeeded}. ` +\n \"See `needsNonInvokerSigningBy` for details.\",\n );\n }\n\n const timeoutInSeconds = this.options.timeoutInSeconds ?? DEFAULT_TIMEOUT;\n this.built = TransactionBuilder.cloneFrom(this.built!, {\n fee: this.built!.fee,\n timebounds: undefined,\n sorobanData: this.simulationData.transactionData,\n })\n .setTimeout(timeoutInSeconds)\n .build();\n\n const signOpts: Parameters<\n NonNullable<ClientOptions[\"signTransaction\"]>\n >[1] = {\n networkPassphrase: this.options.networkPassphrase,\n };\n\n if (this.options.address) signOpts.address = this.options.address;\n if (this.options.submit !== undefined)\n signOpts.submit = this.options.submit;\n if (this.options.submitUrl) signOpts.submitUrl = this.options.submitUrl;\n\n const { signedTxXdr: signature, error } = await signTransaction(\n this.built.toXDR(),\n signOpts,\n );\n\n this.handleWalletError(error);\n\n this.signed = TransactionBuilder.fromXDR(\n signature,\n this.options.networkPassphrase,\n ) as Tx;\n };\n\n /**\n * Sends the transaction to the network to return a `SentTransaction` that\n * keeps track of all the attempts to fetch the transaction. Optionally pass\n * a {@link Watcher} that allows you to keep track of the progress as the\n * transaction is sent and processed.\n */\n async send(watcher?: Watcher) {\n if (!this.signed) {\n throw new Error(\n \"The transaction has not yet been signed. Run `sign` first, or use `signAndSend` instead.\",\n );\n }\n const sent = await SentTransaction.init(this, watcher);\n return sent;\n }\n\n /**\n * Sign the transaction with the `signTransaction` function included previously.\n * If you did not previously include one, you need to include one now.\n * After signing, this method will send the transaction to the network and\n * return a `SentTransaction` that keeps track of all the attempts to fetch\n * the transaction. You may pass a {@link Watcher} to keep\n * track of this progress.\n */\n signAndSend = async ({\n force = false,\n signTransaction = this.options.signTransaction,\n watcher,\n }: {\n /**\n * If `true`, sign and send the transaction even if it is a read call\n */\n force?: boolean;\n /**\n * You must provide this here if you did not provide one before\n */\n signTransaction?: ClientOptions[\"signTransaction\"];\n /**\n * A {@link Watcher} to notify after the transaction is successfully\n * submitted to the network (`onSubmitted`) and as the transaction is\n * processed (`onProgress`).\n */\n watcher?: Watcher;\n } = {}): Promise<SentTransaction<T>> => {\n if (!this.signed) {\n // Wrap signTransaction to disable submit and prevent double submission,\n // without mutating the shared this.options object\n const signer = signTransaction || this.options.signTransaction;\n const wrappedSignTransaction: typeof signTransaction =\n this.options.submit && signer\n ? (tx, opts) => signer(tx, { ...opts, submit: false })\n : signTransaction;\n\n await this.sign({ force, signTransaction: wrappedSignTransaction });\n }\n return this.send(watcher);\n };\n\n /**\n * Get a list of accounts, other than the invoker of the simulation, that\n * need to sign auth entries in this transaction.\n *\n * Soroban allows multiple people to sign a transaction. Someone needs to\n * sign the final transaction envelope; this person/account is called the\n * _invoker_, or _source_. Other accounts might need to sign individual auth\n * entries in the transaction, if they're not also the invoker.\n *\n * This function returns a list of accounts that need to sign auth entries,\n * assuming that the same invoker/source account will sign the final\n * transaction envelope as signed the initial simulation.\n *\n * One at a time, for each public key in this array, you will need to\n * serialize this transaction with `toJSON`, send to the owner of that key,\n * deserialize the transaction with `txFromJson`, and call\n * {@link AssembledTransaction.signAuthEntries}. Then re-serialize and send to\n * the next account in this list.\n */\n needsNonInvokerSigningBy = ({\n includeAlreadySigned = false,\n }: {\n /**\n * Whether or not to include auth entries that have already been signed.\n * Default: false\n */\n includeAlreadySigned?: boolean;\n } = {}): string[] => {\n if (!this.built) {\n throw new Error(\"Transaction has not yet been simulated\");\n }\n\n // We expect that any transaction constructed by these libraries has a\n // single operation, which is an InvokeHostFunction operation. The host\n // function being invoked is the contract method call.\n if (!(\"operations\" in this.built)) {\n throw new Error(\n `Unexpected Transaction type; no operations: ${JSON.stringify(\n this.built,\n )}`,\n );\n }\n const rawInvokeHostFunctionOp = this.built\n .operations[0] as Operation.InvokeHostFunction;\n\n return [\n ...new Set(\n (rawInvokeHostFunctionOp.auth ?? [])\n .map((entry) => inspectAuthEntry(entry))\n .filter(\n (info) =>\n // skip source-account credentials (no address payload), which\n // are covered by the envelope signature on the source account.\n // Only the top-level credentials (signers[0]) matter here — this\n // method reports (and signAuthEntries signs) the top-level\n // address, so unsigned delegate nodes must not keep it listed.\n info.address !== null &&\n (includeAlreadySigned || !info.signers[0].signed),\n )\n .map((info) => info.address as string),\n ),\n ];\n };\n\n /**\n * If {@link AssembledTransaction.needsNonInvokerSigningBy} returns a\n * non-empty list, you can serialize the transaction with `toJSON`, send it to\n * the owner of one of the public keys in the map, deserialize with\n * `txFromJSON`, and call this method on their machine. Internally, this will\n * use `signAuthEntry` function from connected `wallet` for each.\n *\n * Then, re-serialize the transaction and either send to the next\n * `needsNonInvokerSigningBy` owner, or send it back to the original account\n * who simulated the transaction so they can {@link AssembledTransaction.sign}\n * the transaction envelope and {@link AssembledTransaction.send} it to the\n * network.\n *\n * Sending to all `needsNonInvokerSigningBy` owners in parallel is not\n * currently supported!\n */\n signAuthEntries = async ({\n expiration = (async () =>\n (await this.server.getLatestLedger()).sequence + 100)(),\n signAuthEntry = this.options.signAuthEntry,\n address = this.options.publicKey,\n authorizeEntry = stellarBaseAuthorizeEntry,\n }: {\n /**\n * When to set each auth entry to expire. Could be any number of blocks in\n * the future. Can be supplied as a promise or a raw number. Default:\n * about 8.3 minutes from now.\n */\n expiration?: number | Promise<number>;\n /**\n * Sign all auth entries for this account. Default: the account that\n * constructed the transaction\n */\n address?: string;\n /**\n * You must provide this here if you did not provide one before and you are not passing `authorizeEntry`. Default: the `signAuthEntry` function from the `Client` options. Must sign things as the given `publicKey`.\n */\n signAuthEntry?: ClientOptions[\"signAuthEntry\"];\n\n /**\n * If you have a pro use-case and need to override the default `authorizeEntry` function, rather than using the one in `@stellar/stellar-base`, you can do that! Your function needs to take at least the first argument, `entry: xdr.SorobanAuthorizationEntry`, and return a `Promise<xdr.SorobanAuthorizationEntry>`.\n *\n * Note that you if you pass this, then `signAuthEntry` will be ignored.\n */\n authorizeEntry?: typeof stellarBaseAuthorizeEntry;\n } = {}): Promise<void> => {\n if (!this.built)\n throw new Error(\"Transaction has not yet been assembled or simulated\");\n\n // Likely if we're using a custom authorizeEntry then we know better than the `needsNonInvokerSigningBy` logic.\n if (authorizeEntry === stellarBaseAuthorizeEntry) {\n const needsNonInvokerSigningBy = this.needsNonInvokerSigningBy();\n if (needsNonInvokerSigningBy.length === 0) {\n throw new AssembledTransaction.Errors.NoUnsignedNonInvokerAuthEntries(\n \"No unsigned non-invoker auth entries; maybe you already signed?\",\n );\n }\n if (needsNonInvokerSigningBy.indexOf(address ?? \"\") === -1) {\n throw new AssembledTransaction.Errors.NoSignatureNeeded(\n `No auth entries for public key \"${address}\"`,\n );\n }\n if (!signAuthEntry) {\n throw new AssembledTransaction.Errors.NoSigner(\n \"You must provide `signAuthEntry` or a custom `authorizeEntry`\",\n );\n }\n }\n\n const rawInvokeHostFunctionOp = this.built\n .operations[0] as Operation.InvokeHostFunction;\n\n const authEntries = rawInvokeHostFunctionOp.auth ?? [];\n\n for (const [i, entry] of authEntries.entries()) {\n // workaround for https://github.com/stellar/js-stellar-sdk/issues/1070\n const credentials = xdr.SorobanCredentials.fromXDR(\n entry.credentials().toXDR(),\n );\n const addrAuth = getAddressCredentials(credentials);\n if (addrAuth === null) {\n // if the invoker/source account, then the entry doesn't need explicit\n // signature, since the tx envelope is already signed by the source\n // account, so only address-based credentials need signing here\n continue;\n }\n const authEntryAddress = Address.fromScAddress(\n addrAuth.address(),\n ).toString();\n\n // this auth entry needs to be signed by a different account\n // (or maybe already was!)\n if (authEntryAddress !== address) continue;\n\n const sign: typeof signAuthEntry = signAuthEntry ?? Promise.resolve;\n\n authEntries[i] = await authorizeEntry(\n entry,\n async (preimage) => {\n const { signedAuthEntry, error } = await sign(\n preimage.toXDR(\"base64\"),\n {\n address,\n },\n );\n this.handleWalletError(error);\n return Buffer.from(signedAuthEntry, \"base64\");\n },\n await expiration,\n this.options.networkPassphrase,\n );\n }\n };\n\n /**\n * Whether this transaction is a read call. This is determined by the\n * simulation result and the transaction data. If the transaction is a read\n * call, it will not need to be signed and sent to the network. If this\n * returns `false`, then you need to call `signAndSend` on this transaction.\n */\n get isReadCall(): boolean {\n const authsCount = this.simulationData.result.auth.length;\n const writeLength = this.simulationData.transactionData\n .resources()\n .footprint()\n .readWrite().length;\n return authsCount === 0 && writeLength === 0;\n }\n\n /**\n * Restores the footprint (resource ledger entries that can be read or written)\n * of an expired transaction.\n *\n * The method will:\n * 1. Build a new transaction aimed at restoring the necessary resources.\n * 2. Sign this new transaction if a `signTransaction` handler is provided.\n * 3. Send the signed transaction to the network.\n * 4. Await and return the response from the network.\n *\n * Preconditions:\n * - A `signTransaction` function must be provided during the Client initialization.\n * - The provided `restorePreamble` should include a minimum resource fee and valid\n * transaction data.\n *\n * @throws - Throws an error if no `signTransaction` function is provided during\n * Client initialization.\n * @throws - Throws a custom error if the\n * restore transaction fails, providing the details of the failure.\n */\n async restoreFootprint(\n /**\n * The preamble object containing data required to\n * build the restore transaction.\n */\n restorePreamble: {\n minResourceFee: string;\n transactionData: SorobanDataBuilder;\n },\n /** The account that is executing the footprint restore operation. If omitted, will use the account from the AssembledTransaction. */\n account?: Account,\n ): Promise<Api.GetTransactionResponse> {\n if (!this.options.signTransaction) {\n throw new Error(\n \"For automatic restore to work you must provide a signTransaction function when initializing your Client\",\n );\n }\n account = account ?? (await getAccount(this.options, this.server));\n // first try restoring the contract\n const restoreTx =\n await AssembledTransaction.buildFootprintRestoreTransaction(\n { ...this.options },\n restorePreamble.transactionData,\n account,\n restorePreamble.minResourceFee,\n );\n const sentTransaction = await restoreTx.signAndSend();\n if (!sentTransaction.getTransactionResponse) {\n throw new AssembledTransaction.Errors.RestorationFailure(\n `The attempt at automatic restore failed. \\n${JSON.stringify(sentTransaction)}`,\n );\n }\n return sentTransaction.getTransactionResponse;\n }\n}\n"],"names":["Server","xdr","authorizeEntry","stellarBaseAuthorizeEntry"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiQO,MAAM,oBAAA,CAAwB;AAAA,EA6R3B,YAAmB,OAAA,EAAyC;AAAzC,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AACzB,IAAA,IAAA,CAAK,OAAA,CAAQ,QAAA,GAAW,IAAA,CAAK,OAAA,CAAQ,QAAA,IAAY,IAAA;AACjD,IAAA,MAAM,EAAE,MAAA,EAAQ,SAAA,EAAW,OAAA,EAAS,MAAA,KAAW,IAAA,CAAK,OAAA;AACpD,IAAA,IAAA,CAAK,MAAA,GAAS,UAAU,IAAIA,SAAA,CAAO,QAAQ,EAAE,SAAA,EAAW,SAAS,CAAA;AAAA,EACnE;AAAA,EAJ2B,OAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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