@stellar/stellar-sdk 16.0.0-rc.1 → 16.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -28
- package/dist/stellar-sdk-axios.js +245 -232
- package/dist/stellar-sdk-axios.js.map +1 -1
- package/dist/stellar-sdk-axios.min.js +1 -1
- package/dist/stellar-sdk-axios.min.js.map +1 -1
- package/dist/stellar-sdk.js +49 -36
- package/dist/stellar-sdk.js.map +1 -1
- package/dist/stellar-sdk.min.js +2 -2
- package/dist/stellar-sdk.min.js.map +1 -1
- package/lib/axios/cjs/base/auth.js +11 -11
- package/lib/axios/cjs/base/auth.js.map +1 -1
- package/lib/axios/cjs/base/keypair.js +1 -1
- package/lib/axios/cjs/base/keypair.js.map +1 -1
- package/lib/axios/cjs/base/transaction_builder.js +13 -1
- package/lib/axios/cjs/base/transaction_builder.js.map +1 -1
- package/lib/axios/cjs/bindings/config.js +1 -1
- package/lib/axios/cjs/bindings/config.js.map +1 -1
- package/lib/axios/cjs/bindings/wasm_fetcher.js +1 -1
- package/lib/axios/cjs/bindings/wasm_fetcher.js.map +1 -1
- package/lib/axios/cjs/contract/client.js.map +1 -1
- package/lib/axios/cjs/contract/spec.js.map +1 -1
- package/lib/axios/cjs/contract/types.js.map +1 -1
- package/lib/axios/cjs/contract/utils.js.map +1 -1
- package/lib/axios/cjs/contract/wasm_spec_parser.js +1 -1
- package/lib/axios/cjs/contract/wasm_spec_parser.js.map +1 -1
- package/lib/axios/cjs/horizon/call_builder.js.map +1 -1
- package/lib/axios/cjs/horizon/horizon_api.js.map +1 -1
- package/lib/axios/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/cjs/horizon/horizon_axios_client.js.map +1 -1
- package/lib/axios/cjs/http-client/fetch-client.js +1 -1
- package/lib/axios/cjs/http-client/fetch-client.js.map +1 -1
- package/lib/axios/cjs/http-client/types.js.map +1 -1
- package/lib/axios/cjs/rpc/axios.js +1 -1
- package/lib/axios/cjs/rpc/axios.js.map +1 -1
- package/lib/axios/cjs/rpc/jsonrpc.js.map +1 -1
- package/lib/axios/cjs/rpc/server.js +2 -2
- package/lib/axios/cjs/rpc/server.js.map +1 -1
- package/lib/axios/cjs/webauth/challenge_transaction.js.map +1 -1
- package/lib/axios/esm/base/auth.d.ts +19 -7
- package/lib/axios/esm/base/auth.js +11 -11
- package/lib/axios/esm/base/auth.js.map +1 -1
- package/lib/axios/esm/base/keypair.js +1 -1
- package/lib/axios/esm/base/keypair.js.map +1 -1
- package/lib/axios/esm/base/transaction_builder.js +13 -1
- package/lib/axios/esm/base/transaction_builder.js.map +1 -1
- package/lib/axios/esm/bindings/config.js +1 -1
- package/lib/axios/esm/bindings/config.js.map +1 -1
- package/lib/axios/esm/bindings/wasm_fetcher.js +1 -1
- package/lib/axios/esm/bindings/wasm_fetcher.js.map +1 -1
- package/lib/axios/esm/contract/client.js.map +1 -1
- package/lib/axios/esm/contract/spec.js.map +1 -1
- package/lib/axios/esm/contract/types.js.map +1 -1
- package/lib/axios/esm/contract/utils.js.map +1 -1
- package/lib/axios/esm/contract/wasm_spec_parser.js +1 -1
- package/lib/axios/esm/contract/wasm_spec_parser.js.map +1 -1
- package/lib/axios/esm/horizon/call_builder.js.map +1 -1
- package/lib/axios/esm/horizon/horizon_api.js.map +1 -1
- package/lib/axios/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/esm/horizon/horizon_axios_client.js.map +1 -1
- package/lib/axios/esm/http-client/fetch-client.js +1 -1
- package/lib/axios/esm/http-client/fetch-client.js.map +1 -1
- package/lib/axios/esm/http-client/types.js.map +1 -1
- package/lib/axios/esm/rpc/axios.js +1 -1
- package/lib/axios/esm/rpc/axios.js.map +1 -1
- package/lib/axios/esm/rpc/jsonrpc.js.map +1 -1
- package/lib/axios/esm/rpc/server.js +2 -2
- package/lib/axios/esm/rpc/server.js.map +1 -1
- package/lib/axios/esm/webauth/challenge_transaction.js.map +1 -1
- package/lib/cjs/base/auth.js +11 -11
- package/lib/cjs/base/auth.js.map +1 -1
- package/lib/cjs/base/keypair.js +1 -1
- package/lib/cjs/base/keypair.js.map +1 -1
- package/lib/cjs/base/transaction_builder.js +13 -1
- package/lib/cjs/base/transaction_builder.js.map +1 -1
- package/lib/cjs/bindings/config.js +1 -1
- package/lib/cjs/bindings/config.js.map +1 -1
- package/lib/cjs/bindings/wasm_fetcher.js +1 -1
- package/lib/cjs/bindings/wasm_fetcher.js.map +1 -1
- package/lib/cjs/contract/client.js.map +1 -1
- package/lib/cjs/contract/spec.js.map +1 -1
- package/lib/cjs/contract/types.js.map +1 -1
- package/lib/cjs/contract/utils.js.map +1 -1
- package/lib/cjs/contract/wasm_spec_parser.js +1 -1
- package/lib/cjs/contract/wasm_spec_parser.js.map +1 -1
- package/lib/cjs/horizon/call_builder.js.map +1 -1
- package/lib/cjs/horizon/horizon_api.js.map +1 -1
- package/lib/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/cjs/horizon/horizon_axios_client.js.map +1 -1
- package/lib/cjs/http-client/fetch-client.js +1 -1
- package/lib/cjs/http-client/fetch-client.js.map +1 -1
- package/lib/cjs/http-client/types.js.map +1 -1
- package/lib/cjs/rpc/axios.js +1 -1
- package/lib/cjs/rpc/axios.js.map +1 -1
- package/lib/cjs/rpc/jsonrpc.js.map +1 -1
- package/lib/cjs/rpc/server.js +2 -2
- package/lib/cjs/rpc/server.js.map +1 -1
- package/lib/cjs/webauth/challenge_transaction.js.map +1 -1
- package/lib/esm/base/auth.d.ts +19 -7
- package/lib/esm/base/auth.js +11 -11
- package/lib/esm/base/auth.js.map +1 -1
- package/lib/esm/base/keypair.js +1 -1
- package/lib/esm/base/keypair.js.map +1 -1
- package/lib/esm/base/transaction_builder.js +13 -1
- package/lib/esm/base/transaction_builder.js.map +1 -1
- package/lib/esm/bindings/config.js +1 -1
- package/lib/esm/bindings/config.js.map +1 -1
- package/lib/esm/bindings/wasm_fetcher.js +1 -1
- package/lib/esm/bindings/wasm_fetcher.js.map +1 -1
- package/lib/esm/contract/client.js.map +1 -1
- package/lib/esm/contract/spec.js.map +1 -1
- package/lib/esm/contract/types.js.map +1 -1
- package/lib/esm/contract/utils.js.map +1 -1
- package/lib/esm/contract/wasm_spec_parser.js +1 -1
- package/lib/esm/contract/wasm_spec_parser.js.map +1 -1
- package/lib/esm/horizon/call_builder.js.map +1 -1
- package/lib/esm/horizon/horizon_api.js.map +1 -1
- package/lib/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/esm/horizon/horizon_axios_client.js.map +1 -1
- package/lib/esm/http-client/fetch-client.js +1 -1
- package/lib/esm/http-client/fetch-client.js.map +1 -1
- package/lib/esm/http-client/types.js.map +1 -1
- package/lib/esm/rpc/axios.js +1 -1
- package/lib/esm/rpc/axios.js.map +1 -1
- package/lib/esm/rpc/jsonrpc.js.map +1 -1
- package/lib/esm/rpc/server.js +2 -2
- package/lib/esm/rpc/server.js.map +1 -1
- package/lib/esm/webauth/challenge_transaction.js.map +1 -1
- package/package.json +2 -5
package/lib/cjs/base/auth.js.map
CHANGED
|
@@ -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,QAAA,GAAW,+BAAA;AAAA,IACf,KAAA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,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,KAAA,EACA,MAAA,EACA,mBAA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,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;;;;;;;;"}
|
package/lib/cjs/base/keypair.js
CHANGED
|
@@ -111,7 +111,7 @@ class Keypair {
|
|
|
111
111
|
* Create a random `Keypair` object.
|
|
112
112
|
*/
|
|
113
113
|
static random() {
|
|
114
|
-
const
|
|
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,CAA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AAS,EAAE,CAAC,CAAA;AAC9C,IAAA,IAAI,IAAA,CAAK,SAAS,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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,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;;;;"}
|
|
@@ -133,7 +133,19 @@ class TransactionBuilder {
|
|
|
133
133
|
"cannot clone a transaction with no operations: per-operation base fee cannot be determined"
|
|
134
134
|
);
|
|
135
135
|
}
|
|
136
|
-
|
|
136
|
+
let sorobanData;
|
|
137
|
+
const envelope = tx.toEnvelope();
|
|
138
|
+
if (envelope.switch() === curr_generated.default.EnvelopeType.envelopeTypeTx()) {
|
|
139
|
+
sorobanData = envelope.v1().tx().ext().value() ?? void 0;
|
|
140
|
+
}
|
|
141
|
+
let totalFee = parseInt(tx.fee, 10);
|
|
142
|
+
if (sorobanData) {
|
|
143
|
+
const resourceFee = Number(sorobanData.resourceFee().toBigInt());
|
|
144
|
+
if (totalFee - resourceFee > 0) {
|
|
145
|
+
totalFee -= resourceFee;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const unscaledFee = Math.floor(totalFee / tx.operations.length);
|
|
137
149
|
const builderOpts = {
|
|
138
150
|
fee: (unscaledFee || BASE_FEE).toString(),
|
|
139
151
|
memo: tx.memo,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction_builder.js","sources":["../../../src/base/transaction_builder.ts"],"sourcesContent":["import { Hyper } from \"@stellar/js-xdr\";\nimport BigNumber from \"./util/bignumber.js\";\n\nimport xdr from \"./xdr.js\";\n\nimport { Account } from \"./account.js\";\nimport { MuxedAccount } from \"./muxed_account.js\";\nimport type { TransactionSource } from \"./transaction_source.js\";\nimport {\n decodeAddressToMuxedAccount,\n extractBaseAddress,\n} from \"./util/decode_encode_muxed_account.js\";\n\nimport { Transaction } from \"./transaction.js\";\nimport { FeeBumpTransaction } from \"./fee_bump_transaction.js\";\nimport { SorobanDataBuilder } from \"./sorobandata_builder.js\";\n\nimport { StrKey } from \"./strkey.js\";\nimport { SignerKey } from \"./signerkey.js\";\nimport { Memo } from \"./memo.js\";\nimport { Asset } from \"./asset.js\";\nimport { nativeToScVal } from \"./scval.js\";\nimport { Operation } from \"./operation.js\";\nimport { Address } from \"./address.js\";\nimport { Keypair } from \"./keypair.js\";\n\nconst HYPER_MAX_VALUE = Hyper.MAX_VALUE as unknown as bigint;\nconst UINT32_MAX = 4294967295; // 2^32 - 1\n\n/**\n * Minimum base fee for transactions. If this fee is below the network\n * minimum, the transaction will fail. The more operations in the\n * transaction, the greater the required fee. Use\n * {@link Horizon.Server.fetchBaseFee} to get an accurate value of minimum\n * transaction fee on the network.\n *\n * @see [Fees](https://developers.stellar.org/docs/glossary/fees/)\n */\nexport const BASE_FEE = \"100\"; // Stroops\n\n/**\n * @see {@link TransactionBuilder.setTimeout}\n * @see [Timeout](https://developers.stellar.org/api/resources/transactions/post/)\n */\nexport const TimeoutInfinite = 0;\n\n/**\n * Soroban fee parameters for resource-limited transactions.\n */\nexport interface SorobanFees {\n /** The number of instructions executed by the transaction. */\n instructions: number;\n /** The number of bytes read from the ledger by the transaction. */\n readBytes: number;\n /** The number of bytes written to the ledger by the transaction. */\n writeBytes: number;\n /** The fee to be paid for the transaction, in stroops. */\n resourceFee: bigint;\n}\n\n/**\n * Options for constructing a {@link TransactionBuilder}.\n */\nexport interface TransactionBuilderOptions {\n /** Max fee you're willing to pay per operation in this transaction (**in stroops**). */\n fee: string;\n /** Memo for the transaction. */\n memo?: Memo;\n /**\n * Passphrase of the target Stellar network (e.g. \"Public Global Stellar\n * Network ; September 2015\" for the pubnet).\n */\n networkPassphrase?: string;\n /** Timebounds for the validity of this transaction. */\n timebounds?: {\n /** 64-bit UNIX timestamp or Date object. */\n minTime?: Date | number | string;\n /** 64-bit UNIX timestamp or Date object. */\n maxTime?: Date | number | string;\n };\n /** Ledger bounds for the validity of this transaction. */\n ledgerbounds?: {\n /** Number of the minimum ledger sequence. */\n minLedger?: number;\n /** Number of the maximum ledger sequence. */\n maxLedger?: number;\n };\n /** Minimum source account sequence number this transaction is valid for. */\n minAccountSequence?: string;\n /** Minimum seconds between source account sequence time and ledger time. */\n minAccountSequenceAge?: bigint;\n /** Minimum ledgers between source account sequence and current ledger. */\n minAccountSequenceLedgerGap?: number;\n /** List of extra signers required for this transaction. */\n extraSigners?: string[];\n /**\n * An instance of {@link xdr.SorobanTransactionData} or a base64 string.\n * Provides resource estimations for Soroban transactions. Has no effect on\n * non-contract transactions.\n */\n sorobanData?: xdr.SorobanTransactionData | string;\n}\n\n/**\n * <p>Transaction builder helps constructs a new `{@link Transaction}` using the\n * given {@link Account} as the transaction's \"source account\". The transaction\n * will use the current sequence number of the given account as its sequence\n * number and increment the given account's sequence number by one. The given\n * source account must include a private key for signing the transaction or an\n * error will be thrown.</p>\n *\n * <p>Operations can be added to the transaction via their corresponding builder\n * methods, and each returns the TransactionBuilder object so they can be\n * chained together. After adding the desired operations, call the `build()`\n * method on the `TransactionBuilder` to return a fully constructed\n * {@link Transaction} that can be signed. The returned transaction will contain the\n * sequence number of the source account and include the signature from the\n * source account.</p>\n *\n * <p><strong>Be careful about unsubmitted transactions!</strong> When you build\n * a transaction, `stellar-sdk` automatically increments the source account's\n * sequence number. If you end up not submitting this transaction and submitting\n * another one instead, it'll fail due to the sequence number being wrong. So if\n * you decide not to use a built transaction, make sure to update the source\n * account's sequence number with\n * [Server.loadAccount](https://stellar.github.io/js-stellar-sdk/Server.html#loadAccount)\n * before creating another transaction.</p>\n *\n * <p>The following code example creates a new transaction with {@link\n * Operation.createAccount} and {@link Operation.payment} operations. The\n * Transaction's source account first funds `destinationA`, then sends a payment\n * to `destinationB`. The built transaction is then signed by\n * `sourceKeypair`.</p>\n *\n * ```\n * var transaction = new TransactionBuilder(source, { fee, networkPassphrase: Networks.TESTNET })\n * .addOperation(Operation.createAccount({\n * destination: destinationA,\n * startingBalance: \"20\"\n * })) // <- funds and creates destinationA\n * .addOperation(Operation.payment({\n * destination: destinationB,\n * amount: \"100\",\n * asset: Asset.native()\n * })) // <- sends 100 XLM to destinationB\n * .setTimeout(30)\n * .build();\n *\n * transaction.sign(sourceKeypair);\n * ```\n *\n */\nexport class TransactionBuilder {\n source: TransactionSource;\n operations: xdr.Operation[];\n baseFee: string;\n timebounds: {\n minTime?: Date | number | string;\n maxTime?: Date | number | string;\n } | null;\n ledgerbounds: { minLedger?: number; maxLedger?: number } | null;\n minAccountSequence: string | null;\n minAccountSequenceAge: bigint | null;\n minAccountSequenceLedgerGap: number | null;\n extraSigners: string[] | null;\n memo: Memo;\n networkPassphrase: string | null;\n sorobanData: xdr.SorobanTransactionData | null;\n\n /**\n * @param sourceAccount - source account for this transaction\n * @param opts - options object (see {@link TransactionBuilderOptions})\n */\n constructor(\n sourceAccount: TransactionSource,\n opts: TransactionBuilderOptions = {} as TransactionBuilderOptions,\n ) {\n if (!sourceAccount) {\n throw new Error(\"must specify source account for the transaction\");\n }\n\n if (opts.fee === undefined) {\n throw new Error(\"must specify fee for the transaction (in stroops)\");\n }\n\n this.source = sourceAccount;\n this.operations = [];\n\n this.baseFee = opts.fee;\n if (opts.timebounds) {\n const minTime = toEpochSeconds(opts.timebounds.minTime);\n const maxTime = toEpochSeconds(opts.timebounds.maxTime);\n\n if (minTime !== undefined && minTime < 0) {\n throw new Error(\"min_time cannot be negative\");\n }\n\n if (maxTime !== undefined && maxTime < 0) {\n throw new Error(\"max_time cannot be negative\");\n }\n\n if (\n minTime !== undefined &&\n maxTime !== undefined &&\n maxTime > 0 &&\n minTime > maxTime\n ) {\n throw new Error(\"min_time cannot be greater than max_time\");\n }\n\n this.timebounds = { ...opts.timebounds };\n } else {\n this.timebounds = null;\n }\n\n if (opts.ledgerbounds) {\n const minLedger = opts.ledgerbounds.minLedger;\n const maxLedger = opts.ledgerbounds.maxLedger;\n\n if (minLedger !== undefined && minLedger < 0) {\n throw new Error(\"min_ledger cannot be negative\");\n }\n\n if (maxLedger !== undefined && maxLedger < 0) {\n throw new Error(\"max_ledger cannot be negative\");\n }\n\n if (\n minLedger !== undefined &&\n maxLedger !== undefined &&\n maxLedger > 0 &&\n minLedger > maxLedger\n ) {\n throw new Error(\"min_ledger cannot be greater than max_ledger\");\n }\n\n this.ledgerbounds = { ...opts.ledgerbounds };\n } else {\n this.ledgerbounds = null;\n }\n this.minAccountSequence = opts.minAccountSequence || null;\n this.minAccountSequenceAge =\n opts.minAccountSequenceAge !== undefined\n ? opts.minAccountSequenceAge\n : null;\n this.minAccountSequenceLedgerGap =\n opts.minAccountSequenceLedgerGap !== undefined\n ? opts.minAccountSequenceLedgerGap\n : null;\n this.extraSigners = opts.extraSigners ? [...opts.extraSigners] : null;\n this.memo = opts.memo || Memo.none();\n this.networkPassphrase = opts.networkPassphrase || null;\n\n this.sorobanData = opts.sorobanData\n ? new SorobanDataBuilder(opts.sorobanData).build()\n : null;\n }\n\n /**\n * Creates a builder instance using an existing {@link Transaction} as a\n * template, ignoring any existing envelope signatures.\n *\n * Note that the sequence number WILL be cloned, so EITHER this transaction or\n * the one it was cloned from will be valid. This is useful in situations\n * where you are constructing a transaction in pieces and need to make\n * adjustments as you go (for example, when filling out Soroban resource\n * information).\n *\n * @param tx - a \"template\" transaction to clone exactly\n * @param opts - additional options to override the clone, e.g.\n * `{fee: '1000'}` will override the existing base fee derived from `tx`\n * (see the {@link TransactionBuilder} constructor for detailed options)\n *\n * **Warning:** This does not clone the transaction's\n * {@link xdr.SorobanTransactionData} (if applicable), use\n * {@link SorobanDataBuilder} and {@link TransactionBuilder.setSorobanData}\n * as needed, instead.\n *\n * TODO: This cannot clone {@link FeeBumpTransaction}s, yet.\n */\n static cloneFrom(\n tx: Transaction,\n opts: Partial<TransactionBuilderOptions> = {},\n ): TransactionBuilder {\n if (!(tx instanceof Transaction)) {\n throw new TypeError(`expected a 'Transaction', got: ${String(tx)}`);\n }\n\n const sequenceNum = (BigInt(tx.sequence) - 1n).toString();\n\n let source;\n\n // rebuild the source account based on the strkey\n if (StrKey.isValidMed25519PublicKey(tx.source)) {\n source = MuxedAccount.fromAddress(tx.source, sequenceNum);\n } else if (StrKey.isValidEd25519PublicKey(tx.source)) {\n source = new Account(tx.source, sequenceNum);\n } else {\n throw new TypeError(`unsupported tx source account: ${tx.source}`);\n }\n\n if (tx.operations.length === 0) {\n throw new Error(\n \"cannot clone a transaction with no operations: \" +\n \"per-operation base fee cannot be determined\",\n );\n }\n\n // the initial fee passed to the builder gets scaled up based on the number\n // of operations at the end, so we have to down-scale first\n const unscaledFee = Math.floor(parseInt(tx.fee, 10) / tx.operations.length);\n\n const builderOpts: TransactionBuilderOptions = {\n fee: (unscaledFee || BASE_FEE).toString(),\n memo: tx.memo,\n networkPassphrase: tx.networkPassphrase,\n };\n\n if (tx.timeBounds) {\n builderOpts.timebounds = tx.timeBounds;\n }\n if (tx.ledgerBounds) {\n builderOpts.ledgerbounds = tx.ledgerBounds;\n }\n if (tx.minAccountSequence) {\n builderOpts.minAccountSequence = tx.minAccountSequence;\n }\n if (tx.minAccountSequenceAge !== undefined) {\n builderOpts.minAccountSequenceAge = tx.minAccountSequenceAge;\n }\n if (tx.minAccountSequenceLedgerGap !== undefined) {\n builderOpts.minAccountSequenceLedgerGap = tx.minAccountSequenceLedgerGap;\n }\n if (tx.extraSigners) {\n builderOpts.extraSigners = tx.extraSigners.map((s) =>\n SignerKey.encodeSignerKey(s),\n );\n }\n\n // User-provided opts override transaction defaults\n Object.assign(builderOpts, opts);\n\n const builder = new TransactionBuilder(source, builderOpts);\n\n tx.tx.operations().forEach((op) => builder.addOperation(op));\n\n return builder;\n }\n\n /**\n * Adds an operation to the transaction.\n *\n * @param operation - The xdr operation object, use {@link\n * Operation} static methods.\n */\n addOperation(operation: xdr.Operation): TransactionBuilder {\n this.operations.push(operation);\n return this;\n }\n\n /**\n * Adds an operation to the transaction at a specific index.\n *\n * @param operation - The xdr operation object to add, use {@link Operation} static methods.\n * @param index - The index at which to insert the operation.\n */\n addOperationAt(operation: xdr.Operation, index: number): TransactionBuilder {\n this.operations.splice(index, 0, operation);\n return this;\n }\n\n /**\n * Removes the operations from the builder (useful when cloning).\n */\n clearOperations(): TransactionBuilder {\n this.operations = [];\n return this;\n }\n\n /**\n * Removes the operation at the specified index from the transaction.\n *\n * @param index - The index of the operation to remove.\n */\n clearOperationAt(index: number): TransactionBuilder {\n this.operations.splice(index, 1);\n return this;\n }\n\n /**\n * Adds a memo to the transaction.\n * @param memo - {@link Memo} object\n */\n addMemo(memo: Memo): TransactionBuilder {\n this.memo = memo;\n return this;\n }\n\n /**\n * Sets a timeout precondition on the transaction.\n *\n * Because of the distributed nature of the Stellar network it is possible\n * that the status of your transaction will be determined after a long time\n * if the network is highly congested. If you want to be sure to receive the\n * status of the transaction within a given period you should set the\n * time bounds with `maxTime` on the transaction (this is what `setTimeout`\n * does internally; if there's `minTime` set but no `maxTime` it will be\n * added).\n *\n * A call to `TransactionBuilder.setTimeout` is **required** if Transaction\n * does not have `max_time` set. If you don't want to set timeout, use\n * {@link TimeoutInfinite}. In general you should set\n * {@link TimeoutInfinite} only in smart contracts.\n *\n * Please note that Horizon may still return <code>504 Gateway Timeout</code>\n * error, even for short timeouts. In such case you need to resubmit the same\n * transaction again without making any changes to receive a status. This\n * method is using the machine system time (UTC), make sure it is set\n * correctly.\n *\n * @param timeoutSeconds - Number of seconds the transaction is good.\n * Can't be negative. If the value is {@link TimeoutInfinite}, the\n * transaction is good indefinitely.\n *\n * @see {@link TimeoutInfinite}\n * @see https://developers.stellar.org/docs/tutorials/handling-errors/\n */\n setTimeout(timeoutSeconds: number): TransactionBuilder {\n if (this.timebounds !== null && Number(this.timebounds.maxTime) > 0) {\n throw new Error(\n \"TimeBounds.max_time has been already set - setting timeout would overwrite it.\",\n );\n }\n\n if (timeoutSeconds < 0) {\n throw new Error(\"timeout cannot be negative\");\n }\n\n if (timeoutSeconds > 0) {\n const timeoutTimestamp = Math.floor(Date.now() / 1000) + timeoutSeconds;\n\n if (this.timebounds === null) {\n this.timebounds = { minTime: 0, maxTime: timeoutTimestamp };\n } else {\n this.timebounds = {\n minTime: this.timebounds.minTime ?? 0,\n maxTime: timeoutTimestamp,\n };\n }\n } else {\n this.timebounds = {\n minTime: 0,\n maxTime: 0,\n };\n }\n\n return this;\n }\n\n /**\n * If you want to prepare a transaction which will become valid at some point\n * in the future, or be invalid after some time, you can set a timebounds\n * precondition. Internally this will set the `minTime`, and `maxTime`\n * preconditions. Conflicts with `setTimeout`, so use one or the other.\n *\n * @param minEpochOrDate - Either a JS Date object, or a number\n * of UNIX epoch seconds. The transaction is valid after this timestamp.\n * Can't be negative. If the value is `0`, the transaction is valid\n * immediately.\n * @param maxEpochOrDate - Either a JS Date object, or a number\n * of UNIX epoch seconds. The transaction is valid until this timestamp.\n * Can't be negative. If the value is `0`, the transaction is valid\n * indefinitely.\n */\n setTimebounds(\n minEpochOrDate: Date | number,\n maxEpochOrDate: Date | number,\n ): TransactionBuilder {\n // Force it to a date type\n if (typeof minEpochOrDate === \"number\") {\n minEpochOrDate = new Date(minEpochOrDate * 1000);\n }\n if (typeof maxEpochOrDate === \"number\") {\n maxEpochOrDate = new Date(maxEpochOrDate * 1000);\n }\n\n if (this.timebounds !== null) {\n throw new Error(\n \"TimeBounds has been already set - setting timebounds would overwrite it.\",\n );\n }\n\n // Convert that date to the epoch seconds\n const minTime = Math.floor(minEpochOrDate.valueOf() / 1000);\n const maxTime = Math.floor(maxEpochOrDate.valueOf() / 1000);\n if (minTime < 0) {\n throw new Error(\"min_time cannot be negative\");\n }\n if (maxTime < 0) {\n throw new Error(\"max_time cannot be negative\");\n }\n if (maxTime > 0 && minTime > maxTime) {\n throw new Error(\"min_time cannot be greater than max_time\");\n }\n\n this.timebounds = { minTime, maxTime };\n\n return this;\n }\n\n /**\n * If you want to prepare a transaction which will only be valid within some\n * range of ledgers, you can set a ledgerbounds precondition.\n * Internally this will set the `minLedger` and `maxLedger` preconditions.\n *\n * @param minLedger - The minimum ledger this transaction is valid at\n * or after. Cannot be negative. If the value is `0` (the default), the\n * transaction is valid immediately.\n *\n * @param maxLedger - The maximum ledger this transaction is valid\n * before. Cannot be negative. If the value is `0`, the transaction is\n * valid indefinitely.\n */\n setLedgerbounds(minLedger: number, maxLedger: number): TransactionBuilder {\n if (this.ledgerbounds !== null) {\n throw new Error(\n \"LedgerBounds has been already set - setting ledgerbounds would overwrite it.\",\n );\n }\n\n if (minLedger < 0) {\n throw new Error(\"min_ledger cannot be negative\");\n }\n if (maxLedger < 0) {\n throw new Error(\"max_ledger cannot be negative\");\n }\n if (maxLedger > 0 && minLedger > maxLedger) {\n throw new Error(\"min_ledger cannot be greater than max_ledger\");\n }\n\n this.ledgerbounds = { minLedger, maxLedger };\n\n return this;\n }\n\n /**\n * If you want to prepare a transaction which will be valid only while the\n * account sequence number is\n *\n * `minAccountSequence <= sourceAccountSequence < tx.seqNum`\n *\n * Note that after execution the account's sequence number is always raised to\n * `tx.seqNum`. Internally this will set the `minAccountSequence`\n * precondition.\n *\n * @param minAccountSequence - The minimum source account sequence\n * number this transaction is valid for. If the value is `0` (the\n * default), the transaction is valid when `sourceAccount`'s sequence\n * number `== tx.seqNum - 1`.\n */\n setMinAccountSequence(minAccountSequence: string): TransactionBuilder {\n if (this.minAccountSequence !== null) {\n throw new Error(\n \"min_account_sequence has been already set - setting min_account_sequence would overwrite it.\",\n );\n }\n\n this.minAccountSequence = minAccountSequence;\n\n return this;\n }\n\n /**\n * For the transaction to be valid, the current ledger time must be at least\n * `minAccountSequenceAge` greater than sourceAccount's `sequenceTime`.\n * Internally this will set the `minAccountSequenceAge` precondition.\n *\n * @param durationInSeconds - The minimum amount of time between\n * source account sequence time and the ledger time when this transaction\n * will become valid. If the value is `0`, the transaction is unrestricted\n * by the account sequence age. Cannot be negative.\n */\n setMinAccountSequenceAge(durationInSeconds: bigint): TransactionBuilder {\n if (typeof durationInSeconds !== \"bigint\") {\n throw new Error(\"min_account_sequence_age must be a bigint\");\n }\n if (this.minAccountSequenceAge !== null) {\n throw new Error(\n \"min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.\",\n );\n }\n\n if (durationInSeconds < 0) {\n throw new Error(\"min_account_sequence_age cannot be negative\");\n }\n\n this.minAccountSequenceAge = durationInSeconds;\n\n return this;\n }\n\n /**\n * For the transaction to be valid, the current ledger number must be at least\n * `minAccountSequenceLedgerGap` greater than sourceAccount's ledger sequence.\n * Internally this will set the `minAccountSequenceLedgerGap` precondition.\n *\n * @param gap - The minimum number of ledgers between source account\n * sequence and the ledger number when this transaction will become valid.\n * If the value is `0`, the transaction is unrestricted by the account\n * sequence ledger. Cannot be negative.\n */\n setMinAccountSequenceLedgerGap(gap: number): TransactionBuilder {\n if (this.minAccountSequenceLedgerGap !== null) {\n throw new Error(\n \"min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.\",\n );\n }\n\n if (gap < 0) {\n throw new Error(\"min_account_sequence_ledger_gap cannot be negative\");\n }\n\n this.minAccountSequenceLedgerGap = gap;\n\n return this;\n }\n\n /**\n * For the transaction to be valid, there must be a signature corresponding to\n * every Signer in this array, even if the signature is not otherwise required\n * by the sourceAccount or operations. Internally this will set the\n * `extraSigners` precondition.\n *\n * @param extraSigners - required extra signers (as {@link StrKey}s)\n */\n setExtraSigners(extraSigners: string[]): TransactionBuilder {\n if (!Array.isArray(extraSigners)) {\n throw new Error(\"extra_signers must be an array of strings.\");\n }\n\n if (this.extraSigners !== null) {\n throw new Error(\n \"extra_signers has been already set - setting extra_signers would overwrite it.\",\n );\n }\n\n if (extraSigners.length > 2) {\n throw new Error(\"extra_signers cannot be longer than 2 elements.\");\n }\n\n this.extraSigners = [...extraSigners];\n\n return this;\n }\n\n /**\n * Set network passphrase for the Transaction that will be built.\n *\n * @param networkPassphrase - passphrase of the target Stellar\n * network (e.g. \"Public Global Stellar Network ; September 2015\").\n */\n setNetworkPassphrase(networkPassphrase: string): TransactionBuilder {\n this.networkPassphrase = networkPassphrase;\n return this;\n }\n\n /**\n * Sets the transaction's internal Soroban transaction data (resources,\n * footprint, etc.).\n *\n * For non-contract(non-Soroban) transactions, this setting has no effect. In\n * the case of Soroban transactions, this is either an instance of\n * {@link xdr.SorobanTransactionData} or a base64-encoded string of said\n * structure. This is usually obtained from the simulation response based on a\n * transaction with a Soroban operation (e.g.\n * {@link Operation.invokeHostFunction}, providing necessary resource\n * and storage footprint estimations for contract invocation.\n *\n * @param sorobanData - the {@link xdr.SorobanTransactionData} as a raw xdr\n * object or a base64 string to be decoded\n *\n * @see {@link SorobanDataBuilder}\n */\n setSorobanData(\n sorobanData: xdr.SorobanTransactionData | string,\n ): TransactionBuilder {\n this.sorobanData = new SorobanDataBuilder(sorobanData).build();\n return this;\n }\n\n /**\n * Creates and adds an invoke host function operation for transferring SAC tokens.\n * This method removes the need for simulation by handling the creation of the\n * appropriate authorization entries and ledger footprint for the transfer operation.\n *\n * @param destination - the address of the recipient of the SAC transfer (should be a valid Stellar address or contract ID)\n * @param asset - the SAC asset to be transferred\n * @param amount - the amount of tokens to be transferred in 7 decimals. IE 1 token with 7 decimals of precision would be represented as \"1_0000000\"\n * @param sorobanFees - optional Soroban fees for the transaction to override the default fees used\n */\n addSacTransferOperation(\n destination: string,\n asset: Asset,\n amount: bigint | string,\n sorobanFees?: SorobanFees,\n ): TransactionBuilder {\n if (BigInt(amount) <= 0n) {\n throw new Error(\"Amount must be a positive integer\");\n } else if (BigInt(amount) > HYPER_MAX_VALUE) {\n // The largest supported value for SAC is i64 however the contract interface uses i128 which is why we convert it to i128\n throw new Error(\"Amount exceeds maximum value for i64\");\n }\n\n if (sorobanFees) {\n const { instructions, readBytes, writeBytes, resourceFee } = sorobanFees;\n const U32_MAX = 4294967295;\n\n if (instructions <= 0 || instructions > U32_MAX) {\n throw new Error(\n `instructions must be greater than 0 and at most ${U32_MAX}`,\n );\n }\n if (readBytes <= 0 || readBytes > U32_MAX) {\n throw new Error(\n `readBytes must be greater than 0 and at most ${U32_MAX}`,\n );\n }\n if (writeBytes <= 0 || writeBytes > U32_MAX) {\n throw new Error(\n `writeBytes must be greater than 0 and at most ${U32_MAX}`,\n );\n }\n if (resourceFee <= 0n || resourceFee > HYPER_MAX_VALUE) {\n throw new Error(\n \"resourceFee must be greater than 0 and at most i64 max\",\n );\n }\n }\n\n const isDestinationContract = StrKey.isValidContract(destination);\n if (!isDestinationContract) {\n if (\n !StrKey.isValidEd25519PublicKey(destination) &&\n !StrKey.isValidMed25519PublicKey(destination)\n ) {\n throw new Error(\n \"Invalid destination address. Must be a valid Stellar address or contract ID.\",\n );\n }\n }\n\n // Resolve M... muxed addresses to their underlying G... address for\n // ledger key construction (Keypair.fromPublicKey only accepts G... keys).\n const destinationBaseAddress = isDestinationContract\n ? destination\n : extractBaseAddress(destination);\n\n if (\n destinationBaseAddress === extractBaseAddress(this.source.accountId())\n ) {\n throw new Error(\"Destination cannot be the same as the source account.\");\n }\n\n if (this.networkPassphrase === null) {\n throw new Error(\n \"networkPassphrase must be set to add a SAC transfer operation\",\n );\n }\n\n const contractId = asset.contractId(this.networkPassphrase);\n const functionName = \"transfer\";\n const source = this.source.accountId();\n const sourceBaseAddress = extractBaseAddress(source);\n const args = [\n nativeToScVal(source, { type: \"address\" }),\n nativeToScVal(destination, { type: \"address\" }),\n nativeToScVal(amount, { type: \"i128\" }),\n ];\n const isAssetNative = asset.isNative();\n\n const auths = new xdr.SorobanAuthorizationEntry({\n credentials: xdr.SorobanCredentials.sorobanCredentialsSourceAccount(),\n rootInvocation: new xdr.SorobanAuthorizedInvocation({\n function:\n xdr.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn(\n new xdr.InvokeContractArgs({\n contractAddress: Address.fromString(contractId).toScAddress(),\n functionName,\n args,\n }),\n ),\n subInvocations: [],\n }),\n });\n\n const footprint = new xdr.LedgerFootprint({\n readOnly: [\n xdr.LedgerKey.contractData(\n new xdr.LedgerKeyContractData({\n contract: Address.fromString(contractId).toScAddress(),\n key: xdr.ScVal.scvLedgerKeyContractInstance(),\n durability: xdr.ContractDataDurability.persistent(),\n }),\n ),\n ],\n readWrite: [],\n });\n\n // Ledger entries for the destination account\n if (isDestinationContract) {\n footprint.readWrite().push(\n xdr.LedgerKey.contractData(\n new xdr.LedgerKeyContractData({\n contract: Address.fromString(contractId).toScAddress(),\n key: xdr.ScVal.scvVec([\n nativeToScVal(\"Balance\", { type: \"symbol\" }),\n nativeToScVal(destination, { type: \"address\" }),\n ]),\n durability: xdr.ContractDataDurability.persistent(),\n }),\n ),\n );\n\n if (!isAssetNative) {\n const assetIssuer = asset.getIssuer();\n\n if (!assetIssuer) {\n throw new Error(\"Asset issuer must be set for non-native assets.\");\n }\n\n footprint.readOnly().push(\n xdr.LedgerKey.account(\n new xdr.LedgerKeyAccount({\n accountId: Keypair.fromPublicKey(assetIssuer).xdrPublicKey(),\n }),\n ),\n );\n }\n } else if (isAssetNative) {\n footprint.readWrite().push(\n xdr.LedgerKey.account(\n new xdr.LedgerKeyAccount({\n accountId: Keypair.fromPublicKey(\n destinationBaseAddress,\n ).xdrPublicKey(),\n }),\n ),\n );\n } else if (asset.getIssuer() !== destinationBaseAddress) {\n footprint.readWrite().push(\n xdr.LedgerKey.trustline(\n new xdr.LedgerKeyTrustLine({\n accountId: Keypair.fromPublicKey(\n destinationBaseAddress,\n ).xdrPublicKey(),\n asset: asset.toTrustLineXDRObject(),\n }),\n ),\n );\n }\n\n // Ledger entries for the source account\n if (asset.isNative()) {\n footprint.readWrite().push(\n xdr.LedgerKey.account(\n new xdr.LedgerKeyAccount({\n accountId: Keypair.fromPublicKey(sourceBaseAddress).xdrPublicKey(),\n }),\n ),\n );\n } else if (asset.getIssuer() !== sourceBaseAddress) {\n footprint.readWrite().push(\n xdr.LedgerKey.trustline(\n new xdr.LedgerKeyTrustLine({\n accountId: Keypair.fromPublicKey(sourceBaseAddress).xdrPublicKey(),\n asset: asset.toTrustLineXDRObject(),\n }),\n ),\n );\n }\n\n const defaultPaymentFees = {\n instructions: 400_000,\n readBytes: 1_000,\n writeBytes: 1_000,\n resourceFee: BigInt(5_000_000),\n };\n\n const sorobanData = new xdr.SorobanTransactionData({\n resources: new xdr.SorobanResources({\n footprint,\n instructions: sorobanFees\n ? sorobanFees.instructions\n : defaultPaymentFees.instructions,\n diskReadBytes: sorobanFees\n ? sorobanFees.readBytes\n : defaultPaymentFees.readBytes,\n writeBytes: sorobanFees\n ? sorobanFees.writeBytes\n : defaultPaymentFees.writeBytes,\n }),\n ext: new xdr.SorobanTransactionDataExt(0),\n resourceFee: new xdr.Int64(\n sorobanFees ? sorobanFees.resourceFee : defaultPaymentFees.resourceFee,\n ),\n });\n const operation = Operation.invokeContractFunction({\n contract: contractId,\n function: functionName,\n args,\n auth: [auths],\n });\n this.setSorobanData(sorobanData);\n return this.addOperation(operation);\n }\n\n /**\n * Builds the transaction and increments the source account's sequence\n * number by 1.\n */\n build(): Transaction {\n const sequenceNumber = new BigNumber(this.source.sequenceNumber()).plus(1);\n const fee = new BigNumber(this.baseFee)\n .times(this.operations.length)\n .toNumber();\n\n if (fee > UINT32_MAX) {\n throw new Error(\n `Total fee (baseFee * operations) exceeds the maximum uint32 value (${UINT32_MAX}). ` +\n `Got ${fee} from baseFee=${this.baseFee} and ${this.operations.length} operation(s).`,\n );\n }\n\n const attrs: {\n fee: number;\n seqNum: xdr.SequenceNumber;\n memo: xdr.Memo | null;\n cond?: xdr.Preconditions;\n sourceAccount?: xdr.MuxedAccount;\n ext?: xdr.TransactionExt;\n } = {\n fee,\n seqNum: xdr.Int64.fromString(sequenceNumber.toString()),\n memo: this.memo ? this.memo.toXDRObject() : null,\n };\n\n if (\n this.timebounds === null ||\n typeof this.timebounds.minTime === \"undefined\" ||\n typeof this.timebounds.maxTime === \"undefined\"\n ) {\n throw new Error(\n \"TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).\",\n );\n }\n\n if (isValidDate(this.timebounds.minTime)) {\n this.timebounds.minTime = Math.floor(\n this.timebounds.minTime.getTime() / 1000,\n );\n }\n\n if (isValidDate(this.timebounds.maxTime)) {\n this.timebounds.maxTime = Math.floor(\n this.timebounds.maxTime.getTime() / 1000,\n );\n }\n\n const minTime = xdr.Uint64.fromString(this.timebounds.minTime.toString());\n const maxTime = xdr.Uint64.fromString(this.timebounds.maxTime.toString());\n\n const timeBounds = new xdr.TimeBounds({ minTime, maxTime });\n\n if (this.hasV2Preconditions()) {\n let ledgerBounds = null;\n\n if (this.ledgerbounds !== null) {\n ledgerBounds = new xdr.LedgerBounds({\n minLedger: this.ledgerbounds.minLedger ?? 0,\n maxLedger: this.ledgerbounds.maxLedger ?? 0,\n });\n }\n\n const minSeqNum = this.minAccountSequence\n ? xdr.Int64.fromString(this.minAccountSequence)\n : null;\n\n const minSeqAge = xdr.Uint64.fromString(\n this.minAccountSequenceAge !== null\n ? this.minAccountSequenceAge.toString()\n : \"0\",\n );\n\n const minSeqLedgerGap = this.minAccountSequenceLedgerGap || 0;\n\n const extraSigners =\n this.extraSigners !== null\n ? this.extraSigners.map((s) => SignerKey.decodeAddress(s))\n : [];\n\n attrs.cond = xdr.Preconditions.precondV2(\n new xdr.PreconditionsV2({\n timeBounds,\n ledgerBounds,\n minSeqNum,\n minSeqAge,\n minSeqLedgerGap,\n extraSigners,\n }),\n );\n } else {\n attrs.cond = xdr.Preconditions.precondTime(timeBounds);\n }\n\n attrs.sourceAccount = decodeAddressToMuxedAccount(this.source.accountId());\n\n // Previously used @ts-ignore and passed xdr.Void as second arg to TransactionExt(0)\n // due to broken TransactionExt types in dts-xdr.\n // Fixed upstream: https://github.com/stellar/dts-xdr/issues/5\n if (this.sorobanData) {\n attrs.ext = new xdr.TransactionExt(1, this.sorobanData);\n // Soroban transactions pay the resource fee in addition to the regular fee, so we need to add it here.\n attrs.fee = new BigNumber(attrs.fee)\n .plus(this.sorobanData.resourceFee().toString())\n .toNumber();\n\n if (attrs.fee > UINT32_MAX) {\n throw new Error(\n `Total fee (baseFee * operations + resourceFee) exceeds the maximum uint32 value (${UINT32_MAX}). ` +\n `Got ${attrs.fee}.`,\n );\n }\n } else {\n attrs.ext = new xdr.TransactionExt(0);\n }\n\n const xtx = new xdr.Transaction(\n attrs as ConstructorParameters<typeof xdr.Transaction>[0],\n );\n xtx.operations(this.operations);\n\n const txEnvelope = xdr.TransactionEnvelope.envelopeTypeTx(\n new xdr.TransactionV1Envelope({ tx: xtx, signatures: [] }),\n );\n\n if (this.networkPassphrase === null) {\n throw new Error(\"networkPassphrase must be set to build a transaction\");\n }\n\n const tx = new Transaction(txEnvelope, this.networkPassphrase);\n\n this.source.incrementSequenceNumber();\n\n return tx;\n }\n\n /**\n * Checks whether any v2 preconditions have been set on this builder.\n */\n hasV2Preconditions() {\n return (\n this.ledgerbounds !== null ||\n this.minAccountSequence !== null ||\n this.minAccountSequenceAge !== null ||\n this.minAccountSequenceLedgerGap !== null ||\n (this.extraSigners !== null && this.extraSigners.length > 0)\n );\n }\n\n /**\n * Builds a {@link FeeBumpTransaction}, enabling you to resubmit an existing\n * transaction with a higher fee.\n *\n * @param feeSource - account paying for the transaction,\n * in the form of either a Keypair (only the public key is used) or\n * an account ID (in G... or M... form, but refer to `withMuxing`)\n * @param baseFee - max fee willing to pay per operation\n * in inner transaction (**in stroops**)\n * @param innerTx - {@link Transaction} to be bumped by\n * the fee bump transaction\n * @param networkPassphrase - passphrase of the target\n * Stellar network (e.g. \"Public Global Stellar Network ; September 2015\",\n * see {@link Networks})\n *\n * TODO: Alongside the next major version bump, this type signature can be\n * changed to be less awkward: accept a MuxedAccount as the `feeSource`\n * rather than a keypair or string.\n *\n * Your fee-bump amount should be `>= 10x` the original fee.\n * @see https://developers.stellar.org/docs/glossary/fee-bumps/#replace-by-fee\n */\n static buildFeeBumpTransaction(\n feeSource: Keypair | string,\n baseFee: string,\n innerTx: Transaction,\n networkPassphrase: string,\n ): FeeBumpTransaction {\n const innerOps = innerTx.operations.length;\n\n const minBaseFee = new BigNumber(BASE_FEE);\n let resourceFee = new BigNumber(0);\n\n // Do we need to do special Soroban fee handling? We only want the fee-bump\n // requirement to match the inclusion fee, not the inclusion+resource fee.\n const env = innerTx.toEnvelope();\n switch (env.switch().value) {\n case xdr.EnvelopeType.envelopeTypeTx().value: {\n const sorobanData = env.v1().tx().ext().value();\n resourceFee = new BigNumber(sorobanData?.resourceFee().toString() ?? 0);\n\n break;\n }\n default:\n break;\n }\n const innerInclusionFee = new BigNumber(innerTx.fee)\n .minus(resourceFee)\n .div(innerOps);\n const base = new BigNumber(baseFee);\n\n // The fee rate for fee bump is at least the fee rate of the inner transaction\n if (base.lt(innerInclusionFee)) {\n throw new Error(\n `Invalid baseFee, it should be at least ${innerInclusionFee.toString()} stroops.`,\n );\n }\n\n // The fee rate is at least the minimum fee\n if (base.lt(minBaseFee)) {\n throw new Error(\n `Invalid baseFee, it should be at least ${minBaseFee.toString()} stroops.`,\n );\n }\n\n let innerTxEnvelope = innerTx.toEnvelope();\n if (innerTxEnvelope.switch() === xdr.EnvelopeType.envelopeTypeTxV0()) {\n const v0Tx = innerTxEnvelope.v0().tx();\n const v0TimeBounds = v0Tx.timeBounds();\n\n if (v0TimeBounds === null) {\n throw new Error(\"Inner transaction must have time bounds\");\n }\n\n const v1Tx = new xdr.Transaction({\n sourceAccount: xdr.MuxedAccount.keyTypeEd25519(\n v0Tx.sourceAccountEd25519(),\n ),\n fee: v0Tx.fee(),\n seqNum: v0Tx.seqNum(),\n cond: xdr.Preconditions.precondTime(v0TimeBounds),\n memo: v0Tx.memo(),\n operations: v0Tx.operations(),\n ext: new xdr.TransactionExt(0),\n });\n innerTxEnvelope = xdr.TransactionEnvelope.envelopeTypeTx(\n new xdr.TransactionV1Envelope({\n tx: v1Tx,\n signatures: innerTxEnvelope.v0().signatures(),\n }),\n );\n }\n\n let feeSourceAccount;\n if (typeof feeSource === \"string\") {\n feeSourceAccount = decodeAddressToMuxedAccount(feeSource);\n } else {\n feeSourceAccount = feeSource.xdrMuxedAccount();\n }\n\n const tx = new xdr.FeeBumpTransaction({\n feeSource: feeSourceAccount,\n fee: xdr.Int64.fromString(\n base\n .times(innerOps + 1)\n .plus(resourceFee)\n .toString(),\n ),\n innerTx: xdr.FeeBumpTransactionInnerTx.envelopeTypeTx(\n innerTxEnvelope.v1(),\n ),\n ext: new xdr.FeeBumpTransactionExt(0),\n });\n const feeBumpTxEnvelope = new xdr.FeeBumpTransactionEnvelope({\n tx,\n signatures: [],\n });\n const envelope =\n xdr.TransactionEnvelope.envelopeTypeTxFeeBump(feeBumpTxEnvelope);\n\n return new FeeBumpTransaction(envelope, networkPassphrase);\n }\n\n /**\n * Build a {@link Transaction} or {@link FeeBumpTransaction} from an\n * xdr.TransactionEnvelope.\n *\n * @param envelope - The transaction envelope\n * object or base64 encoded string.\n * @param networkPassphrase - The network passphrase of the target\n * Stellar network (e.g. \"Public Global Stellar Network ; September\n * 2015\"), see {@link Networks}.\n */\n static fromXDR(\n envelope: xdr.TransactionEnvelope | string,\n networkPassphrase: string,\n ): FeeBumpTransaction | Transaction {\n if (typeof envelope === \"string\") {\n envelope = xdr.TransactionEnvelope.fromXDR(envelope, \"base64\");\n }\n\n if (envelope.switch() === xdr.EnvelopeType.envelopeTypeTxFeeBump()) {\n return new FeeBumpTransaction(envelope, networkPassphrase);\n }\n\n return new Transaction(envelope, networkPassphrase);\n }\n}\n\n/**\n * Checks whether a provided object is a valid Date.\n * @param d - date object\n */\nexport function isValidDate(d: Date | number | string): d is Date {\n return d instanceof Date && !Number.isNaN(d.getTime());\n}\n\n/**\n * Converts a Date, number, or string time value to epoch seconds for\n * validation. Returns undefined if the value is undefined.\n */\nfunction toEpochSeconds(\n value: Date | number | string | undefined,\n): number | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n const num =\n value instanceof Date ? Math.floor(value.getTime() / 1000) : Number(value);\n\n if (!Number.isFinite(num) || num % 1 !== 0) {\n throw new Error(\"timebounds value must be a finite integer or Date\");\n }\n\n return num;\n}\n"],"names":["Hyper","Memo","SorobanDataBuilder","Transaction","StrKey","MuxedAccount","Account","SignerKey","extractBaseAddress","nativeToScVal","xdr","Address","Keypair","operation","Operation","BigNumber","decodeAddressToMuxedAccount","FeeBumpTransaction"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,kBAAkBA,WAAA,CAAM,SAAA;AAC9B,MAAM,UAAA,GAAa,UAAA;AAWZ,MAAM,QAAA,GAAW;AAMjB,MAAM,eAAA,GAAkB;AA4GxB,MAAM,kBAAA,CAAmB;AAAA,EAC9B,MAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,UAAA;AAAA,EAIA,YAAA;AAAA,EACA,kBAAA;AAAA,EACA,qBAAA;AAAA,EACA,2BAAA;AAAA,EACA,YAAA;AAAA,EACA,IAAA;AAAA,EACA,iBAAA;AAAA,EACA,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAA,CACE,aAAA,EACA,IAAA,GAAkC,EAAC,EACnC;AACA,IAAA,IAAI,CAAC,aAAA,EAAe;AAClB,MAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;AAAA,IACnE;AAEA,IAAA,IAAI,IAAA,CAAK,QAAQ,MAAA,EAAW;AAC1B,MAAA,MAAM,IAAI,MAAM,mDAAmD,CAAA;AAAA,IACrE;AAEA,IAAA,IAAA,CAAK,MAAA,GAAS,aAAA;AACd,IAAA,IAAA,CAAK,aAAa,EAAC;AAEnB,IAAA,IAAA,CAAK,UAAU,IAAA,CAAK,GAAA;AACpB,IAAA,IAAI,KAAK,UAAA,EAAY;AACnB,MAAA,MAAM,OAAA,GAAU,cAAA,CAAe,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AAId,uBAAA,CAAY,QAAA,EAAU,iBAAiB,CAAA;AAAA,EACpD;AACF;AAMO,SAAS,YAAY,CAAA,EAAsC;AAChE,EAAA,OAAO,aAAa,IAAA,IAAQ,CAAC,OAAO,KAAA,CAAM,CAAA,CAAE,SAAS,CAAA;AACvD;AAMA,SAAS,eACP,KAAA,EACoB;AACpB,EAAA,IAAI,UAAU,MAAA,EAAW;AACvB,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAM,GAAA,GACJ,KAAA,YAAiB,IAAA,GAAO,IAAA,CAAK,KAAA,CAAM,KAAA,CAAM,OAAA,EAAQ,GAAI,GAAI,CAAA,GAAI,MAAA,CAAO,KAAK,CAAA;AAE3E,EAAA,IAAI,CAAC,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,IAAK,GAAA,GAAM,MAAM,CAAA,EAAG;AAC1C,IAAA,MAAM,IAAI,MAAM,mDAAmD,CAAA;AAAA,EACrE;AAEA,EAAA,OAAO,GAAA;AACT;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"transaction_builder.js","sources":["../../../src/base/transaction_builder.ts"],"sourcesContent":["import { Hyper } from \"@stellar/js-xdr\";\nimport BigNumber from \"./util/bignumber.js\";\n\nimport xdr from \"./xdr.js\";\n\nimport { Account } from \"./account.js\";\nimport { MuxedAccount } from \"./muxed_account.js\";\nimport type { TransactionSource } from \"./transaction_source.js\";\nimport {\n decodeAddressToMuxedAccount,\n extractBaseAddress,\n} from \"./util/decode_encode_muxed_account.js\";\n\nimport { Transaction } from \"./transaction.js\";\nimport { FeeBumpTransaction } from \"./fee_bump_transaction.js\";\nimport { SorobanDataBuilder } from \"./sorobandata_builder.js\";\n\nimport { StrKey } from \"./strkey.js\";\nimport { SignerKey } from \"./signerkey.js\";\nimport { Memo } from \"./memo.js\";\nimport { Asset } from \"./asset.js\";\nimport { nativeToScVal } from \"./scval.js\";\nimport { Operation } from \"./operation.js\";\nimport { Address } from \"./address.js\";\nimport { Keypair } from \"./keypair.js\";\n\nconst HYPER_MAX_VALUE = Hyper.MAX_VALUE as unknown as bigint;\nconst UINT32_MAX = 4294967295; // 2^32 - 1\n\n/**\n * Minimum base fee for transactions. If this fee is below the network\n * minimum, the transaction will fail. The more operations in the\n * transaction, the greater the required fee. Use\n * {@link Horizon.Server.fetchBaseFee} to get an accurate value of minimum\n * transaction fee on the network.\n *\n * @see [Fees](https://developers.stellar.org/docs/glossary/fees/)\n */\nexport const BASE_FEE = \"100\"; // Stroops\n\n/**\n * @see {@link TransactionBuilder.setTimeout}\n * @see [Timeout](https://developers.stellar.org/api/resources/transactions/post/)\n */\nexport const TimeoutInfinite = 0;\n\n/**\n * Soroban fee parameters for resource-limited transactions.\n */\nexport interface SorobanFees {\n /** The number of instructions executed by the transaction. */\n instructions: number;\n /** The number of bytes read from the ledger by the transaction. */\n readBytes: number;\n /** The number of bytes written to the ledger by the transaction. */\n writeBytes: number;\n /** The fee to be paid for the transaction, in stroops. */\n resourceFee: bigint;\n}\n\n/**\n * Options for constructing a {@link TransactionBuilder}.\n */\nexport interface TransactionBuilderOptions {\n /** Max fee you're willing to pay per operation in this transaction (**in stroops**). */\n fee: string;\n /** Memo for the transaction. */\n memo?: Memo;\n /**\n * Passphrase of the target Stellar network (e.g. \"Public Global Stellar\n * Network ; September 2015\" for the pubnet).\n */\n networkPassphrase?: string;\n /** Timebounds for the validity of this transaction. */\n timebounds?: {\n /** 64-bit UNIX timestamp or Date object. */\n minTime?: Date | number | string;\n /** 64-bit UNIX timestamp or Date object. */\n maxTime?: Date | number | string;\n };\n /** Ledger bounds for the validity of this transaction. */\n ledgerbounds?: {\n /** Number of the minimum ledger sequence. */\n minLedger?: number;\n /** Number of the maximum ledger sequence. */\n maxLedger?: number;\n };\n /** Minimum source account sequence number this transaction is valid for. */\n minAccountSequence?: string;\n /** Minimum seconds between source account sequence time and ledger time. */\n minAccountSequenceAge?: bigint;\n /** Minimum ledgers between source account sequence and current ledger. */\n minAccountSequenceLedgerGap?: number;\n /** List of extra signers required for this transaction. */\n extraSigners?: string[];\n /**\n * An instance of {@link xdr.SorobanTransactionData} or a base64 string.\n * Provides resource estimations for Soroban transactions. Has no effect on\n * non-contract transactions.\n */\n sorobanData?: xdr.SorobanTransactionData | string;\n}\n\n/**\n * <p>Transaction builder helps constructs a new `{@link Transaction}` using the\n * given {@link Account} as the transaction's \"source account\". The transaction\n * will use the current sequence number of the given account as its sequence\n * number and increment the given account's sequence number by one. The given\n * source account must include a private key for signing the transaction or an\n * error will be thrown.</p>\n *\n * <p>Operations can be added to the transaction via their corresponding builder\n * methods, and each returns the TransactionBuilder object so they can be\n * chained together. After adding the desired operations, call the `build()`\n * method on the `TransactionBuilder` to return a fully constructed\n * {@link Transaction} that can be signed. The returned transaction will contain the\n * sequence number of the source account and include the signature from the\n * source account.</p>\n *\n * <p><strong>Be careful about unsubmitted transactions!</strong> When you build\n * a transaction, `stellar-sdk` automatically increments the source account's\n * sequence number. If you end up not submitting this transaction and submitting\n * another one instead, it'll fail due to the sequence number being wrong. So if\n * you decide not to use a built transaction, make sure to update the source\n * account's sequence number with\n * [Server.loadAccount](https://stellar.github.io/js-stellar-sdk/Server.html#loadAccount)\n * before creating another transaction.</p>\n *\n * <p>The following code example creates a new transaction with {@link\n * Operation.createAccount} and {@link Operation.payment} operations. The\n * Transaction's source account first funds `destinationA`, then sends a payment\n * to `destinationB`. The built transaction is then signed by\n * `sourceKeypair`.</p>\n *\n * ```\n * var transaction = new TransactionBuilder(source, { fee, networkPassphrase: Networks.TESTNET })\n * .addOperation(Operation.createAccount({\n * destination: destinationA,\n * startingBalance: \"20\"\n * })) // <- funds and creates destinationA\n * .addOperation(Operation.payment({\n * destination: destinationB,\n * amount: \"100\",\n * asset: Asset.native()\n * })) // <- sends 100 XLM to destinationB\n * .setTimeout(30)\n * .build();\n *\n * transaction.sign(sourceKeypair);\n * ```\n *\n */\nexport class TransactionBuilder {\n source: TransactionSource;\n operations: xdr.Operation[];\n baseFee: string;\n timebounds: {\n minTime?: Date | number | string;\n maxTime?: Date | number | string;\n } | null;\n ledgerbounds: { minLedger?: number; maxLedger?: number } | null;\n minAccountSequence: string | null;\n minAccountSequenceAge: bigint | null;\n minAccountSequenceLedgerGap: number | null;\n extraSigners: string[] | null;\n memo: Memo;\n networkPassphrase: string | null;\n sorobanData: xdr.SorobanTransactionData | null;\n\n /**\n * @param sourceAccount - source account for this transaction\n * @param opts - options object (see {@link TransactionBuilderOptions})\n */\n constructor(\n sourceAccount: TransactionSource,\n opts: TransactionBuilderOptions = {} as TransactionBuilderOptions,\n ) {\n if (!sourceAccount) {\n throw new Error(\"must specify source account for the transaction\");\n }\n\n if (opts.fee === undefined) {\n throw new Error(\"must specify fee for the transaction (in stroops)\");\n }\n\n this.source = sourceAccount;\n this.operations = [];\n\n this.baseFee = opts.fee;\n if (opts.timebounds) {\n const minTime = toEpochSeconds(opts.timebounds.minTime);\n const maxTime = toEpochSeconds(opts.timebounds.maxTime);\n\n if (minTime !== undefined && minTime < 0) {\n throw new Error(\"min_time cannot be negative\");\n }\n\n if (maxTime !== undefined && maxTime < 0) {\n throw new Error(\"max_time cannot be negative\");\n }\n\n if (\n minTime !== undefined &&\n maxTime !== undefined &&\n maxTime > 0 &&\n minTime > maxTime\n ) {\n throw new Error(\"min_time cannot be greater than max_time\");\n }\n\n this.timebounds = { ...opts.timebounds };\n } else {\n this.timebounds = null;\n }\n\n if (opts.ledgerbounds) {\n const minLedger = opts.ledgerbounds.minLedger;\n const maxLedger = opts.ledgerbounds.maxLedger;\n\n if (minLedger !== undefined && minLedger < 0) {\n throw new Error(\"min_ledger cannot be negative\");\n }\n\n if (maxLedger !== undefined && maxLedger < 0) {\n throw new Error(\"max_ledger cannot be negative\");\n }\n\n if (\n minLedger !== undefined &&\n maxLedger !== undefined &&\n maxLedger > 0 &&\n minLedger > maxLedger\n ) {\n throw new Error(\"min_ledger cannot be greater than max_ledger\");\n }\n\n this.ledgerbounds = { ...opts.ledgerbounds };\n } else {\n this.ledgerbounds = null;\n }\n this.minAccountSequence = opts.minAccountSequence || null;\n this.minAccountSequenceAge =\n opts.minAccountSequenceAge !== undefined\n ? opts.minAccountSequenceAge\n : null;\n this.minAccountSequenceLedgerGap =\n opts.minAccountSequenceLedgerGap !== undefined\n ? opts.minAccountSequenceLedgerGap\n : null;\n this.extraSigners = opts.extraSigners ? [...opts.extraSigners] : null;\n this.memo = opts.memo || Memo.none();\n this.networkPassphrase = opts.networkPassphrase || null;\n\n this.sorobanData = opts.sorobanData\n ? new SorobanDataBuilder(opts.sorobanData).build()\n : null;\n }\n\n /**\n * Creates a builder instance using an existing {@link Transaction} as a\n * template, ignoring any existing envelope signatures.\n *\n * Note that the sequence number WILL be cloned, so EITHER this transaction or\n * the one it was cloned from will be valid. This is useful in situations\n * where you are constructing a transaction in pieces and need to make\n * adjustments as you go (for example, when filling out Soroban resource\n * information).\n *\n * @param tx - a \"template\" transaction to clone exactly\n * @param opts - additional options to override the clone, e.g.\n * `{fee: '1000'}` will override the existing base fee derived from `tx`\n * (see the {@link TransactionBuilder} constructor for detailed options)\n *\n * **Warning:** This does not clone the transaction's\n * {@link xdr.SorobanTransactionData} (if applicable), use\n * {@link SorobanDataBuilder} and {@link TransactionBuilder.setSorobanData}\n * as needed, instead.\n *\n * TODO: This cannot clone {@link FeeBumpTransaction}s, yet.\n */\n static cloneFrom(\n tx: Transaction,\n opts: Partial<TransactionBuilderOptions> = {},\n ): TransactionBuilder {\n if (!(tx instanceof Transaction)) {\n throw new TypeError(`expected a 'Transaction', got: ${String(tx)}`);\n }\n\n const sequenceNum = (BigInt(tx.sequence) - 1n).toString();\n\n let source;\n\n // rebuild the source account based on the strkey\n if (StrKey.isValidMed25519PublicKey(tx.source)) {\n source = MuxedAccount.fromAddress(tx.source, sequenceNum);\n } else if (StrKey.isValidEd25519PublicKey(tx.source)) {\n source = new Account(tx.source, sequenceNum);\n } else {\n throw new TypeError(`unsupported tx source account: ${tx.source}`);\n }\n\n if (tx.operations.length === 0) {\n throw new Error(\n \"cannot clone a transaction with no operations: \" +\n \"per-operation base fee cannot be determined\",\n );\n }\n\n // if this is a Soroban transaction, the resource fee is folded into the\n // total fee and gets re-added on build(), so it has to be excluded before\n // deriving the per-operation base fee\n let sorobanData: xdr.SorobanTransactionData | undefined;\n const envelope = tx.toEnvelope();\n if (envelope.switch() === xdr.EnvelopeType.envelopeTypeTx()) {\n sorobanData = envelope.v1().tx().ext().value() ?? undefined;\n }\n let totalFee = parseInt(tx.fee, 10);\n if (sorobanData) {\n const resourceFee = Number(sorobanData.resourceFee().toBigInt());\n // only subtract if it leaves a positive inclusion fee: a malformed tx\n // can declare a resource fee that eats the entire fee (or more)\n if (totalFee - resourceFee > 0) {\n totalFee -= resourceFee;\n }\n }\n\n // the initial fee passed to the builder gets scaled up based on the number\n // of operations at the end, so we have to down-scale first\n const unscaledFee = Math.floor(totalFee / tx.operations.length);\n\n const builderOpts: TransactionBuilderOptions = {\n fee: (unscaledFee || BASE_FEE).toString(),\n memo: tx.memo,\n networkPassphrase: tx.networkPassphrase,\n };\n\n if (tx.timeBounds) {\n builderOpts.timebounds = tx.timeBounds;\n }\n if (tx.ledgerBounds) {\n builderOpts.ledgerbounds = tx.ledgerBounds;\n }\n if (tx.minAccountSequence) {\n builderOpts.minAccountSequence = tx.minAccountSequence;\n }\n if (tx.minAccountSequenceAge !== undefined) {\n builderOpts.minAccountSequenceAge = tx.minAccountSequenceAge;\n }\n if (tx.minAccountSequenceLedgerGap !== undefined) {\n builderOpts.minAccountSequenceLedgerGap = tx.minAccountSequenceLedgerGap;\n }\n if (tx.extraSigners) {\n builderOpts.extraSigners = tx.extraSigners.map((s) =>\n SignerKey.encodeSignerKey(s),\n );\n }\n\n // User-provided opts override transaction defaults\n Object.assign(builderOpts, opts);\n\n const builder = new TransactionBuilder(source, builderOpts);\n\n tx.tx.operations().forEach((op) => builder.addOperation(op));\n\n return builder;\n }\n\n /**\n * Adds an operation to the transaction.\n *\n * @param operation - The xdr operation object, use {@link\n * Operation} static methods.\n */\n addOperation(operation: xdr.Operation): TransactionBuilder {\n this.operations.push(operation);\n return this;\n }\n\n /**\n * Adds an operation to the transaction at a specific index.\n *\n * @param operation - The xdr operation object to add, use {@link Operation} static methods.\n * @param index - The index at which to insert the operation.\n */\n addOperationAt(operation: xdr.Operation, index: number): TransactionBuilder {\n this.operations.splice(index, 0, operation);\n return this;\n }\n\n /**\n * Removes the operations from the builder (useful when cloning).\n */\n clearOperations(): TransactionBuilder {\n this.operations = [];\n return this;\n }\n\n /**\n * Removes the operation at the specified index from the transaction.\n *\n * @param index - The index of the operation to remove.\n */\n clearOperationAt(index: number): TransactionBuilder {\n this.operations.splice(index, 1);\n return this;\n }\n\n /**\n * Adds a memo to the transaction.\n * @param memo - {@link Memo} object\n */\n addMemo(memo: Memo): TransactionBuilder {\n this.memo = memo;\n return this;\n }\n\n /**\n * Sets a timeout precondition on the transaction.\n *\n * Because of the distributed nature of the Stellar network it is possible\n * that the status of your transaction will be determined after a long time\n * if the network is highly congested. If you want to be sure to receive the\n * status of the transaction within a given period you should set the\n * time bounds with `maxTime` on the transaction (this is what `setTimeout`\n * does internally; if there's `minTime` set but no `maxTime` it will be\n * added).\n *\n * A call to `TransactionBuilder.setTimeout` is **required** if Transaction\n * does not have `max_time` set. If you don't want to set timeout, use\n * {@link TimeoutInfinite}. In general you should set\n * {@link TimeoutInfinite} only in smart contracts.\n *\n * Please note that Horizon may still return <code>504 Gateway Timeout</code>\n * error, even for short timeouts. In such case you need to resubmit the same\n * transaction again without making any changes to receive a status. This\n * method is using the machine system time (UTC), make sure it is set\n * correctly.\n *\n * @param timeoutSeconds - Number of seconds the transaction is good.\n * Can't be negative. If the value is {@link TimeoutInfinite}, the\n * transaction is good indefinitely.\n *\n * @see {@link TimeoutInfinite}\n * @see https://developers.stellar.org/docs/tutorials/handling-errors/\n */\n setTimeout(timeoutSeconds: number): TransactionBuilder {\n if (this.timebounds !== null && Number(this.timebounds.maxTime) > 0) {\n throw new Error(\n \"TimeBounds.max_time has been already set - setting timeout would overwrite it.\",\n );\n }\n\n if (timeoutSeconds < 0) {\n throw new Error(\"timeout cannot be negative\");\n }\n\n if (timeoutSeconds > 0) {\n const timeoutTimestamp = Math.floor(Date.now() / 1000) + timeoutSeconds;\n\n if (this.timebounds === null) {\n this.timebounds = { minTime: 0, maxTime: timeoutTimestamp };\n } else {\n this.timebounds = {\n minTime: this.timebounds.minTime ?? 0,\n maxTime: timeoutTimestamp,\n };\n }\n } else {\n this.timebounds = {\n minTime: 0,\n maxTime: 0,\n };\n }\n\n return this;\n }\n\n /**\n * If you want to prepare a transaction which will become valid at some point\n * in the future, or be invalid after some time, you can set a timebounds\n * precondition. Internally this will set the `minTime`, and `maxTime`\n * preconditions. Conflicts with `setTimeout`, so use one or the other.\n *\n * @param minEpochOrDate - Either a JS Date object, or a number\n * of UNIX epoch seconds. The transaction is valid after this timestamp.\n * Can't be negative. If the value is `0`, the transaction is valid\n * immediately.\n * @param maxEpochOrDate - Either a JS Date object, or a number\n * of UNIX epoch seconds. The transaction is valid until this timestamp.\n * Can't be negative. If the value is `0`, the transaction is valid\n * indefinitely.\n */\n setTimebounds(\n minEpochOrDate: Date | number,\n maxEpochOrDate: Date | number,\n ): TransactionBuilder {\n // Force it to a date type\n if (typeof minEpochOrDate === \"number\") {\n minEpochOrDate = new Date(minEpochOrDate * 1000);\n }\n if (typeof maxEpochOrDate === \"number\") {\n maxEpochOrDate = new Date(maxEpochOrDate * 1000);\n }\n\n if (this.timebounds !== null) {\n throw new Error(\n \"TimeBounds has been already set - setting timebounds would overwrite it.\",\n );\n }\n\n // Convert that date to the epoch seconds\n const minTime = Math.floor(minEpochOrDate.valueOf() / 1000);\n const maxTime = Math.floor(maxEpochOrDate.valueOf() / 1000);\n if (minTime < 0) {\n throw new Error(\"min_time cannot be negative\");\n }\n if (maxTime < 0) {\n throw new Error(\"max_time cannot be negative\");\n }\n if (maxTime > 0 && minTime > maxTime) {\n throw new Error(\"min_time cannot be greater than max_time\");\n }\n\n this.timebounds = { minTime, maxTime };\n\n return this;\n }\n\n /**\n * If you want to prepare a transaction which will only be valid within some\n * range of ledgers, you can set a ledgerbounds precondition.\n * Internally this will set the `minLedger` and `maxLedger` preconditions.\n *\n * @param minLedger - The minimum ledger this transaction is valid at\n * or after. Cannot be negative. If the value is `0` (the default), the\n * transaction is valid immediately.\n *\n * @param maxLedger - The maximum ledger this transaction is valid\n * before. Cannot be negative. If the value is `0`, the transaction is\n * valid indefinitely.\n */\n setLedgerbounds(minLedger: number, maxLedger: number): TransactionBuilder {\n if (this.ledgerbounds !== null) {\n throw new Error(\n \"LedgerBounds has been already set - setting ledgerbounds would overwrite it.\",\n );\n }\n\n if (minLedger < 0) {\n throw new Error(\"min_ledger cannot be negative\");\n }\n if (maxLedger < 0) {\n throw new Error(\"max_ledger cannot be negative\");\n }\n if (maxLedger > 0 && minLedger > maxLedger) {\n throw new Error(\"min_ledger cannot be greater than max_ledger\");\n }\n\n this.ledgerbounds = { minLedger, maxLedger };\n\n return this;\n }\n\n /**\n * If you want to prepare a transaction which will be valid only while the\n * account sequence number is\n *\n * `minAccountSequence <= sourceAccountSequence < tx.seqNum`\n *\n * Note that after execution the account's sequence number is always raised to\n * `tx.seqNum`. Internally this will set the `minAccountSequence`\n * precondition.\n *\n * @param minAccountSequence - The minimum source account sequence\n * number this transaction is valid for. If the value is `0` (the\n * default), the transaction is valid when `sourceAccount`'s sequence\n * number `== tx.seqNum - 1`.\n */\n setMinAccountSequence(minAccountSequence: string): TransactionBuilder {\n if (this.minAccountSequence !== null) {\n throw new Error(\n \"min_account_sequence has been already set - setting min_account_sequence would overwrite it.\",\n );\n }\n\n this.minAccountSequence = minAccountSequence;\n\n return this;\n }\n\n /**\n * For the transaction to be valid, the current ledger time must be at least\n * `minAccountSequenceAge` greater than sourceAccount's `sequenceTime`.\n * Internally this will set the `minAccountSequenceAge` precondition.\n *\n * @param durationInSeconds - The minimum amount of time between\n * source account sequence time and the ledger time when this transaction\n * will become valid. If the value is `0`, the transaction is unrestricted\n * by the account sequence age. Cannot be negative.\n */\n setMinAccountSequenceAge(durationInSeconds: bigint): TransactionBuilder {\n if (typeof durationInSeconds !== \"bigint\") {\n throw new Error(\"min_account_sequence_age must be a bigint\");\n }\n if (this.minAccountSequenceAge !== null) {\n throw new Error(\n \"min_account_sequence_age has been already set - setting min_account_sequence_age would overwrite it.\",\n );\n }\n\n if (durationInSeconds < 0) {\n throw new Error(\"min_account_sequence_age cannot be negative\");\n }\n\n this.minAccountSequenceAge = durationInSeconds;\n\n return this;\n }\n\n /**\n * For the transaction to be valid, the current ledger number must be at least\n * `minAccountSequenceLedgerGap` greater than sourceAccount's ledger sequence.\n * Internally this will set the `minAccountSequenceLedgerGap` precondition.\n *\n * @param gap - The minimum number of ledgers between source account\n * sequence and the ledger number when this transaction will become valid.\n * If the value is `0`, the transaction is unrestricted by the account\n * sequence ledger. Cannot be negative.\n */\n setMinAccountSequenceLedgerGap(gap: number): TransactionBuilder {\n if (this.minAccountSequenceLedgerGap !== null) {\n throw new Error(\n \"min_account_sequence_ledger_gap has been already set - setting min_account_sequence_ledger_gap would overwrite it.\",\n );\n }\n\n if (gap < 0) {\n throw new Error(\"min_account_sequence_ledger_gap cannot be negative\");\n }\n\n this.minAccountSequenceLedgerGap = gap;\n\n return this;\n }\n\n /**\n * For the transaction to be valid, there must be a signature corresponding to\n * every Signer in this array, even if the signature is not otherwise required\n * by the sourceAccount or operations. Internally this will set the\n * `extraSigners` precondition.\n *\n * @param extraSigners - required extra signers (as {@link StrKey}s)\n */\n setExtraSigners(extraSigners: string[]): TransactionBuilder {\n if (!Array.isArray(extraSigners)) {\n throw new Error(\"extra_signers must be an array of strings.\");\n }\n\n if (this.extraSigners !== null) {\n throw new Error(\n \"extra_signers has been already set - setting extra_signers would overwrite it.\",\n );\n }\n\n if (extraSigners.length > 2) {\n throw new Error(\"extra_signers cannot be longer than 2 elements.\");\n }\n\n this.extraSigners = [...extraSigners];\n\n return this;\n }\n\n /**\n * Set network passphrase for the Transaction that will be built.\n *\n * @param networkPassphrase - passphrase of the target Stellar\n * network (e.g. \"Public Global Stellar Network ; September 2015\").\n */\n setNetworkPassphrase(networkPassphrase: string): TransactionBuilder {\n this.networkPassphrase = networkPassphrase;\n return this;\n }\n\n /**\n * Sets the transaction's internal Soroban transaction data (resources,\n * footprint, etc.).\n *\n * For non-contract(non-Soroban) transactions, this setting has no effect. In\n * the case of Soroban transactions, this is either an instance of\n * {@link xdr.SorobanTransactionData} or a base64-encoded string of said\n * structure. This is usually obtained from the simulation response based on a\n * transaction with a Soroban operation (e.g.\n * {@link Operation.invokeHostFunction}, providing necessary resource\n * and storage footprint estimations for contract invocation.\n *\n * @param sorobanData - the {@link xdr.SorobanTransactionData} as a raw xdr\n * object or a base64 string to be decoded\n *\n * @see {@link SorobanDataBuilder}\n */\n setSorobanData(\n sorobanData: xdr.SorobanTransactionData | string,\n ): TransactionBuilder {\n this.sorobanData = new SorobanDataBuilder(sorobanData).build();\n return this;\n }\n\n /**\n * Creates and adds an invoke host function operation for transferring SAC tokens.\n * This method removes the need for simulation by handling the creation of the\n * appropriate authorization entries and ledger footprint for the transfer operation.\n *\n * @param destination - the address of the recipient of the SAC transfer (should be a valid Stellar address or contract ID)\n * @param asset - the SAC asset to be transferred\n * @param amount - the amount of tokens to be transferred in 7 decimals. IE 1 token with 7 decimals of precision would be represented as \"1_0000000\"\n * @param sorobanFees - optional Soroban fees for the transaction to override the default fees used\n */\n addSacTransferOperation(\n destination: string,\n asset: Asset,\n amount: bigint | string,\n sorobanFees?: SorobanFees,\n ): TransactionBuilder {\n if (BigInt(amount) <= 0n) {\n throw new Error(\"Amount must be a positive integer\");\n } else if (BigInt(amount) > HYPER_MAX_VALUE) {\n // The largest supported value for SAC is i64 however the contract interface uses i128 which is why we convert it to i128\n throw new Error(\"Amount exceeds maximum value for i64\");\n }\n\n if (sorobanFees) {\n const { instructions, readBytes, writeBytes, resourceFee } = sorobanFees;\n const U32_MAX = 4294967295;\n\n if (instructions <= 0 || instructions > U32_MAX) {\n throw new Error(\n `instructions must be greater than 0 and at most ${U32_MAX}`,\n );\n }\n if (readBytes <= 0 || readBytes > U32_MAX) {\n throw new Error(\n `readBytes must be greater than 0 and at most ${U32_MAX}`,\n );\n }\n if (writeBytes <= 0 || writeBytes > U32_MAX) {\n throw new Error(\n `writeBytes must be greater than 0 and at most ${U32_MAX}`,\n );\n }\n if (resourceFee <= 0n || resourceFee > HYPER_MAX_VALUE) {\n throw new Error(\n \"resourceFee must be greater than 0 and at most i64 max\",\n );\n }\n }\n\n const isDestinationContract = StrKey.isValidContract(destination);\n if (!isDestinationContract) {\n if (\n !StrKey.isValidEd25519PublicKey(destination) &&\n !StrKey.isValidMed25519PublicKey(destination)\n ) {\n throw new Error(\n \"Invalid destination address. Must be a valid Stellar address or contract ID.\",\n );\n }\n }\n\n // Resolve M... muxed addresses to their underlying G... address for\n // ledger key construction (Keypair.fromPublicKey only accepts G... keys).\n const destinationBaseAddress = isDestinationContract\n ? destination\n : extractBaseAddress(destination);\n\n if (\n destinationBaseAddress === extractBaseAddress(this.source.accountId())\n ) {\n throw new Error(\"Destination cannot be the same as the source account.\");\n }\n\n if (this.networkPassphrase === null) {\n throw new Error(\n \"networkPassphrase must be set to add a SAC transfer operation\",\n );\n }\n\n const contractId = asset.contractId(this.networkPassphrase);\n const functionName = \"transfer\";\n const source = this.source.accountId();\n const sourceBaseAddress = extractBaseAddress(source);\n const args = [\n nativeToScVal(source, { type: \"address\" }),\n nativeToScVal(destination, { type: \"address\" }),\n nativeToScVal(amount, { type: \"i128\" }),\n ];\n const isAssetNative = asset.isNative();\n\n const auths = new xdr.SorobanAuthorizationEntry({\n credentials: xdr.SorobanCredentials.sorobanCredentialsSourceAccount(),\n rootInvocation: new xdr.SorobanAuthorizedInvocation({\n function:\n xdr.SorobanAuthorizedFunction.sorobanAuthorizedFunctionTypeContractFn(\n new xdr.InvokeContractArgs({\n contractAddress: Address.fromString(contractId).toScAddress(),\n functionName,\n args,\n }),\n ),\n subInvocations: [],\n }),\n });\n\n const footprint = new xdr.LedgerFootprint({\n readOnly: [\n xdr.LedgerKey.contractData(\n new xdr.LedgerKeyContractData({\n contract: Address.fromString(contractId).toScAddress(),\n key: xdr.ScVal.scvLedgerKeyContractInstance(),\n durability: xdr.ContractDataDurability.persistent(),\n }),\n ),\n ],\n readWrite: [],\n });\n\n // Ledger entries for the destination account\n if (isDestinationContract) {\n footprint.readWrite().push(\n xdr.LedgerKey.contractData(\n new xdr.LedgerKeyContractData({\n contract: Address.fromString(contractId).toScAddress(),\n key: xdr.ScVal.scvVec([\n nativeToScVal(\"Balance\", { type: \"symbol\" }),\n nativeToScVal(destination, { type: \"address\" }),\n ]),\n durability: xdr.ContractDataDurability.persistent(),\n }),\n ),\n );\n\n if (!isAssetNative) {\n const assetIssuer = asset.getIssuer();\n\n if (!assetIssuer) {\n throw new Error(\"Asset issuer must be set for non-native assets.\");\n }\n\n footprint.readOnly().push(\n xdr.LedgerKey.account(\n new xdr.LedgerKeyAccount({\n accountId: Keypair.fromPublicKey(assetIssuer).xdrPublicKey(),\n }),\n ),\n );\n }\n } else if (isAssetNative) {\n footprint.readWrite().push(\n xdr.LedgerKey.account(\n new xdr.LedgerKeyAccount({\n accountId: Keypair.fromPublicKey(\n destinationBaseAddress,\n ).xdrPublicKey(),\n }),\n ),\n );\n } else if (asset.getIssuer() !== destinationBaseAddress) {\n footprint.readWrite().push(\n xdr.LedgerKey.trustline(\n new xdr.LedgerKeyTrustLine({\n accountId: Keypair.fromPublicKey(\n destinationBaseAddress,\n ).xdrPublicKey(),\n asset: asset.toTrustLineXDRObject(),\n }),\n ),\n );\n }\n\n // Ledger entries for the source account\n if (asset.isNative()) {\n footprint.readWrite().push(\n xdr.LedgerKey.account(\n new xdr.LedgerKeyAccount({\n accountId: Keypair.fromPublicKey(sourceBaseAddress).xdrPublicKey(),\n }),\n ),\n );\n } else if (asset.getIssuer() !== sourceBaseAddress) {\n footprint.readWrite().push(\n xdr.LedgerKey.trustline(\n new xdr.LedgerKeyTrustLine({\n accountId: Keypair.fromPublicKey(sourceBaseAddress).xdrPublicKey(),\n asset: asset.toTrustLineXDRObject(),\n }),\n ),\n );\n }\n\n const defaultPaymentFees = {\n instructions: 400_000,\n readBytes: 1_000,\n writeBytes: 1_000,\n resourceFee: BigInt(5_000_000),\n };\n\n const sorobanData = new xdr.SorobanTransactionData({\n resources: new xdr.SorobanResources({\n footprint,\n instructions: sorobanFees\n ? sorobanFees.instructions\n : defaultPaymentFees.instructions,\n diskReadBytes: sorobanFees\n ? sorobanFees.readBytes\n : defaultPaymentFees.readBytes,\n writeBytes: sorobanFees\n ? sorobanFees.writeBytes\n : defaultPaymentFees.writeBytes,\n }),\n ext: new xdr.SorobanTransactionDataExt(0),\n resourceFee: new xdr.Int64(\n sorobanFees ? sorobanFees.resourceFee : defaultPaymentFees.resourceFee,\n ),\n });\n const operation = Operation.invokeContractFunction({\n contract: contractId,\n function: functionName,\n args,\n auth: [auths],\n });\n this.setSorobanData(sorobanData);\n return this.addOperation(operation);\n }\n\n /**\n * Builds the transaction and increments the source account's sequence\n * number by 1.\n */\n build(): Transaction {\n const sequenceNumber = new BigNumber(this.source.sequenceNumber()).plus(1);\n const fee = new BigNumber(this.baseFee)\n .times(this.operations.length)\n .toNumber();\n\n if (fee > UINT32_MAX) {\n throw new Error(\n `Total fee (baseFee * operations) exceeds the maximum uint32 value (${UINT32_MAX}). ` +\n `Got ${fee} from baseFee=${this.baseFee} and ${this.operations.length} operation(s).`,\n );\n }\n\n const attrs: {\n fee: number;\n seqNum: xdr.SequenceNumber;\n memo: xdr.Memo | null;\n cond?: xdr.Preconditions;\n sourceAccount?: xdr.MuxedAccount;\n ext?: xdr.TransactionExt;\n } = {\n fee,\n seqNum: xdr.Int64.fromString(sequenceNumber.toString()),\n memo: this.memo ? this.memo.toXDRObject() : null,\n };\n\n if (\n this.timebounds === null ||\n typeof this.timebounds.minTime === \"undefined\" ||\n typeof this.timebounds.maxTime === \"undefined\"\n ) {\n throw new Error(\n \"TimeBounds has to be set or you must call setTimeout(TimeoutInfinite).\",\n );\n }\n\n if (isValidDate(this.timebounds.minTime)) {\n this.timebounds.minTime = Math.floor(\n this.timebounds.minTime.getTime() / 1000,\n );\n }\n\n if (isValidDate(this.timebounds.maxTime)) {\n this.timebounds.maxTime = Math.floor(\n this.timebounds.maxTime.getTime() / 1000,\n );\n }\n\n const minTime = xdr.Uint64.fromString(this.timebounds.minTime.toString());\n const maxTime = xdr.Uint64.fromString(this.timebounds.maxTime.toString());\n\n const timeBounds = new xdr.TimeBounds({ minTime, maxTime });\n\n if (this.hasV2Preconditions()) {\n let ledgerBounds = null;\n\n if (this.ledgerbounds !== null) {\n ledgerBounds = new xdr.LedgerBounds({\n minLedger: this.ledgerbounds.minLedger ?? 0,\n maxLedger: this.ledgerbounds.maxLedger ?? 0,\n });\n }\n\n const minSeqNum = this.minAccountSequence\n ? xdr.Int64.fromString(this.minAccountSequence)\n : null;\n\n const minSeqAge = xdr.Uint64.fromString(\n this.minAccountSequenceAge !== null\n ? this.minAccountSequenceAge.toString()\n : \"0\",\n );\n\n const minSeqLedgerGap = this.minAccountSequenceLedgerGap || 0;\n\n const extraSigners =\n this.extraSigners !== null\n ? this.extraSigners.map((s) => SignerKey.decodeAddress(s))\n : [];\n\n attrs.cond = xdr.Preconditions.precondV2(\n new xdr.PreconditionsV2({\n timeBounds,\n ledgerBounds,\n minSeqNum,\n minSeqAge,\n minSeqLedgerGap,\n extraSigners,\n }),\n );\n } else {\n attrs.cond = xdr.Preconditions.precondTime(timeBounds);\n }\n\n attrs.sourceAccount = decodeAddressToMuxedAccount(this.source.accountId());\n\n // Previously used @ts-ignore and passed xdr.Void as second arg to TransactionExt(0)\n // due to broken TransactionExt types in dts-xdr.\n // Fixed upstream: https://github.com/stellar/dts-xdr/issues/5\n if (this.sorobanData) {\n attrs.ext = new xdr.TransactionExt(1, this.sorobanData);\n // Soroban transactions pay the resource fee in addition to the regular fee, so we need to add it here.\n attrs.fee = new BigNumber(attrs.fee)\n .plus(this.sorobanData.resourceFee().toString())\n .toNumber();\n\n if (attrs.fee > UINT32_MAX) {\n throw new Error(\n `Total fee (baseFee * operations + resourceFee) exceeds the maximum uint32 value (${UINT32_MAX}). ` +\n `Got ${attrs.fee}.`,\n );\n }\n } else {\n attrs.ext = new xdr.TransactionExt(0);\n }\n\n const xtx = new xdr.Transaction(\n attrs as ConstructorParameters<typeof xdr.Transaction>[0],\n );\n xtx.operations(this.operations);\n\n const txEnvelope = xdr.TransactionEnvelope.envelopeTypeTx(\n new xdr.TransactionV1Envelope({ tx: xtx, signatures: [] }),\n );\n\n if (this.networkPassphrase === null) {\n throw new Error(\"networkPassphrase must be set to build a transaction\");\n }\n\n const tx = new Transaction(txEnvelope, this.networkPassphrase);\n\n this.source.incrementSequenceNumber();\n\n return tx;\n }\n\n /**\n * Checks whether any v2 preconditions have been set on this builder.\n */\n hasV2Preconditions() {\n return (\n this.ledgerbounds !== null ||\n this.minAccountSequence !== null ||\n this.minAccountSequenceAge !== null ||\n this.minAccountSequenceLedgerGap !== null ||\n (this.extraSigners !== null && this.extraSigners.length > 0)\n );\n }\n\n /**\n * Builds a {@link FeeBumpTransaction}, enabling you to resubmit an existing\n * transaction with a higher fee.\n *\n * @param feeSource - account paying for the transaction,\n * in the form of either a Keypair (only the public key is used) or\n * an account ID (in G... or M... form, but refer to `withMuxing`)\n * @param baseFee - max fee willing to pay per operation\n * in inner transaction (**in stroops**)\n * @param innerTx - {@link Transaction} to be bumped by\n * the fee bump transaction\n * @param networkPassphrase - passphrase of the target\n * Stellar network (e.g. \"Public Global Stellar Network ; September 2015\",\n * see {@link Networks})\n *\n * TODO: Alongside the next major version bump, this type signature can be\n * changed to be less awkward: accept a MuxedAccount as the `feeSource`\n * rather than a keypair or string.\n *\n * Your fee-bump amount should be `>= 10x` the original fee.\n * @see https://developers.stellar.org/docs/glossary/fee-bumps/#replace-by-fee\n */\n static buildFeeBumpTransaction(\n feeSource: Keypair | string,\n baseFee: string,\n innerTx: Transaction,\n networkPassphrase: string,\n ): FeeBumpTransaction {\n const innerOps = innerTx.operations.length;\n\n const minBaseFee = new BigNumber(BASE_FEE);\n let resourceFee = new BigNumber(0);\n\n // Do we need to do special Soroban fee handling? We only want the fee-bump\n // requirement to match the inclusion fee, not the inclusion+resource fee.\n const env = innerTx.toEnvelope();\n switch (env.switch().value) {\n case xdr.EnvelopeType.envelopeTypeTx().value: {\n const sorobanData = env.v1().tx().ext().value();\n resourceFee = new BigNumber(sorobanData?.resourceFee().toString() ?? 0);\n\n break;\n }\n default:\n break;\n }\n const innerInclusionFee = new BigNumber(innerTx.fee)\n .minus(resourceFee)\n .div(innerOps);\n const base = new BigNumber(baseFee);\n\n // The fee rate for fee bump is at least the fee rate of the inner transaction\n if (base.lt(innerInclusionFee)) {\n throw new Error(\n `Invalid baseFee, it should be at least ${innerInclusionFee.toString()} stroops.`,\n );\n }\n\n // The fee rate is at least the minimum fee\n if (base.lt(minBaseFee)) {\n throw new Error(\n `Invalid baseFee, it should be at least ${minBaseFee.toString()} stroops.`,\n );\n }\n\n let innerTxEnvelope = innerTx.toEnvelope();\n if (innerTxEnvelope.switch() === xdr.EnvelopeType.envelopeTypeTxV0()) {\n const v0Tx = innerTxEnvelope.v0().tx();\n const v0TimeBounds = v0Tx.timeBounds();\n\n if (v0TimeBounds === null) {\n throw new Error(\"Inner transaction must have time bounds\");\n }\n\n const v1Tx = new xdr.Transaction({\n sourceAccount: xdr.MuxedAccount.keyTypeEd25519(\n v0Tx.sourceAccountEd25519(),\n ),\n fee: v0Tx.fee(),\n seqNum: v0Tx.seqNum(),\n cond: xdr.Preconditions.precondTime(v0TimeBounds),\n memo: v0Tx.memo(),\n operations: v0Tx.operations(),\n ext: new xdr.TransactionExt(0),\n });\n innerTxEnvelope = xdr.TransactionEnvelope.envelopeTypeTx(\n new xdr.TransactionV1Envelope({\n tx: v1Tx,\n signatures: innerTxEnvelope.v0().signatures(),\n }),\n );\n }\n\n let feeSourceAccount;\n if (typeof feeSource === \"string\") {\n feeSourceAccount = decodeAddressToMuxedAccount(feeSource);\n } else {\n feeSourceAccount = feeSource.xdrMuxedAccount();\n }\n\n const tx = new xdr.FeeBumpTransaction({\n feeSource: feeSourceAccount,\n fee: xdr.Int64.fromString(\n base\n .times(innerOps + 1)\n .plus(resourceFee)\n .toString(),\n ),\n innerTx: xdr.FeeBumpTransactionInnerTx.envelopeTypeTx(\n innerTxEnvelope.v1(),\n ),\n ext: new xdr.FeeBumpTransactionExt(0),\n });\n const feeBumpTxEnvelope = new xdr.FeeBumpTransactionEnvelope({\n tx,\n signatures: [],\n });\n const envelope =\n xdr.TransactionEnvelope.envelopeTypeTxFeeBump(feeBumpTxEnvelope);\n\n return new FeeBumpTransaction(envelope, networkPassphrase);\n }\n\n /**\n * Build a {@link Transaction} or {@link FeeBumpTransaction} from an\n * xdr.TransactionEnvelope.\n *\n * @param envelope - The transaction envelope\n * object or base64 encoded string.\n * @param networkPassphrase - The network passphrase of the target\n * Stellar network (e.g. \"Public Global Stellar Network ; September\n * 2015\"), see {@link Networks}.\n */\n static fromXDR(\n envelope: xdr.TransactionEnvelope | string,\n networkPassphrase: string,\n ): FeeBumpTransaction | Transaction {\n if (typeof envelope === \"string\") {\n envelope = xdr.TransactionEnvelope.fromXDR(envelope, \"base64\");\n }\n\n if (envelope.switch() === xdr.EnvelopeType.envelopeTypeTxFeeBump()) {\n return new FeeBumpTransaction(envelope, networkPassphrase);\n }\n\n return new Transaction(envelope, networkPassphrase);\n }\n}\n\n/**\n * Checks whether a provided object is a valid Date.\n * @param d - date object\n */\nexport function isValidDate(d: Date | number | string): d is Date {\n return d instanceof Date && !Number.isNaN(d.getTime());\n}\n\n/**\n * Converts a Date, number, or string time value to epoch seconds for\n * validation. Returns undefined if the value is undefined.\n */\nfunction toEpochSeconds(\n value: Date | number | string | undefined,\n): number | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n const num =\n value instanceof Date ? Math.floor(value.getTime() / 1000) : Number(value);\n\n if (!Number.isFinite(num) || num % 1 !== 0) {\n throw new Error(\"timebounds value must be a finite integer or Date\");\n }\n\n return num;\n}\n"],"names":["Hyper","Memo","SorobanDataBuilder","Transaction","StrKey","MuxedAccount","Account","xdr","SignerKey","extractBaseAddress","nativeToScVal","Address","Keypair","operation","Operation","BigNumber","decodeAddressToMuxedAccount","FeeBumpTransaction"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,kBAAkBA,WAAA,CAAM,SAAA;AAC9B,MAAM,UAAA,GAAa,UAAA;AAWZ,MAAM,QAAA,GAAW;AAMjB,MAAM,eAAA,GAAkB;AA4GxB,MAAM,kBAAA,CAAmB;AAAA,EAC9B,MAAA;AAAA,EACA,UAAA;AAAA,EACA,OAAA;AAAA,EACA,UAAA;AAAA,EAIA,YAAA;AAAA,EACA,kBAAA;AAAA,EACA,qBAAA;AAAA,EACA,2BAAA;AAAA,EACA,YAAA;AAAA,EACA,IAAA;AAAA,EACA,iBAAA;AAAA,EACA,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,WAAA,CACE,aAAA,EACA,IAAA,GAAkC,EAAC,EACnC;AACA,IAAA,IAAI,CAAC,aAAA,EAAe;AAClB,MAAA,MAAM,IAAI,MAAM,iDAAiD,CAAA;AAAA,IACnE;AAEA,IAAA,IAAI,IAAA,CAAK,QAAQ,MAAA,EAAW;AAC1B,MAAA,MAAM,IAAI,MAAM,mDAAmD,CAAA;AAAA,IACrE;AAEA,IAAA,IAAA,CAAK,MAAA,GAAS,aAAA;AACd,IAAA,IAAA,CAAK,aAAa,EAAC;AAEnB,IAAA,IAAA,CAAK,UAAU,IAAA,CAAK,GAAA;AACpB,IAAA,IAAI,KAAK,UAAA,EAAY;AACnB,MAAA,MAAM,OAAA,GAAU,cAAA,CAAe,IAAA,CAAK,UAAA,CAAW,OAAO,CAAA;AACtD,MAAA,MAAM,OAAA,GAAU,cAAA,CAAe,IAAA,CAAK,UAAA,CAAW,OAAO,CA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