@stellar/stellar-sdk 16.0.0-rc.2 → 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.
Files changed (121) hide show
  1. package/dist/stellar-sdk-axios.js +25 -27
  2. package/dist/stellar-sdk-axios.js.map +1 -1
  3. package/dist/stellar-sdk-axios.min.js +1 -1
  4. package/dist/stellar-sdk-axios.min.js.map +1 -1
  5. package/dist/stellar-sdk.js +26 -28
  6. package/dist/stellar-sdk.js.map +1 -1
  7. package/dist/stellar-sdk.min.js +2 -2
  8. package/dist/stellar-sdk.min.js.map +1 -1
  9. package/lib/axios/cjs/base/transaction_builder.js +13 -1
  10. package/lib/axios/cjs/base/transaction_builder.js.map +1 -1
  11. package/lib/axios/cjs/bindings/config.js +1 -1
  12. package/lib/axios/cjs/bindings/config.js.map +1 -1
  13. package/lib/axios/cjs/bindings/wasm_fetcher.js +1 -1
  14. package/lib/axios/cjs/bindings/wasm_fetcher.js.map +1 -1
  15. package/lib/axios/cjs/contract/assembled_transaction.js +1 -6
  16. package/lib/axios/cjs/contract/assembled_transaction.js.map +1 -1
  17. package/lib/axios/cjs/contract/client.js.map +1 -1
  18. package/lib/axios/cjs/contract/spec.js.map +1 -1
  19. package/lib/axios/cjs/contract/types.js.map +1 -1
  20. package/lib/axios/cjs/contract/utils.js.map +1 -1
  21. package/lib/axios/cjs/contract/wasm_spec_parser.js +1 -1
  22. package/lib/axios/cjs/contract/wasm_spec_parser.js.map +1 -1
  23. package/lib/axios/cjs/horizon/call_builder.js.map +1 -1
  24. package/lib/axios/cjs/horizon/horizon_api.js.map +1 -1
  25. package/lib/axios/cjs/horizon/horizon_axios_client.js +1 -1
  26. package/lib/axios/cjs/horizon/horizon_axios_client.js.map +1 -1
  27. package/lib/axios/cjs/http-client/fetch-client.js +1 -1
  28. package/lib/axios/cjs/http-client/fetch-client.js.map +1 -1
  29. package/lib/axios/cjs/http-client/types.js.map +1 -1
  30. package/lib/axios/cjs/rpc/axios.js +1 -1
  31. package/lib/axios/cjs/rpc/axios.js.map +1 -1
  32. package/lib/axios/cjs/rpc/jsonrpc.js.map +1 -1
  33. package/lib/axios/cjs/rpc/server.js +6 -15
  34. package/lib/axios/cjs/rpc/server.js.map +1 -1
  35. package/lib/axios/cjs/webauth/challenge_transaction.js.map +1 -1
  36. package/lib/axios/esm/base/transaction_builder.js +13 -1
  37. package/lib/axios/esm/base/transaction_builder.js.map +1 -1
  38. package/lib/axios/esm/bindings/config.js +1 -1
  39. package/lib/axios/esm/bindings/config.js.map +1 -1
  40. package/lib/axios/esm/bindings/wasm_fetcher.js +1 -1
  41. package/lib/axios/esm/bindings/wasm_fetcher.js.map +1 -1
  42. package/lib/axios/esm/contract/assembled_transaction.js +1 -6
  43. package/lib/axios/esm/contract/assembled_transaction.js.map +1 -1
  44. package/lib/axios/esm/contract/client.js.map +1 -1
  45. package/lib/axios/esm/contract/spec.js.map +1 -1
  46. package/lib/axios/esm/contract/types.d.ts +0 -9
  47. package/lib/axios/esm/contract/types.js.map +1 -1
  48. package/lib/axios/esm/contract/utils.js.map +1 -1
  49. package/lib/axios/esm/contract/wasm_spec_parser.js +1 -1
  50. package/lib/axios/esm/contract/wasm_spec_parser.js.map +1 -1
  51. package/lib/axios/esm/horizon/call_builder.js.map +1 -1
  52. package/lib/axios/esm/horizon/horizon_api.js.map +1 -1
  53. package/lib/axios/esm/horizon/horizon_axios_client.js +1 -1
  54. package/lib/axios/esm/horizon/horizon_axios_client.js.map +1 -1
  55. package/lib/axios/esm/http-client/fetch-client.js +1 -1
  56. package/lib/axios/esm/http-client/fetch-client.js.map +1 -1
  57. package/lib/axios/esm/http-client/types.js.map +1 -1
  58. package/lib/axios/esm/rpc/axios.js +1 -1
  59. package/lib/axios/esm/rpc/axios.js.map +1 -1
  60. package/lib/axios/esm/rpc/jsonrpc.js.map +1 -1
  61. package/lib/axios/esm/rpc/server.d.ts +2 -7
  62. package/lib/axios/esm/rpc/server.js +6 -15
  63. package/lib/axios/esm/rpc/server.js.map +1 -1
  64. package/lib/axios/esm/webauth/challenge_transaction.js.map +1 -1
  65. package/lib/cjs/base/transaction_builder.js +13 -1
  66. package/lib/cjs/base/transaction_builder.js.map +1 -1
  67. package/lib/cjs/bindings/config.js +1 -1
  68. package/lib/cjs/bindings/config.js.map +1 -1
  69. package/lib/cjs/bindings/wasm_fetcher.js +1 -1
  70. package/lib/cjs/bindings/wasm_fetcher.js.map +1 -1
  71. package/lib/cjs/contract/assembled_transaction.js +1 -6
  72. package/lib/cjs/contract/assembled_transaction.js.map +1 -1
  73. package/lib/cjs/contract/client.js.map +1 -1
  74. package/lib/cjs/contract/spec.js.map +1 -1
  75. package/lib/cjs/contract/types.js.map +1 -1
  76. package/lib/cjs/contract/utils.js.map +1 -1
  77. package/lib/cjs/contract/wasm_spec_parser.js +1 -1
  78. package/lib/cjs/contract/wasm_spec_parser.js.map +1 -1
  79. package/lib/cjs/horizon/call_builder.js.map +1 -1
  80. package/lib/cjs/horizon/horizon_api.js.map +1 -1
  81. package/lib/cjs/horizon/horizon_axios_client.js +1 -1
  82. package/lib/cjs/horizon/horizon_axios_client.js.map +1 -1
  83. package/lib/cjs/http-client/fetch-client.js +1 -1
  84. package/lib/cjs/http-client/fetch-client.js.map +1 -1
  85. package/lib/cjs/http-client/types.js.map +1 -1
  86. package/lib/cjs/rpc/axios.js +1 -1
  87. package/lib/cjs/rpc/axios.js.map +1 -1
  88. package/lib/cjs/rpc/jsonrpc.js.map +1 -1
  89. package/lib/cjs/rpc/server.js +6 -15
  90. package/lib/cjs/rpc/server.js.map +1 -1
  91. package/lib/cjs/webauth/challenge_transaction.js.map +1 -1
  92. package/lib/esm/base/transaction_builder.js +13 -1
  93. package/lib/esm/base/transaction_builder.js.map +1 -1
  94. package/lib/esm/bindings/config.js +1 -1
  95. package/lib/esm/bindings/config.js.map +1 -1
  96. package/lib/esm/bindings/wasm_fetcher.js +1 -1
  97. package/lib/esm/bindings/wasm_fetcher.js.map +1 -1
  98. package/lib/esm/contract/assembled_transaction.js +1 -6
  99. package/lib/esm/contract/assembled_transaction.js.map +1 -1
  100. package/lib/esm/contract/client.js.map +1 -1
  101. package/lib/esm/contract/spec.js.map +1 -1
  102. package/lib/esm/contract/types.d.ts +0 -9
  103. package/lib/esm/contract/types.js.map +1 -1
  104. package/lib/esm/contract/utils.js.map +1 -1
  105. package/lib/esm/contract/wasm_spec_parser.js +1 -1
  106. package/lib/esm/contract/wasm_spec_parser.js.map +1 -1
  107. package/lib/esm/horizon/call_builder.js.map +1 -1
  108. package/lib/esm/horizon/horizon_api.js.map +1 -1
  109. package/lib/esm/horizon/horizon_axios_client.js +1 -1
  110. package/lib/esm/horizon/horizon_axios_client.js.map +1 -1
  111. package/lib/esm/http-client/fetch-client.js +1 -1
  112. package/lib/esm/http-client/fetch-client.js.map +1 -1
  113. package/lib/esm/http-client/types.js.map +1 -1
  114. package/lib/esm/rpc/axios.js +1 -1
  115. package/lib/esm/rpc/axios.js.map +1 -1
  116. package/lib/esm/rpc/jsonrpc.js.map +1 -1
  117. package/lib/esm/rpc/server.d.ts +2 -7
  118. package/lib/esm/rpc/server.js +6 -15
  119. package/lib/esm/rpc/server.js.map +1 -1
  120. package/lib/esm/webauth/challenge_transaction.js.map +1 -1
  121. package/package.json +2 -5
