@stellar/stellar-sdk 16.0.0-rc.1 → 16.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +22 -28
  2. package/dist/stellar-sdk-axios.js +247 -232
  3. package/dist/stellar-sdk-axios.js.map +1 -1
  4. package/dist/stellar-sdk-axios.min.js +1 -1
  5. package/dist/stellar-sdk-axios.min.js.map +1 -1
  6. package/dist/stellar-sdk.js +50 -35
  7. package/dist/stellar-sdk.js.map +1 -1
  8. package/dist/stellar-sdk.min.js +1 -1
  9. package/dist/stellar-sdk.min.js.map +1 -1
  10. package/lib/axios/cjs/base/auth.js +11 -11
  11. package/lib/axios/cjs/base/auth.js.map +1 -1
  12. package/lib/axios/cjs/base/keypair.js +1 -1
  13. package/lib/axios/cjs/base/keypair.js.map +1 -1
  14. package/lib/axios/cjs/bindings/config.js +1 -1
  15. package/lib/axios/cjs/contract/assembled_transaction.js +6 -1
  16. package/lib/axios/cjs/contract/assembled_transaction.js.map +1 -1
  17. package/lib/axios/cjs/contract/types.js.map +1 -1
  18. package/lib/axios/cjs/horizon/horizon_axios_client.js +1 -1
  19. package/lib/axios/cjs/rpc/axios.js +1 -1
  20. package/lib/axios/cjs/rpc/server.js +13 -4
  21. package/lib/axios/cjs/rpc/server.js.map +1 -1
  22. package/lib/axios/esm/base/auth.d.ts +19 -7
  23. package/lib/axios/esm/base/auth.js +11 -11
  24. package/lib/axios/esm/base/auth.js.map +1 -1
  25. package/lib/axios/esm/base/keypair.js +1 -1
  26. package/lib/axios/esm/base/keypair.js.map +1 -1
  27. package/lib/axios/esm/bindings/config.js +1 -1
  28. package/lib/axios/esm/contract/assembled_transaction.js +6 -1
  29. package/lib/axios/esm/contract/assembled_transaction.js.map +1 -1
  30. package/lib/axios/esm/contract/types.d.ts +9 -0
  31. package/lib/axios/esm/contract/types.js.map +1 -1
  32. package/lib/axios/esm/horizon/horizon_axios_client.js +1 -1
  33. package/lib/axios/esm/rpc/axios.js +1 -1
  34. package/lib/axios/esm/rpc/server.d.ts +7 -2
  35. package/lib/axios/esm/rpc/server.js +13 -4
  36. package/lib/axios/esm/rpc/server.js.map +1 -1
  37. package/lib/cjs/base/auth.js +11 -11
  38. package/lib/cjs/base/auth.js.map +1 -1
  39. package/lib/cjs/base/keypair.js +1 -1
  40. package/lib/cjs/base/keypair.js.map +1 -1
  41. package/lib/cjs/bindings/config.js +1 -1
  42. package/lib/cjs/contract/assembled_transaction.js +6 -1
  43. package/lib/cjs/contract/assembled_transaction.js.map +1 -1
  44. package/lib/cjs/contract/types.js.map +1 -1
  45. package/lib/cjs/horizon/horizon_axios_client.js +1 -1
  46. package/lib/cjs/rpc/axios.js +1 -1
  47. package/lib/cjs/rpc/server.js +13 -4
  48. package/lib/cjs/rpc/server.js.map +1 -1
  49. package/lib/esm/base/auth.d.ts +19 -7
  50. package/lib/esm/base/auth.js +11 -11
  51. package/lib/esm/base/auth.js.map +1 -1
  52. package/lib/esm/base/keypair.js +1 -1
  53. package/lib/esm/base/keypair.js.map +1 -1
  54. package/lib/esm/bindings/config.js +1 -1
  55. package/lib/esm/contract/assembled_transaction.js +6 -1
  56. package/lib/esm/contract/assembled_transaction.js.map +1 -1
  57. package/lib/esm/contract/types.d.ts +9 -0
  58. package/lib/esm/contract/types.js.map +1 -1
  59. package/lib/esm/horizon/horizon_axios_client.js +1 -1
  60. package/lib/esm/rpc/axios.js +1 -1
  61. package/lib/esm/rpc/server.d.ts +7 -2
  62. package/lib/esm/rpc/server.js +13 -4
  63. package/lib/esm/rpc/server.js.map +1 -1
  64. package/package.json +1 -1
@@ -79,7 +79,8 @@ function authorizeInvocation(params) {
79
79
  validUntilLedgerSeq,
80
80
  invocation,
81
81
  networkPassphrase,
82
- publicKey = ""
82
+ publicKey = "",
83
+ authV2 = false
83
84
  } = params;
84
85
  const kp = keypair.Keypair.random().rawPublicKey();
85
86
  const nonce = new curr_generated.default.Int64(bytesToInt64(kp));
@@ -87,18 +88,17 @@ function authorizeInvocation(params) {
87
88
  if (!pk) {
88
89
  throw new Error(`authorizeInvocation requires publicKey parameter`);
89
90
  }
91
+ const addressCredentials = new curr_generated.default.SorobanAddressCredentials({
92
+ address: new address.Address(pk).toScAddress(),
93
+ nonce,
94
+ signatureExpirationLedger: 0,
95
+ // replaced
96
+ signature: curr_generated.default.ScVal.scvVec([])
97
+ // replaced
98
+ });
90
99
  const entry = new curr_generated.default.SorobanAuthorizationEntry({
91
100
  rootInvocation: invocation,
92
- credentials: curr_generated.default.SorobanCredentials.sorobanCredentialsAddressV2(
93
- new curr_generated.default.SorobanAddressCredentials({
94
- address: new address.Address(pk).toScAddress(),
95
- nonce,
96
- signatureExpirationLedger: 0,
97
- // replaced
98
- signature: curr_generated.default.ScVal.scvVec([])
99
- // replaced
100
- })
101
- )
101
+ credentials: authV2 ? curr_generated.default.SorobanCredentials.sorobanCredentialsAddressV2(addressCredentials) : curr_generated.default.SorobanCredentials.sorobanCredentialsAddress(addressCredentials)
102
102
  });
103
103
  return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase);
104
104
  }
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sources":["../../../../src/base/auth.ts"],"sourcesContent":["import xdr from \"./xdr.js\";\n\nimport { Keypair } from \"./keypair.js\";\nimport { StrKey } from \"./strkey.js\";\n\nimport type { Networks } from \"./network.js\";\nimport { hash } from \"./hashing.js\";\n\nimport { Address } from \"./address.js\";\nimport { nativeToScVal } from \"./scval.js\";\n\ntype BufferLike = ArrayBuffer | Buffer | Uint8Array;\n\nfunction toBuffer(value: BufferLike): Buffer {\n if (value instanceof ArrayBuffer) {\n return Buffer.from(new Uint8Array(value));\n }\n return Buffer.from(value);\n}\n\n/**\n * A callback for signing an XDR structure representing all of the details\n * necessary to authorize an invocation tree.\n *\n * @param preimage - the entire authorization envelope whose hash you should\n * sign, so that you can inspect the entire structure if necessary (rather\n * than blindly signing a hash)\n *\n * @returns the signature of the raw payload (which is the sha256 hash of the\n * preimage bytes, so `hash(preimage.toXDR())`) either naked, implying it is\n * signed by the key corresponding to the public key in the entry you pass to\n * {@link authorizeEntry} (decipherable from its\n * `credentials().address().address()`), or alongside an explicit `publicKey`.\n */\nexport type SigningCallback = (\n preimage: xdr.HashIdPreimage,\n) => Promise<BufferLike | { signature: BufferLike; publicKey: string }>;\n\n/**\n * Actually authorizes an existing authorization entry using the given\n * credentials and expiration details, returning a signed copy.\n *\n * This \"fills out\" the authorization entry with a signature, indicating to the\n * {@link Operation.invokeHostFunction} its attached to that:\n * - a particular identity (i.e. signing {@link Keypair} or other signer)\n * - approving the execution of an invocation tree (i.e. a simulation-acquired\n * {@link xdr.SorobanAuthorizedInvocation} or otherwise built)\n * - on a particular network (uniquely identified by its passphrase, see\n * {@link Networks})\n * - until a particular ledger sequence is reached.\n *\n * This one lets you pass either a {@link Keypair} (or, more accurately,\n * anything with a `sign(Buffer): Buffer` method) or a callback function (see\n * {@link SigningCallback}) to handle signing the envelope hash.\n *\n * @param entry - an unsigned authorization entry\n * @param signer - either a {@link Keypair} instance or a function which takes a\n * {@link xdr.HashIdPreimageSorobanAuthorization} input payload and returns\n * EITHER\n *\n * (a) an object containing a `signature` of the hash of the raw payload\n * bytes as a Buffer-like and a `publicKey` string representing who just\n * created this signature, or\n * (b) just the naked signature of the hash of the raw payload bytes (where\n * the signing key is implied to be the address in the `entry`).\n *\n * The latter option (b) is JUST for backwards compatibility and will be\n * removed in the future.\n * @param validUntilLedgerSeq - the (exclusive) future ledger sequence number\n * until which this authorization entry should be valid (if\n * `currentLedgerSeq==validUntil`, this is expired)\n * @param networkPassphrase - the network passphrase is incorporated into the\n * signature (see {@link Networks} for options)\n *\n * If using the `SigningCallback` variation, the signer is assumed to be\n * the entry's credential address unless you use the variant that returns\n * the object.\n *\n * @param forAddress - which credential node the signature should be written\n * to. Only relevant for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`, where\n * a single entry can be signed by the top-level account and/or any of its\n * (possibly nested) delegates. Per CAP-71-01 every one of these signers\n * signs the *same* payload (bound to the top-level address), so the\n * signature produced here is written to whichever node(s) carry\n * `forAddress`. When omitted, the signature is written to the top-level\n * credentials, which preserves the behavior for `SOROBAN_CREDENTIALS_ADDRESS`\n * / `SOROBAN_CREDENTIALS_ADDRESS_V2` and for accounts whose signing key\n * differs from the credential address (e.g. multisig).\n *\n * @see authorizeInvocation\n * @example\n * ```ts\n * import {\n * SorobanRpc,\n * Transaction,\n * Networks,\n * authorizeEntry\n * } from '@stellar/stellar-sdk';\n *\n * // Assume signPayloadCallback is a well-formed signing callback.\n * //\n * // It might, for example, pop up a modal from a browser extension, send the\n * // transaction to a third-party service for signing, or just do simple\n * // signing via Keypair like it does here:\n * function signPayloadCallback(payload) {\n * return signer.sign(hash(payload.toXDR()));\n * }\n *\n * function multiPartyAuth(\n * server: SorobanRpc.Server,\n * // assume this involves multi-party auth\n * tx: Transaction,\n * ) {\n * return server\n * .simulateTransaction(tx)\n * .then((simResult) => {\n * tx.operations[0].auth.map(entry =>\n * authorizeEntry(\n * entry,\n * signPayloadCallback,\n * currentLedger + 1000,\n * Networks.TESTNET)\n * );\n *\n * return server.prepareTransaction(tx, simResult);\n * })\n * .then((preppedTx) => {\n * preppedTx.sign(source);\n * return server.sendTransaction(preppedTx);\n * });\n * }\n * ```\n */\nexport async function authorizeEntry(\n entry: xdr.SorobanAuthorizationEntry,\n signer: Keypair | SigningCallback,\n validUntilLedgerSeq: number,\n networkPassphrase: string,\n forAddress?: string,\n): Promise<xdr.SorobanAuthorizationEntry> {\n // no-op if it's source account auth\n if (\n entry.credentials().switch().value ===\n xdr.SorobanCredentialsType.sorobanCredentialsSourceAccount().value\n ) {\n return entry;\n }\n\n const clone = xdr.SorobanAuthorizationEntry.fromXDR(entry.toXDR());\n const credentials = clone.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (addrAuth === null) {\n // We should have already returned if the credentials were source account credentials,\n // so if we can't get address credentials out of this, it's an unsupported credential type.\n throw new Error(`unsupported credential type ${credentials.switch().name}`);\n }\n\n // Set the expiration before building the preimage, so the hash that gets\n // signed commits to the same expiration ledger stored in the credentials.\n // Otherwise the network reconstructs the preimage from the (updated)\n // credentials and the signature no longer matches.\n addrAuth.signatureExpirationLedger(validUntilLedgerSeq);\n\n const preimage = buildAuthorizationEntryPreimage(\n clone,\n validUntilLedgerSeq,\n networkPassphrase,\n );\n\n const payload = hash(preimage.toXDR());\n\n let signature: Buffer;\n let publicKey: string;\n if (typeof signer === \"function\") {\n const sigResult = await signer(preimage);\n if (\n sigResult !== null &&\n typeof sigResult === \"object\" &&\n \"signature\" in sigResult\n ) {\n signature = toBuffer(sigResult.signature);\n publicKey = sigResult.publicKey;\n } else {\n // if using the deprecated form, assume it's for the entry\n signature = toBuffer(sigResult);\n publicKey = Address.fromScAddress(addrAuth.address()).toString();\n }\n } else {\n signature = toBuffer(signer.sign(payload));\n publicKey = signer.publicKey();\n }\n\n if (!Keypair.fromPublicKey(publicKey).verify(payload, signature)) {\n throw new Error(`signature doesn't match payload`);\n }\n\n // This structure is defined here:\n // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures\n //\n // Encoding a contract structure as an ScVal means the map keys are supposed\n // to be symbols, hence the forced typing here.\n const sigScVal = nativeToScVal(\n {\n public_key: StrKey.decodeEd25519PublicKey(publicKey),\n signature,\n },\n {\n type: {\n public_key: [\"symbol\", null],\n signature: [\"symbol\", null],\n },\n },\n );\n\n const signatureScVal = xdr.ScVal.scvVec([sigScVal]);\n\n // CAP-71-01: the signature payload is shared across the top-level address\n // and every (possibly nested) delegate, so this signer's signature is\n // written to whichever credential node(s) carry `forAddress`. When no\n // `forAddress` is given we fall back to the top-level credentials, which\n // preserves the behavior for ADDRESS / ADDRESS_V2 and for accounts whose\n // signing key differs from the credential address (e.g. multisig).\n const targets: SignableCredential[] =\n forAddress === undefined\n ? [addrAuth]\n : collectSignatureNodes(credentials).filter(\n (node) =>\n Address.fromScAddress(node.address()).toString() === forAddress,\n );\n\n if (targets.length === 0) {\n throw new Error(\n `the authorization entry has no credential node for address ${forAddress}`,\n );\n }\n\n targets.forEach((node) => node.signature(signatureScVal));\n return clone;\n}\n\n/**\n * This builds an entry from scratch, allowing you to express authorization as a\n * function of:\n * - a particular identity (i.e. signing {@link Keypair} or other signer)\n * - approving the execution of an invocation tree (i.e. a simulation-acquired\n * {@link xdr.SorobanAuthorizedInvocation} or otherwise built)\n * - on a particular network (uniquely identified by its passphrase, see\n * {@link Networks})\n * - until a particular ledger sequence is reached.\n *\n * This is in contrast to {@link authorizeEntry}, which signs an existing entry.\n *\n * @param params - the parameters for building and signing the authorization\n * - `signer`: either a {@link Keypair} instance (or anything with a\n * `.sign(buf): Buffer-like` method) or a function which takes a payload (a\n * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns\n * the signature of the hash of the raw payload bytes (where the signing key\n * should correspond to the address in the `entry`)\n * - `validUntilLedgerSeq`: the (exclusive) future ledger sequence\n * number until which this authorization entry should be valid (if\n * `currentLedgerSeq==validUntilLedgerSeq`, this is expired)\n * - `invocation`: the invocation tree that we're authorizing\n * (likely, this comes from transaction simulation)\n * - `networkPassphrase`: the network passphrase is incorporated into\n * the signature (see {@link Networks} for options)\n * - `publicKey`: the public identity of the signer (when providing a\n * {@link Keypair} to `signer`, this can be omitted, as it just uses\n * {@link Keypair.publicKey})\n *\n * @see authorizeEntry\n */\nexport interface AuthorizeInvocationParams {\n signer: Keypair | SigningCallback;\n validUntilLedgerSeq: number;\n invocation: xdr.SorobanAuthorizedInvocation;\n networkPassphrase: string;\n publicKey?: string;\n}\n\nexport function authorizeInvocation(\n params: AuthorizeInvocationParams,\n): Promise<xdr.SorobanAuthorizationEntry> {\n const {\n signer,\n validUntilLedgerSeq,\n invocation,\n networkPassphrase,\n publicKey = \"\",\n } = params;\n // We use keypairs as a source of randomness for the nonce to avoid mucking\n // with any crypto dependencies. Note that this just has to be random and\n // unique, not cryptographically secure, so it's fine.\n const kp = Keypair.random().rawPublicKey();\n const nonce = new xdr.Int64(bytesToInt64(kp));\n\n const pk =\n publicKey || (signer instanceof Keypair ? signer.publicKey() : null);\n if (!pk) {\n throw new Error(`authorizeInvocation requires publicKey parameter`);\n }\n\n const entry = new xdr.SorobanAuthorizationEntry({\n rootInvocation: invocation,\n credentials: xdr.SorobanCredentials.sorobanCredentialsAddressV2(\n new xdr.SorobanAddressCredentials({\n address: new Address(pk).toScAddress(),\n nonce,\n signatureExpirationLedger: 0, // replaced\n signature: xdr.ScVal.scvVec([]), // replaced\n }),\n ),\n });\n\n return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase);\n}\n\n/**\n * Builds the {@link xdr.HashIdPreimage} whose hash a signer must sign to\n * authorize `entry`. This is the low-level signature payload used by\n * {@link authorizeEntry}, exposed for callers that drive signing themselves —\n * most notably for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`, where the\n * client (not simulation) decides which delegates sign and how.\n *\n * For `SOROBAN_CREDENTIALS_ADDRESS` this is the legacy, non-address-bound\n * `ENVELOPE_TYPE_SOROBAN_AUTHORIZATION` preimage. For `SOROBAN_CREDENTIALS_ADDRESS_V2`\n * and `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` it is the address-bound\n * `ENVELOPE_TYPE_SOROBAN_AUTHORIZATION_WITH_ADDRESS` preimage (CAP-71). For the\n * delegates variant this single payload — bound to the *top-level* address — is\n * what the top-level account and every (nested) delegate each sign.\n *\n * To get the raw bytes to sign, hash the XDR: `hash(preimage.toXDR())`.\n *\n * @param entry - the authorization entry to build the payload for\n * @param validUntilLedgerSeq - the expiration ledger committed into the payload\n * (must match the `signatureExpirationLedger` on the credentials you submit)\n * @param networkPassphrase - the network passphrase mixed into the payload\n * @throws `Error` if `entry` carries source-account or otherwise non-address\n * credentials\n */\nexport function buildAuthorizationEntryPreimage(\n entry: xdr.SorobanAuthorizationEntry,\n validUntilLedgerSeq: number,\n networkPassphrase: string,\n): xdr.HashIdPreimage {\n const credentials = entry.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (addrAuth === null) {\n throw new Error(\n `cannot build a signature payload for credential type ${credentials.switch().name}`,\n );\n }\n\n const networkId = hash(Buffer.from(networkPassphrase));\n\n switch (credentials.switch().value) {\n // legacy address credentials are not address-bound\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(\n new xdr.HashIdPreimageSorobanAuthorization({\n networkId,\n nonce: addrAuth.nonce(),\n invocation: entry.rootInvocation(),\n signatureExpirationLedger: validUntilLedgerSeq,\n }),\n );\n\n // ADDRESS_V2 and ADDRESS_WITH_DELEGATES bind the address into the signed\n // payload via the WithAddress preimage (CAP-71)\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value:\n return xdr.HashIdPreimage.envelopeTypeSorobanAuthorizationWithAddress(\n new xdr.HashIdPreimageSorobanAuthorizationWithAddress({\n networkId,\n nonce: addrAuth.nonce(),\n invocation: entry.rootInvocation(),\n address: addrAuth.address(),\n signatureExpirationLedger: validUntilLedgerSeq,\n }),\n );\n\n default:\n throw new Error(\n `unsupported credential type ${credentials.switch().name}`,\n );\n }\n}\n\n/**\n * A delegate signer to attach to a\n * `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` entry via\n * {@link buildWithDelegatesEntry}.\n */\nexport interface DelegateSignature {\n /** the delegate's address (`G…` account or `C…` contract). */\n address: string;\n /**\n * the delegate's signature value. Defaults to a `scvVoid` placeholder, which\n * you can fill afterwards with {@link authorizeEntry} (passing this address\n * as `forAddress`) or by editing the entry directly.\n */\n signature?: xdr.ScVal;\n /** signers this delegate in turn delegates to (recursive). */\n nestedDelegates?: DelegateSignature[];\n}\n\n/** Parameters for {@link buildWithDelegatesEntry}. */\nexport interface BuildWithDelegatesParams {\n /**\n * an existing `SOROBAN_CREDENTIALS_ADDRESS` or\n * `SOROBAN_CREDENTIALS_ADDRESS_V2` entry — typically one returned by\n * simulation — whose address credentials should be wrapped.\n */\n entry: xdr.SorobanAuthorizationEntry;\n /** the expiration ledger sequence stored on the top-level credentials. */\n validUntilLedgerSeq: number;\n /** the delegate signers to attach. */\n delegates: DelegateSignature[];\n /**\n * the top-level account's signature. Defaults to `scvVoid`, which is valid\n * for accounts that authorize purely via delegated signers (CAP-71-01).\n */\n signature?: xdr.ScVal;\n}\n\n/**\n * Builds a `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` authorization entry by\n * wrapping the address credentials of an existing `ADDRESS`/`ADDRESS_V2` entry\n * (e.g. one returned by simulation) together with a caller-provided set of\n * delegate signers.\n *\n * Simulation never emits the delegates variant on its own — which accounts use\n * delegated authentication is account-specific policy known only to the client\n * (much like a multisig policy). This helper just assembles the wrapper XDR;\n * you supply the delegate tree (addresses and, optionally, signatures). To\n * produce the signatures, build the shared payload with\n * {@link buildAuthorizationEntryPreimage} on the returned entry and sign it,\n * or fill each node afterwards with {@link authorizeEntry} (passing the\n * signer's address as `forAddress`).\n *\n * Each delegates array (the top-level set and every `nestedDelegates`) is\n * sorted by address in ascending order, and duplicate addresses within an array\n * are rejected, as the protocol requires (CAP-71-01) — otherwise the host\n * rejects the entry.\n *\n * @param params - see {@link BuildWithDelegatesParams}\n * @throws `Error` if `entry` is not an `ADDRESS`/`ADDRESS_V2` entry, or if any\n * delegates array contains a duplicate address.\n */\nexport function buildWithDelegatesEntry(\n params: BuildWithDelegatesParams,\n): xdr.SorobanAuthorizationEntry {\n const { entry, validUntilLedgerSeq, delegates, signature } = params;\n const credentials = entry.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (\n addrAuth === null ||\n credentials.switch().value ===\n xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value\n ) {\n throw new Error(\n `buildWithDelegatesEntry expects ADDRESS or ADDRESS_V2 credentials, got ${\n credentials.switch().name\n }`,\n );\n }\n\n return new xdr.SorobanAuthorizationEntry({\n rootInvocation: entry.rootInvocation(),\n credentials: xdr.SorobanCredentials.sorobanCredentialsAddressWithDelegates(\n new xdr.SorobanAddressCredentialsWithDelegates({\n addressCredentials: new xdr.SorobanAddressCredentials({\n address: addrAuth.address(),\n nonce: addrAuth.nonce(),\n signatureExpirationLedger: validUntilLedgerSeq,\n signature: signature ?? xdr.ScVal.scvVoid(),\n }),\n delegates: buildDelegateNodes(delegates),\n }),\n ),\n });\n}\n\n/**\n * Recursively converts {@link DelegateSignature} descriptors into\n * {@link xdr.SorobanDelegateSignature} nodes, sorting each level by address and\n * rejecting duplicates (CAP-71-01).\n */\nfunction buildDelegateNodes(\n delegates: DelegateSignature[],\n): xdr.SorobanDelegateSignature[] {\n const nodes = delegates.map(\n (delegate) =>\n new xdr.SorobanDelegateSignature({\n address: new Address(delegate.address).toScAddress(),\n signature: delegate.signature ?? xdr.ScVal.scvVoid(),\n nestedDelegates: buildDelegateNodes(delegate.nestedDelegates ?? []),\n }),\n );\n\n nodes.sort((a, b) =>\n Buffer.compare(a.address().toXDR(), b.address().toXDR()),\n );\n\n for (let i = 1; i < nodes.length; i++) {\n if (\n Buffer.compare(\n nodes[i - 1].address().toXDR(),\n nodes[i].address().toXDR(),\n ) === 0\n ) {\n throw new Error(\n `duplicate delegate address ${Address.fromScAddress(\n nodes[i].address(),\n ).toString()}`,\n );\n }\n }\n\n return nodes;\n}\n\n/**\n * Internal helper — intentionally NOT re-exported from `base/index.js`, so it\n * is not part of the public SDK API. Shared with the contract package, which\n * imports it directly from this module. If a public need arises, add it to the\n * explicit auth re-exports in `base/index.ts`.\n *\n * Extracts the {@link xdr.SorobanAddressCredentials} from any address-based\n * Soroban credential, regardless of which credential type variant is used.\n *\n * This unifies access across `SOROBAN_CREDENTIALS_ADDRESS`,\n * `SOROBAN_CREDENTIALS_ADDRESS_V2` (which carries identical fields but binds\n * the address into the signature payload), and\n * `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` (which wraps the same address\n * credentials alongside a set of delegate signatures).\n *\n * @param credentials - the credentials to inspect\n * @returns the inner address credentials, or `null` for source-account\n * credentials (which carry no address payload)\n */\nexport function getAddressCredentials(\n credentials: xdr.SorobanCredentials,\n): xdr.SorobanAddressCredentials | null {\n switch (credentials.switch().value) {\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return credentials.address();\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n return credentials.addressV2();\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value:\n return credentials.addressWithDelegates().addressCredentials();\n default:\n return null;\n }\n}\n\n/**\n * The common shape of every node in an authorization entry that can carry a\n * signature: the top-level {@link xdr.SorobanAddressCredentials} and, for the\n * delegates variant, each {@link xdr.SorobanDelegateSignature}. Both expose an\n * `address()` and a `signature()` accessor.\n */\ninterface SignableCredential {\n address(value?: xdr.ScAddress): xdr.ScAddress;\n signature(value?: xdr.ScVal): xdr.ScVal;\n}\n\n/**\n * Internal helper. Returns every node in an address-based credential that can\n * carry a signature, in a stable order: the top-level address credentials\n * first, then (only for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`) the\n * delegates and their nested delegates, depth-first. Returns an empty array\n * for source-account credentials, which carry no signature.\n *\n * Per CAP-71-01 all of these nodes commit to the same payload (the one bound to\n * the top-level address), so the caller can fill any of them with a signature\n * produced from that shared payload.\n */\nfunction collectSignatureNodes(\n credentials: xdr.SorobanCredentials,\n): SignableCredential[] {\n switch (credentials.switch().value) {\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return [credentials.address()];\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n return [credentials.addressV2()];\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value: {\n const withDelegates = credentials.addressWithDelegates();\n const nodes: SignableCredential[] = [withDelegates.addressCredentials()];\n const walk = (delegates: xdr.SorobanDelegateSignature[]) => {\n delegates.forEach((delegate) => {\n nodes.push(delegate);\n walk(delegate.nestedDelegates());\n });\n };\n walk(withDelegates.delegates());\n return nodes;\n }\n default:\n return [];\n }\n}\n\nfunction bytesToInt64(bytes: Uint8Array): bigint {\n const buf = bytes.subarray(0, 8);\n if (buf.length < 8) {\n throw new Error(\n `need at least 8 bytes to convert to Int64, got ${bytes.length}`,\n );\n }\n const view = new DataView(buf.buffer, buf.byteOffset, 8);\n const value = view.getBigInt64(0, false);\n\n return value;\n}\n"],"names":["Buffer","xdr","hash","Address","Keypair","nativeToScVal","StrKey"],"mappings":";;;;;;;;;;AAaA,SAAS,SAAS,KAAA,EAA2B;AAC3C,EAAA,IAAI,iBAAiB,WAAA,EAAa;AAChC,IAAA,OAAOA,aAAA,CAAO,IAAA,CAAK,IAAI,UAAA,CAAW,KAAK,CAAC,CAAA;AAAA,EAC1C;AACA,EAAA,OAAOA,aAAA,CAAO,KAAK,KAAK,CAAA;AAC1B;AAmHA,eAAsB,cAAA,CACpB,KAAA,EACA,MAAA,EACA,mBAAA,EACA,mBACA,UAAA,EACwC;AAExC,EAAA,IACE,KAAA,CAAM,WAAA,EAAY,CAAE,MAAA,EAAO,CAAE,UAC7BC,sBAAA,CAAI,sBAAA,CAAuB,+BAAA,EAAgC,CAAE,KAAA,EAC7D;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,QAAQA,sBAAA,CAAI,yBAAA,CAA0B,OAAA,CAAQ,KAAA,CAAM,OAAO,CAAA;AACjE,EAAA,MAAM,WAAA,GAAc,MAAM,WAAA,EAAY;AACtC,EAAA,MAAM,QAAA,GAAW,sBAAsB,WAAW,CAAA;AAClD,EAAA,IAAI,aAAa,IAAA,EAAM;AAGrB,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,4BAAA,EAA+B,YAAY,MAAA,EAAO,CAAE,IAAI,CAAA,CAAE,CAAA;AAAA,EAC5E;AAMA,EAAA,QAAA,CAAS,0BAA0B,mBAAmB,CAAA;AAEtD,EAAA,MAAM,QAA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CAAC,SAAA,KAA8C;AAC1D,QAAA,SAAA,CAAU,OAAA,CAAQ,CAAC,QAAA,KAAa;AAC9B,UAAA,KAAA,CAAM,KAAK,QAAQ,CAAA;AACnB,UAAA,IAAA,CAAK,QAAA,CAAS,iBAAiB,CAAA;AAAA,QACjC,CAAC,CAAA;AAAA,MACH,CAAA;AACA,MAAA,IAAA,CAAK,aAAA,CAAc,WAAW,CAAA;AAC9B,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,IACA;AACE,MAAA,OAAO,EAAC;AAAA;AAEd;AAEA,SAAS,aAAa,KAAA,EAA2B;AAC/C,EAAA,MAAM,GAAA,GAAM,KAAA,CAAM,QAAA,CAAS,CAAA,EAAG,CAAC,CAAA;AAC/B,EAAA,IAAI,GAAA,CAAI,SAAS,CAAA,EAAG;AAClB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,+CAAA,EAAkD,MAAM,MAAM,CAAA;AAAA,KAChE;AAAA,EACF;AACA,EAAA,MAAM,OAAO,IAAI,QAAA,CAAS,IAAI,MAAA,EAAQ,GAAA,CAAI,YAAY,CAAC,CAAA;AACvD,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,WAAA,CAAY,CAAA,EAAG,KAAK,CAAA;AAEvC,EAAA,OAAO,KAAA;AACT;;;;;;;;"}
1
+ {"version":3,"file":"auth.js","sources":["../../../../src/base/auth.ts"],"sourcesContent":["import xdr from \"./xdr.js\";\n\nimport { Keypair } from \"./keypair.js\";\nimport { StrKey } from \"./strkey.js\";\n\nimport type { Networks } from \"./network.js\";\nimport { hash } from \"./hashing.js\";\n\nimport { Address } from \"./address.js\";\nimport { nativeToScVal } from \"./scval.js\";\n\ntype BufferLike = ArrayBuffer | Buffer | Uint8Array;\n\nfunction toBuffer(value: BufferLike): Buffer {\n if (value instanceof ArrayBuffer) {\n return Buffer.from(new Uint8Array(value));\n }\n return Buffer.from(value);\n}\n\n/**\n * A callback for signing an XDR structure representing all of the details\n * necessary to authorize an invocation tree.\n *\n * @param preimage - the entire authorization envelope whose hash you should\n * sign, so that you can inspect the entire structure if necessary (rather\n * than blindly signing a hash)\n *\n * @returns the signature of the raw payload (which is the sha256 hash of the\n * preimage bytes, so `hash(preimage.toXDR())`) either naked, implying it is\n * signed by the key corresponding to the public key in the entry you pass to\n * {@link authorizeEntry} (decipherable from its\n * `credentials().address().address()`), or alongside an explicit `publicKey`.\n */\nexport type SigningCallback = (\n preimage: xdr.HashIdPreimage,\n) => Promise<BufferLike | { signature: BufferLike; publicKey: string }>;\n\n/**\n * Actually authorizes an existing authorization entry using the given\n * credentials and expiration details, returning a signed copy.\n *\n * This \"fills out\" the authorization entry with a signature, indicating to the\n * {@link Operation.invokeHostFunction} its attached to that:\n * - a particular identity (i.e. signing {@link Keypair} or other signer)\n * - approving the execution of an invocation tree (i.e. a simulation-acquired\n * {@link xdr.SorobanAuthorizedInvocation} or otherwise built)\n * - on a particular network (uniquely identified by its passphrase, see\n * {@link Networks})\n * - until a particular ledger sequence is reached.\n *\n * This one lets you pass either a {@link Keypair} (or, more accurately,\n * anything with a `sign(Buffer): Buffer` method) or a callback function (see\n * {@link SigningCallback}) to handle signing the envelope hash.\n *\n * @param entry - an unsigned authorization entry\n * @param signer - either a {@link Keypair} instance or a function which takes a\n * {@link xdr.HashIdPreimageSorobanAuthorization} input payload and returns\n * EITHER\n *\n * (a) an object containing a `signature` of the hash of the raw payload\n * bytes as a Buffer-like and a `publicKey` string representing who just\n * created this signature, or\n * (b) just the naked signature of the hash of the raw payload bytes (where\n * the signing key is implied to be the address in the `entry`).\n *\n * The latter option (b) is JUST for backwards compatibility and will be\n * removed in the future.\n * @param validUntilLedgerSeq - the (exclusive) future ledger sequence number\n * until which this authorization entry should be valid (if\n * `currentLedgerSeq==validUntil`, this is expired)\n * @param networkPassphrase - the network passphrase is incorporated into the\n * signature (see {@link Networks} for options)\n *\n * If using the `SigningCallback` variation, the signer is assumed to be\n * the entry's credential address unless you use the variant that returns\n * the object.\n *\n * @param forAddress - which credential node the signature should be written\n * to. Only relevant for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`, where\n * a single entry can be signed by the top-level account and/or any of its\n * (possibly nested) delegates. Per CAP-71-01 every one of these signers\n * signs the *same* payload (bound to the top-level address), so the\n * signature produced here is written to whichever node(s) carry\n * `forAddress`. When omitted, the signature is written to the top-level\n * credentials, which preserves the behavior for `SOROBAN_CREDENTIALS_ADDRESS`\n * / `SOROBAN_CREDENTIALS_ADDRESS_V2` and for accounts whose signing key\n * differs from the credential address (e.g. multisig).\n *\n * @see authorizeInvocation\n * @example\n * ```ts\n * import {\n * SorobanRpc,\n * Transaction,\n * Networks,\n * authorizeEntry\n * } from '@stellar/stellar-sdk';\n *\n * // Assume signPayloadCallback is a well-formed signing callback.\n * //\n * // It might, for example, pop up a modal from a browser extension, send the\n * // transaction to a third-party service for signing, or just do simple\n * // signing via Keypair like it does here:\n * function signPayloadCallback(payload) {\n * return signer.sign(hash(payload.toXDR()));\n * }\n *\n * function multiPartyAuth(\n * server: SorobanRpc.Server,\n * // assume this involves multi-party auth\n * tx: Transaction,\n * ) {\n * return server\n * .simulateTransaction(tx)\n * .then((simResult) => {\n * tx.operations[0].auth.map(entry =>\n * authorizeEntry(\n * entry,\n * signPayloadCallback,\n * currentLedger + 1000,\n * Networks.TESTNET)\n * );\n *\n * return server.prepareTransaction(tx, simResult);\n * })\n * .then((preppedTx) => {\n * preppedTx.sign(source);\n * return server.sendTransaction(preppedTx);\n * });\n * }\n * ```\n */\nexport async function authorizeEntry(\n entry: xdr.SorobanAuthorizationEntry,\n signer: Keypair | SigningCallback,\n validUntilLedgerSeq: number,\n networkPassphrase: string,\n forAddress?: string,\n): Promise<xdr.SorobanAuthorizationEntry> {\n // no-op if it's source account auth\n if (\n entry.credentials().switch().value ===\n xdr.SorobanCredentialsType.sorobanCredentialsSourceAccount().value\n ) {\n return entry;\n }\n\n const clone = xdr.SorobanAuthorizationEntry.fromXDR(entry.toXDR());\n const credentials = clone.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (addrAuth === null) {\n // We should have already returned if the credentials were source account credentials,\n // so if we can't get address credentials out of this, it's an unsupported credential type.\n throw new Error(`unsupported credential type ${credentials.switch().name}`);\n }\n\n // Set the expiration before building the preimage, so the hash that gets\n // signed commits to the same expiration ledger stored in the credentials.\n // Otherwise the network reconstructs the preimage from the (updated)\n // credentials and the signature no longer matches.\n addrAuth.signatureExpirationLedger(validUntilLedgerSeq);\n\n const preimage = buildAuthorizationEntryPreimage(\n clone,\n validUntilLedgerSeq,\n networkPassphrase,\n );\n\n const payload = hash(preimage.toXDR());\n\n let signature: Buffer;\n let publicKey: string;\n if (typeof signer === \"function\") {\n const sigResult = await signer(preimage);\n if (\n sigResult !== null &&\n typeof sigResult === \"object\" &&\n \"signature\" in sigResult\n ) {\n signature = toBuffer(sigResult.signature);\n publicKey = sigResult.publicKey;\n } else {\n // if using the deprecated form, assume it's for the entry\n signature = toBuffer(sigResult);\n publicKey = Address.fromScAddress(addrAuth.address()).toString();\n }\n } else {\n signature = toBuffer(signer.sign(payload));\n publicKey = signer.publicKey();\n }\n\n if (!Keypair.fromPublicKey(publicKey).verify(payload, signature)) {\n throw new Error(`signature doesn't match payload`);\n }\n\n // This structure is defined here:\n // https://soroban.stellar.org/docs/fundamentals-and-concepts/invoking-contracts-with-transactions#stellar-account-signatures\n //\n // Encoding a contract structure as an ScVal means the map keys are supposed\n // to be symbols, hence the forced typing here.\n const sigScVal = nativeToScVal(\n {\n public_key: StrKey.decodeEd25519PublicKey(publicKey),\n signature,\n },\n {\n type: {\n public_key: [\"symbol\", null],\n signature: [\"symbol\", null],\n },\n },\n );\n\n const signatureScVal = xdr.ScVal.scvVec([sigScVal]);\n\n // CAP-71-01: the signature payload is shared across the top-level address\n // and every (possibly nested) delegate, so this signer's signature is\n // written to whichever credential node(s) carry `forAddress`. When no\n // `forAddress` is given we fall back to the top-level credentials, which\n // preserves the behavior for ADDRESS / ADDRESS_V2 and for accounts whose\n // signing key differs from the credential address (e.g. multisig).\n const targets: SignableCredential[] =\n forAddress === undefined\n ? [addrAuth]\n : collectSignatureNodes(credentials).filter(\n (node) =>\n Address.fromScAddress(node.address()).toString() === forAddress,\n );\n\n if (targets.length === 0) {\n throw new Error(\n `the authorization entry has no credential node for address ${forAddress}`,\n );\n }\n\n targets.forEach((node) => node.signature(signatureScVal));\n return clone;\n}\n\nexport interface AuthorizeInvocationParams {\n signer: Keypair | SigningCallback;\n validUntilLedgerSeq: number;\n invocation: xdr.SorobanAuthorizedInvocation;\n networkPassphrase: string;\n publicKey?: string;\n /**\n * Build `SOROBAN_CREDENTIALS_ADDRESS_V2` (CAP-71) credentials instead of the\n * legacy `SOROBAN_CREDENTIALS_ADDRESS`. V2 credentials bind the address into\n * the signed payload but are only valid on networks that have activated\n * CAP-71, so leave this off until the activation vote passes for your target\n * network. The default flips to `true` once V2 becomes mandatory.\n * @defaultValue false\n */\n authV2?: boolean;\n}\n/**\n * This builds an entry from scratch, allowing you to express authorization as a\n * function of:\n * - a particular identity (i.e. signing {@link Keypair} or other signer)\n * - approving the execution of an invocation tree (i.e. a simulation-acquired\n * {@link xdr.SorobanAuthorizedInvocation} or otherwise built)\n * - on a particular network (uniquely identified by its passphrase, see\n * {@link Networks})\n * - until a particular ledger sequence is reached.\n *\n * This is in contrast to {@link authorizeEntry}, which signs an existing entry.\n *\n * @param params - the parameters for building and signing the authorization\n * - `signer`: either a {@link Keypair} instance (or anything with a\n * `.sign(buf): Buffer-like` method) or a function which takes a payload (a\n * {@link xdr.HashIdPreimageSorobanAuthorization} instance) input and returns\n * the signature of the hash of the raw payload bytes (where the signing key\n * should correspond to the address in the `entry`)\n * - `validUntilLedgerSeq`: the (exclusive) future ledger sequence\n * number until which this authorization entry should be valid (if\n * `currentLedgerSeq==validUntilLedgerSeq`, this is expired)\n * - `invocation`: the invocation tree that we're authorizing\n * (likely, this comes from transaction simulation)\n * - `networkPassphrase`: the network passphrase is incorporated into\n * the signature (see {@link Networks} for options)\n * - `publicKey`: the public identity of the signer (when providing a\n * {@link Keypair} to `signer`, this can be omitted, as it just uses\n * {@link Keypair.publicKey})\n * - `authV2`: build `SOROBAN_CREDENTIALS_ADDRESS_V2` (CAP-71) credentials\n * rather than the legacy `SOROBAN_CREDENTIALS_ADDRESS`. Defaults to `false`;\n * only enable it for networks that have activated CAP-71.\n *\n * @see authorizeEntry\n */\nexport function authorizeInvocation(\n params: AuthorizeInvocationParams,\n): Promise<xdr.SorobanAuthorizationEntry> {\n const {\n signer,\n validUntilLedgerSeq,\n invocation,\n networkPassphrase,\n publicKey = \"\",\n authV2 = false,\n } = params;\n // We use keypairs as a source of randomness for the nonce to avoid mucking\n // with any crypto dependencies. Note that this just has to be random and\n // unique, not cryptographically secure, so it's fine.\n const kp = Keypair.random().rawPublicKey();\n const nonce = new xdr.Int64(bytesToInt64(kp));\n\n const pk =\n publicKey || (signer instanceof Keypair ? signer.publicKey() : null);\n if (!pk) {\n throw new Error(`authorizeInvocation requires publicKey parameter`);\n }\n\n // V1 and V2 carry the identical SorobanAddressCredentials payload; only the\n // credential union arm differs. authorizeEntry picks the matching signature\n // preimage (legacy vs. address-bound) off whichever arm we build here.\n const addressCredentials = new xdr.SorobanAddressCredentials({\n address: new Address(pk).toScAddress(),\n nonce,\n signatureExpirationLedger: 0, // replaced\n signature: xdr.ScVal.scvVec([]), // replaced\n });\n\n const entry = new xdr.SorobanAuthorizationEntry({\n rootInvocation: invocation,\n credentials: authV2\n ? xdr.SorobanCredentials.sorobanCredentialsAddressV2(addressCredentials)\n : xdr.SorobanCredentials.sorobanCredentialsAddress(addressCredentials),\n });\n\n return authorizeEntry(entry, signer, validUntilLedgerSeq, networkPassphrase);\n}\n\n/**\n * Builds the {@link xdr.HashIdPreimage} whose hash a signer must sign to\n * authorize `entry`. This is the low-level signature payload used by\n * {@link authorizeEntry}, exposed for callers that drive signing themselves —\n * most notably for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`, where the\n * client (not simulation) decides which delegates sign and how.\n *\n * For `SOROBAN_CREDENTIALS_ADDRESS` this is the legacy, non-address-bound\n * `ENVELOPE_TYPE_SOROBAN_AUTHORIZATION` preimage. For `SOROBAN_CREDENTIALS_ADDRESS_V2`\n * and `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` it is the address-bound\n * `ENVELOPE_TYPE_SOROBAN_AUTHORIZATION_WITH_ADDRESS` preimage (CAP-71). For the\n * delegates variant this single payload — bound to the *top-level* address — is\n * what the top-level account and every (nested) delegate each sign.\n *\n * To get the raw bytes to sign, hash the XDR: `hash(preimage.toXDR())`.\n *\n * @param entry - the authorization entry to build the payload for\n * @param validUntilLedgerSeq - the expiration ledger committed into the payload\n * (must match the `signatureExpirationLedger` on the credentials you submit)\n * @param networkPassphrase - the network passphrase mixed into the payload\n * @throws `Error` if `entry` carries source-account or otherwise non-address\n * credentials\n */\nexport function buildAuthorizationEntryPreimage(\n entry: xdr.SorobanAuthorizationEntry,\n validUntilLedgerSeq: number,\n networkPassphrase: string,\n): xdr.HashIdPreimage {\n const credentials = entry.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (addrAuth === null) {\n throw new Error(\n `cannot build a signature payload for credential type ${credentials.switch().name}`,\n );\n }\n\n const networkId = hash(Buffer.from(networkPassphrase));\n\n switch (credentials.switch().value) {\n // legacy address credentials are not address-bound\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return xdr.HashIdPreimage.envelopeTypeSorobanAuthorization(\n new xdr.HashIdPreimageSorobanAuthorization({\n networkId,\n nonce: addrAuth.nonce(),\n invocation: entry.rootInvocation(),\n signatureExpirationLedger: validUntilLedgerSeq,\n }),\n );\n\n // ADDRESS_V2 and ADDRESS_WITH_DELEGATES bind the address into the signed\n // payload via the WithAddress preimage (CAP-71)\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value:\n return xdr.HashIdPreimage.envelopeTypeSorobanAuthorizationWithAddress(\n new xdr.HashIdPreimageSorobanAuthorizationWithAddress({\n networkId,\n nonce: addrAuth.nonce(),\n invocation: entry.rootInvocation(),\n address: addrAuth.address(),\n signatureExpirationLedger: validUntilLedgerSeq,\n }),\n );\n\n default:\n throw new Error(\n `unsupported credential type ${credentials.switch().name}`,\n );\n }\n}\n\n/**\n * A delegate signer to attach to a\n * `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` entry via\n * {@link buildWithDelegatesEntry}.\n */\nexport interface DelegateSignature {\n /** the delegate's address (`G…` account or `C…` contract). */\n address: string;\n /**\n * the delegate's signature value. Defaults to a `scvVoid` placeholder, which\n * you can fill afterwards with {@link authorizeEntry} (passing this address\n * as `forAddress`) or by editing the entry directly.\n */\n signature?: xdr.ScVal;\n /** signers this delegate in turn delegates to (recursive). */\n nestedDelegates?: DelegateSignature[];\n}\n\n/** Parameters for {@link buildWithDelegatesEntry}. */\nexport interface BuildWithDelegatesParams {\n /**\n * an existing `SOROBAN_CREDENTIALS_ADDRESS` or\n * `SOROBAN_CREDENTIALS_ADDRESS_V2` entry — typically one returned by\n * simulation — whose address credentials should be wrapped.\n */\n entry: xdr.SorobanAuthorizationEntry;\n /** the expiration ledger sequence stored on the top-level credentials. */\n validUntilLedgerSeq: number;\n /** the delegate signers to attach. */\n delegates: DelegateSignature[];\n /**\n * the top-level account's signature. Defaults to `scvVoid`, which is valid\n * for accounts that authorize purely via delegated signers (CAP-71-01).\n */\n signature?: xdr.ScVal;\n}\n\n/**\n * Builds a `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` authorization entry by\n * wrapping the address credentials of an existing `ADDRESS`/`ADDRESS_V2` entry\n * (e.g. one returned by simulation) together with a caller-provided set of\n * delegate signers.\n *\n * Simulation never emits the delegates variant on its own — which accounts use\n * delegated authentication is account-specific policy known only to the client\n * (much like a multisig policy). This helper just assembles the wrapper XDR;\n * you supply the delegate tree (addresses and, optionally, signatures). To\n * produce the signatures, build the shared payload with\n * {@link buildAuthorizationEntryPreimage} on the returned entry and sign it,\n * or fill each node afterwards with {@link authorizeEntry} (passing the\n * signer's address as `forAddress`).\n *\n * Each delegates array (the top-level set and every `nestedDelegates`) is\n * sorted by address in ascending order, and duplicate addresses within an array\n * are rejected, as the protocol requires (CAP-71-01) — otherwise the host\n * rejects the entry.\n *\n * @param params - see {@link BuildWithDelegatesParams}\n * @throws `Error` if `entry` is not an `ADDRESS`/`ADDRESS_V2` entry, or if any\n * delegates array contains a duplicate address.\n */\nexport function buildWithDelegatesEntry(\n params: BuildWithDelegatesParams,\n): xdr.SorobanAuthorizationEntry {\n const { entry, validUntilLedgerSeq, delegates, signature } = params;\n const credentials = entry.credentials();\n const addrAuth = getAddressCredentials(credentials);\n if (\n addrAuth === null ||\n credentials.switch().value ===\n xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates().value\n ) {\n throw new Error(\n `buildWithDelegatesEntry expects ADDRESS or ADDRESS_V2 credentials, got ${\n credentials.switch().name\n }`,\n );\n }\n\n return new xdr.SorobanAuthorizationEntry({\n rootInvocation: entry.rootInvocation(),\n credentials: xdr.SorobanCredentials.sorobanCredentialsAddressWithDelegates(\n new xdr.SorobanAddressCredentialsWithDelegates({\n addressCredentials: new xdr.SorobanAddressCredentials({\n address: addrAuth.address(),\n nonce: addrAuth.nonce(),\n signatureExpirationLedger: validUntilLedgerSeq,\n signature: signature ?? xdr.ScVal.scvVoid(),\n }),\n delegates: buildDelegateNodes(delegates),\n }),\n ),\n });\n}\n\n/**\n * Recursively converts {@link DelegateSignature} descriptors into\n * {@link xdr.SorobanDelegateSignature} nodes, sorting each level by address and\n * rejecting duplicates (CAP-71-01).\n */\nfunction buildDelegateNodes(\n delegates: DelegateSignature[],\n): xdr.SorobanDelegateSignature[] {\n const nodes = delegates.map(\n (delegate) =>\n new xdr.SorobanDelegateSignature({\n address: new Address(delegate.address).toScAddress(),\n signature: delegate.signature ?? xdr.ScVal.scvVoid(),\n nestedDelegates: buildDelegateNodes(delegate.nestedDelegates ?? []),\n }),\n );\n\n nodes.sort((a, b) =>\n Buffer.compare(a.address().toXDR(), b.address().toXDR()),\n );\n\n for (let i = 1; i < nodes.length; i++) {\n if (\n Buffer.compare(\n nodes[i - 1].address().toXDR(),\n nodes[i].address().toXDR(),\n ) === 0\n ) {\n throw new Error(\n `duplicate delegate address ${Address.fromScAddress(\n nodes[i].address(),\n ).toString()}`,\n );\n }\n }\n\n return nodes;\n}\n\n/**\n * Internal helper — intentionally NOT re-exported from `base/index.js`, so it\n * is not part of the public SDK API. Shared with the contract package, which\n * imports it directly from this module. If a public need arises, add it to the\n * explicit auth re-exports in `base/index.ts`.\n *\n * Extracts the {@link xdr.SorobanAddressCredentials} from any address-based\n * Soroban credential, regardless of which credential type variant is used.\n *\n * This unifies access across `SOROBAN_CREDENTIALS_ADDRESS`,\n * `SOROBAN_CREDENTIALS_ADDRESS_V2` (which carries identical fields but binds\n * the address into the signature payload), and\n * `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES` (which wraps the same address\n * credentials alongside a set of delegate signatures).\n *\n * @param credentials - the credentials to inspect\n * @returns the inner address credentials, or `null` for source-account\n * credentials (which carry no address payload)\n */\nexport function getAddressCredentials(\n credentials: xdr.SorobanCredentials,\n): xdr.SorobanAddressCredentials | null {\n switch (credentials.switch().value) {\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return credentials.address();\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n return credentials.addressV2();\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value:\n return credentials.addressWithDelegates().addressCredentials();\n default:\n return null;\n }\n}\n\n/**\n * The common shape of every node in an authorization entry that can carry a\n * signature: the top-level {@link xdr.SorobanAddressCredentials} and, for the\n * delegates variant, each {@link xdr.SorobanDelegateSignature}. Both expose an\n * `address()` and a `signature()` accessor.\n */\ninterface SignableCredential {\n address(value?: xdr.ScAddress): xdr.ScAddress;\n signature(value?: xdr.ScVal): xdr.ScVal;\n}\n\n/**\n * Internal helper. Returns every node in an address-based credential that can\n * carry a signature, in a stable order: the top-level address credentials\n * first, then (only for `SOROBAN_CREDENTIALS_ADDRESS_WITH_DELEGATES`) the\n * delegates and their nested delegates, depth-first. Returns an empty array\n * for source-account credentials, which carry no signature.\n *\n * Per CAP-71-01 all of these nodes commit to the same payload (the one bound to\n * the top-level address), so the caller can fill any of them with a signature\n * produced from that shared payload.\n */\nfunction collectSignatureNodes(\n credentials: xdr.SorobanCredentials,\n): SignableCredential[] {\n switch (credentials.switch().value) {\n case xdr.SorobanCredentialsType.sorobanCredentialsAddress().value:\n return [credentials.address()];\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressV2().value:\n return [credentials.addressV2()];\n case xdr.SorobanCredentialsType.sorobanCredentialsAddressWithDelegates()\n .value: {\n const withDelegates = credentials.addressWithDelegates();\n const nodes: SignableCredential[] = [withDelegates.addressCredentials()];\n const walk = (delegates: xdr.SorobanDelegateSignature[]) => {\n delegates.forEach((delegate) => {\n nodes.push(delegate);\n walk(delegate.nestedDelegates());\n });\n };\n walk(withDelegates.delegates());\n return nodes;\n }\n default:\n return [];\n }\n}\n\nfunction bytesToInt64(bytes: Uint8Array): bigint {\n const buf = bytes.subarray(0, 8);\n if (buf.length < 8) {\n throw new Error(\n `need at least 8 bytes to convert to Int64, got ${bytes.length}`,\n );\n }\n const view = new DataView(buf.buffer, buf.byteOffset, 8);\n const value = view.getBigInt64(0, false);\n\n return value;\n}\n"],"names":["Buffer","xdr","hash","Address","Keypair","nativeToScVal","StrKey"],"mappings":";;;;;;;;;;AAaA,SAAS,SAAS,KAAA,EAA2B;AAC3C,EAAA,IAAI,iBAAiB,WAAA,EAAa;AAChC,IAAA,OAAOA,aAAA,CAAO,IAAA,CAAK,IAAI,UAAA,CAAW,KAAK,CAAC,CAAA;AAAA,EAC1C;AACA,EAAA,OAAOA,aAAA,CAAO,KAAK,KAAK,CAAA;AAC1B;AAmHA,eAAsB,cAAA,CACpB,K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,CAAA;AAC/B,EAAA,IAAI,GAAA,CAAI,SAAS,CAAA,EAAG;AAClB,IAAA,MAAM,IAAI,KAAA;AAAA,MACR,CAAA,+CAAA,EAAkD,MAAM,MAAM,CAAA;AAAA,KAChE;AAAA,EACF;AACA,EAAA,MAAM,OAAO,IAAI,QAAA,CAAS,IAAI,MAAA,EAAQ,GAAA,CAAI,YAAY,CAAC,CAAA;AACvD,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,WAAA,CAAY,CAAA,EAAG,KAAK,CAAA;AAEvC,EAAA,OAAO,KAAA;AACT;;;;;;;;"}
@@ -111,7 +111,7 @@ class Keypair {
111
111
  * Create a random `Keypair` object.
112
112
  */
113
113
  static random() {
114
- const { secretKey } = ed__namespace.keygen();
114
+ const secretKey = ed__namespace.utils.randomSecretKey();
115
115
  return this.fromRawEd25519Seed(buffer.Buffer.from(secretKey));
116
116
  }
117
117
  /** Returns this public key as an xdr.AccountId. */
@@ -1 +1 @@
1
- {"version":3,"file":"keypair.js","sources":["../../../../src/base/keypair.ts"],"sourcesContent":["import * as ed from \"@noble/ed25519\";\nimport { sha512 } from \"@noble/hashes/sha2.js\";\nimport { sign, verify, generate } from \"./signing.js\";\nimport { StrKey } from \"./strkey.js\";\nimport { hash } from \"./hashing.js\";\n\nimport xdr from \"./xdr.js\";\n\ned.hashes.sha512 = sha512;\n/**\n * `Keypair` represents public (and secret) keys of the account.\n *\n * Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other\n * public-key signature systems.\n *\n * Use more convenient methods to create `Keypair` object:\n * * `{@link Keypair.fromPublicKey}`\n * * `{@link Keypair.fromSecret}`\n * * `{@link Keypair.random}`\n */\nexport class Keypair {\n readonly type: \"ed25519\";\n private _publicKey: Buffer;\n private _secretSeed?: Buffer;\n private _secretKey?: Buffer;\n\n /**\n * @param keys - at least one of keys must be provided.\n * - `type`: public-key signature system name (currently only `ed25519` keys are supported)\n * - `publicKey`: raw public key\n * - `secretKey`: raw secret key (32-byte secret seed in ed25519)\n */\n constructor(\n keys:\n | {\n type: \"ed25519\";\n secretKey: Buffer | string;\n publicKey?: Buffer | string;\n }\n | { type: \"ed25519\"; publicKey: Buffer | string },\n ) {\n if (keys.type !== \"ed25519\") {\n throw new Error(\"Invalid keys type\");\n }\n\n this.type = keys.type;\n\n if (\"secretKey\" in keys) {\n keys.secretKey = Buffer.from(keys.secretKey);\n\n if (keys.secretKey.length !== 32) {\n throw new Error(\"secretKey length is invalid\");\n }\n\n this._secretSeed = keys.secretKey;\n this._publicKey = generate(keys.secretKey);\n this._secretKey = keys.secretKey;\n\n if (\n keys.publicKey &&\n !this._publicKey.equals(Buffer.from(keys.publicKey))\n ) {\n throw new Error(\"secretKey does not match publicKey\");\n }\n } else if (\"publicKey\" in keys) {\n this._publicKey = Buffer.from(keys.publicKey);\n\n if (this._publicKey.length !== 32) {\n throw new Error(\"publicKey length is invalid\");\n }\n } else {\n throw new Error(\n \"At least one of publicKey or secretKey must be provided\",\n );\n }\n }\n\n /**\n * Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending\n * on underlying public-key signature system. Currently `Keypair` only supports ed25519.\n * @param secret - secret key (ex. `SDAK....`)\n */\n static fromSecret(secret: string): Keypair {\n const rawSecret = StrKey.decodeEd25519SecretSeed(secret);\n return this.fromRawEd25519Seed(rawSecret);\n }\n\n /**\n * Creates a new `Keypair` object from ed25519 secret key seed raw bytes.\n *\n * @param rawSeed - raw 32-byte ed25519 secret key seed\n */\n static fromRawEd25519Seed(rawSeed: Buffer): Keypair {\n return new this({ type: \"ed25519\", secretKey: rawSeed });\n }\n\n /**\n * Returns `Keypair` object representing network master key.\n * @param networkPassphrase - passphrase of the target stellar network (e.g. \"Public Global Stellar Network ; September 2015\")\n */\n static master(networkPassphrase: string): Keypair {\n if (!networkPassphrase) {\n throw new Error(\n \"No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.\",\n );\n }\n\n return this.fromRawEd25519Seed(hash(networkPassphrase));\n }\n\n /**\n * Creates a new `Keypair` object from public key.\n * @param publicKey - public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`)\n */\n static fromPublicKey(publicKey: string): Keypair {\n const publicKeyBuffer = StrKey.decodeEd25519PublicKey(publicKey);\n if (publicKeyBuffer.length !== 32) {\n throw new Error(\"Invalid Stellar public key\");\n }\n\n return new this({ type: \"ed25519\", publicKey: publicKeyBuffer });\n }\n\n /**\n * Create a random `Keypair` object.\n */\n static random(): Keypair {\n const { secretKey } = ed.keygen();\n return this.fromRawEd25519Seed(Buffer.from(secretKey));\n }\n\n /** Returns this public key as an xdr.AccountId. */\n xdrAccountId(): xdr.AccountId {\n return xdr.PublicKey.publicKeyTypeEd25519(this._publicKey);\n }\n\n /** Returns this public key as an xdr.PublicKey. */\n xdrPublicKey(): xdr.PublicKey {\n return xdr.PublicKey.publicKeyTypeEd25519(this._publicKey);\n }\n\n /**\n * Creates a {@link xdr.MuxedAccount} object from the public key.\n *\n * You will get a different type of muxed account depending on whether or not\n * you pass an ID.\n *\n * @param id - (optional) stringified integer indicating the underlying muxed\n * ID of the new account object\n */\n xdrMuxedAccount(id?: string): xdr.MuxedAccount {\n if (typeof id !== \"undefined\") {\n if (typeof id !== \"string\") {\n throw new TypeError(`expected string for ID, got ${typeof id}`);\n }\n\n return xdr.MuxedAccount.keyTypeMuxedEd25519(\n new xdr.MuxedAccountMed25519({\n id: xdr.Uint64.fromString(id),\n ed25519: this._publicKey,\n }),\n );\n }\n\n return xdr.MuxedAccount.keyTypeEd25519(this._publicKey);\n }\n\n /**\n * Returns raw public key bytes\n */\n rawPublicKey(): Buffer {\n return this._publicKey;\n }\n\n /**\n * Returns the signature hint for this keypair.\n * The hint is the last 4 bytes of the account ID XDR representation.\n */\n signatureHint(): Buffer {\n const a = this.xdrAccountId().toXDR();\n\n return a.subarray(a.length - 4);\n }\n\n /**\n * Returns public key associated with this `Keypair` object.\n */\n publicKey(): string {\n return StrKey.encodeEd25519PublicKey(this._publicKey);\n }\n\n /**\n * Returns secret key associated with this `Keypair` object.\n *\n * The secret key is encoded in Stellar format (e.g., `SDAK....`).\n *\n * @throws if no secret key is available\n */\n secret(): string {\n if (!this._secretSeed) {\n throw new Error(\"no secret key available\");\n }\n\n if (this.type === \"ed25519\") {\n return StrKey.encodeEd25519SecretSeed(this._secretSeed);\n }\n\n throw new Error(\"Invalid Keypair type\");\n }\n\n /**\n * Returns raw secret key bytes.\n *\n * @throws if no secret seed is available\n */\n rawSecretKey(): Buffer {\n if (!this._secretSeed) {\n throw new Error(\"no secret seed available\");\n }\n return this._secretSeed;\n }\n\n /**\n * Returns `true` if this `Keypair` object contains secret key and can sign.\n */\n canSign(): boolean {\n return !!this._secretKey;\n }\n\n /**\n * Signs data.\n *\n * @param data - data to sign\n * @throws if no secret key is available\n */\n sign(data: Buffer): Buffer {\n if (!this._secretKey) {\n throw new Error(\"cannot sign: no secret key available\");\n }\n\n return sign(data, this._secretKey);\n }\n\n /**\n * Verifies if `signature` for `data` is valid.\n *\n * @param data - signed data\n * @param signature - signature to verify\n */\n verify(data: Buffer, signature: Buffer): boolean {\n try {\n return verify(data, signature, this._publicKey);\n } catch {\n return false;\n }\n }\n\n /**\n * Returns the decorated signature (hint+sig) for arbitrary data.\n *\n * The returned structure can be added directly to a transaction envelope.\n *\n * @param data - arbitrary data to sign\n *\n * @see TransactionBase.addDecoratedSignature\n */\n signDecorated(data: Buffer): xdr.DecoratedSignature {\n const signature = this.sign(data);\n const hint = this.signatureHint();\n\n return new xdr.DecoratedSignature({ hint, signature });\n }\n\n /**\n * Returns the raw decorated signature (hint+sig) for a signed payload signer.\n *\n * The hint is defined as the last 4 bytes of the signer key XORed with last\n * 4 bytes of the payload (zero-left-padded if necessary).\n *\n * @param data - data to both sign and treat as the payload\n *\n * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0040.md#signature-hint\n * @see TransactionBase.addDecoratedSignature\n */\n signPayloadDecorated(data: Buffer): xdr.DecoratedSignature {\n // Ensure data is a Buffer to support array-like inputs\n const dataBuffer = Buffer.isBuffer(data) ? data : Buffer.from(data);\n\n const signature = this.sign(dataBuffer);\n const keyHint = this.signatureHint();\n\n let hint = Buffer.from(dataBuffer.subarray(-4));\n if (hint.length < 4) {\n // append zeroes as needed\n hint = Buffer.concat([hint, Buffer.alloc(4 - hint.length, 0)]);\n }\n\n // XOR each byte of hint with corresponding byte of keyHint\n for (let i = 0; i < hint.length; i++) {\n hint[i] = (hint[i] as number) ^ (keyHint[i] as number);\n }\n\n return new xdr.DecoratedSignature({\n hint,\n signature,\n });\n }\n}\n"],"names":["ed","sha512","Buffer","generate","StrKey","hash","xdr","sign","verify"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQAA,aAAA,CAAG,OAAO,MAAA,GAASC,cAAA;AAYZ,MAAM,OAAA,CAAQ;AAAA,EACV,IAAA;AAAA,EACD,UAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQR,YACE,IAAA,EAOA;AACA,IAAA,IAAI,IAAA,CAAK,SAAS,SAAA,EAAW;AAC3B,MAAA,MAAM,IAAI,MAAM,mBAAmB,CAAA;AAAA,IACrC;AAEA,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AAEjB,IAAA,IAAI,eAAe,IAAA,EAAM;AACvB,MAAA,IAAA,CAAK,SAAA,GAAYC,aAAA,CAAO,IAAA,CAAK,IAAA,CAAK,SAAS,CAAA;AAE3C,MAAA,IAAI,IAAA,CAAK,SAAA,CAAU,MAAA,KAAW,EAAA,EAAI;AAChC,QAAA,MAAM,IAAI,MAAM,6BAA6B,CAAA;AAAA,MAC/C;AAEA,MAAA,IAAA,CAAK,cAAc,IAAA,CAAK,SAAA;AACxB,MAAA,IAAA,CAAK,UAAA,GAAaC,gBAAA,CAAS,IAAA,CAAK,SAAS,CAAA;AACzC,MAAA,IAAA,CAAK,aAAa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AAS,CAAA,EAAG;AAEnB,MAAA,IAAA,GAAOA,aAAA,CAAO,MAAA,CAAO,CAAC,IAAA,EAAMA,aAAA,CAAO,KAAA,CAAM,CAAA,GAAI,IAAA,CAAK,MAAA,EAAQ,CAAC,CAAC,CAAC,CAAA;AAAA,IAC/D;AAGA,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,QAAQ,CAAA,EAAA,EAAK;AACpC,MAAA,IAAA,CAAK,CAAC,CAAA,GAAK,IAAA,CAAK,CAAC,CAAA,GAAgB,QAAQ,CAAC,CAAA;AAAA,IAC5C;AAEA,IAAA,OAAO,IAAII,uBAAI,kBAAA,CAAmB;AAAA,MAChC,IAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AACF;;;;"}
1
+ {"version":3,"file":"keypair.js","sources":["../../../../src/base/keypair.ts"],"sourcesContent":["import * as ed from \"@noble/ed25519\";\nimport { sha512 } from \"@noble/hashes/sha2.js\";\nimport { sign, verify, generate } from \"./signing.js\";\nimport { StrKey } from \"./strkey.js\";\nimport { hash } from \"./hashing.js\";\n\nimport xdr from \"./xdr.js\";\n\ned.hashes.sha512 = sha512;\n/**\n * `Keypair` represents public (and secret) keys of the account.\n *\n * Currently `Keypair` only supports ed25519 but in a future this class can be abstraction layer for other\n * public-key signature systems.\n *\n * Use more convenient methods to create `Keypair` object:\n * * `{@link Keypair.fromPublicKey}`\n * * `{@link Keypair.fromSecret}`\n * * `{@link Keypair.random}`\n */\nexport class Keypair {\n readonly type: \"ed25519\";\n private _publicKey: Buffer;\n private _secretSeed?: Buffer;\n private _secretKey?: Buffer;\n\n /**\n * @param keys - at least one of keys must be provided.\n * - `type`: public-key signature system name (currently only `ed25519` keys are supported)\n * - `publicKey`: raw public key\n * - `secretKey`: raw secret key (32-byte secret seed in ed25519)\n */\n constructor(\n keys:\n | {\n type: \"ed25519\";\n secretKey: Buffer | string;\n publicKey?: Buffer | string;\n }\n | { type: \"ed25519\"; publicKey: Buffer | string },\n ) {\n if (keys.type !== \"ed25519\") {\n throw new Error(\"Invalid keys type\");\n }\n\n this.type = keys.type;\n\n if (\"secretKey\" in keys) {\n keys.secretKey = Buffer.from(keys.secretKey);\n\n if (keys.secretKey.length !== 32) {\n throw new Error(\"secretKey length is invalid\");\n }\n\n this._secretSeed = keys.secretKey;\n this._publicKey = generate(keys.secretKey);\n this._secretKey = keys.secretKey;\n\n if (\n keys.publicKey &&\n !this._publicKey.equals(Buffer.from(keys.publicKey))\n ) {\n throw new Error(\"secretKey does not match publicKey\");\n }\n } else if (\"publicKey\" in keys) {\n this._publicKey = Buffer.from(keys.publicKey);\n\n if (this._publicKey.length !== 32) {\n throw new Error(\"publicKey length is invalid\");\n }\n } else {\n throw new Error(\n \"At least one of publicKey or secretKey must be provided\",\n );\n }\n }\n\n /**\n * Creates a new `Keypair` instance from secret. This can either be secret key or secret seed depending\n * on underlying public-key signature system. Currently `Keypair` only supports ed25519.\n * @param secret - secret key (ex. `SDAK....`)\n */\n static fromSecret(secret: string): Keypair {\n const rawSecret = StrKey.decodeEd25519SecretSeed(secret);\n return this.fromRawEd25519Seed(rawSecret);\n }\n\n /**\n * Creates a new `Keypair` object from ed25519 secret key seed raw bytes.\n *\n * @param rawSeed - raw 32-byte ed25519 secret key seed\n */\n static fromRawEd25519Seed(rawSeed: Buffer): Keypair {\n return new this({ type: \"ed25519\", secretKey: rawSeed });\n }\n\n /**\n * Returns `Keypair` object representing network master key.\n * @param networkPassphrase - passphrase of the target stellar network (e.g. \"Public Global Stellar Network ; September 2015\")\n */\n static master(networkPassphrase: string): Keypair {\n if (!networkPassphrase) {\n throw new Error(\n \"No network selected. Please pass a network argument, e.g. `Keypair.master(Networks.PUBLIC)`.\",\n );\n }\n\n return this.fromRawEd25519Seed(hash(networkPassphrase));\n }\n\n /**\n * Creates a new `Keypair` object from public key.\n * @param publicKey - public key (ex. `GB3KJPLFUYN5VL6R3GU3EGCGVCKFDSD7BEDX42HWG5BWFKB3KQGJJRMA`)\n */\n static fromPublicKey(publicKey: string): Keypair {\n const publicKeyBuffer = StrKey.decodeEd25519PublicKey(publicKey);\n if (publicKeyBuffer.length !== 32) {\n throw new Error(\"Invalid Stellar public key\");\n }\n\n return new this({ type: \"ed25519\", publicKey: publicKeyBuffer });\n }\n\n /**\n * Create a random `Keypair` object.\n */\n static random(): Keypair {\n const secretKey = ed.utils.randomSecretKey();\n return this.fromRawEd25519Seed(Buffer.from(secretKey));\n }\n\n /** Returns this public key as an xdr.AccountId. */\n xdrAccountId(): xdr.AccountId {\n return xdr.PublicKey.publicKeyTypeEd25519(this._publicKey);\n }\n\n /** Returns this public key as an xdr.PublicKey. */\n xdrPublicKey(): xdr.PublicKey {\n return xdr.PublicKey.publicKeyTypeEd25519(this._publicKey);\n }\n\n /**\n * Creates a {@link xdr.MuxedAccount} object from the public key.\n *\n * You will get a different type of muxed account depending on whether or not\n * you pass an ID.\n *\n * @param id - (optional) stringified integer indicating the underlying muxed\n * ID of the new account object\n */\n xdrMuxedAccount(id?: string): xdr.MuxedAccount {\n if (typeof id !== \"undefined\") {\n if (typeof id !== \"string\") {\n throw new TypeError(`expected string for ID, got ${typeof id}`);\n }\n\n return xdr.MuxedAccount.keyTypeMuxedEd25519(\n new xdr.MuxedAccountMed25519({\n id: xdr.Uint64.fromString(id),\n ed25519: this._publicKey,\n }),\n );\n }\n\n return xdr.MuxedAccount.keyTypeEd25519(this._publicKey);\n }\n\n /**\n * Returns raw public key bytes\n */\n rawPublicKey(): Buffer {\n return this._publicKey;\n }\n\n /**\n * Returns the signature hint for this keypair.\n * The hint is the last 4 bytes of the account ID XDR representation.\n */\n signatureHint(): Buffer {\n const a = this.xdrAccountId().toXDR();\n\n return a.subarray(a.length - 4);\n }\n\n /**\n * Returns public key associated with this `Keypair` object.\n */\n publicKey(): string {\n return StrKey.encodeEd25519PublicKey(this._publicKey);\n }\n\n /**\n * Returns secret key associated with this `Keypair` object.\n *\n * The secret key is encoded in Stellar format (e.g., `SDAK....`).\n *\n * @throws if no secret key is available\n */\n secret(): string {\n if (!this._secretSeed) {\n throw new Error(\"no secret key available\");\n }\n\n if (this.type === \"ed25519\") {\n return StrKey.encodeEd25519SecretSeed(this._secretSeed);\n }\n\n throw new Error(\"Invalid Keypair type\");\n }\n\n /**\n * Returns raw secret key bytes.\n *\n * @throws if no secret seed is available\n */\n rawSecretKey(): Buffer {\n if (!this._secretSeed) {\n throw new Error(\"no secret seed available\");\n }\n return this._secretSeed;\n }\n\n /**\n * Returns `true` if this `Keypair` object contains secret key and can sign.\n */\n canSign(): boolean {\n return !!this._secretKey;\n }\n\n /**\n * Signs data.\n *\n * @param data - data to sign\n * @throws if no secret key is available\n */\n sign(data: Buffer): Buffer {\n if (!this._secretKey) {\n throw new Error(\"cannot sign: no secret key available\");\n }\n\n return sign(data, this._secretKey);\n }\n\n /**\n * Verifies if `signature` for `data` is valid.\n *\n * @param data - signed data\n * @param signature - signature to verify\n */\n verify(data: Buffer, signature: Buffer): boolean {\n try {\n return verify(data, signature, this._publicKey);\n } catch {\n return false;\n }\n }\n\n /**\n * Returns the decorated signature (hint+sig) for arbitrary data.\n *\n * The returned structure can be added directly to a transaction envelope.\n *\n * @param data - arbitrary data to sign\n *\n * @see TransactionBase.addDecoratedSignature\n */\n signDecorated(data: Buffer): xdr.DecoratedSignature {\n const signature = this.sign(data);\n const hint = this.signatureHint();\n\n return new xdr.DecoratedSignature({ hint, signature });\n }\n\n /**\n * Returns the raw decorated signature (hint+sig) for a signed payload signer.\n *\n * The hint is defined as the last 4 bytes of the signer key XORed with last\n * 4 bytes of the payload (zero-left-padded if necessary).\n *\n * @param data - data to both sign and treat as the payload\n *\n * @see https://github.com/stellar/stellar-protocol/blob/master/core/cap-0040.md#signature-hint\n * @see TransactionBase.addDecoratedSignature\n */\n signPayloadDecorated(data: Buffer): xdr.DecoratedSignature {\n // Ensure data is a Buffer to support array-like inputs\n const dataBuffer = Buffer.isBuffer(data) ? data : Buffer.from(data);\n\n const signature = this.sign(dataBuffer);\n const keyHint = this.signatureHint();\n\n let hint = Buffer.from(dataBuffer.subarray(-4));\n if (hint.length < 4) {\n // append zeroes as needed\n hint = Buffer.concat([hint, Buffer.alloc(4 - hint.length, 0)]);\n }\n\n // XOR each byte of hint with corresponding byte of keyHint\n for (let i = 0; i < hint.length; i++) {\n hint[i] = (hint[i] as number) ^ (keyHint[i] as number);\n }\n\n return new xdr.DecoratedSignature({\n hint,\n signature,\n });\n }\n}\n"],"names":["ed","sha512","Buffer","generate","StrKey","hash","xdr","sign","verify"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQAA,aAAA,CAAG,OAAO,MAAA,GAASC,cAAA;AAYZ,MAAM,OAAA,CAAQ;AAAA,EACV,IAAA;AAAA,EACD,UAAA;AAAA,EACA,WAAA;AAAA,EACA,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQR,YACE,IAAA,EAOA;AACA,IAAA,IAAI,IAAA,CAAK,SAAS,SAAA,EAAW;AAC3B,MAAA,MAAM,IAAI,MAAM,mBAAmB,CAAA;AAAA,IACrC;AAEA,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AAEjB,IAAA,IAAI,eAAe,IAAA,EAAM;AACvB,MAAA,IAAA,CAAK,SAAA,GAAYC,aAAA,CAAO,IAAA,CAAK,IAAA,CAAK,SAAS,CAAA;AAE3C,MAAA,IAAI,IAAA,CAAK,SAAA,CAAU,MAAA,KAAW,EAAA,EAAI;AAChC,QAAA,MAAM,IAAI,MAAM,6BAA6B,CAAA;AAAA,MAC/C;AAEA,MAAA,IAAA,CAAK,cAAc,IAAA,CAAK,SAAA;AACxB,MAAA,IAAA,CAAK,UAAA,GAAaC,gBAAA,CAAS,IAAA,CAAK,SAAS,CAAA;AACzC,MAAA,IAAA,CAAK,aAAa,IAAA,CAAK,SAAA;AAEvB,MAAA,IACE,IAAA,CAAK,SAAA,IACL,CAAC,IAAA,CAAK,UAAA,CAAW,MA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A,CAAO,KAAA,CAAM,CAAA,GAAI,IAAA,CAAK,MAAA,EAAQ,CAAC,CAAC,CAAC,CAAA;AAAA,IAC/D;AAGA,IAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,QAAQ,CAAA,EAAA,EAAK;AACpC,MAAA,IAAA,CAAK,CAAC,CAAA,GAAK,IAAA,CAAK,CAAC,CAAA,GAAgB,QAAQ,CAAC,CAAA;AAAA,IAC5C;AAEA,IAAA,OAAO,IAAII,uBAAI,kBAAA,CAAmB;AAAA,MAChC,IAAA;AAAA,MACA;AAAA,KACD,CAAA;AAAA,EACH;AACF;;;;"}
@@ -28,7 +28,7 @@ class ConfigGenerator {
28
28
  build: "tsc"
29
29
  },
30
30
  dependencies: {
31
- "@stellar/stellar-sdk": `^${"16.0.0-rc.1"}`,
31
+ "@stellar/stellar-sdk": `^${"16.0.0-rc.2"}`,
32
32
  buffer: "6.0.3"
33
33
  },
34
34
  devDependencies: {
@@ -353,7 +353,12 @@ class AssembledTransaction {
353
353
  restore = restore ?? this.options.restore;
354
354
  delete this.simulationResult;
355
355
  delete this.simulationTransactionData;
356
- this.simulation = await this.server.simulateTransaction(this.built);
356
+ this.simulation = await this.server.simulateTransaction(
357
+ this.built,
358
+ void 0,
359
+ void 0,
360
+ this.options.authV2
361
+ );
357
362
  if (restore && api.Api.isSimulationRestore(this.simulation)) {
358
363
  const account = await utils.getAccount(this.options, this.server);
359
364
  const result = await this.restoreFootprint(
@@ -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","Server","ExpiredStateError","RestoreFailureError","NeedsMoreSignaturesError","NoSignatureNeededError","NoUnsignedNonInvokerAuthEntriesError","NoSignerError","NotYetSimulatedError","FakeAccountError","SimulationFailedError","InternalWalletError","ExternalServiceError","InvalidClientRequestError","UserRejectedError","Address","TransactionBuilder","xdr","contract","Contract","getAccount","BASE_FEE","DEFAULT_TIMEOUT","SorobanDataBuilder","Operation","Api","assembleTransaction","implementsToString","contractErrorPattern","Err","SentTransaction","getAddressCredentials","address","stellarBaseAuthorizeEntry","Buffer"],"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,UAAEA,QAAA,EAAQ,SAAA,EAAW,OAAA,EAAS,MAAA,KAAW,IAAA,CAAK,OAAA;AACpD,IAAA,IAAA,CAAK,MAAA,GAASA,YAAU,IAAIC,gBAAA,CAAO,QAAQ,EAAE,SAAA,EAAW,SAAS,CAAA;AAAA,EACnE;AAAA,EAJ2B,OAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA9QpB,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMC,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOD,KAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,UAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaC,gBAAA;AAAA;AAAA;A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A;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 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(\n this.built,\n undefined,\n undefined,\n this.options.authV2,\n );\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","Server","ExpiredStateError","RestoreFailureError","NeedsMoreSignaturesError","NoSignatureNeededError","NoUnsignedNonInvokerAuthEntriesError","NoSignerError","NotYetSimulatedError","FakeAccountError","SimulationFailedError","InternalWalletError","ExternalServiceError","InvalidClientRequestError","UserRejectedError","Address","TransactionBuilder","xdr","contract","Contract","getAccount","BASE_FEE","DEFAULT_TIMEOUT","SorobanDataBuilder","Operation","Api","assembleTransaction","implementsToString","contractErrorPattern","Err","SentTransaction","getAddressCredentials","address","stellarBaseAuthorizeEntry","Buffer"],"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,UAAEA,QAAA,EAAQ,SAAA,EAAW,OAAA,EAAS,MAAA,KAAW,IAAA,CAAK,OAAA;AACpD,IAAA,IAAA,CAAK,MAAA,GAASA,YAAU,IAAIC,gBAAA,CAAO,QAAQ,EA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