@@ -209,8 +209,8 @@ class RpcServer {
209
209
  async getClaimableBalance(id) {
210
210
  let balanceId;
211
211
  if (strkey.StrKey.isValidClaimableBalance(id)) {
212
- let buffer$1 = strkey.StrKey.decodeClaimableBalance(id);
213
- let v = buffer.Buffer.concat([
212
+ const buffer$1 = strkey.StrKey.decodeClaimableBalance(id);
213
+ const v = buffer.Buffer.concat([
214
214
  buffer.Buffer.from("\0\0\0"),
215
215
  buffer$1.subarray(0, 1)
216
216
  ]);
@@ -798,11 +798,6 @@ class RpcServer {
798
798
  * auth mode to use for simulation: `enforce` for enforcement mode,
799
799
  * `record` for recording mode, or `record_allow_nonroot` for recording
800
800
  * mode that allows non-root authorization
801
- * @param authV2 - (optional) request `SOROBAN_CREDENTIALS_ADDRESS_V2`
802
- * (CAP-71) auth credentials from simulation instead of the legacy
803
- * `SOROBAN_CREDENTIALS_ADDRESS`. Defaults to `false`; only enable it for
804
- * networks that have activated CAP-71, as V2 credentials are otherwise
805
- * rejected.
806
801
  *
807
802
  * @returns An object with the
808
803
  * cost, footprint, result/auth requirements (if applicable), and error of
@@ -842,12 +837,12 @@ class RpcServer {
842
837
  * });
843
838
  * ```
844
839
  */
845
- async simulateTransaction(tx, addlResources, authMode, authV2 = false) {
846
- return this._simulateTransaction(tx, addlResources, authMode, authV2).then(
840
+ async simulateTransaction(tx, addlResources, authMode) {
841
+ return this._simulateTransaction(tx, addlResources, authMode).then(
847
842
  parsers.parseRawSimulation
848
843
  );
849
844
  }
850
- async _simulateTransaction(transaction, addlResources, authMode, authV2 = false) {
845
+ async _simulateTransaction(transaction, addlResources, authMode) {
851
846
  return jsonrpc.postObject(
852
847
  this.httpClient,
853
848
  this.serverURL.toString(),
@@ -859,11 +854,7 @@ class RpcServer {
859
854
  resourceConfig: {
860
855
  instructionLeeway: addlResources.cpuInstructions
861
856
  }
862
- },
863
- // CAP-71: only request ADDRESS_V2 auth credentials when explicitly
864
- // opted in. They are rejected by networks that have not activated
865
- // CAP-71, so default to omitting the flag (legacy ADDRESS credentials).
866
- ...authV2 && { authV2: true }
857
+ }
867
858
  }
868
859
  );
869
860
  }
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sources":["../../../../src/rpc/server.ts"],"sourcesContent":["/* tslint:disable:variable-name no-namespace */\nimport {\n Account,\n Address,\n Asset,\n Contract,\n FeeBumpTransaction,\n Keypair,\n StrKey,\n Transaction,\n nativeToScVal,\n scValToNative,\n xdr,\n} from \"../base/index.js\";\n\nimport type { TransactionBuilder } from \"../base/index.js\";\nimport type { Config } from \"../config.js\";\nimport { createHttpClient } from \"./axios.js\";\nimport type { Api as FriendbotApi } from \"../friendbot/index.js\";\nimport * as jsonrpc from \"./jsonrpc.js\";\nimport { Api } from \"./api.js\";\nimport { assembleTransaction } from \"./transaction.js\";\nimport {\n parseRawSendTransaction,\n parseRawSimulation,\n parseRawLedgerEntries,\n parseRawEvents,\n parseRawTransactions,\n parseTransactionInfo,\n parseRawLedger,\n parseRawLatestLedger,\n} from \"./parsers.js\";\nimport { Utils } from \"../utils.js\";\nimport type { HttpClient } from \"../http-client/index.js\";\n\n/**\n * Default transaction submission timeout for RPC requests, in milliseconds\n * @defaultValue 60000\n */\nexport const SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000;\n\n/**\n * Specifies the durability namespace of contract-related ledger entries.\n *\n * @see {@link https://developers.stellar.org/docs/learn/smart-contract-internals/state-archival | State Archival docs}\n * @see {@link https://docs.rs/soroban-sdk/latest/soroban_sdk/storage/struct.Storage.html | Rust SDK Storage docs}\n */\nexport enum Durability {\n Temporary = \"temporary\",\n Persistent = \"persistent\",\n}\n\nexport namespace RpcServer {\n /**\n * @deprecated Use `Api.GetEventsRequest` instead.\n * @see {@link Api.GetEventsRequest}\n */\n export type GetEventsRequest = Api.GetEventsRequest;\n\n export interface PollingOptions {\n attempts?: number;\n sleepStrategy?: SleepStrategy;\n }\n\n /**\n * Describes additional resource leeways for transaction simulation.\n */\n export interface ResourceLeeway {\n /** Simulate the transaction with more CPU instructions available. */\n cpuInstructions: number;\n }\n\n /**\n * Options for configuring connections to RPC servers.\n */\n export interface Options {\n /** Allow connecting to http servers, default: `false`. This must be set to false in production deployments! */\n allowHttp?: boolean;\n /** Allow a timeout, default: 0. Allows user to avoid nasty lag. */\n timeout?: number;\n /** Additional headers that should be added to any requests to the RPC server. */\n headers?: Record<string, string>;\n }\n}\n\nconst DEFAULT_GET_TRANSACTION_TIMEOUT: number = 30;\n\n/// A strategy that will sleep 1 second each time\n\nexport const BasicSleepStrategy: SleepStrategy = (_iter: number) => 1000;\n\n/// A strategy that will sleep 1 second longer on each attempt\nexport const LinearSleepStrategy: SleepStrategy = (iter: number) => 1000 * iter;\n\n/**\n * A function that returns the number of *milliseconds* to sleep\n * on a given `iter`ation.\n */\nexport type SleepStrategy = (iter: number) => number;\n\nfunction findCreatedAccountSequenceInTransactionMeta(\n meta: xdr.TransactionMeta,\n): string {\n let operations: xdr.OperationMeta[] = [];\n switch (meta.switch()) {\n case 0:\n operations = meta.operations();\n break;\n case 1:\n case 2:\n case 3:\n case 4: // all four have the same interface\n operations = (meta.value() as xdr.TransactionMetaV4).operations();\n break;\n default:\n throw new Error(\"Unexpected transaction meta switch value\");\n }\n const sequenceNumber = operations\n .flatMap((op) => op.changes())\n .find(\n (c) =>\n c.switch() === xdr.LedgerEntryChangeType.ledgerEntryCreated() &&\n c.created().data().switch() === xdr.LedgerEntryType.account(),\n )\n ?.created()\n ?.data()\n ?.account()\n ?.seqNum()\n ?.toString();\n\n if (sequenceNumber) {\n return sequenceNumber;\n }\n throw new Error(\"No account created in transaction\");\n}\n\n/**\n * Handles the network connection to a Soroban RPC instance, exposing an\n * interface for requests to that instance.\n *\n *\n * @param serverURL - Soroban-RPC Server URL (ex. `http://localhost:8000/soroban/rpc`).\n * @param opts - (optional) Options object\n * - `allowHttp` (optional): Allows connecting to insecure http servers\n * (default: `false`). This must be set to false in production deployments!\n * You can also use {@link Config} class to set this globally.\n * - `headers` (optional): Allows setting custom headers\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods | API reference docs}\n */\nexport class RpcServer {\n public readonly serverURL: URL;\n /**\n * HTTP client instance for making requests to Horizon.\n * Exposes interceptors, defaults, and other configuration options.\n *\n * @example\n * ```ts\n * // Add authentication header\n * server.httpClient.defaults.headers['Authorization'] = 'Bearer token';\n *\n * // Add request interceptor\n * server.httpClient.interceptors.request.use((config) => {\n * console.log('Request:', config.url);\n * return config;\n * });\n * ```\n */\n public readonly httpClient: HttpClient;\n constructor(serverURL: string, opts: RpcServer.Options = {}) {\n /**\n * RPC Server URL (ex. `http://localhost:8000/soroban/rpc`).\n */\n this.serverURL = new URL(serverURL);\n this.httpClient = createHttpClient(opts.headers);\n if (this.serverURL.protocol !== \"https:\" && !opts.allowHttp) {\n throw new Error(\n \"Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set\",\n );\n }\n }\n\n /**\n * Fetch a minimal set of current info about a Stellar account.\n *\n * Needed to get the current sequence number for the account so you can build\n * a successful transaction with {@link TransactionBuilder}.\n *\n * @param address - The public address of the account to load.\n * @returns A promise which resolves to the {@link Account}\n * object with a populated sequence number\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n *\n * @example\n * ```ts\n * const accountId = \"GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4\";\n * server.getAccount(accountId).then((account) => {\n * console.log(\"sequence:\", account.sequence);\n * });\n * ```\n */\n public async getAccount(address: string): Promise<Account> {\n const entry = await this.getAccountEntry(address);\n return new Account(address, entry.seqNum().toString());\n }\n\n /**\n * Fetch the full account entry for a Stellar account.\n *\n * @param address - The public address of the account to load.\n * @returns Resolves to the full on-chain account\n * entry\n *\n * @see\n * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n *\n * @example\n * ```ts\n * const accountId = \"GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4\";\n * server.getAccountEntry(accountId).then((account) => {\n * console.log(\"sequence:\", account.balance().toString());\n * });\n * ```\n */\n public async getAccountEntry(address: string): Promise<xdr.AccountEntry> {\n const ledgerKey = xdr.LedgerKey.account(\n new xdr.LedgerKeyAccount({\n accountId: Keypair.fromPublicKey(address).xdrPublicKey(),\n }),\n );\n\n try {\n const resp = await this.getLedgerEntry(ledgerKey);\n return resp.val.account();\n } catch {\n throw new Error(`Account not found: ${address}`);\n }\n }\n\n /**\n * Fetch the full trustline entry for a Stellar account.\n *\n * @param account - The public address of the account whose trustline it is\n * @param asset - The trustline's asset\n * @returns Resolves to the full on-chain trustline\n * entry\n *\n * @see\n * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n *\n * @deprecated Use {@link getAssetBalance}, instead\n * @example\n * ```ts\n * const accountId = \"GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4\";\n * const asset = new Asset(\n * \"USDC\",\n * \"GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5\"\n * );\n * server.getTrustline(accountId, asset).then((entry) => {\n * console.log(`{asset.toString()} balance for ${accountId}:\", entry.balance().toString());\n * });\n * ```\n */\n public async getTrustline(\n account: string,\n asset: Asset,\n ): Promise<xdr.TrustLineEntry> {\n const trustlineLedgerKey = xdr.LedgerKey.trustline(\n new xdr.LedgerKeyTrustLine({\n accountId: Keypair.fromPublicKey(account).xdrAccountId(),\n asset: asset.toTrustLineXDRObject(),\n }),\n );\n\n try {\n const entry = await this.getLedgerEntry(trustlineLedgerKey);\n return entry.val.trustLine();\n } catch {\n throw new Error(\n `Trustline for ${asset.getCode()}:${asset.getIssuer()} not found for ${account}`,\n );\n }\n }\n\n /**\n * Fetch the full claimable balance entry for a Stellar account.\n *\n * @param id - The strkey (`B...`) or hex (`00000000abcde...`) (both\n * IDs with and without the 000... version prefix are accepted) of the\n * claimable balance to load\n * @returns Resolves to the full on-chain\n * claimable balance entry\n *\n * @see\n * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n *\n * @example\n * ```ts\n * const id = \"00000000178826fbfe339e1f5c53417c6fedfe2c05e8bec14303143ec46b38981b09c3f9\";\n * server.getClaimableBalance(id).then((entry) => {\n * console.log(`Claimable balance {id.substr(0, 12)} has:`);\n * console.log(` asset: ${Asset.fromXDRObject(entry.asset()).toString()}`;\n * console.log(` amount: ${entry.amount().toString()}`;\n * });\n * ```\n */\n public async getClaimableBalance(\n id: string,\n ): Promise<xdr.ClaimableBalanceEntry> {\n let balanceId;\n if (StrKey.isValidClaimableBalance(id)) {\n let buffer = StrKey.decodeClaimableBalance(id);\n\n // Pad the version byte to be a full int32 like in the XDR spec\n let v = Buffer.concat([\n Buffer.from(\"\\x00\\x00\\x00\"),\n buffer.subarray(0, 1),\n ]);\n\n // Slap on the rest of it and decode it\n balanceId = xdr.ClaimableBalanceId.fromXDR(\n Buffer.concat([v, buffer.subarray(1)]),\n );\n } else if (id.match(/[a-f0-9]{72}/i)) {\n balanceId = xdr.ClaimableBalanceId.fromXDR(id, \"hex\");\n } else if (id.match(/[a-f0-9]{64}/i)) {\n balanceId = xdr.ClaimableBalanceId.fromXDR(id.padStart(72, \"0\"), \"hex\");\n } else {\n throw new TypeError(`expected 72-char hex ID or strkey, not ${id}`);\n }\n\n const trustlineLedgerKey = xdr.LedgerKey.claimableBalance(\n new xdr.LedgerKeyClaimableBalance({ balanceId }),\n );\n\n try {\n const entry = await this.getLedgerEntry(trustlineLedgerKey);\n return entry.val.claimableBalance();\n } catch {\n throw new Error(`Claimable balance ${id} not found`);\n }\n }\n\n /**\n * Fetch the balance of an asset held by an account or contract.\n *\n * The `address` argument may be provided as a string (as a {@link StrKey}),\n * {@link Address}, or {@link Contract}.\n *\n * @param address - The account or contract whose\n * balance should be fetched.\n * @param asset - The asset whose balance you want to inspect.\n * @param networkPassphrase - (optional) optionally, when requesting the\n * balance of a contract, the network passphrase to which this token\n * applies. If omitted and necessary, a request about network information\n * will be made (see {@link getNetwork}), since contract IDs for assets are\n * specific to a network. You can refer to {@link Networks} for a list of\n * built-in passphrases, e.g., `Networks.TESTNET`.\n * @returns Resolves with balance entry details\n * when available.\n *\n * @throws If the supplied `address` is not a valid account or\n * contract strkey.\n *\n * @example\n * ```ts\n * const usdc = new Asset(\n * \"USDC\",\n * \"GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5\"\n * );\n * const balance = await server.getAssetBalance(\"GD...\", usdc);\n * console.log(balance.balanceEntry?.amount);\n * ```\n */\n public async getAssetBalance(\n address: string | Address | Contract,\n asset: Asset,\n networkPassphrase?: string,\n ): Promise<Api.BalanceResponse> {\n let addr: string = address as string;\n // Coalesce to a strkey\n if (typeof address === \"string\") {\n addr = address;\n } else if (address instanceof Address) {\n addr = address.toString();\n } else if (address instanceof Contract) {\n addr = address.toString();\n } else {\n // shouldn't happen, but be defensive\n throw new TypeError(`invalid address: ${address}`);\n }\n\n if (StrKey.isValidEd25519PublicKey(addr)) {\n const [tl, ll] = await Promise.all([\n this.getTrustline(addr, asset),\n this.getLatestLedger(),\n ]);\n\n return {\n latestLedger: ll.sequence,\n balanceEntry: {\n amount: tl.balance().toString(),\n // Extract actual flags from the coalesced value.\n authorized: Boolean(tl.flags() & 0x1), // AUTHORIZED_FLAG\n clawback: Boolean(tl.flags() & 0x4), // TRUSTLINE_CLAWBACK_ENABLED_FLAG\n authorizedToMaintainLiabilities: Boolean(tl.flags() & 0x2), // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG\n revocable: Boolean(tl.flags() & 0x2), // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG (deprecated, will be removed in a future major release)\n },\n };\n } else if (StrKey.isValidContract(addr)) {\n return this.getSACBalance(addr, asset, networkPassphrase);\n }\n\n throw new Error(`invalid address: ${address}`);\n }\n\n /**\n * General node health check.\n *\n * @returns A promise which resolves to the\n * {@link Api.GetHealthResponse} object with the status of the\n * server (e.g. \"healthy\").\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getHealth | getLedgerEntries docs}\n *\n * @example\n * ```ts\n * server.getHealth().then((health) => {\n * console.log(\"status:\", health.status);\n * });\n * ```\n */\n\n public async getHealth(): Promise<Api.GetHealthResponse> {\n return jsonrpc.postObject<Api.GetHealthResponse>(\n this.httpClient,\n this.serverURL.toString(),\n \"getHealth\",\n );\n }\n\n /**\n * Reads the current value of contract data ledger entries directly.\n *\n * Allows you to directly inspect the current state of a contract. This is a\n * backup way to access your contract data which may not be available via\n * events or {@link rpc.Server.simulateTransaction}.\n *\n * @param contract - The contract ID containing the\n * data to load as a strkey (`C...` form), a {@link Contract}, or an\n * {@link Address} instance\n * @param key - The key of the contract data to load\n * @param durability - (optional) The \"durability\n * keyspace\" that this ledger key belongs to, which is either 'temporary'\n * or 'persistent' (the default), see {@link rpc.Durability}.\n * @returns The current data value\n *\n * **Warning:** If the data entry in question is a 'temporary' entry, it's\n * entirely possible that it has expired out of existence.\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n *\n * @example\n * ```ts\n * const contractId = \"CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5\";\n * const key = xdr.ScVal.scvSymbol(\"counter\");\n * server.getContractData(contractId, key, Durability.Temporary).then(data => {\n * console.log(\"value:\", data.val);\n * console.log(\"liveUntilLedgerSeq:\", data.liveUntilLedgerSeq);\n * console.log(\"lastModified:\", data.lastModifiedLedgerSeq);\n * console.log(\"latestLedger:\", data.latestLedger);\n * });\n * ```\n */\n\n public async getContractData(\n contract: string | Address | Contract,\n key: xdr.ScVal,\n durability: Durability = Durability.Persistent,\n ): Promise<Api.LedgerEntryResult> {\n // coalesce `contract` param variants to an ScAddress\n let scAddress: xdr.ScAddress;\n if (typeof contract === \"string\") {\n scAddress = new Contract(contract).address().toScAddress();\n } else if (contract instanceof Address) {\n scAddress = contract.toScAddress();\n } else if (contract instanceof Contract) {\n scAddress = contract.address().toScAddress();\n } else {\n throw new TypeError(`unknown contract type: ${contract}`);\n }\n\n let xdrDurability: xdr.ContractDataDurability;\n switch (durability) {\n case Durability.Temporary:\n xdrDurability = xdr.ContractDataDurability.temporary();\n break;\n\n case Durability.Persistent:\n xdrDurability = xdr.ContractDataDurability.persistent();\n break;\n\n default:\n throw new TypeError(`invalid durability: ${durability}`);\n }\n\n const contractKey = xdr.LedgerKey.contractData(\n new xdr.LedgerKeyContractData({\n key,\n contract: scAddress,\n durability: xdrDurability,\n }),\n );\n\n try {\n return await this.getLedgerEntry(contractKey);\n } catch {\n throw {\n code: 404,\n message: `Contract data not found for ${Address.fromScAddress(\n scAddress,\n ).toString()} with key ${key.toXDR(\"base64\")} and durability: ${durability}`,\n };\n }\n }\n\n /**\n * Retrieves the WASM bytecode for a given contract.\n *\n * This method allows you to fetch the WASM bytecode associated with a contract\n * deployed on the Soroban network. The WASM bytecode represents the executable\n * code of the contract.\n *\n * @param contractId - The contract ID containing the WASM bytecode to retrieve\n * @returns A Buffer containing the WASM bytecode\n * @throws If the contract or its associated WASM bytecode cannot be\n * found on the network.\n *\n * @example\n * ```ts\n * const contractId = \"CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5\";\n * server.getContractWasmByContractId(contractId).then(wasmBuffer => {\n * console.log(\"WASM bytecode length:\", wasmBuffer.length);\n * // ... do something with the WASM bytecode ...\n * }).catch(err => {\n * console.error(\"Error fetching WASM bytecode:\", err);\n * });\n * ```\n */\n public async getContractWasmByContractId(\n contractId: string,\n ): Promise<Buffer> {\n const contractLedgerKey = new Contract(contractId).getFootprint();\n const response = await this.getLedgerEntries(contractLedgerKey);\n if (!response.entries.length || !response.entries[0]?.val) {\n return Promise.reject({\n code: 404,\n message: `Could not obtain contract hash from server`,\n });\n }\n\n const wasmHash = response.entries[0].val\n .contractData()\n .val()\n .instance()\n .executable()\n .wasmHash();\n\n return this.getContractWasmByHash(wasmHash);\n }\n\n /**\n * Retrieves the WASM bytecode for a given contract hash.\n *\n * This method allows you to fetch the WASM bytecode associated with a contract\n * deployed on the Soroban network using the contract's WASM hash. The WASM bytecode\n * represents the executable code of the contract.\n *\n * @param wasmHash - The WASM hash of the contract\n * @returns A Buffer containing the WASM bytecode\n * @throws If the contract or its associated WASM bytecode cannot be\n * found on the network.\n *\n * @example\n * ```ts\n * const wasmHash = Buffer.from(\"...\");\n * server.getContractWasmByHash(wasmHash).then(wasmBuffer => {\n * console.log(\"WASM bytecode length:\", wasmBuffer.length);\n * // ... do something with the WASM bytecode ...\n * }).catch(err => {\n * console.error(\"Error fetching WASM bytecode:\", err);\n * });\n * ```\n */\n public async getContractWasmByHash(\n wasmHash: Buffer | string,\n format: undefined | \"hex\" | \"base64\" = undefined,\n ): Promise<Buffer> {\n const wasmHashBuffer =\n typeof wasmHash === \"string\"\n ? Buffer.from(wasmHash, format)\n : (wasmHash as Buffer);\n\n const ledgerKeyWasmHash = xdr.LedgerKey.contractCode(\n new xdr.LedgerKeyContractCode({\n hash: wasmHashBuffer,\n }),\n );\n\n const responseWasm = await this.getLedgerEntries(ledgerKeyWasmHash);\n if (!responseWasm.entries.length || !responseWasm.entries[0]?.val) {\n return Promise.reject({\n code: 404,\n message: \"Could not obtain contract wasm from server\",\n });\n }\n const wasmBuffer = responseWasm.entries[0].val.contractCode().code();\n\n return wasmBuffer;\n }\n\n /**\n * Reads the current value of arbitrary ledger entries directly.\n *\n * Allows you to directly inspect the current state of contracts, contract's\n * code, accounts, or any other ledger entries.\n *\n * To fetch a contract's WASM byte-code, built the appropriate\n * {@link xdr.LedgerKeyContractCode} ledger entry key (or see\n * {@link Contract.getFootprint}).\n *\n * @param keys - One or more ledger entry keys to load\n * @returns The current on-chain\n * values for the given ledger keys\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n * @see RpcServer._getLedgerEntries\n * @example\n * ```ts\n * const contractId = \"CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM\";\n * const key = xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({\n * contractId: StrKey.decodeContract(contractId),\n * key: xdr.ScVal.scvSymbol(\"counter\"),\n * }));\n *\n * server.getLedgerEntries([key]).then(response => {\n * const ledgerData = response.entries[0];\n * console.log(\"key:\", ledgerData.key);\n * console.log(\"value:\", ledgerData.val);\n * console.log(\"liveUntilLedgerSeq:\", ledgerData.liveUntilLedgerSeq);\n * console.log(\"lastModified:\", ledgerData.lastModifiedLedgerSeq);\n * console.log(\"latestLedger:\", response.latestLedger);\n * });\n * ```\n */\n public getLedgerEntries(...keys: xdr.LedgerKey[]) {\n return this._getLedgerEntries(...keys).then(parseRawLedgerEntries);\n }\n\n public _getLedgerEntries(...keys: xdr.LedgerKey[]) {\n return jsonrpc.postObject<Api.RawGetLedgerEntriesResponse>(\n this.httpClient,\n this.serverURL.toString(),\n \"getLedgerEntries\",\n {\n keys: keys.map((k) => k.toXDR(\"base64\")),\n },\n );\n }\n\n public async getLedgerEntry(key: xdr.LedgerKey) {\n const results = await this._getLedgerEntries(key).then(\n parseRawLedgerEntries,\n );\n if (results.entries.length !== 1) {\n throw new Error(`failed to find an entry for key ${key.toXDR(\"base64\")}`);\n }\n return results.entries[0];\n }\n\n /**\n * Poll for a particular transaction with certain parameters.\n *\n * After submitting a transaction, clients can use this to poll for\n * transaction completion and return a definitive state of success or failure.\n *\n * @param hash - the transaction you're polling for\n * @param opts - (optional) polling options\n * - `attempts` (optional): (optional) the number of attempts to make\n * before returning the last-seen status. By default or on invalid inputs,\n * try 5 times.\n * - `sleepStrategy` (optional): (optional) the amount of time\n * to wait for between each attempt. By default, sleep for 1 second between\n * each attempt.\n *\n * @returns the response after a \"found\"\n * response (which may be success or failure) or the last response obtained\n * after polling the maximum number of specified attempts.\n *\n * @example\n * ```ts\n * const h = \"c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a\";\n * const txStatus = await server.pollTransaction(h, {\n * attempts: 100, // I'm a maniac\n * sleepStrategy: rpc.LinearSleepStrategy\n * }); // this will take 5,050 seconds to complete\n * ```\n */\n public async pollTransaction(\n hash: string,\n opts?: RpcServer.PollingOptions,\n ): Promise<Api.GetTransactionResponse> {\n const maxAttempts: number =\n (opts?.attempts ?? 0) < 1\n ? DEFAULT_GET_TRANSACTION_TIMEOUT\n : (opts?.attempts ?? DEFAULT_GET_TRANSACTION_TIMEOUT); // \"positive and defined user value or default\"\n\n let foundInfo: Api.GetTransactionResponse;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n foundInfo = await this.getTransaction(hash);\n if (foundInfo.status !== Api.GetTransactionStatus.NOT_FOUND) {\n return foundInfo;\n }\n\n await Utils.sleep((opts?.sleepStrategy ?? BasicSleepStrategy)(attempt));\n }\n\n return foundInfo!;\n }\n\n /**\n * Fetch the details of a submitted transaction.\n *\n * After submitting a transaction, clients should poll this to tell when the\n * transaction has completed.\n *\n * @param hash - Hex-encoded hash of the transaction to check\n * @returns The status, result, and\n * other details about the transaction\n *\n * @see\n * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransaction | getTransaction docs}\n *\n * @example\n * ```ts\n * const transactionHash = \"c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a\";\n * server.getTransaction(transactionHash).then((tx) => {\n * console.log(\"status:\", tx.status);\n * console.log(\"envelopeXdr:\", tx.envelopeXdr);\n * console.log(\"resultMetaXdr:\", tx.resultMetaXdr);\n * console.log(\"resultXdr:\", tx.resultXdr);\n * });\n * ```\n */\n\n public async getTransaction(\n hash: string,\n ): Promise<Api.GetTransactionResponse> {\n return this._getTransaction(hash).then((raw) => {\n const foundInfo: Omit<\n Api.GetSuccessfulTransactionResponse,\n keyof Api.GetMissingTransactionResponse\n > = {} as any;\n\n if (raw.status !== Api.GetTransactionStatus.NOT_FOUND) {\n Object.assign(foundInfo, parseTransactionInfo(raw));\n }\n\n const result: Api.GetTransactionResponse = {\n status: raw.status,\n txHash: hash,\n latestLedger: raw.latestLedger,\n latestLedgerCloseTime: raw.latestLedgerCloseTime,\n oldestLedger: raw.oldestLedger,\n oldestLedgerCloseTime: raw.oldestLedgerCloseTime,\n ...foundInfo,\n };\n\n return result;\n });\n }\n\n public async _getTransaction(\n hash: string,\n ): Promise<Api.RawGetTransactionResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getTransaction\",\n {\n hash,\n },\n );\n }\n\n /**\n * Fetch transactions starting from a given start ledger or a cursor. The end ledger is the latest ledger\n * in that RPC instance.\n *\n * @param request - The request parameters.\n * @returns - A promise that resolves to the transactions response.\n *\n * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransactions\n * @example\n * ```ts\n * server.getTransactions({\n * startLedger: 10000,\n * limit: 10,\n * }).then((response) => {\n * console.log(\"Transactions:\", response.transactions);\n * console.log(\"Latest Ledger:\", response.latestLedger);\n * console.log(\"Cursor:\", response.cursor);\n * });\n * ```\n */\n public async getTransactions(\n request: Api.GetTransactionsRequest,\n ): Promise<Api.GetTransactionsResponse> {\n return this._getTransactions(request).then(\n (raw: Api.RawGetTransactionsResponse) => {\n const result: Api.GetTransactionsResponse = {\n transactions: (raw.transactions || []).map(parseRawTransactions),\n latestLedger: raw.latestLedger,\n latestLedgerCloseTimestamp: raw.latestLedgerCloseTimestamp,\n oldestLedger: raw.oldestLedger,\n oldestLedgerCloseTimestamp: raw.oldestLedgerCloseTimestamp,\n cursor: raw.cursor,\n };\n return result;\n },\n );\n }\n\n async _getTransactions(\n request: Api.GetTransactionsRequest,\n ): Promise<Api.RawGetTransactionsResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getTransactions\",\n request,\n );\n }\n\n /**\n * Fetch all events that match a given set of filters.\n *\n * The given filters (see {@link Api.EventFilter}\n * for detailed fields) are combined only in a logical OR fashion, and all of\n * the fields in each filter are optional.\n *\n * To page through events, use the `pagingToken` field on the relevant\n * {@link Api.EventResponse} object to set the `cursor` parameter.\n *\n * @param request - Event filters {@link Api.GetEventsRequest},\n * @returns A paginatable set of the events\n * matching the given event filters\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getEvents | getEvents docs}\n *\n * @example\n * ```ts\n *\n * server.getEvents({\n * startLedger: 1000,\n * endLedger: 2000,\n * filters: [\n * {\n * type: \"contract\",\n * contractIds: [ \"deadb33f...\" ],\n * topics: [[ \"AAAABQAAAAh0cmFuc2Zlcg==\", \"AAAAAQB6Mcc=\", \"*\" ]]\n * }, {\n * type: \"system\",\n * contractIds: [ \"...c4f3b4b3...\" ],\n * topics: [[ \"*\" ], [ \"*\", \"AAAAAQB6Mcc=\" ]]\n * }, {\n * contractIds: [ \"...c4f3b4b3...\" ],\n * topics: [[ \"AAAABQAAAAh0cmFuc2Zlcg==\" ]]\n * }, {\n * type: \"diagnostic\",\n * topics: [[ \"AAAAAQB6Mcc=\" ]]\n * }\n * ],\n * limit: 10,\n * });\n * ```\n */\n\n public async getEvents(\n request: Api.GetEventsRequest,\n ): Promise<Api.GetEventsResponse> {\n return this._getEvents(request).then(parseRawEvents);\n }\n\n public async _getEvents(\n request: Api.GetEventsRequest,\n ): Promise<Api.RawGetEventsResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getEvents\",\n {\n filters: request.filters ?? [],\n pagination: {\n ...(request.cursor && { cursor: request.cursor }), // add if defined\n ...(request.limit && { limit: request.limit }),\n },\n ...(request.startLedger && {\n startLedger: request.startLedger,\n }),\n ...(request.endLedger && {\n endLedger: request.endLedger,\n }),\n },\n );\n }\n\n /**\n * Fetch metadata about the network this Soroban RPC server is connected to.\n *\n * @returns Metadata about the current\n * network this RPC server is connected to\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getNetwork | getNetwork docs}\n *\n * @example\n * ```ts\n * server.getNetwork().then((network) => {\n * console.log(\"friendbotUrl:\", network.friendbotUrl);\n * console.log(\"passphrase:\", network.passphrase);\n * console.log(\"protocolVersion:\", network.protocolVersion);\n * });\n * ```\n */\n\n public async getNetwork(): Promise<Api.GetNetworkResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getNetwork\",\n );\n }\n\n /**\n * Fetch the latest ledger meta info from network which this Soroban RPC\n * server is connected to.\n *\n * @returns metadata about the\n * latest ledger on the network that this RPC server is connected to\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLatestLedger | getLatestLedger docs}\n *\n * @example\n * ```ts\n * server.getLatestLedger().then((response) => {\n * console.log(\"hash:\", response.id);\n * console.log(\"sequence:\", response.sequence);\n * console.log(\"protocolVersion:\", response.protocolVersion);\n * });\n * ```\n */\n public async getLatestLedger(): Promise<Api.GetLatestLedgerResponse> {\n return this._getLatestLedger().then(parseRawLatestLedger);\n }\n\n public async _getLatestLedger(): Promise<Api.RawGetLatestLedgerResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getLatestLedger\",\n );\n }\n\n /**\n * Submit a trial contract invocation to get back return values, expected\n * ledger footprint, expected authorizations, and expected costs.\n *\n * @param tx - the transaction to simulate,\n * which should include exactly one operation (one of\n * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTtlOp}, or\n * {@link xdr.RestoreFootprintOp}). Any provided footprint or auth\n * information will be ignored.\n * @param addlResources - (optional) any additional resources\n * to add to the simulation-provided ones, for example if you know you will\n * need extra CPU instructions\n * @param authMode - (optional) optionally, specify the type of\n * auth mode to use for simulation: `enforce` for enforcement mode,\n * `record` for recording mode, or `record_allow_nonroot` for recording\n * mode that allows non-root authorization\n * @param authV2 - (optional) request `SOROBAN_CREDENTIALS_ADDRESS_V2`\n * (CAP-71) auth credentials from simulation instead of the legacy\n * `SOROBAN_CREDENTIALS_ADDRESS`. Defaults to `false`; only enable it for\n * networks that have activated CAP-71, as V2 credentials are otherwise\n * rejected.\n *\n * @returns An object with the\n * cost, footprint, result/auth requirements (if applicable), and error of\n * the transaction\n *\n * @see\n * {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs}\n * @see\n * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs}\n * @see\n * {@link https://developers.stellar.org/docs/learn/fundamentals/contract-development/contract-interactions/transaction-simulation#authorization | authorization modes}\n * @see module:rpc.Server#prepareTransaction\n * @see module:rpc.assembleTransaction\n *\n * @example\n * ```ts\n * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE';\n * const contract = new StellarSdk.Contract(contractId);\n *\n * // Right now, this is just the default fee for this example.\n * const fee = StellarSdk.BASE_FEE;\n * const transaction = new StellarSdk.TransactionBuilder(account, { fee })\n * // Uncomment the following line to build transactions for the live network. Be\n * // sure to also change the horizon hostname.\n * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC)\n * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET)\n * .setTimeout(30) // valid for the next 30s\n * // Add an operation to call increment() on the contract\n * .addOperation(contract.call(\"increment\"))\n * .build();\n *\n * server.simulateTransaction(transaction).then((sim) => {\n * console.log(\"cost:\", sim.cost);\n * console.log(\"result:\", sim.result);\n * console.log(\"error:\", sim.error);\n * console.log(\"latestLedger:\", sim.latestLedger);\n * });\n * ```\n */\n\n public async simulateTransaction(\n tx: Transaction | FeeBumpTransaction,\n addlResources?: RpcServer.ResourceLeeway,\n authMode?: Api.SimulationAuthMode,\n authV2: boolean = false,\n ): Promise<Api.SimulateTransactionResponse> {\n return this._simulateTransaction(tx, addlResources, authMode, authV2).then(\n parseRawSimulation,\n );\n }\n\n public async _simulateTransaction(\n transaction: Transaction | FeeBumpTransaction,\n addlResources?: RpcServer.ResourceLeeway,\n authMode?: Api.SimulationAuthMode,\n authV2: boolean = false,\n ): Promise<Api.RawSimulateTransactionResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"simulateTransaction\",\n {\n transaction: transaction.toXDR(),\n authMode,\n ...(addlResources !== undefined && {\n resourceConfig: {\n instructionLeeway: addlResources.cpuInstructions,\n },\n }),\n // CAP-71: only request ADDRESS_V2 auth credentials when explicitly\n // opted in. They are rejected by networks that have not activated\n // CAP-71, so default to omitting the flag (legacy ADDRESS credentials).\n ...(authV2 && { authV2: true }),\n },\n );\n }\n\n /**\n * Submit a trial contract invocation, first run a simulation of the contract\n * invocation as defined on the incoming transaction, and apply the results to\n * a new copy of the transaction which is then returned. Setting the ledger\n * footprint and authorization, so the resulting transaction is ready for\n * signing & sending.\n *\n * The returned transaction will also have an updated fee that is the sum of\n * fee set on incoming transaction with the contract resource fees estimated\n * from simulation. It is advisable to check the fee on returned transaction\n * and validate or take appropriate measures for interaction with user to\n * confirm it is acceptable.\n *\n * You can call the {@link rpc.Server.simulateTransaction} method\n * directly first if you want to inspect estimated fees for a given\n * transaction in detail first, then re-assemble it manually or via\n * {@link rpc.assembleTransaction}.\n *\n * @param tx - the transaction to\n * prepare. It should include exactly one operation, which must be one of\n * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTtlOp},\n * or {@link xdr.RestoreFootprintOp}.\n *\n * Any provided footprint will be overwritten. However, if your operation\n * has existing auth entries, they will be preferred over ALL auth entries\n * from the simulation. In other words, if you include auth entries, you\n * don't care about the auth returned from the simulation. Other fields\n * (footprint, etc.) will be filled as normal.\n * @returns A copy of the\n * transaction with the expected authorizations (in the case of\n * invocation), resources, and ledger footprints added. The transaction fee\n * will also automatically be padded with the contract's minimum resource\n * fees discovered from the simulation.\n * @throws * If simulation fails\n *\n * @see module:rpc.assembleTransaction\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs}\n *\n * @example\n * ```ts\n * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE';\n * const contract = new StellarSdk.Contract(contractId);\n *\n * // Right now, this is just the default fee for this example.\n * const fee = StellarSdk.BASE_FEE;\n * const transaction = new StellarSdk.TransactionBuilder(account, { fee })\n * // Uncomment the following line to build transactions for the live network. Be\n * // sure to also change the horizon hostname.\n * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC)\n * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET)\n * .setTimeout(30) // valid for the next 30s\n * // Add an operation to call increment() on the contract\n * .addOperation(contract.call(\"increment\"))\n * .build();\n *\n * const preparedTransaction = await server.prepareTransaction(transaction);\n *\n * // Sign this transaction with the secret key\n * // NOTE: signing is transaction is network specific. Test network transactions\n * // won't work in the public network. To switch networks, use the Network object\n * // as explained above (look for StellarSdk.Network).\n * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey);\n * preparedTransaction.sign(sourceKeypair);\n *\n * server.sendTransaction(transaction).then(result => {\n * console.log(\"hash:\", result.hash);\n * console.log(\"status:\", result.status);\n * console.log(\"errorResultXdr:\", result.errorResultXdr);\n * });\n * ```\n */\n public async prepareTransaction(tx: Transaction | FeeBumpTransaction) {\n const simResponse = await this.simulateTransaction(tx);\n if (Api.isSimulationError(simResponse)) {\n throw new Error(simResponse.error);\n }\n\n return assembleTransaction(tx, simResponse).build();\n }\n\n /**\n * Submit a real transaction to the Stellar network.\n *\n * Unlike Horizon, RPC does not wait for transaction completion. It\n * simply validates the transaction and enqueues it. Clients should call\n * {@link rpc.Server.getTransaction} to learn about transaction\n * success/failure.\n *\n * @param transaction - to submit\n * @returns the\n * transaction id, status, and any error if available\n *\n * @see {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs}\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/sendTransaction | sendTransaction docs}\n *\n * @example\n * ```ts\n * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE';\n * const contract = new StellarSdk.Contract(contractId);\n *\n * // Right now, this is just the default fee for this example.\n * const fee = StellarSdk.BASE_FEE;\n * const transaction = new StellarSdk.TransactionBuilder(account, { fee })\n * // Uncomment the following line to build transactions for the live network. Be\n * // sure to also change the horizon hostname.\n * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC)\n * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET)\n * .setTimeout(30) // valid for the next 30s\n * // Add an operation to call increment() on the contract\n * .addOperation(contract.call(\"increment\"))\n * .build();\n *\n * // Sign this transaction with the secret key\n * // NOTE: signing is transaction is network specific. Test network transactions\n * // won't work in the public network. To switch networks, use the Network object\n * // as explained above (look for StellarSdk.Network).\n * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey);\n * transaction.sign(sourceKeypair);\n *\n * server.sendTransaction(transaction).then((result) => {\n * console.log(\"hash:\", result.hash);\n * console.log(\"status:\", result.status);\n * console.log(\"errorResultXdr:\", result.errorResultXdr);\n * });\n * ```\n */\n public async sendTransaction(\n transaction: Transaction | FeeBumpTransaction,\n ): Promise<Api.SendTransactionResponse> {\n return this._sendTransaction(transaction).then(parseRawSendTransaction);\n }\n\n public async _sendTransaction(\n transaction: Transaction | FeeBumpTransaction,\n ): Promise<Api.RawSendTransactionResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"sendTransaction\",\n {\n transaction: transaction.toXDR(),\n },\n );\n }\n\n /**\n * Fund a new account using the network's Friendbot faucet, if any.\n *\n * @param address - The address or account instance that we\n * want to create and fund with Friendbot\n * @param friendbotUrl - (optional) Optionally, an explicit address for\n * friendbot (by default: this calls the Soroban RPC\n * {@link rpc.Server.getNetwork | getNetwork} method to try to\n * discover this network's Friendbot url).\n * @returns An {@link Account} object for the created\n * account, or the existing account if it's already funded with the\n * populated sequence number (note that the account will not be \"topped\n * off\" if it already exists)\n * @throws If Friendbot is not configured on this network or request failure\n *\n * @see {@link https://developers.stellar.org/docs/learn/fundamentals/networks#friendbot | Friendbot docs}\n * @see {@link Friendbot.Api.Response}\n *\n * @deprecated Use {@link Server.fundAddress} instead, which supports both\n * account (G...) and contract (C...) addresses.\n *\n * @example\n * ```ts\n * server\n * .requestAirdrop(\"GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4\")\n * .then((accountCreated) => {\n * console.log(\"accountCreated:\", accountCreated);\n * }).catch((error) => {\n * console.error(\"error:\", error);\n * });\n * ```\n */\n public async requestAirdrop(\n address: string | Pick<Account, \"accountId\">,\n friendbotUrl?: string,\n ): Promise<Account> {\n const account = typeof address === \"string\" ? address : address.accountId();\n friendbotUrl = friendbotUrl || (await this.getNetwork()).friendbotUrl;\n if (!friendbotUrl) {\n throw new Error(\"No friendbot URL configured for current network\");\n }\n\n try {\n const response = await this.httpClient.post<FriendbotApi.Response>(\n `${friendbotUrl}?addr=${encodeURIComponent(account)}`,\n );\n\n let meta: xdr.TransactionMeta;\n if (!response.data.result_meta_xdr) {\n const txMeta = await this.getTransaction(response.data.hash);\n if (txMeta.status !== Api.GetTransactionStatus.SUCCESS) {\n throw new Error(`Funding account ${address} failed`);\n }\n meta = txMeta.resultMetaXdr;\n } else {\n meta = xdr.TransactionMeta.fromXDR(\n response.data.result_meta_xdr,\n \"base64\",\n );\n }\n\n const sequence = findCreatedAccountSequenceInTransactionMeta(meta);\n return new Account(account, sequence);\n } catch (error: any) {\n if (error.response?.status === 400) {\n if (\n error.response.data?.detail?.includes(\"createAccountAlreadyExist\")\n ) {\n // Account already exists, load the sequence number\n return this.getAccount(account);\n }\n }\n throw error;\n }\n }\n\n /**\n * Fund an address using the network's Friendbot faucet, if any.\n *\n * This method supports both account (G...) and contract (C...) addresses.\n *\n * @param address - The address to fund. Can be either a Stellar\n * account (G...) or contract (C...) address.\n * @param friendbotUrl - (optional) Optionally, an explicit Friendbot URL\n * (by default: this calls the Stellar RPC\n * {@link rpc.Server.getNetwork | getNetwork} method to try to\n * discover this network's Friendbot url).\n * @returns The transaction\n * response from the Friendbot funding transaction.\n * @throws If Friendbot is not configured on this network or the\n * funding transaction fails.\n *\n * @see {@link https://developers.stellar.org/docs/learn/fundamentals/networks#friendbot | Friendbot docs}\n *\n * @example\n * ```ts\n * // Funding an account (G... address)\n * const tx = await server.fundAddress(\"GBZC6Y2Y7...\");\n * console.log(\"Funded! Hash:\", tx.txHash);\n * // If you need the Account object:\n * const account = await server.getAccount(\"GBZC6Y2Y7...\");\n * ```\n *\n * @example\n * ```ts\n * // Funding a contract (C... address)\n * const tx = await server.fundAddress(\"CBZC6Y2Y7...\");\n * console.log(\"Contract funded! Hash:\", tx.txHash);\n * ```\n */\n public async fundAddress(\n address: string,\n friendbotUrl?: string,\n ): Promise<Api.GetSuccessfulTransactionResponse> {\n if (\n !StrKey.isValidEd25519PublicKey(address) &&\n !StrKey.isValidContract(address)\n ) {\n throw new Error(\n `Invalid address: ${address}. Expected a Stellar account (G...) or contract (C...) address.`,\n );\n }\n\n friendbotUrl = friendbotUrl || (await this.getNetwork()).friendbotUrl;\n if (!friendbotUrl) {\n throw new Error(\"No friendbot URL configured for current network\");\n }\n\n try {\n const response = await this.httpClient.post<FriendbotApi.Response>(\n `${friendbotUrl}?addr=${encodeURIComponent(address)}`,\n );\n\n const txResponse = await this.getTransaction(response.data.hash);\n if (txResponse.status !== Api.GetTransactionStatus.SUCCESS) {\n throw new Error(\n `Funding address ${address} failed: transaction status ${txResponse.status}`,\n );\n }\n\n return txResponse;\n } catch (error: any) {\n if (error.response?.status === 400) {\n throw new Error(error.response.data?.detail ?? \"Bad Request\");\n }\n throw error;\n }\n }\n\n /**\n * Provides an analysis of the recent fee stats for regular and smart\n * contract operations.\n *\n * @returns the fee stats\n * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getFeeStats\n */\n public async getFeeStats(): Promise<Api.GetFeeStatsResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getFeeStats\",\n );\n }\n\n /**\n * Provides information about the current version details of the Soroban RPC and captive-core\n *\n * @returns the version info\n * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getVersionInfo\n */\n public async getVersionInfo(): Promise<Api.GetVersionInfoResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getVersionInfo\",\n );\n }\n\n /**\n * Returns a contract's balance of a particular SAC asset, if any.\n *\n * This is a convenience wrapper around {@link Server.getLedgerEntries}.\n *\n * @param address - the contract (string `C...`) whose balance of\n * `sac` you want to know\n * @param sac - the built-in SAC token (e.g. `USDC:GABC...`) that\n * you are querying from the given `contract`.\n * @param networkPassphrase - (optional) optionally, the network passphrase to\n * which this token applies. If omitted, a request about network\n * information will be made (see {@link getNetwork}), since contract IDs\n * for assets are specific to a network. You can refer to {@link Networks}\n * for a list of built-in passphrases, e.g., `Networks.TESTNET`.\n *\n * @returns , which will contain the balance\n * entry details if and only if the request returned a valid balance ledger\n * entry. If it doesn't, the `balanceEntry` field will not exist.\n *\n * @throws If `address` is not a valid contract ID (C...).\n *\n * @see getLedgerEntries\n * @see https://developers.stellar.org/docs/tokens/stellar-asset-contract\n *\n * @deprecated Use {@link getAssetBalance}, instead\n * @example\n * ```ts\n * // assume `address` is some contract or account with an XLM balance\n * // assume server is an instantiated `Server` instance.\n * const entry = (await server.getSACBalance(\n * new Address(address),\n * Asset.native(),\n * Networks.PUBLIC\n * ));\n *\n * // assumes BigInt support:\n * console.log(\n * entry.balanceEntry ?\n * BigInt(entry.balanceEntry.amount) :\n * \"Address has no XLM\");\n * ```\n */\n public async getSACBalance(\n address: string | Address,\n sac: Asset,\n networkPassphrase?: string,\n ): Promise<Api.BalanceResponse> {\n const addressString =\n address instanceof Address ? address.toString() : address;\n\n if (!StrKey.isValidContract(addressString)) {\n throw new TypeError(`expected contract ID, got ${addressString}`);\n }\n\n // Call out to RPC if passphrase isn't provided.\n const passphrase: string =\n networkPassphrase ?? (await this.getNetwork().then((n) => n.passphrase));\n\n // Turn SAC into predictable contract ID\n const sacId = sac.contractId(passphrase);\n\n // Rust union enum type with \"Balance(ScAddress)\" structure\n const key = nativeToScVal([\"Balance\", addressString], {\n type: [\"symbol\", \"address\"],\n });\n\n // Note a quirk here: the contract address in the key is the *token*\n // rather than the *holding contract*. This is because each token stores a\n // balance entry for each contract, not the other way around (i.e. XLM\n // holds a reserve for contract X, rather that contract X having a balance\n // of N XLM).\n const ledgerKey = xdr.LedgerKey.contractData(\n new xdr.LedgerKeyContractData({\n contract: new Address(sacId).toScAddress(),\n durability: xdr.ContractDataDurability.persistent(),\n key,\n }),\n );\n\n const response = await this.getLedgerEntries(ledgerKey);\n if (response.entries.length === 0) {\n return { latestLedger: response.latestLedger };\n }\n\n const { lastModifiedLedgerSeq, liveUntilLedgerSeq, val } =\n response.entries[0];\n\n if (val.switch().value !== xdr.LedgerEntryType.contractData().value) {\n return { latestLedger: response.latestLedger };\n }\n\n const entry = scValToNative(val.contractData().val());\n\n // Since we are requesting a SAC's contract data, we know for a fact that\n // it should follow the expected structure format. Thus, we can presume\n // these fields exist:\n return {\n latestLedger: response.latestLedger,\n balanceEntry: {\n liveUntilLedgerSeq,\n lastModifiedLedgerSeq,\n amount: entry.amount.toString(),\n authorized: entry.authorized,\n clawback: entry.clawback,\n },\n };\n }\n\n /**\n * Fetch a detailed list of ledgers starting from a specified point.\n *\n * Returns ledger data with support for pagination as long as the requested\n * pages fall within the history retention of the RPC provider.\n *\n * @param request - The request parameters for fetching ledgers. {@link Api.GetLedgersRequest}\n * @returns A promise that resolves to the\n * ledgers response containing an array of ledger data and pagination info. {@link Api.GetLedgersResponse}\n *\n * @throws If startLedger is less than the oldest ledger stored in this\n * node, or greater than the latest ledger seen by this node.\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgers | getLedgers docs}\n *\n * @example\n * ```ts\n * // Fetch ledgers starting from a specific sequence number\n * server.getLedgers({\n * startLedger: 36233,\n * pagination: {\n * limit: 10\n * }\n * }).then((response) => {\n * console.log(\"Ledgers:\", response.ledgers);\n * console.log(\"Latest Ledger:\", response.latestLedger);\n * console.log(\"Cursor:\", response.cursor);\n * });\n * ```\n *\n * @example\n * ```ts\n * // Paginate through ledgers using cursor\n * const firstPage = await server.getLedgers({\n * startLedger: 36233,\n * pagination: {\n * limit: 5\n * }\n * });\n *\n * const nextPage = await server.getLedgers({\n * pagination: {\n * cursor: firstPage.cursor,\n * limit: 5\n * }\n * });\n * ```\n */\n\n public async getLedgers(\n request: Api.GetLedgersRequest,\n ): Promise<Api.GetLedgersResponse> {\n return this._getLedgers(request).then((raw) => {\n const result: Api.GetLedgersResponse = {\n ledgers: (raw.ledgers || []).map(parseRawLedger),\n latestLedger: raw.latestLedger,\n latestLedgerCloseTime: raw.latestLedgerCloseTime,\n oldestLedger: raw.oldestLedger,\n oldestLedgerCloseTime: raw.oldestLedgerCloseTime,\n cursor: raw.cursor,\n };\n return result;\n });\n }\n\n public async _getLedgers(\n request: Api.GetLedgersRequest,\n ): Promise<Api.RawGetLedgersResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getLedgers\",\n request,\n );\n }\n}\n"],"names":["Durability","xdr","createHttpClient","Account","Keypair","StrKey","buffer","Buffer","address","Address","Contract","jsonrpc.postObject","contract","parseRawLedgerEntries","Api","Utils","parseTransactionInfo","parseRawTransactions","parseRawEvents","parseRawLatestLedger","parseRawSimulation","assembleTransaction","parseRawSendTransaction","account","nativeToScVal","scValToNative","parseRawLedger"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CO,IAAK,UAAA,qBAAAA,WAAAA,KAAL;AACL,EAAAA,YAAA,WAAA,CAAA,GAAY,WAAA;AACZ,EAAAA,YAAA,YAAA,CAAA,GAAa,YAAA;AAFH,EAAA,OAAAA,WAAAA;AAAA,CAAA,EAAA,UAAA,IAAA,EAAA;AAsCZ,MAAM,+BAAA,GAA0C,EAAA;AAIzC,MAAM,kBAAA,GAAoC,CAAC,KAAA,KAAkB;AAG7D,MAAM,mBAAA,GAAqC,CAAC,IAAA,KAAiB,GAAA,GAAO;AAQ3E,SAAS,4CACP,IAAA,EACQ;AACR,EAAA,IAAI,aAAkC,EAAC;AACvC,EAAA,QAAQ,IAAA,CAAK,QAAO;AAAG,IACrB,KAAK,CAAA;AACH,MAAA,UAAA,GAAa,KA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KAAQ;AAC7C,MAAA,MAAM,MAAA,GAAiC;AAAA,QACrC,UAAU,GAAA,CAAI,OAAA,IAAW,EAAC,EAAG,IAAIC,sBAAc,CAAA;AAAA,QAC/C,cAAc,GAAA,CAAI,YAAA;AAAA,QAClB,uBAAuB,GAAA,CAAI,qBAAA;AAAA,QAC3B,cAAc,GAAA,CAAI,YAAA;AAAA,QAClB,uBAAuB,GAAA,CAAI,qBAAA;AAAA,QAC3B,QAAQ,GAAA,CAAI;AAAA,OACd;AACA,MAAA,OAAO,MAAA;AAAA,IACT,CAAC,CAAA;AAAA,EACH;AAAA,EAEA,MAAa,YACX,OAAA,EACoC;AACpC,IAAA,OAAOf,kBAAQ;AAAA,MACb,IAAA,CAAK,UAAA;AAAA,MACL,IAAA,CAAK,UAAU,QAAA,EAAS;AAAA,MACxB,YAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;;;;;;;"}
1
+ {"version":3,"file":"server.js","sources":["../../../../src/rpc/server.ts"],"sourcesContent":["/* tslint:disable:variable-name no-namespace */\nimport {\n Account,\n Address,\n Asset,\n Contract,\n FeeBumpTransaction,\n Keypair,\n StrKey,\n Transaction,\n nativeToScVal,\n scValToNative,\n xdr,\n} from \"../base/index.js\";\n\nimport type { TransactionBuilder } from \"../base/index.js\";\nimport type { Config } from \"../config.js\";\nimport { createHttpClient } from \"./axios.js\";\nimport type { Api as FriendbotApi } from \"../friendbot/index.js\";\nimport * as jsonrpc from \"./jsonrpc.js\";\nimport { Api } from \"./api.js\";\nimport { assembleTransaction } from \"./transaction.js\";\nimport {\n parseRawSendTransaction,\n parseRawSimulation,\n parseRawLedgerEntries,\n parseRawEvents,\n parseRawTransactions,\n parseTransactionInfo,\n parseRawLedger,\n parseRawLatestLedger,\n} from \"./parsers.js\";\nimport { Utils } from \"../utils.js\";\nimport type { HttpClient } from \"../http-client/index.js\";\n\n/**\n * Default transaction submission timeout for RPC requests, in milliseconds\n * @defaultValue 60000\n */\nexport const SUBMIT_TRANSACTION_TIMEOUT = 60 * 1000;\n\n/**\n * Specifies the durability namespace of contract-related ledger entries.\n *\n * @see {@link https://developers.stellar.org/docs/learn/smart-contract-internals/state-archival | State Archival docs}\n * @see {@link https://docs.rs/soroban-sdk/latest/soroban_sdk/storage/struct.Storage.html | Rust SDK Storage docs}\n */\nexport enum Durability {\n Temporary = \"temporary\",\n Persistent = \"persistent\",\n}\n\nexport namespace RpcServer {\n /**\n * @deprecated Use `Api.GetEventsRequest` instead.\n * @see {@link Api.GetEventsRequest}\n */\n export type GetEventsRequest = Api.GetEventsRequest;\n\n export interface PollingOptions {\n attempts?: number;\n sleepStrategy?: SleepStrategy;\n }\n\n /**\n * Describes additional resource leeways for transaction simulation.\n */\n export interface ResourceLeeway {\n /** Simulate the transaction with more CPU instructions available. */\n cpuInstructions: number;\n }\n\n /**\n * Options for configuring connections to RPC servers.\n */\n export interface Options {\n /** Allow connecting to http servers, default: `false`. This must be set to false in production deployments! */\n allowHttp?: boolean;\n /** Allow a timeout, default: 0. Allows user to avoid nasty lag. */\n timeout?: number;\n /** Additional headers that should be added to any requests to the RPC server. */\n headers?: Record<string, string>;\n }\n}\n\nconst DEFAULT_GET_TRANSACTION_TIMEOUT: number = 30;\n\n/// A strategy that will sleep 1 second each time\n\nexport const BasicSleepStrategy: SleepStrategy = (_iter: number) => 1000;\n\n/// A strategy that will sleep 1 second longer on each attempt\nexport const LinearSleepStrategy: SleepStrategy = (iter: number) => 1000 * iter;\n\n/**\n * A function that returns the number of *milliseconds* to sleep\n * on a given `iter`ation.\n */\nexport type SleepStrategy = (iter: number) => number;\n\nfunction findCreatedAccountSequenceInTransactionMeta(\n meta: xdr.TransactionMeta,\n): string {\n let operations: xdr.OperationMeta[] = [];\n switch (meta.switch()) {\n case 0:\n operations = meta.operations();\n break;\n case 1:\n case 2:\n case 3:\n case 4: // all four have the same interface\n operations = (meta.value() as xdr.TransactionMetaV4).operations();\n break;\n default:\n throw new Error(\"Unexpected transaction meta switch value\");\n }\n const sequenceNumber = operations\n .flatMap((op) => op.changes())\n .find(\n (c) =>\n c.switch() === xdr.LedgerEntryChangeType.ledgerEntryCreated() &&\n c.created().data().switch() === xdr.LedgerEntryType.account(),\n )\n ?.created()\n ?.data()\n ?.account()\n ?.seqNum()\n ?.toString();\n\n if (sequenceNumber) {\n return sequenceNumber;\n }\n throw new Error(\"No account created in transaction\");\n}\n\n/**\n * Handles the network connection to a Soroban RPC instance, exposing an\n * interface for requests to that instance.\n *\n *\n * @param serverURL - Soroban-RPC Server URL (ex. `http://localhost:8000/soroban/rpc`).\n * @param opts - (optional) Options object\n * - `allowHttp` (optional): Allows connecting to insecure http servers\n * (default: `false`). This must be set to false in production deployments!\n * You can also use {@link Config} class to set this globally.\n * - `headers` (optional): Allows setting custom headers\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods | API reference docs}\n */\nexport class RpcServer {\n public readonly serverURL: URL;\n /**\n * HTTP client instance for making requests to Horizon.\n * Exposes interceptors, defaults, and other configuration options.\n *\n * @example\n * ```ts\n * // Add authentication header\n * server.httpClient.defaults.headers['Authorization'] = 'Bearer token';\n *\n * // Add request interceptor\n * server.httpClient.interceptors.request.use((config) => {\n * console.log('Request:', config.url);\n * return config;\n * });\n * ```\n */\n public readonly httpClient: HttpClient;\n constructor(serverURL: string, opts: RpcServer.Options = {}) {\n /**\n * RPC Server URL (ex. `http://localhost:8000/soroban/rpc`).\n */\n this.serverURL = new URL(serverURL);\n this.httpClient = createHttpClient(opts.headers);\n if (this.serverURL.protocol !== \"https:\" && !opts.allowHttp) {\n throw new Error(\n \"Cannot connect to insecure Soroban RPC server if `allowHttp` isn't set\",\n );\n }\n }\n\n /**\n * Fetch a minimal set of current info about a Stellar account.\n *\n * Needed to get the current sequence number for the account so you can build\n * a successful transaction with {@link TransactionBuilder}.\n *\n * @param address - The public address of the account to load.\n * @returns A promise which resolves to the {@link Account}\n * object with a populated sequence number\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n *\n * @example\n * ```ts\n * const accountId = \"GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4\";\n * server.getAccount(accountId).then((account) => {\n * console.log(\"sequence:\", account.sequence);\n * });\n * ```\n */\n public async getAccount(address: string): Promise<Account> {\n const entry = await this.getAccountEntry(address);\n return new Account(address, entry.seqNum().toString());\n }\n\n /**\n * Fetch the full account entry for a Stellar account.\n *\n * @param address - The public address of the account to load.\n * @returns Resolves to the full on-chain account\n * entry\n *\n * @see\n * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n *\n * @example\n * ```ts\n * const accountId = \"GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4\";\n * server.getAccountEntry(accountId).then((account) => {\n * console.log(\"sequence:\", account.balance().toString());\n * });\n * ```\n */\n public async getAccountEntry(address: string): Promise<xdr.AccountEntry> {\n const ledgerKey = xdr.LedgerKey.account(\n new xdr.LedgerKeyAccount({\n accountId: Keypair.fromPublicKey(address).xdrPublicKey(),\n }),\n );\n\n try {\n const resp = await this.getLedgerEntry(ledgerKey);\n return resp.val.account();\n } catch {\n throw new Error(`Account not found: ${address}`);\n }\n }\n\n /**\n * Fetch the full trustline entry for a Stellar account.\n *\n * @param account - The public address of the account whose trustline it is\n * @param asset - The trustline's asset\n * @returns Resolves to the full on-chain trustline\n * entry\n *\n * @see\n * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n *\n * @deprecated Use {@link getAssetBalance}, instead\n * @example\n * ```ts\n * const accountId = \"GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4\";\n * const asset = new Asset(\n * \"USDC\",\n * \"GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5\"\n * );\n * server.getTrustline(accountId, asset).then((entry) => {\n * console.log(`{asset.toString()} balance for ${accountId}:\", entry.balance().toString());\n * });\n * ```\n */\n public async getTrustline(\n account: string,\n asset: Asset,\n ): Promise<xdr.TrustLineEntry> {\n const trustlineLedgerKey = xdr.LedgerKey.trustline(\n new xdr.LedgerKeyTrustLine({\n accountId: Keypair.fromPublicKey(account).xdrAccountId(),\n asset: asset.toTrustLineXDRObject(),\n }),\n );\n\n try {\n const entry = await this.getLedgerEntry(trustlineLedgerKey);\n return entry.val.trustLine();\n } catch {\n throw new Error(\n `Trustline for ${asset.getCode()}:${asset.getIssuer()} not found for ${account}`,\n );\n }\n }\n\n /**\n * Fetch the full claimable balance entry for a Stellar account.\n *\n * @param id - The strkey (`B...`) or hex (`00000000abcde...`) (both\n * IDs with and without the 000... version prefix are accepted) of the\n * claimable balance to load\n * @returns Resolves to the full on-chain\n * claimable balance entry\n *\n * @see\n * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n *\n * @example\n * ```ts\n * const id = \"00000000178826fbfe339e1f5c53417c6fedfe2c05e8bec14303143ec46b38981b09c3f9\";\n * server.getClaimableBalance(id).then((entry) => {\n * console.log(`Claimable balance {id.substr(0, 12)} has:`);\n * console.log(` asset: ${Asset.fromXDRObject(entry.asset()).toString()}`;\n * console.log(` amount: ${entry.amount().toString()}`;\n * });\n * ```\n */\n public async getClaimableBalance(\n id: string,\n ): Promise<xdr.ClaimableBalanceEntry> {\n let balanceId;\n if (StrKey.isValidClaimableBalance(id)) {\n const buffer = StrKey.decodeClaimableBalance(id);\n\n // Pad the version byte to be a full int32 like in the XDR spec\n const v = Buffer.concat([\n Buffer.from(\"\\x00\\x00\\x00\"),\n buffer.subarray(0, 1),\n ]);\n\n // Slap on the rest of it and decode it\n balanceId = xdr.ClaimableBalanceId.fromXDR(\n Buffer.concat([v, buffer.subarray(1)]),\n );\n } else if (id.match(/[a-f0-9]{72}/i)) {\n balanceId = xdr.ClaimableBalanceId.fromXDR(id, \"hex\");\n } else if (id.match(/[a-f0-9]{64}/i)) {\n balanceId = xdr.ClaimableBalanceId.fromXDR(id.padStart(72, \"0\"), \"hex\");\n } else {\n throw new TypeError(`expected 72-char hex ID or strkey, not ${id}`);\n }\n\n const trustlineLedgerKey = xdr.LedgerKey.claimableBalance(\n new xdr.LedgerKeyClaimableBalance({ balanceId }),\n );\n\n try {\n const entry = await this.getLedgerEntry(trustlineLedgerKey);\n return entry.val.claimableBalance();\n } catch {\n throw new Error(`Claimable balance ${id} not found`);\n }\n }\n\n /**\n * Fetch the balance of an asset held by an account or contract.\n *\n * The `address` argument may be provided as a string (as a {@link StrKey}),\n * {@link Address}, or {@link Contract}.\n *\n * @param address - The account or contract whose\n * balance should be fetched.\n * @param asset - The asset whose balance you want to inspect.\n * @param networkPassphrase - (optional) optionally, when requesting the\n * balance of a contract, the network passphrase to which this token\n * applies. If omitted and necessary, a request about network information\n * will be made (see {@link getNetwork}), since contract IDs for assets are\n * specific to a network. You can refer to {@link Networks} for a list of\n * built-in passphrases, e.g., `Networks.TESTNET`.\n * @returns Resolves with balance entry details\n * when available.\n *\n * @throws If the supplied `address` is not a valid account or\n * contract strkey.\n *\n * @example\n * ```ts\n * const usdc = new Asset(\n * \"USDC\",\n * \"GBBD47IF6LWK7P7MDEVSCWR7DPUWV3NY3DTQEVFL4NAT4AQH3ZLLFLA5\"\n * );\n * const balance = await server.getAssetBalance(\"GD...\", usdc);\n * console.log(balance.balanceEntry?.amount);\n * ```\n */\n public async getAssetBalance(\n address: string | Address | Contract,\n asset: Asset,\n networkPassphrase?: string,\n ): Promise<Api.BalanceResponse> {\n let addr: string = address as string;\n // Coalesce to a strkey\n if (typeof address === \"string\") {\n addr = address;\n } else if (address instanceof Address) {\n addr = address.toString();\n } else if (address instanceof Contract) {\n addr = address.toString();\n } else {\n // shouldn't happen, but be defensive\n throw new TypeError(`invalid address: ${address}`);\n }\n\n if (StrKey.isValidEd25519PublicKey(addr)) {\n const [tl, ll] = await Promise.all([\n this.getTrustline(addr, asset),\n this.getLatestLedger(),\n ]);\n\n return {\n latestLedger: ll.sequence,\n balanceEntry: {\n amount: tl.balance().toString(),\n // Extract actual flags from the coalesced value.\n authorized: Boolean(tl.flags() & 0x1), // AUTHORIZED_FLAG\n clawback: Boolean(tl.flags() & 0x4), // TRUSTLINE_CLAWBACK_ENABLED_FLAG\n authorizedToMaintainLiabilities: Boolean(tl.flags() & 0x2), // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG\n revocable: Boolean(tl.flags() & 0x2), // AUTHORIZED_TO_MAINTAIN_LIABILITIES_FLAG (deprecated, will be removed in a future major release)\n },\n };\n } else if (StrKey.isValidContract(addr)) {\n return this.getSACBalance(addr, asset, networkPassphrase);\n }\n\n throw new Error(`invalid address: ${address}`);\n }\n\n /**\n * General node health check.\n *\n * @returns A promise which resolves to the\n * {@link Api.GetHealthResponse} object with the status of the\n * server (e.g. \"healthy\").\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getHealth | getLedgerEntries docs}\n *\n * @example\n * ```ts\n * server.getHealth().then((health) => {\n * console.log(\"status:\", health.status);\n * });\n * ```\n */\n\n public async getHealth(): Promise<Api.GetHealthResponse> {\n return jsonrpc.postObject<Api.GetHealthResponse>(\n this.httpClient,\n this.serverURL.toString(),\n \"getHealth\",\n );\n }\n\n /**\n * Reads the current value of contract data ledger entries directly.\n *\n * Allows you to directly inspect the current state of a contract. This is a\n * backup way to access your contract data which may not be available via\n * events or {@link rpc.Server.simulateTransaction}.\n *\n * @param contract - The contract ID containing the\n * data to load as a strkey (`C...` form), a {@link Contract}, or an\n * {@link Address} instance\n * @param key - The key of the contract data to load\n * @param durability - (optional) The \"durability\n * keyspace\" that this ledger key belongs to, which is either 'temporary'\n * or 'persistent' (the default), see {@link rpc.Durability}.\n * @returns The current data value\n *\n * **Warning:** If the data entry in question is a 'temporary' entry, it's\n * entirely possible that it has expired out of existence.\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n *\n * @example\n * ```ts\n * const contractId = \"CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5\";\n * const key = xdr.ScVal.scvSymbol(\"counter\");\n * server.getContractData(contractId, key, Durability.Temporary).then(data => {\n * console.log(\"value:\", data.val);\n * console.log(\"liveUntilLedgerSeq:\", data.liveUntilLedgerSeq);\n * console.log(\"lastModified:\", data.lastModifiedLedgerSeq);\n * console.log(\"latestLedger:\", data.latestLedger);\n * });\n * ```\n */\n\n public async getContractData(\n contract: string | Address | Contract,\n key: xdr.ScVal,\n durability: Durability = Durability.Persistent,\n ): Promise<Api.LedgerEntryResult> {\n // coalesce `contract` param variants to an ScAddress\n let scAddress: xdr.ScAddress;\n if (typeof contract === \"string\") {\n scAddress = new Contract(contract).address().toScAddress();\n } else if (contract instanceof Address) {\n scAddress = contract.toScAddress();\n } else if (contract instanceof Contract) {\n scAddress = contract.address().toScAddress();\n } else {\n throw new TypeError(`unknown contract type: ${contract}`);\n }\n\n let xdrDurability: xdr.ContractDataDurability;\n switch (durability) {\n case Durability.Temporary:\n xdrDurability = xdr.ContractDataDurability.temporary();\n break;\n\n case Durability.Persistent:\n xdrDurability = xdr.ContractDataDurability.persistent();\n break;\n\n default:\n throw new TypeError(`invalid durability: ${durability}`);\n }\n\n const contractKey = xdr.LedgerKey.contractData(\n new xdr.LedgerKeyContractData({\n key,\n contract: scAddress,\n durability: xdrDurability,\n }),\n );\n\n try {\n return await this.getLedgerEntry(contractKey);\n } catch {\n throw {\n code: 404,\n message: `Contract data not found for ${Address.fromScAddress(\n scAddress,\n ).toString()} with key ${key.toXDR(\"base64\")} and durability: ${durability}`,\n };\n }\n }\n\n /**\n * Retrieves the WASM bytecode for a given contract.\n *\n * This method allows you to fetch the WASM bytecode associated with a contract\n * deployed on the Soroban network. The WASM bytecode represents the executable\n * code of the contract.\n *\n * @param contractId - The contract ID containing the WASM bytecode to retrieve\n * @returns A Buffer containing the WASM bytecode\n * @throws If the contract or its associated WASM bytecode cannot be\n * found on the network.\n *\n * @example\n * ```ts\n * const contractId = \"CCJZ5DGASBWQXR5MPFCJXMBI333XE5U3FSJTNQU7RIKE3P5GN2K2WYD5\";\n * server.getContractWasmByContractId(contractId).then(wasmBuffer => {\n * console.log(\"WASM bytecode length:\", wasmBuffer.length);\n * // ... do something with the WASM bytecode ...\n * }).catch(err => {\n * console.error(\"Error fetching WASM bytecode:\", err);\n * });\n * ```\n */\n public async getContractWasmByContractId(\n contractId: string,\n ): Promise<Buffer> {\n const contractLedgerKey = new Contract(contractId).getFootprint();\n const response = await this.getLedgerEntries(contractLedgerKey);\n if (!response.entries.length || !response.entries[0]?.val) {\n return Promise.reject({\n code: 404,\n message: `Could not obtain contract hash from server`,\n });\n }\n\n const wasmHash = response.entries[0].val\n .contractData()\n .val()\n .instance()\n .executable()\n .wasmHash();\n\n return this.getContractWasmByHash(wasmHash);\n }\n\n /**\n * Retrieves the WASM bytecode for a given contract hash.\n *\n * This method allows you to fetch the WASM bytecode associated with a contract\n * deployed on the Soroban network using the contract's WASM hash. The WASM bytecode\n * represents the executable code of the contract.\n *\n * @param wasmHash - The WASM hash of the contract\n * @returns A Buffer containing the WASM bytecode\n * @throws If the contract or its associated WASM bytecode cannot be\n * found on the network.\n *\n * @example\n * ```ts\n * const wasmHash = Buffer.from(\"...\");\n * server.getContractWasmByHash(wasmHash).then(wasmBuffer => {\n * console.log(\"WASM bytecode length:\", wasmBuffer.length);\n * // ... do something with the WASM bytecode ...\n * }).catch(err => {\n * console.error(\"Error fetching WASM bytecode:\", err);\n * });\n * ```\n */\n public async getContractWasmByHash(\n wasmHash: Buffer | string,\n format: undefined | \"hex\" | \"base64\" = undefined,\n ): Promise<Buffer> {\n const wasmHashBuffer =\n typeof wasmHash === \"string\"\n ? Buffer.from(wasmHash, format)\n : (wasmHash as Buffer);\n\n const ledgerKeyWasmHash = xdr.LedgerKey.contractCode(\n new xdr.LedgerKeyContractCode({\n hash: wasmHashBuffer,\n }),\n );\n\n const responseWasm = await this.getLedgerEntries(ledgerKeyWasmHash);\n if (!responseWasm.entries.length || !responseWasm.entries[0]?.val) {\n return Promise.reject({\n code: 404,\n message: \"Could not obtain contract wasm from server\",\n });\n }\n const wasmBuffer = responseWasm.entries[0].val.contractCode().code();\n\n return wasmBuffer;\n }\n\n /**\n * Reads the current value of arbitrary ledger entries directly.\n *\n * Allows you to directly inspect the current state of contracts, contract's\n * code, accounts, or any other ledger entries.\n *\n * To fetch a contract's WASM byte-code, built the appropriate\n * {@link xdr.LedgerKeyContractCode} ledger entry key (or see\n * {@link Contract.getFootprint}).\n *\n * @param keys - One or more ledger entry keys to load\n * @returns The current on-chain\n * values for the given ledger keys\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgerEntries | getLedgerEntries docs}\n * @see RpcServer._getLedgerEntries\n * @example\n * ```ts\n * const contractId = \"CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD2KM\";\n * const key = xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({\n * contractId: StrKey.decodeContract(contractId),\n * key: xdr.ScVal.scvSymbol(\"counter\"),\n * }));\n *\n * server.getLedgerEntries([key]).then(response => {\n * const ledgerData = response.entries[0];\n * console.log(\"key:\", ledgerData.key);\n * console.log(\"value:\", ledgerData.val);\n * console.log(\"liveUntilLedgerSeq:\", ledgerData.liveUntilLedgerSeq);\n * console.log(\"lastModified:\", ledgerData.lastModifiedLedgerSeq);\n * console.log(\"latestLedger:\", response.latestLedger);\n * });\n * ```\n */\n public getLedgerEntries(...keys: xdr.LedgerKey[]) {\n return this._getLedgerEntries(...keys).then(parseRawLedgerEntries);\n }\n\n public _getLedgerEntries(...keys: xdr.LedgerKey[]) {\n return jsonrpc.postObject<Api.RawGetLedgerEntriesResponse>(\n this.httpClient,\n this.serverURL.toString(),\n \"getLedgerEntries\",\n {\n keys: keys.map((k) => k.toXDR(\"base64\")),\n },\n );\n }\n\n public async getLedgerEntry(key: xdr.LedgerKey) {\n const results = await this._getLedgerEntries(key).then(\n parseRawLedgerEntries,\n );\n if (results.entries.length !== 1) {\n throw new Error(`failed to find an entry for key ${key.toXDR(\"base64\")}`);\n }\n return results.entries[0];\n }\n\n /**\n * Poll for a particular transaction with certain parameters.\n *\n * After submitting a transaction, clients can use this to poll for\n * transaction completion and return a definitive state of success or failure.\n *\n * @param hash - the transaction you're polling for\n * @param opts - (optional) polling options\n * - `attempts` (optional): (optional) the number of attempts to make\n * before returning the last-seen status. By default or on invalid inputs,\n * try 5 times.\n * - `sleepStrategy` (optional): (optional) the amount of time\n * to wait for between each attempt. By default, sleep for 1 second between\n * each attempt.\n *\n * @returns the response after a \"found\"\n * response (which may be success or failure) or the last response obtained\n * after polling the maximum number of specified attempts.\n *\n * @example\n * ```ts\n * const h = \"c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a\";\n * const txStatus = await server.pollTransaction(h, {\n * attempts: 100, // I'm a maniac\n * sleepStrategy: rpc.LinearSleepStrategy\n * }); // this will take 5,050 seconds to complete\n * ```\n */\n public async pollTransaction(\n hash: string,\n opts?: RpcServer.PollingOptions,\n ): Promise<Api.GetTransactionResponse> {\n const maxAttempts: number =\n (opts?.attempts ?? 0) < 1\n ? DEFAULT_GET_TRANSACTION_TIMEOUT\n : (opts?.attempts ?? DEFAULT_GET_TRANSACTION_TIMEOUT); // \"positive and defined user value or default\"\n\n let foundInfo: Api.GetTransactionResponse;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n foundInfo = await this.getTransaction(hash);\n if (foundInfo.status !== Api.GetTransactionStatus.NOT_FOUND) {\n return foundInfo;\n }\n\n await Utils.sleep((opts?.sleepStrategy ?? BasicSleepStrategy)(attempt));\n }\n\n return foundInfo!;\n }\n\n /**\n * Fetch the details of a submitted transaction.\n *\n * After submitting a transaction, clients should poll this to tell when the\n * transaction has completed.\n *\n * @param hash - Hex-encoded hash of the transaction to check\n * @returns The status, result, and\n * other details about the transaction\n *\n * @see\n * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransaction | getTransaction docs}\n *\n * @example\n * ```ts\n * const transactionHash = \"c4515e3bdc0897f21cc5dbec8c82cf0a936d4741cb74a8e158eb51b9fb00411a\";\n * server.getTransaction(transactionHash).then((tx) => {\n * console.log(\"status:\", tx.status);\n * console.log(\"envelopeXdr:\", tx.envelopeXdr);\n * console.log(\"resultMetaXdr:\", tx.resultMetaXdr);\n * console.log(\"resultXdr:\", tx.resultXdr);\n * });\n * ```\n */\n\n public async getTransaction(\n hash: string,\n ): Promise<Api.GetTransactionResponse> {\n return this._getTransaction(hash).then((raw) => {\n const foundInfo: Omit<\n Api.GetSuccessfulTransactionResponse,\n keyof Api.GetMissingTransactionResponse\n > = {} as any;\n\n if (raw.status !== Api.GetTransactionStatus.NOT_FOUND) {\n Object.assign(foundInfo, parseTransactionInfo(raw));\n }\n\n const result: Api.GetTransactionResponse = {\n status: raw.status,\n txHash: hash,\n latestLedger: raw.latestLedger,\n latestLedgerCloseTime: raw.latestLedgerCloseTime,\n oldestLedger: raw.oldestLedger,\n oldestLedgerCloseTime: raw.oldestLedgerCloseTime,\n ...foundInfo,\n };\n\n return result;\n });\n }\n\n public async _getTransaction(\n hash: string,\n ): Promise<Api.RawGetTransactionResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getTransaction\",\n {\n hash,\n },\n );\n }\n\n /**\n * Fetch transactions starting from a given start ledger or a cursor. The end ledger is the latest ledger\n * in that RPC instance.\n *\n * @param request - The request parameters.\n * @returns - A promise that resolves to the transactions response.\n *\n * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getTransactions\n * @example\n * ```ts\n * server.getTransactions({\n * startLedger: 10000,\n * limit: 10,\n * }).then((response) => {\n * console.log(\"Transactions:\", response.transactions);\n * console.log(\"Latest Ledger:\", response.latestLedger);\n * console.log(\"Cursor:\", response.cursor);\n * });\n * ```\n */\n public async getTransactions(\n request: Api.GetTransactionsRequest,\n ): Promise<Api.GetTransactionsResponse> {\n return this._getTransactions(request).then(\n (raw: Api.RawGetTransactionsResponse) => {\n const result: Api.GetTransactionsResponse = {\n transactions: (raw.transactions || []).map(parseRawTransactions),\n latestLedger: raw.latestLedger,\n latestLedgerCloseTimestamp: raw.latestLedgerCloseTimestamp,\n oldestLedger: raw.oldestLedger,\n oldestLedgerCloseTimestamp: raw.oldestLedgerCloseTimestamp,\n cursor: raw.cursor,\n };\n return result;\n },\n );\n }\n\n async _getTransactions(\n request: Api.GetTransactionsRequest,\n ): Promise<Api.RawGetTransactionsResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getTransactions\",\n request,\n );\n }\n\n /**\n * Fetch all events that match a given set of filters.\n *\n * The given filters (see {@link Api.EventFilter}\n * for detailed fields) are combined only in a logical OR fashion, and all of\n * the fields in each filter are optional.\n *\n * To page through events, use the `pagingToken` field on the relevant\n * {@link Api.EventResponse} object to set the `cursor` parameter.\n *\n * @param request - Event filters {@link Api.GetEventsRequest},\n * @returns A paginatable set of the events\n * matching the given event filters\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getEvents | getEvents docs}\n *\n * @example\n * ```ts\n *\n * server.getEvents({\n * startLedger: 1000,\n * endLedger: 2000,\n * filters: [\n * {\n * type: \"contract\",\n * contractIds: [ \"deadb33f...\" ],\n * topics: [[ \"AAAABQAAAAh0cmFuc2Zlcg==\", \"AAAAAQB6Mcc=\", \"*\" ]]\n * }, {\n * type: \"system\",\n * contractIds: [ \"...c4f3b4b3...\" ],\n * topics: [[ \"*\" ], [ \"*\", \"AAAAAQB6Mcc=\" ]]\n * }, {\n * contractIds: [ \"...c4f3b4b3...\" ],\n * topics: [[ \"AAAABQAAAAh0cmFuc2Zlcg==\" ]]\n * }, {\n * type: \"diagnostic\",\n * topics: [[ \"AAAAAQB6Mcc=\" ]]\n * }\n * ],\n * limit: 10,\n * });\n * ```\n */\n\n public async getEvents(\n request: Api.GetEventsRequest,\n ): Promise<Api.GetEventsResponse> {\n return this._getEvents(request).then(parseRawEvents);\n }\n\n public async _getEvents(\n request: Api.GetEventsRequest,\n ): Promise<Api.RawGetEventsResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getEvents\",\n {\n filters: request.filters ?? [],\n pagination: {\n ...(request.cursor && { cursor: request.cursor }), // add if defined\n ...(request.limit && { limit: request.limit }),\n },\n ...(request.startLedger && {\n startLedger: request.startLedger,\n }),\n ...(request.endLedger && {\n endLedger: request.endLedger,\n }),\n },\n );\n }\n\n /**\n * Fetch metadata about the network this Soroban RPC server is connected to.\n *\n * @returns Metadata about the current\n * network this RPC server is connected to\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getNetwork | getNetwork docs}\n *\n * @example\n * ```ts\n * server.getNetwork().then((network) => {\n * console.log(\"friendbotUrl:\", network.friendbotUrl);\n * console.log(\"passphrase:\", network.passphrase);\n * console.log(\"protocolVersion:\", network.protocolVersion);\n * });\n * ```\n */\n\n public async getNetwork(): Promise<Api.GetNetworkResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getNetwork\",\n );\n }\n\n /**\n * Fetch the latest ledger meta info from network which this Soroban RPC\n * server is connected to.\n *\n * @returns metadata about the\n * latest ledger on the network that this RPC server is connected to\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLatestLedger | getLatestLedger docs}\n *\n * @example\n * ```ts\n * server.getLatestLedger().then((response) => {\n * console.log(\"hash:\", response.id);\n * console.log(\"sequence:\", response.sequence);\n * console.log(\"protocolVersion:\", response.protocolVersion);\n * });\n * ```\n */\n public async getLatestLedger(): Promise<Api.GetLatestLedgerResponse> {\n return this._getLatestLedger().then(parseRawLatestLedger);\n }\n\n public async _getLatestLedger(): Promise<Api.RawGetLatestLedgerResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getLatestLedger\",\n );\n }\n\n /**\n * Submit a trial contract invocation to get back return values, expected\n * ledger footprint, expected authorizations, and expected costs.\n *\n * @param tx - the transaction to simulate,\n * which should include exactly one operation (one of\n * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTtlOp}, or\n * {@link xdr.RestoreFootprintOp}). Any provided footprint or auth\n * information will be ignored.\n * @param addlResources - (optional) any additional resources\n * to add to the simulation-provided ones, for example if you know you will\n * need extra CPU instructions\n * @param authMode - (optional) optionally, specify the type of\n * auth mode to use for simulation: `enforce` for enforcement mode,\n * `record` for recording mode, or `record_allow_nonroot` for recording\n * mode that allows non-root authorization\n *\n * @returns An object with the\n * cost, footprint, result/auth requirements (if applicable), and error of\n * the transaction\n *\n * @see\n * {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs}\n * @see\n * {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs}\n * @see\n * {@link https://developers.stellar.org/docs/learn/fundamentals/contract-development/contract-interactions/transaction-simulation#authorization | authorization modes}\n * @see module:rpc.Server#prepareTransaction\n * @see module:rpc.assembleTransaction\n *\n * @example\n * ```ts\n * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE';\n * const contract = new StellarSdk.Contract(contractId);\n *\n * // Right now, this is just the default fee for this example.\n * const fee = StellarSdk.BASE_FEE;\n * const transaction = new StellarSdk.TransactionBuilder(account, { fee })\n * // Uncomment the following line to build transactions for the live network. Be\n * // sure to also change the horizon hostname.\n * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC)\n * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET)\n * .setTimeout(30) // valid for the next 30s\n * // Add an operation to call increment() on the contract\n * .addOperation(contract.call(\"increment\"))\n * .build();\n *\n * server.simulateTransaction(transaction).then((sim) => {\n * console.log(\"cost:\", sim.cost);\n * console.log(\"result:\", sim.result);\n * console.log(\"error:\", sim.error);\n * console.log(\"latestLedger:\", sim.latestLedger);\n * });\n * ```\n */\n\n public async simulateTransaction(\n tx: Transaction | FeeBumpTransaction,\n addlResources?: RpcServer.ResourceLeeway,\n authMode?: Api.SimulationAuthMode,\n ): Promise<Api.SimulateTransactionResponse> {\n return this._simulateTransaction(tx, addlResources, authMode).then(\n parseRawSimulation,\n );\n }\n\n public async _simulateTransaction(\n transaction: Transaction | FeeBumpTransaction,\n addlResources?: RpcServer.ResourceLeeway,\n authMode?: Api.SimulationAuthMode,\n ): Promise<Api.RawSimulateTransactionResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"simulateTransaction\",\n {\n transaction: transaction.toXDR(),\n authMode,\n ...(addlResources !== undefined && {\n resourceConfig: {\n instructionLeeway: addlResources.cpuInstructions,\n },\n }),\n },\n );\n }\n\n /**\n * Submit a trial contract invocation, first run a simulation of the contract\n * invocation as defined on the incoming transaction, and apply the results to\n * a new copy of the transaction which is then returned. Setting the ledger\n * footprint and authorization, so the resulting transaction is ready for\n * signing & sending.\n *\n * The returned transaction will also have an updated fee that is the sum of\n * fee set on incoming transaction with the contract resource fees estimated\n * from simulation. It is advisable to check the fee on returned transaction\n * and validate or take appropriate measures for interaction with user to\n * confirm it is acceptable.\n *\n * You can call the {@link rpc.Server.simulateTransaction} method\n * directly first if you want to inspect estimated fees for a given\n * transaction in detail first, then re-assemble it manually or via\n * {@link rpc.assembleTransaction}.\n *\n * @param tx - the transaction to\n * prepare. It should include exactly one operation, which must be one of\n * {@link xdr.InvokeHostFunctionOp}, {@link xdr.ExtendFootprintTtlOp},\n * or {@link xdr.RestoreFootprintOp}.\n *\n * Any provided footprint will be overwritten. However, if your operation\n * has existing auth entries, they will be preferred over ALL auth entries\n * from the simulation. In other words, if you include auth entries, you\n * don't care about the auth returned from the simulation. Other fields\n * (footprint, etc.) will be filled as normal.\n * @returns A copy of the\n * transaction with the expected authorizations (in the case of\n * invocation), resources, and ledger footprints added. The transaction fee\n * will also automatically be padded with the contract's minimum resource\n * fees discovered from the simulation.\n * @throws * If simulation fails\n *\n * @see module:rpc.assembleTransaction\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/simulateTransaction | simulateTransaction docs}\n *\n * @example\n * ```ts\n * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE';\n * const contract = new StellarSdk.Contract(contractId);\n *\n * // Right now, this is just the default fee for this example.\n * const fee = StellarSdk.BASE_FEE;\n * const transaction = new StellarSdk.TransactionBuilder(account, { fee })\n * // Uncomment the following line to build transactions for the live network. Be\n * // sure to also change the horizon hostname.\n * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC)\n * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET)\n * .setTimeout(30) // valid for the next 30s\n * // Add an operation to call increment() on the contract\n * .addOperation(contract.call(\"increment\"))\n * .build();\n *\n * const preparedTransaction = await server.prepareTransaction(transaction);\n *\n * // Sign this transaction with the secret key\n * // NOTE: signing is transaction is network specific. Test network transactions\n * // won't work in the public network. To switch networks, use the Network object\n * // as explained above (look for StellarSdk.Network).\n * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey);\n * preparedTransaction.sign(sourceKeypair);\n *\n * server.sendTransaction(transaction).then(result => {\n * console.log(\"hash:\", result.hash);\n * console.log(\"status:\", result.status);\n * console.log(\"errorResultXdr:\", result.errorResultXdr);\n * });\n * ```\n */\n public async prepareTransaction(tx: Transaction | FeeBumpTransaction) {\n const simResponse = await this.simulateTransaction(tx);\n if (Api.isSimulationError(simResponse)) {\n throw new Error(simResponse.error);\n }\n\n return assembleTransaction(tx, simResponse).build();\n }\n\n /**\n * Submit a real transaction to the Stellar network.\n *\n * Unlike Horizon, RPC does not wait for transaction completion. It\n * simply validates the transaction and enqueues it. Clients should call\n * {@link rpc.Server.getTransaction} to learn about transaction\n * success/failure.\n *\n * @param transaction - to submit\n * @returns the\n * transaction id, status, and any error if available\n *\n * @see {@link https://developers.stellar.org/docs/learn/fundamentals/stellar-data-structures/operations-and-transactions | transaction docs}\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/sendTransaction | sendTransaction docs}\n *\n * @example\n * ```ts\n * const contractId = 'CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE';\n * const contract = new StellarSdk.Contract(contractId);\n *\n * // Right now, this is just the default fee for this example.\n * const fee = StellarSdk.BASE_FEE;\n * const transaction = new StellarSdk.TransactionBuilder(account, { fee })\n * // Uncomment the following line to build transactions for the live network. Be\n * // sure to also change the horizon hostname.\n * //.setNetworkPassphrase(StellarSdk.Networks.PUBLIC)\n * .setNetworkPassphrase(StellarSdk.Networks.FUTURENET)\n * .setTimeout(30) // valid for the next 30s\n * // Add an operation to call increment() on the contract\n * .addOperation(contract.call(\"increment\"))\n * .build();\n *\n * // Sign this transaction with the secret key\n * // NOTE: signing is transaction is network specific. Test network transactions\n * // won't work in the public network. To switch networks, use the Network object\n * // as explained above (look for StellarSdk.Network).\n * const sourceKeypair = StellarSdk.Keypair.fromSecret(sourceSecretKey);\n * transaction.sign(sourceKeypair);\n *\n * server.sendTransaction(transaction).then((result) => {\n * console.log(\"hash:\", result.hash);\n * console.log(\"status:\", result.status);\n * console.log(\"errorResultXdr:\", result.errorResultXdr);\n * });\n * ```\n */\n public async sendTransaction(\n transaction: Transaction | FeeBumpTransaction,\n ): Promise<Api.SendTransactionResponse> {\n return this._sendTransaction(transaction).then(parseRawSendTransaction);\n }\n\n public async _sendTransaction(\n transaction: Transaction | FeeBumpTransaction,\n ): Promise<Api.RawSendTransactionResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"sendTransaction\",\n {\n transaction: transaction.toXDR(),\n },\n );\n }\n\n /**\n * Fund a new account using the network's Friendbot faucet, if any.\n *\n * @param address - The address or account instance that we\n * want to create and fund with Friendbot\n * @param friendbotUrl - (optional) Optionally, an explicit address for\n * friendbot (by default: this calls the Soroban RPC\n * {@link rpc.Server.getNetwork | getNetwork} method to try to\n * discover this network's Friendbot url).\n * @returns An {@link Account} object for the created\n * account, or the existing account if it's already funded with the\n * populated sequence number (note that the account will not be \"topped\n * off\" if it already exists)\n * @throws If Friendbot is not configured on this network or request failure\n *\n * @see {@link https://developers.stellar.org/docs/learn/fundamentals/networks#friendbot | Friendbot docs}\n * @see {@link Friendbot.Api.Response}\n *\n * @deprecated Use {@link Server.fundAddress} instead, which supports both\n * account (G...) and contract (C...) addresses.\n *\n * @example\n * ```ts\n * server\n * .requestAirdrop(\"GBZC6Y2Y7Q3ZQ2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4QZJ2XZ3Z5YXZ6Z7Z2Y4\")\n * .then((accountCreated) => {\n * console.log(\"accountCreated:\", accountCreated);\n * }).catch((error) => {\n * console.error(\"error:\", error);\n * });\n * ```\n */\n public async requestAirdrop(\n address: string | Pick<Account, \"accountId\">,\n friendbotUrl?: string,\n ): Promise<Account> {\n const account = typeof address === \"string\" ? address : address.accountId();\n friendbotUrl = friendbotUrl || (await this.getNetwork()).friendbotUrl;\n if (!friendbotUrl) {\n throw new Error(\"No friendbot URL configured for current network\");\n }\n\n try {\n const response = await this.httpClient.post<FriendbotApi.Response>(\n `${friendbotUrl}?addr=${encodeURIComponent(account)}`,\n );\n\n let meta: xdr.TransactionMeta;\n if (!response.data.result_meta_xdr) {\n const txMeta = await this.getTransaction(response.data.hash);\n if (txMeta.status !== Api.GetTransactionStatus.SUCCESS) {\n throw new Error(`Funding account ${address} failed`);\n }\n meta = txMeta.resultMetaXdr;\n } else {\n meta = xdr.TransactionMeta.fromXDR(\n response.data.result_meta_xdr,\n \"base64\",\n );\n }\n\n const sequence = findCreatedAccountSequenceInTransactionMeta(meta);\n return new Account(account, sequence);\n } catch (error: any) {\n if (error.response?.status === 400) {\n if (\n error.response.data?.detail?.includes(\"createAccountAlreadyExist\")\n ) {\n // Account already exists, load the sequence number\n return this.getAccount(account);\n }\n }\n throw error;\n }\n }\n\n /**\n * Fund an address using the network's Friendbot faucet, if any.\n *\n * This method supports both account (G...) and contract (C...) addresses.\n *\n * @param address - The address to fund. Can be either a Stellar\n * account (G...) or contract (C...) address.\n * @param friendbotUrl - (optional) Optionally, an explicit Friendbot URL\n * (by default: this calls the Stellar RPC\n * {@link rpc.Server.getNetwork | getNetwork} method to try to\n * discover this network's Friendbot url).\n * @returns The transaction\n * response from the Friendbot funding transaction.\n * @throws If Friendbot is not configured on this network or the\n * funding transaction fails.\n *\n * @see {@link https://developers.stellar.org/docs/learn/fundamentals/networks#friendbot | Friendbot docs}\n *\n * @example\n * ```ts\n * // Funding an account (G... address)\n * const tx = await server.fundAddress(\"GBZC6Y2Y7...\");\n * console.log(\"Funded! Hash:\", tx.txHash);\n * // If you need the Account object:\n * const account = await server.getAccount(\"GBZC6Y2Y7...\");\n * ```\n *\n * @example\n * ```ts\n * // Funding a contract (C... address)\n * const tx = await server.fundAddress(\"CBZC6Y2Y7...\");\n * console.log(\"Contract funded! Hash:\", tx.txHash);\n * ```\n */\n public async fundAddress(\n address: string,\n friendbotUrl?: string,\n ): Promise<Api.GetSuccessfulTransactionResponse> {\n if (\n !StrKey.isValidEd25519PublicKey(address) &&\n !StrKey.isValidContract(address)\n ) {\n throw new Error(\n `Invalid address: ${address}. Expected a Stellar account (G...) or contract (C...) address.`,\n );\n }\n\n friendbotUrl = friendbotUrl || (await this.getNetwork()).friendbotUrl;\n if (!friendbotUrl) {\n throw new Error(\"No friendbot URL configured for current network\");\n }\n\n try {\n const response = await this.httpClient.post<FriendbotApi.Response>(\n `${friendbotUrl}?addr=${encodeURIComponent(address)}`,\n );\n\n const txResponse = await this.getTransaction(response.data.hash);\n if (txResponse.status !== Api.GetTransactionStatus.SUCCESS) {\n throw new Error(\n `Funding address ${address} failed: transaction status ${txResponse.status}`,\n );\n }\n\n return txResponse;\n } catch (error: any) {\n if (error.response?.status === 400) {\n throw new Error(error.response.data?.detail ?? \"Bad Request\");\n }\n throw error;\n }\n }\n\n /**\n * Provides an analysis of the recent fee stats for regular and smart\n * contract operations.\n *\n * @returns the fee stats\n * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getFeeStats\n */\n public async getFeeStats(): Promise<Api.GetFeeStatsResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getFeeStats\",\n );\n }\n\n /**\n * Provides information about the current version details of the Soroban RPC and captive-core\n *\n * @returns the version info\n * @see https://developers.stellar.org/docs/data/rpc/api-reference/methods/getVersionInfo\n */\n public async getVersionInfo(): Promise<Api.GetVersionInfoResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getVersionInfo\",\n );\n }\n\n /**\n * Returns a contract's balance of a particular SAC asset, if any.\n *\n * This is a convenience wrapper around {@link Server.getLedgerEntries}.\n *\n * @param address - the contract (string `C...`) whose balance of\n * `sac` you want to know\n * @param sac - the built-in SAC token (e.g. `USDC:GABC...`) that\n * you are querying from the given `contract`.\n * @param networkPassphrase - (optional) optionally, the network passphrase to\n * which this token applies. If omitted, a request about network\n * information will be made (see {@link getNetwork}), since contract IDs\n * for assets are specific to a network. You can refer to {@link Networks}\n * for a list of built-in passphrases, e.g., `Networks.TESTNET`.\n *\n * @returns , which will contain the balance\n * entry details if and only if the request returned a valid balance ledger\n * entry. If it doesn't, the `balanceEntry` field will not exist.\n *\n * @throws If `address` is not a valid contract ID (C...).\n *\n * @see getLedgerEntries\n * @see https://developers.stellar.org/docs/tokens/stellar-asset-contract\n *\n * @deprecated Use {@link getAssetBalance}, instead\n * @example\n * ```ts\n * // assume `address` is some contract or account with an XLM balance\n * // assume server is an instantiated `Server` instance.\n * const entry = (await server.getSACBalance(\n * new Address(address),\n * Asset.native(),\n * Networks.PUBLIC\n * ));\n *\n * // assumes BigInt support:\n * console.log(\n * entry.balanceEntry ?\n * BigInt(entry.balanceEntry.amount) :\n * \"Address has no XLM\");\n * ```\n */\n public async getSACBalance(\n address: string | Address,\n sac: Asset,\n networkPassphrase?: string,\n ): Promise<Api.BalanceResponse> {\n const addressString =\n address instanceof Address ? address.toString() : address;\n\n if (!StrKey.isValidContract(addressString)) {\n throw new TypeError(`expected contract ID, got ${addressString}`);\n }\n\n // Call out to RPC if passphrase isn't provided.\n const passphrase: string =\n networkPassphrase ?? (await this.getNetwork().then((n) => n.passphrase));\n\n // Turn SAC into predictable contract ID\n const sacId = sac.contractId(passphrase);\n\n // Rust union enum type with \"Balance(ScAddress)\" structure\n const key = nativeToScVal([\"Balance\", addressString], {\n type: [\"symbol\", \"address\"],\n });\n\n // Note a quirk here: the contract address in the key is the *token*\n // rather than the *holding contract*. This is because each token stores a\n // balance entry for each contract, not the other way around (i.e. XLM\n // holds a reserve for contract X, rather that contract X having a balance\n // of N XLM).\n const ledgerKey = xdr.LedgerKey.contractData(\n new xdr.LedgerKeyContractData({\n contract: new Address(sacId).toScAddress(),\n durability: xdr.ContractDataDurability.persistent(),\n key,\n }),\n );\n\n const response = await this.getLedgerEntries(ledgerKey);\n if (response.entries.length === 0) {\n return { latestLedger: response.latestLedger };\n }\n\n const { lastModifiedLedgerSeq, liveUntilLedgerSeq, val } =\n response.entries[0];\n\n if (val.switch().value !== xdr.LedgerEntryType.contractData().value) {\n return { latestLedger: response.latestLedger };\n }\n\n const entry = scValToNative(val.contractData().val());\n\n // Since we are requesting a SAC's contract data, we know for a fact that\n // it should follow the expected structure format. Thus, we can presume\n // these fields exist:\n return {\n latestLedger: response.latestLedger,\n balanceEntry: {\n liveUntilLedgerSeq,\n lastModifiedLedgerSeq,\n amount: entry.amount.toString(),\n authorized: entry.authorized,\n clawback: entry.clawback,\n },\n };\n }\n\n /**\n * Fetch a detailed list of ledgers starting from a specified point.\n *\n * Returns ledger data with support for pagination as long as the requested\n * pages fall within the history retention of the RPC provider.\n *\n * @param request - The request parameters for fetching ledgers. {@link Api.GetLedgersRequest}\n * @returns A promise that resolves to the\n * ledgers response containing an array of ledger data and pagination info. {@link Api.GetLedgersResponse}\n *\n * @throws If startLedger is less than the oldest ledger stored in this\n * node, or greater than the latest ledger seen by this node.\n *\n * @see {@link https://developers.stellar.org/docs/data/rpc/api-reference/methods/getLedgers | getLedgers docs}\n *\n * @example\n * ```ts\n * // Fetch ledgers starting from a specific sequence number\n * server.getLedgers({\n * startLedger: 36233,\n * pagination: {\n * limit: 10\n * }\n * }).then((response) => {\n * console.log(\"Ledgers:\", response.ledgers);\n * console.log(\"Latest Ledger:\", response.latestLedger);\n * console.log(\"Cursor:\", response.cursor);\n * });\n * ```\n *\n * @example\n * ```ts\n * // Paginate through ledgers using cursor\n * const firstPage = await server.getLedgers({\n * startLedger: 36233,\n * pagination: {\n * limit: 5\n * }\n * });\n *\n * const nextPage = await server.getLedgers({\n * pagination: {\n * cursor: firstPage.cursor,\n * limit: 5\n * }\n * });\n * ```\n */\n\n public async getLedgers(\n request: Api.GetLedgersRequest,\n ): Promise<Api.GetLedgersResponse> {\n return this._getLedgers(request).then((raw) => {\n const result: Api.GetLedgersResponse = {\n ledgers: (raw.ledgers || []).map(parseRawLedger),\n latestLedger: raw.latestLedger,\n latestLedgerCloseTime: raw.latestLedgerCloseTime,\n oldestLedger: raw.oldestLedger,\n oldestLedgerCloseTime: raw.oldestLedgerCloseTime,\n cursor: raw.cursor,\n };\n return result;\n });\n }\n\n public async _getLedgers(\n request: Api.GetLedgersRequest,\n ): Promise<Api.RawGetLedgersResponse> {\n return jsonrpc.postObject(\n this.httpClient,\n this.serverURL.toString(),\n \"getLedgers\",\n request,\n );\n }\n}\n"],"names":["Durability","xdr","createHttpClient","Account","Keypair","StrKey","buffer","Buffer","address","Address","Contract","jsonrpc.postObject","contract","parseRawLedgerEntries","Api","Utils","parseTransactionInfo","parseRawTransactions","parseRawEvents","parseRawLatestLedger","parseR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AM;AAAA;AAClB,KACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmDA,MAAa,WACX,OAAA,EACiC;AACjC,IAAA,OAAO,KAAK,WAAA,CAAY,OAAO,CAAA,CAAE,IAAA,CAAK,CAAC,GAAA,KAAQ;AAC7C,MAAA,MAAM,MAAA,GAAiC;AAAA,QACrC,UAAU,GAAA,CAAI,OAAA,IAAW,EAAC,EAAG,IAAIC,sBAAc,CAAA;AAAA,QAC/C,cAAc,GAAA,CAAI,YAAA;AAAA,QAClB,uBAAuB,GAAA,CAAI,qBAAA;AAAA,QAC3B,cAAc,GAAA,CAAI,YAAA;AAAA,QAClB,uBAAuB,GAAA,CAAI,qBAAA;AAAA,QAC3B,QAAQ,GAAA,CAAI;AAAA,OACd;AACA,MAAA,OAAO,MAAA;AAAA,IACT,CAAC,CAAA;AAAA,EACH;AAAA,EAEA,MAAa,YACX,OAAA,EACoC;AACpC,IAAA,OAAOf,kBAAQ;AAAA,MACb,IAAA,CAAK,UAAA;AAAA,MACL,IAAA,CAAK,UAAU,QAAA,EAAS;AAAA,MACxB,YAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AACF;;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"challenge_transaction.js","sources":["../../../../src/webauth/challenge_transaction.ts"],"sourcesContent":["import {\n Keypair,\n Account,\n TransactionBuilder,\n BASE_FEE,\n Operation,\n Memo,\n MemoNone,\n MemoID,\n FeeBumpTransaction,\n TimeoutInfinite,\n Transaction,\n Networks,\n} from \"../base/index.js\";\nimport { InvalidChallengeError } from \"./errors.js\";\nimport { gatherTxSigners, verifyTxSignedBy } from \"./utils.js\";\nimport { Utils } from \"../utils.js\";\nimport { ServerApi } from \"../horizon/server_api.js\";\nimport { uint8ArrayToBase64 } from \"uint8array-extras\";\n\n/**\n * Returns a valid {@link https://stellar.org/protocol/sep-10 | SEP-10}\n * challenge transaction which you can use for Stellar Web Authentication.\n * @param serverKeypair - Keypair for server's signing account.\n * @param clientAccountID - The stellar account (G...) or muxed account\n * (M...) that the wallet wishes to authenticate with the server.\n * @param homeDomain - The fully qualified domain name of the service\n * requiring authentication\n * @param timeout - Challenge duration (default to 5 minutes).\n * @param networkPassphrase - The network passphrase. If you pass this\n * argument then timeout is required.\n * @param webAuthDomain - The fully qualified domain name of the service\n * issuing the challenge.\n * @param memo - The memo to attach to the challenge transaction. The\n * memo must be of type `id`. If the `clientaccountID` is a muxed account,\n * memos cannot be used.\n * @param clientDomain - The fully qualified domain of the client\n * requesting the challenge. Only necessary when the 'client_domain'\n * parameter is passed.\n * @param clientSigningKey - The public key assigned to the SIGNING_KEY\n * attribute specified on the stellar.toml hosted on the client domain. Only\n * necessary when the 'client_domain' parameter is passed.\n * @returns A base64 encoded string of the raw TransactionEnvelope xdr\n * struct for the transaction.\n * @throws Will throw if `clientAccountID` is a muxed account, and `memo`\n * is present.\n * @throws Will throw if `clientDomain` is provided, but\n * `clientSigningKey` is missing\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Keypair, Networks, WebAuth } from 'stellar-sdk'\n *\n * let serverKeyPair = Keypair.fromSecret(\"server-secret\")\n * let challenge = WebAuth.buildChallengeTx(\n * serverKeyPair,\n * \"client-stellar-account-id\",\n * \"stellar.org\",\n * 300,\n * Networks.TESTNET);\n * ```\n */\nexport function buildChallengeTx(\n serverKeypair: Keypair,\n clientAccountID: string,\n homeDomain: string,\n // eslint-disable-next-line @typescript-eslint/default-param-last\n timeout: number = 300,\n networkPassphrase: string,\n webAuthDomain: string,\n memo: string | null = null,\n clientDomain: string | null = null,\n clientSigningKey: string | null = null,\n): string {\n if (clientAccountID.startsWith(\"M\") && memo) {\n throw Error(\"memo cannot be used if clientAccountID is a muxed account\");\n }\n\n const account = new Account(serverKeypair.publicKey(), \"-1\");\n const now = Math.floor(Date.now() / 1000);\n\n // A Base64 digit represents 6 bits, to generate a random 64 bytes\n // base64 string, we need 48 random bytes = (64 * 6)/8\n //\n // Each Base64 digit is in ASCII and each ASCII characters when\n // turned into binary represents 8 bits = 1 bytes.\n const value = uint8ArrayToBase64(crypto.getRandomValues(new Uint8Array(48)));\n\n const builder = new TransactionBuilder(account, {\n fee: BASE_FEE,\n networkPassphrase,\n timebounds: {\n minTime: now,\n maxTime: now + timeout,\n },\n })\n .addOperation(\n Operation.manageData({\n name: `${homeDomain} auth`,\n value,\n source: clientAccountID,\n }),\n )\n .addOperation(\n Operation.manageData({\n name: \"web_auth_domain\",\n value: webAuthDomain,\n source: account.accountId(),\n }),\n );\n\n if (clientDomain) {\n if (!clientSigningKey) {\n throw Error(\"clientSigningKey is required if clientDomain is provided\");\n }\n builder.addOperation(\n Operation.manageData({\n name: `client_domain`,\n value: clientDomain,\n source: clientSigningKey,\n }),\n );\n }\n\n if (memo) {\n builder.addMemo(Memo.id(memo));\n }\n\n const transaction = builder.build();\n transaction.sign(serverKeypair);\n\n return transaction.toEnvelope().toXDR(\"base64\").toString();\n}\n\n/**\n * Reads a SEP-10 challenge transaction and returns the decoded transaction and\n * client account ID contained within.\n *\n * It also verifies that the transaction has been signed by the server.\n *\n * It does not verify that the transaction has been signed by the client or that\n * any signatures other than the server's on the transaction are valid. Use one\n * of the following functions to completely verify the transaction:\n *\n * - {@link WebAuth.verifyChallengeTxThreshold}\n * - {@link WebAuth.verifyChallengeTxSigners}\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks})\n * @param homeDomains - The home domain that is expected\n * to be included in the first Manage Data operation's string key. If an\n * array is provided, one of the domain names in the array must match.\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key.\n * If no such operation is included, this parameter is not used.\n * @returns The actual transaction and the\n * Stellar public key (master key) used to sign the Manage Data operation,\n * the matched home domain, and the memo attached to the transaction, which\n * will be null if not present.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n */\nexport function readChallengeTx(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n homeDomains: string | string[],\n webAuthDomain: string,\n): {\n tx: Transaction;\n clientAccountID: string;\n matchedHomeDomain: string;\n memo: string | null;\n} {\n if (serverAccountID.startsWith(\"M\")) {\n throw Error(\n \"Invalid serverAccountID: multiplexed accounts are not supported.\",\n );\n }\n\n let transaction;\n try {\n transaction = new Transaction(challengeTx, networkPassphrase);\n } catch {\n try {\n transaction = new FeeBumpTransaction(challengeTx, networkPassphrase);\n } catch {\n throw new InvalidChallengeError(\n \"Invalid challenge: unable to deserialize challengeTx transaction string\",\n );\n }\n throw new InvalidChallengeError(\n \"Invalid challenge: expected a Transaction but received a FeeBumpTransaction\",\n );\n }\n\n // verify sequence number\n const sequence = Number.parseInt(transaction.sequence, 10);\n\n if (sequence !== 0) {\n throw new InvalidChallengeError(\n \"The transaction sequence number should be zero\",\n );\n }\n\n // verify transaction source\n if (transaction.source !== serverAccountID) {\n throw new InvalidChallengeError(\n \"The transaction source account is not equal to the server's account\",\n );\n }\n\n // verify operation\n if (transaction.operations.length < 1) {\n throw new InvalidChallengeError(\n \"The transaction should contain at least one operation\",\n );\n }\n\n const [operation, ...subsequentOperations] = transaction.operations;\n\n if (!operation.source) {\n throw new InvalidChallengeError(\n \"The transaction's operation should contain a source account\",\n );\n }\n const clientAccountID: string = operation.source!;\n\n let memo: string | null = null;\n if (transaction.memo.type !== MemoNone) {\n if (clientAccountID.startsWith(\"M\")) {\n throw new InvalidChallengeError(\n \"The transaction has a memo but the client account ID is a muxed account\",\n );\n }\n if (transaction.memo.type !== MemoID) {\n throw new InvalidChallengeError(\n \"The transaction's memo must be of type `id`\",\n );\n }\n memo = transaction.memo.value as string;\n }\n\n if (operation.type !== \"manageData\") {\n throw new InvalidChallengeError(\n \"The transaction's operation type should be 'manageData'\",\n );\n }\n\n // verify timebounds\n if (\n transaction.timeBounds &&\n Number.parseInt(transaction.timeBounds?.maxTime, 10) === TimeoutInfinite\n ) {\n throw new InvalidChallengeError(\n \"The transaction requires non-infinite timebounds\",\n );\n }\n\n // give a small grace period for the transaction time to account for clock drift\n if (!Utils.validateTimebounds(transaction, 60 * 5)) {\n throw new InvalidChallengeError(\"The transaction has expired\");\n }\n\n if (operation.value === undefined) {\n throw new InvalidChallengeError(\n \"The transaction's operation values should not be null\",\n );\n }\n\n // verify base64\n if (!operation.value) {\n throw new InvalidChallengeError(\n \"The transaction's operation value should not be null\",\n );\n }\n\n if (Buffer.from(operation.value.toString(), \"base64\").length !== 48) {\n throw new InvalidChallengeError(\n \"The transaction's operation value should be a 64 bytes base64 random string\",\n );\n }\n\n // verify homeDomains\n if (!homeDomains) {\n throw new InvalidChallengeError(\n \"Invalid homeDomains: a home domain must be provided for verification\",\n );\n }\n\n let matchedHomeDomain;\n\n if (typeof homeDomains === \"string\") {\n if (`${homeDomains} auth` === operation.name) {\n matchedHomeDomain = homeDomains;\n }\n } else if (Array.isArray(homeDomains)) {\n matchedHomeDomain = homeDomains.find(\n (domain) => `${domain} auth` === operation.name,\n );\n } else {\n throw new InvalidChallengeError(\n `Invalid homeDomains: homeDomains type is ${typeof homeDomains} but should be a string or an array`,\n );\n }\n\n if (!matchedHomeDomain) {\n throw new InvalidChallengeError(\n \"Invalid homeDomains: the transaction's operation key name does not match the expected home domain\",\n );\n }\n\n // verify any subsequent operations are manage data ops and source account is the server\n for (const op of subsequentOperations) {\n if (op.type !== \"manageData\") {\n throw new InvalidChallengeError(\n \"The transaction has operations that are not of type 'manageData'\",\n );\n }\n if (op.source !== serverAccountID && op.name !== \"client_domain\") {\n throw new InvalidChallengeError(\n \"The transaction has operations that are unrecognized\",\n );\n }\n if (op.name === \"web_auth_domain\") {\n if (op.value === undefined) {\n throw new InvalidChallengeError(\n \"'web_auth_domain' operation value should not be null\",\n );\n }\n if (op.value.compare(Buffer.from(webAuthDomain))) {\n throw new InvalidChallengeError(\n `'web_auth_domain' operation value does not match ${webAuthDomain}`,\n );\n }\n }\n }\n\n if (!verifyTxSignedBy(transaction, serverAccountID)) {\n throw new InvalidChallengeError(\n `Transaction not signed by server: '${serverAccountID}'`,\n );\n }\n\n return { tx: transaction, clientAccountID, matchedHomeDomain, memo };\n}\n\n/**\n * Verifies that for a SEP 10 challenge transaction all signatures on the\n * transaction are accounted for. A transaction is verified if it is signed by\n * the server account, and all other signatures match a signer that has been\n * provided as an argument (as the accountIDs list). Additional signers can be\n * provided that do not have a signature, but all signatures must be matched to\n * a signer (accountIDs) for verification to succeed. If verification succeeds,\n * a list of signers that were found is returned, not including the server\n * account ID.\n *\n * Signers that are not prefixed as an address/account ID strkey (G...) will be\n * ignored.\n *\n * Errors will be raised if:\n * - The transaction is invalid according to\n * {@link WebAuth.readChallengeTx}.\n * - No client signatures are found on the transaction.\n * - One or more signatures in the transaction are not identifiable as the\n * server account or one of the signers provided in the arguments.\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks}).\n * @param signers - The signers public keys. This list should\n * contain the public keys for all signers that have signed the transaction.\n * @param homeDomains - The home domain(s) that should\n * be included in the first Manage Data operation's string key. Required in\n * readChallengeTx().\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key,\n * if present. Used in readChallengeTx().\n * @returns The list of signers public keys that have signed\n * the transaction, excluding the server account ID.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk';\n *\n * const serverKP = Keypair.random();\n * const clientKP1 = Keypair.random();\n * const clientKP2 = Keypair.random();\n *\n * // Challenge, possibly built in the server side\n * const challenge = WebAuth.buildChallengeTx(\n * serverKP,\n * clientKP1.publicKey(),\n * \"SDF\",\n * 300,\n * Networks.TESTNET\n * );\n *\n * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client\n *\n * // Transaction gathered from a challenge, possibly from the client side\n * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET);\n * transaction.sign(clientKP1, clientKP2);\n * const signedChallenge = transaction\n * .toEnvelope()\n * .toXDR(\"base64\")\n * .toString();\n *\n * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()]\n * WebAuth.verifyChallengeTxSigners(\n * signedChallenge,\n * serverKP.publicKey(),\n * Networks.TESTNET,\n * threshold,\n * [clientKP1.publicKey(), clientKP2.publicKey()]\n * );\n * ```\n */\nexport function verifyChallengeTxSigners(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n signers: string[],\n homeDomains: string | string[],\n webAuthDomain: string,\n): string[] {\n // Read the transaction which validates its structure.\n const { tx } = readChallengeTx(\n challengeTx,\n serverAccountID,\n networkPassphrase,\n homeDomains,\n webAuthDomain,\n );\n\n // Ensure the server account ID is an address and not a seed.\n let serverKP: Keypair;\n try {\n serverKP = Keypair.fromPublicKey(serverAccountID); // can throw 'Invalid Stellar public key'\n } catch (err: any) {\n throw new Error(\n `Couldn't infer keypair from the provided 'serverAccountID': ${\n err.message\n }`,\n );\n }\n\n // Deduplicate the client signers and ensure the server is not included\n // anywhere we check or output the list of signers.\n const clientSigners = new Set<string>();\n for (const signer of signers) {\n // Ignore the server signer if it is in the signers list. It's\n // important when verifying signers of a challenge transaction that we\n // only verify and return client signers. If an account has the server\n // as a signer the server should not play a part in the authentication\n // of the client.\n if (signer === serverKP.publicKey()) {\n continue;\n }\n\n // Ignore non-G... account/address signers.\n if (signer.charAt(0) !== \"G\") {\n continue;\n }\n\n clientSigners.add(signer);\n }\n\n // Don't continue if none of the signers provided are in the final list.\n if (clientSigners.size === 0) {\n throw new InvalidChallengeError(\n \"No verifiable client signers provided, at least one G... address must be provided\",\n );\n }\n\n let clientSigningKey;\n for (const op of tx.operations) {\n if (op.type === \"manageData\" && op.name === \"client_domain\") {\n if (clientSigningKey) {\n throw new InvalidChallengeError(\n \"Found more than one client_domain operation\",\n );\n }\n clientSigningKey = op.source;\n }\n }\n\n // Verify all the transaction's signers (server and client) in one\n // hit. We do this in one hit here even though the server signature was\n // checked in the ReadChallengeTx to ensure that every signature and signer\n // are consumed only once on the transaction.\n const allSigners: string[] = [\n serverKP.publicKey(),\n ...Array.from(clientSigners),\n ];\n if (clientSigningKey) {\n allSigners.push(clientSigningKey);\n }\n\n const signersFound: string[] = gatherTxSigners(tx, allSigners);\n\n let serverSignatureFound = false;\n let clientSigningKeySignatureFound = false;\n for (const signer of signersFound) {\n if (signer === serverKP.publicKey()) {\n serverSignatureFound = true;\n }\n if (signer === clientSigningKey) {\n clientSigningKeySignatureFound = true;\n }\n }\n\n // Confirm we matched a signature to the server signer.\n if (!serverSignatureFound) {\n throw new InvalidChallengeError(\n `Transaction not signed by server: '${serverKP.publicKey()}'`,\n );\n }\n\n // Confirm we matched a signature to the client domain's signer\n if (clientSigningKey && !clientSigningKeySignatureFound) {\n throw new InvalidChallengeError(\n \"Transaction not signed by the source account of the 'client_domain' \" +\n \"ManageData operation\",\n );\n }\n\n // Confirm we matched at least one given signer with the transaction signatures\n if (signersFound.length === 1) {\n throw new InvalidChallengeError(\n \"None of the given signers match the transaction signatures\",\n );\n }\n\n // Confirm all signatures, including the server signature, were consumed by a signer:\n if (signersFound.length !== tx.signatures.length) {\n throw new InvalidChallengeError(\"Transaction has unrecognized signatures\");\n }\n\n // Remove the server public key before returning\n signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1);\n if (clientSigningKey) {\n // Remove the client domain public key public key before returning\n signersFound.splice(signersFound.indexOf(clientSigningKey), 1);\n }\n\n if (signersFound.length === 0) {\n throw new InvalidChallengeError(\n \"None of the given signers match the transaction signatures\",\n );\n }\n\n return signersFound;\n}\n\n/**\n * Verifies that for a SEP-10 challenge transaction all signatures on the\n * transaction are accounted for and that the signatures meet a threshold on an\n * account. A transaction is verified if it is signed by the server account, and\n * all other signatures match a signer that has been provided as an argument,\n * and those signatures meet a threshold on the account.\n *\n * Signers that are not prefixed as an address/account ID strkey (G...) will be\n * ignored.\n *\n * Errors will be raised if:\n * - The transaction is invalid according to\n * {@link WebAuth.readChallengeTx}.\n * - No client signatures are found on the transaction.\n * - One or more signatures in the transaction are not identifiable as the\n * server account or one of the signers provided in the arguments.\n * - The signatures are all valid but do not meet the threshold.\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks}).\n * @param threshold - The required signatures threshold for verifying\n * this transaction.\n * @param signerSummary - a map of all\n * authorized signers to their weights. It's used to validate if the\n * transaction signatures have met the given threshold.\n * @param homeDomains - The home domain(s) that should\n * be included in the first Manage Data operation's string key. Required in\n * `verifyChallengeTxSigners() => readChallengeTx()`.\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key,\n * if present. Used in `verifyChallengeTxSigners() => readChallengeTx()`.\n * @returns The list of signers public keys that have signed\n * the transaction, excluding the server account ID, given that the threshold\n * was met.\n * @throws Will throw if the collective\n * weight of the transaction's signers does not meet the necessary threshold\n * to verify this transaction.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk';\n *\n * const serverKP = Keypair.random();\n * const clientKP1 = Keypair.random();\n * const clientKP2 = Keypair.random();\n *\n * // Challenge, possibly built in the server side\n * const challenge = WebAuth.buildChallengeTx(\n * serverKP,\n * clientKP1.publicKey(),\n * \"SDF\",\n * 300,\n * Networks.TESTNET\n * );\n *\n * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client\n *\n * // Transaction gathered from a challenge, possibly from the client side\n * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET);\n * transaction.sign(clientKP1, clientKP2);\n * const signedChallenge = transaction\n * .toEnvelope()\n * .toXDR(\"base64\")\n * .toString();\n *\n * // Defining the threshold and signerSummary\n * const threshold = 3;\n * const signerSummary = [\n * {\n * key: this.clientKP1.publicKey(),\n * weight: 1,\n * },\n * {\n * key: this.clientKP2.publicKey(),\n * weight: 2,\n * },\n * ];\n *\n * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()]\n * WebAuth.verifyChallengeTxThreshold(\n * signedChallenge,\n * serverKP.publicKey(),\n * Networks.TESTNET,\n * threshold,\n * signerSummary\n * );\n * ```\n */\nexport function verifyChallengeTxThreshold(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n threshold: number,\n signerSummary: ServerApi.AccountRecordSigners[],\n homeDomains: string | string[],\n webAuthDomain: string,\n): string[] {\n const signers = signerSummary.map((signer) => signer.key);\n\n const signersFound = verifyChallengeTxSigners(\n challengeTx,\n serverAccountID,\n networkPassphrase,\n signers,\n homeDomains,\n webAuthDomain,\n );\n\n let weight = 0;\n for (const signer of signersFound) {\n const sigWeight = signerSummary.find((s) => s.key === signer)?.weight || 0;\n weight += sigWeight;\n }\n\n if (weight < threshold) {\n throw new InvalidChallengeError(\n `signers with weight ${weight} do not meet threshold ${threshold}\"`,\n );\n }\n\n return signersFound;\n}\n"],"names":["memo","account","Account","uint8ArrayToBase64","TransactionBuilder","BASE_FEE","Operation","Memo","transaction","Transaction","FeeBumpTransaction","InvalidChallengeError","MemoNone","MemoID","TimeoutInfinite","Utils","Buffer","verifyTxSignedBy","Keypair","gatherTxSigners"],"mappings":";;;;;;;;;;;;;;;;;;;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A,KACF;AAAA,EACF;AAEA,EAAA,OAAO,YAAA;AACT;AA2FO,SAAS,2BACd,WAAA,EACA,eAAA,EACA,mBACA,SAAA,EACA,aAAA,EACA,aACA,aAAA,EACU;AACV,EAAA,MAAM,UAAU,aAAA,CAAc,GAAA,CAAI,CAAC,MAAA,KAAW,OAAO,GAAG,CAAA;AAExD,EAAA,MAAM,YAAA,GAAe,wBAAA;AAAA,IACnB,WAAA;AAAA,IACA,eAAA;AAAA,IACA,iBAAA;AAAA,IACA,OAAA;AAAA,IACA,WAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,KAAA,MAAW,UAAU,YAAA,EAAc;AACjC,IAAA,MAAM,SAAA,GAAY,cAAc,IAAA,CAAK,CAAC,MAAM,CAAA,CAAE,GAAA,KAAQ,MAAM,CAAA,EAAG,MAAA,IAAU,CAAA;AACzE,IAAA,MAAA,IAAU,SAAA;AAAA,EACZ;AAEA,EAAA,IAAI,SAAS,SAAA,EAAW;AACtB,IAAA,MAAM,IAAIA,4BAAA;AAAA,MACR,CAAA,oBAAA,EAAuB,MAAM,CAAA,uBAAA,EAA0B,SAAS,CAAA,CAAA;AAAA,KAClE;AAAA,EACF;AAEA,EAAA,OAAO,YAAA;AACT;;;;;;;"}
1
+ {"version":3,"file":"challenge_transaction.js","sources":["../../../../src/webauth/challenge_transaction.ts"],"sourcesContent":["import {\n Keypair,\n Account,\n TransactionBuilder,\n BASE_FEE,\n Operation,\n Memo,\n MemoNone,\n MemoID,\n FeeBumpTransaction,\n TimeoutInfinite,\n Transaction,\n Networks,\n} from \"../base/index.js\";\nimport { InvalidChallengeError } from \"./errors.js\";\nimport { gatherTxSigners, verifyTxSignedBy } from \"./utils.js\";\nimport { Utils } from \"../utils.js\";\nimport { ServerApi } from \"../horizon/server_api.js\";\nimport { uint8ArrayToBase64 } from \"uint8array-extras\";\n\n/**\n * Returns a valid {@link https://stellar.org/protocol/sep-10 | SEP-10}\n * challenge transaction which you can use for Stellar Web Authentication.\n * @param serverKeypair - Keypair for server's signing account.\n * @param clientAccountID - The stellar account (G...) or muxed account\n * (M...) that the wallet wishes to authenticate with the server.\n * @param homeDomain - The fully qualified domain name of the service\n * requiring authentication\n * @param timeout - Challenge duration (default to 5 minutes).\n * @param networkPassphrase - The network passphrase. If you pass this\n * argument then timeout is required.\n * @param webAuthDomain - The fully qualified domain name of the service\n * issuing the challenge.\n * @param memo - The memo to attach to the challenge transaction. The\n * memo must be of type `id`. If the `clientaccountID` is a muxed account,\n * memos cannot be used.\n * @param clientDomain - The fully qualified domain of the client\n * requesting the challenge. Only necessary when the 'client_domain'\n * parameter is passed.\n * @param clientSigningKey - The public key assigned to the SIGNING_KEY\n * attribute specified on the stellar.toml hosted on the client domain. Only\n * necessary when the 'client_domain' parameter is passed.\n * @returns A base64 encoded string of the raw TransactionEnvelope xdr\n * struct for the transaction.\n * @throws Will throw if `clientAccountID` is a muxed account, and `memo`\n * is present.\n * @throws Will throw if `clientDomain` is provided, but\n * `clientSigningKey` is missing\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Keypair, Networks, WebAuth } from 'stellar-sdk'\n *\n * let serverKeyPair = Keypair.fromSecret(\"server-secret\")\n * let challenge = WebAuth.buildChallengeTx(\n * serverKeyPair,\n * \"client-stellar-account-id\",\n * \"stellar.org\",\n * 300,\n * Networks.TESTNET);\n * ```\n */\nexport function buildChallengeTx(\n serverKeypair: Keypair,\n clientAccountID: string,\n homeDomain: string,\n\n timeout: number = 300,\n networkPassphrase: string,\n webAuthDomain: string,\n memo: string | null = null,\n clientDomain: string | null = null,\n clientSigningKey: string | null = null,\n): string {\n if (clientAccountID.startsWith(\"M\") && memo) {\n throw Error(\"memo cannot be used if clientAccountID is a muxed account\");\n }\n\n const account = new Account(serverKeypair.publicKey(), \"-1\");\n const now = Math.floor(Date.now() / 1000);\n\n // A Base64 digit represents 6 bits, to generate a random 64 bytes\n // base64 string, we need 48 random bytes = (64 * 6)/8\n //\n // Each Base64 digit is in ASCII and each ASCII characters when\n // turned into binary represents 8 bits = 1 bytes.\n const value = uint8ArrayToBase64(crypto.getRandomValues(new Uint8Array(48)));\n\n const builder = new TransactionBuilder(account, {\n fee: BASE_FEE,\n networkPassphrase,\n timebounds: {\n minTime: now,\n maxTime: now + timeout,\n },\n })\n .addOperation(\n Operation.manageData({\n name: `${homeDomain} auth`,\n value,\n source: clientAccountID,\n }),\n )\n .addOperation(\n Operation.manageData({\n name: \"web_auth_domain\",\n value: webAuthDomain,\n source: account.accountId(),\n }),\n );\n\n if (clientDomain) {\n if (!clientSigningKey) {\n throw Error(\"clientSigningKey is required if clientDomain is provided\");\n }\n builder.addOperation(\n Operation.manageData({\n name: `client_domain`,\n value: clientDomain,\n source: clientSigningKey,\n }),\n );\n }\n\n if (memo) {\n builder.addMemo(Memo.id(memo));\n }\n\n const transaction = builder.build();\n transaction.sign(serverKeypair);\n\n return transaction.toEnvelope().toXDR(\"base64\").toString();\n}\n\n/**\n * Reads a SEP-10 challenge transaction and returns the decoded transaction and\n * client account ID contained within.\n *\n * It also verifies that the transaction has been signed by the server.\n *\n * It does not verify that the transaction has been signed by the client or that\n * any signatures other than the server's on the transaction are valid. Use one\n * of the following functions to completely verify the transaction:\n *\n * - {@link WebAuth.verifyChallengeTxThreshold}\n * - {@link WebAuth.verifyChallengeTxSigners}\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks})\n * @param homeDomains - The home domain that is expected\n * to be included in the first Manage Data operation's string key. If an\n * array is provided, one of the domain names in the array must match.\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key.\n * If no such operation is included, this parameter is not used.\n * @returns The actual transaction and the\n * Stellar public key (master key) used to sign the Manage Data operation,\n * the matched home domain, and the memo attached to the transaction, which\n * will be null if not present.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n */\nexport function readChallengeTx(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n homeDomains: string | string[],\n webAuthDomain: string,\n): {\n tx: Transaction;\n clientAccountID: string;\n matchedHomeDomain: string;\n memo: string | null;\n} {\n if (serverAccountID.startsWith(\"M\")) {\n throw Error(\n \"Invalid serverAccountID: multiplexed accounts are not supported.\",\n );\n }\n\n let transaction;\n try {\n transaction = new Transaction(challengeTx, networkPassphrase);\n } catch {\n try {\n transaction = new FeeBumpTransaction(challengeTx, networkPassphrase);\n } catch {\n throw new InvalidChallengeError(\n \"Invalid challenge: unable to deserialize challengeTx transaction string\",\n );\n }\n throw new InvalidChallengeError(\n \"Invalid challenge: expected a Transaction but received a FeeBumpTransaction\",\n );\n }\n\n // verify sequence number\n const sequence = Number.parseInt(transaction.sequence, 10);\n\n if (sequence !== 0) {\n throw new InvalidChallengeError(\n \"The transaction sequence number should be zero\",\n );\n }\n\n // verify transaction source\n if (transaction.source !== serverAccountID) {\n throw new InvalidChallengeError(\n \"The transaction source account is not equal to the server's account\",\n );\n }\n\n // verify operation\n if (transaction.operations.length < 1) {\n throw new InvalidChallengeError(\n \"The transaction should contain at least one operation\",\n );\n }\n\n const [operation, ...subsequentOperations] = transaction.operations;\n\n if (!operation.source) {\n throw new InvalidChallengeError(\n \"The transaction's operation should contain a source account\",\n );\n }\n const clientAccountID: string = operation.source!;\n\n let memo: string | null = null;\n if (transaction.memo.type !== MemoNone) {\n if (clientAccountID.startsWith(\"M\")) {\n throw new InvalidChallengeError(\n \"The transaction has a memo but the client account ID is a muxed account\",\n );\n }\n if (transaction.memo.type !== MemoID) {\n throw new InvalidChallengeError(\n \"The transaction's memo must be of type `id`\",\n );\n }\n memo = transaction.memo.value as string;\n }\n\n if (operation.type !== \"manageData\") {\n throw new InvalidChallengeError(\n \"The transaction's operation type should be 'manageData'\",\n );\n }\n\n // verify timebounds\n if (\n transaction.timeBounds &&\n Number.parseInt(transaction.timeBounds?.maxTime, 10) === TimeoutInfinite\n ) {\n throw new InvalidChallengeError(\n \"The transaction requires non-infinite timebounds\",\n );\n }\n\n // give a small grace period for the transaction time to account for clock drift\n if (!Utils.validateTimebounds(transaction, 60 * 5)) {\n throw new InvalidChallengeError(\"The transaction has expired\");\n }\n\n if (operation.value === undefined) {\n throw new InvalidChallengeError(\n \"The transaction's operation values should not be null\",\n );\n }\n\n // verify base64\n if (!operation.value) {\n throw new InvalidChallengeError(\n \"The transaction's operation value should not be null\",\n );\n }\n\n if (Buffer.from(operation.value.toString(), \"base64\").length !== 48) {\n throw new InvalidChallengeError(\n \"The transaction's operation value should be a 64 bytes base64 random string\",\n );\n }\n\n // verify homeDomains\n if (!homeDomains) {\n throw new InvalidChallengeError(\n \"Invalid homeDomains: a home domain must be provided for verification\",\n );\n }\n\n let matchedHomeDomain;\n\n if (typeof homeDomains === \"string\") {\n if (`${homeDomains} auth` === operation.name) {\n matchedHomeDomain = homeDomains;\n }\n } else if (Array.isArray(homeDomains)) {\n matchedHomeDomain = homeDomains.find(\n (domain) => `${domain} auth` === operation.name,\n );\n } else {\n throw new InvalidChallengeError(\n `Invalid homeDomains: homeDomains type is ${typeof homeDomains} but should be a string or an array`,\n );\n }\n\n if (!matchedHomeDomain) {\n throw new InvalidChallengeError(\n \"Invalid homeDomains: the transaction's operation key name does not match the expected home domain\",\n );\n }\n\n // verify any subsequent operations are manage data ops and source account is the server\n for (const op of subsequentOperations) {\n if (op.type !== \"manageData\") {\n throw new InvalidChallengeError(\n \"The transaction has operations that are not of type 'manageData'\",\n );\n }\n if (op.source !== serverAccountID && op.name !== \"client_domain\") {\n throw new InvalidChallengeError(\n \"The transaction has operations that are unrecognized\",\n );\n }\n if (op.name === \"web_auth_domain\") {\n if (op.value === undefined) {\n throw new InvalidChallengeError(\n \"'web_auth_domain' operation value should not be null\",\n );\n }\n if (op.value.compare(Buffer.from(webAuthDomain))) {\n throw new InvalidChallengeError(\n `'web_auth_domain' operation value does not match ${webAuthDomain}`,\n );\n }\n }\n }\n\n if (!verifyTxSignedBy(transaction, serverAccountID)) {\n throw new InvalidChallengeError(\n `Transaction not signed by server: '${serverAccountID}'`,\n );\n }\n\n return { tx: transaction, clientAccountID, matchedHomeDomain, memo };\n}\n\n/**\n * Verifies that for a SEP 10 challenge transaction all signatures on the\n * transaction are accounted for. A transaction is verified if it is signed by\n * the server account, and all other signatures match a signer that has been\n * provided as an argument (as the accountIDs list). Additional signers can be\n * provided that do not have a signature, but all signatures must be matched to\n * a signer (accountIDs) for verification to succeed. If verification succeeds,\n * a list of signers that were found is returned, not including the server\n * account ID.\n *\n * Signers that are not prefixed as an address/account ID strkey (G...) will be\n * ignored.\n *\n * Errors will be raised if:\n * - The transaction is invalid according to\n * {@link WebAuth.readChallengeTx}.\n * - No client signatures are found on the transaction.\n * - One or more signatures in the transaction are not identifiable as the\n * server account or one of the signers provided in the arguments.\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks}).\n * @param signers - The signers public keys. This list should\n * contain the public keys for all signers that have signed the transaction.\n * @param homeDomains - The home domain(s) that should\n * be included in the first Manage Data operation's string key. Required in\n * readChallengeTx().\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key,\n * if present. Used in readChallengeTx().\n * @returns The list of signers public keys that have signed\n * the transaction, excluding the server account ID.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk';\n *\n * const serverKP = Keypair.random();\n * const clientKP1 = Keypair.random();\n * const clientKP2 = Keypair.random();\n *\n * // Challenge, possibly built in the server side\n * const challenge = WebAuth.buildChallengeTx(\n * serverKP,\n * clientKP1.publicKey(),\n * \"SDF\",\n * 300,\n * Networks.TESTNET\n * );\n *\n * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client\n *\n * // Transaction gathered from a challenge, possibly from the client side\n * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET);\n * transaction.sign(clientKP1, clientKP2);\n * const signedChallenge = transaction\n * .toEnvelope()\n * .toXDR(\"base64\")\n * .toString();\n *\n * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()]\n * WebAuth.verifyChallengeTxSigners(\n * signedChallenge,\n * serverKP.publicKey(),\n * Networks.TESTNET,\n * threshold,\n * [clientKP1.publicKey(), clientKP2.publicKey()]\n * );\n * ```\n */\nexport function verifyChallengeTxSigners(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n signers: string[],\n homeDomains: string | string[],\n webAuthDomain: string,\n): string[] {\n // Read the transaction which validates its structure.\n const { tx } = readChallengeTx(\n challengeTx,\n serverAccountID,\n networkPassphrase,\n homeDomains,\n webAuthDomain,\n );\n\n // Ensure the server account ID is an address and not a seed.\n let serverKP: Keypair;\n try {\n serverKP = Keypair.fromPublicKey(serverAccountID); // can throw 'Invalid Stellar public key'\n } catch (err: any) {\n throw new Error(\n `Couldn't infer keypair from the provided 'serverAccountID': ${\n err.message\n }`,\n );\n }\n\n // Deduplicate the client signers and ensure the server is not included\n // anywhere we check or output the list of signers.\n const clientSigners = new Set<string>();\n for (const signer of signers) {\n // Ignore the server signer if it is in the signers list. It's\n // important when verifying signers of a challenge transaction that we\n // only verify and return client signers. If an account has the server\n // as a signer the server should not play a part in the authentication\n // of the client.\n if (signer === serverKP.publicKey()) {\n continue;\n }\n\n // Ignore non-G... account/address signers.\n if (signer.charAt(0) !== \"G\") {\n continue;\n }\n\n clientSigners.add(signer);\n }\n\n // Don't continue if none of the signers provided are in the final list.\n if (clientSigners.size === 0) {\n throw new InvalidChallengeError(\n \"No verifiable client signers provided, at least one G... address must be provided\",\n );\n }\n\n let clientSigningKey;\n for (const op of tx.operations) {\n if (op.type === \"manageData\" && op.name === \"client_domain\") {\n if (clientSigningKey) {\n throw new InvalidChallengeError(\n \"Found more than one client_domain operation\",\n );\n }\n clientSigningKey = op.source;\n }\n }\n\n // Verify all the transaction's signers (server and client) in one\n // hit. We do this in one hit here even though the server signature was\n // checked in the ReadChallengeTx to ensure that every signature and signer\n // are consumed only once on the transaction.\n const allSigners: string[] = [\n serverKP.publicKey(),\n ...Array.from(clientSigners),\n ];\n if (clientSigningKey) {\n allSigners.push(clientSigningKey);\n }\n\n const signersFound: string[] = gatherTxSigners(tx, allSigners);\n\n let serverSignatureFound = false;\n let clientSigningKeySignatureFound = false;\n for (const signer of signersFound) {\n if (signer === serverKP.publicKey()) {\n serverSignatureFound = true;\n }\n if (signer === clientSigningKey) {\n clientSigningKeySignatureFound = true;\n }\n }\n\n // Confirm we matched a signature to the server signer.\n if (!serverSignatureFound) {\n throw new InvalidChallengeError(\n `Transaction not signed by server: '${serverKP.publicKey()}'`,\n );\n }\n\n // Confirm we matched a signature to the client domain's signer\n if (clientSigningKey && !clientSigningKeySignatureFound) {\n throw new InvalidChallengeError(\n \"Transaction not signed by the source account of the 'client_domain' \" +\n \"ManageData operation\",\n );\n }\n\n // Confirm we matched at least one given signer with the transaction signatures\n if (signersFound.length === 1) {\n throw new InvalidChallengeError(\n \"None of the given signers match the transaction signatures\",\n );\n }\n\n // Confirm all signatures, including the server signature, were consumed by a signer:\n if (signersFound.length !== tx.signatures.length) {\n throw new InvalidChallengeError(\"Transaction has unrecognized signatures\");\n }\n\n // Remove the server public key before returning\n signersFound.splice(signersFound.indexOf(serverKP.publicKey()), 1);\n if (clientSigningKey) {\n // Remove the client domain public key public key before returning\n signersFound.splice(signersFound.indexOf(clientSigningKey), 1);\n }\n\n if (signersFound.length === 0) {\n throw new InvalidChallengeError(\n \"None of the given signers match the transaction signatures\",\n );\n }\n\n return signersFound;\n}\n\n/**\n * Verifies that for a SEP-10 challenge transaction all signatures on the\n * transaction are accounted for and that the signatures meet a threshold on an\n * account. A transaction is verified if it is signed by the server account, and\n * all other signatures match a signer that has been provided as an argument,\n * and those signatures meet a threshold on the account.\n *\n * Signers that are not prefixed as an address/account ID strkey (G...) will be\n * ignored.\n *\n * Errors will be raised if:\n * - The transaction is invalid according to\n * {@link WebAuth.readChallengeTx}.\n * - No client signatures are found on the transaction.\n * - One or more signatures in the transaction are not identifiable as the\n * server account or one of the signers provided in the arguments.\n * - The signatures are all valid but do not meet the threshold.\n * @param challengeTx - SEP0010 challenge transaction in base64.\n * @param serverAccountID - The server's stellar account (public key).\n * @param networkPassphrase - The network passphrase, e.g.: 'Test SDF\n * Network ; September 2015' (see {@link Networks}).\n * @param threshold - The required signatures threshold for verifying\n * this transaction.\n * @param signerSummary - a map of all\n * authorized signers to their weights. It's used to validate if the\n * transaction signatures have met the given threshold.\n * @param homeDomains - The home domain(s) that should\n * be included in the first Manage Data operation's string key. Required in\n * `verifyChallengeTxSigners() => readChallengeTx()`.\n * @param webAuthDomain - The home domain that is expected to be included\n * as the value of the Manage Data operation with the 'web_auth_domain' key,\n * if present. Used in `verifyChallengeTxSigners() => readChallengeTx()`.\n * @returns The list of signers public keys that have signed\n * the transaction, excluding the server account ID, given that the threshold\n * was met.\n * @throws Will throw if the collective\n * weight of the transaction's signers does not meet the necessary threshold\n * to verify this transaction.\n * @see {@link https://stellar.org/protocol/sep-10 | SEP-10: Stellar Web Auth}\n * @example\n * ```ts\n * import { Networks, TransactionBuilder, WebAuth } from 'stellar-sdk';\n *\n * const serverKP = Keypair.random();\n * const clientKP1 = Keypair.random();\n * const clientKP2 = Keypair.random();\n *\n * // Challenge, possibly built in the server side\n * const challenge = WebAuth.buildChallengeTx(\n * serverKP,\n * clientKP1.publicKey(),\n * \"SDF\",\n * 300,\n * Networks.TESTNET\n * );\n *\n * // clock.tick(200); // Simulates a 200 ms delay when communicating from server to client\n *\n * // Transaction gathered from a challenge, possibly from the client side\n * const transaction = TransactionBuilder.fromXDR(challenge, Networks.TESTNET);\n * transaction.sign(clientKP1, clientKP2);\n * const signedChallenge = transaction\n * .toEnvelope()\n * .toXDR(\"base64\")\n * .toString();\n *\n * // Defining the threshold and signerSummary\n * const threshold = 3;\n * const signerSummary = [\n * {\n * key: this.clientKP1.publicKey(),\n * weight: 1,\n * },\n * {\n * key: this.clientKP2.publicKey(),\n * weight: 2,\n * },\n * ];\n *\n * // The result below should be equal to [clientKP1.publicKey(), clientKP2.publicKey()]\n * WebAuth.verifyChallengeTxThreshold(\n * signedChallenge,\n * serverKP.publicKey(),\n * Networks.TESTNET,\n * threshold,\n * signerSummary\n * );\n * ```\n */\nexport function verifyChallengeTxThreshold(\n challengeTx: string,\n serverAccountID: string,\n networkPassphrase: string,\n threshold: number,\n signerSummary: ServerApi.AccountRecordSigners[],\n homeDomains: string | string[],\n webAuthDomain: string,\n): string[] {\n const signers = signerSummary.map((signer) => signer.key);\n\n const signersFound = verifyChallengeTxSigners(\n challengeTx,\n serverAccountID,\n networkPassphrase,\n signers,\n homeDomains,\n webAuthDomain,\n );\n\n let weight = 0;\n for (const signer of signersFound) {\n const sigWeight = signerSummary.find((s) => s.key === signer)?.weight || 0;\n weight += sigWeight;\n }\n\n if (weight < threshold) {\n throw new InvalidChallengeError(\n `signers with weight ${weight} do not meet threshold ${threshold}\"`,\n );\n }\n\n return signersFound;\n}\n"],"names":["memo","account","Account","uint8ArrayToBase64","TransactionBuilder","BASE_FEE","Operation","Memo","transaction","Transaction","FeeBumpTransaction","InvalidChallengeError","MemoNone","MemoID","TimeoutInfinite","Utils","Buffer","verifyTxSignedBy","Keypair","gatherTxSigners"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8DO,SAAS,gBAAA,CACd,aAAA,EACA,eAAA,EACA,UAAA,EAEA,OAAA,GAAkB,GAAA,EAClB,iBAAA,EACA,aAAA,EACAA,MAAA,GAAsB,IAAA,EACtB,YAAA,GAA8B,IAAA,EAC9B,mBAAkC,IAAA,EAC1B;AACR,EAAA,IAAI,eAAA,CAAgB,UAAA,CAAW,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