@stellar/stellar-sdk 16.0.0 → 16.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/stellar-sdk-axios.js +5608 -4598
- package/dist/stellar-sdk-axios.js.map +1 -1
- package/dist/stellar-sdk-axios.min.js +12 -11
- package/dist/stellar-sdk-axios.min.js.map +1 -1
- package/dist/stellar-sdk.js +3902 -3434
- package/dist/stellar-sdk.js.map +1 -1
- package/dist/stellar-sdk.min.js +17 -17
- package/dist/stellar-sdk.min.js.map +1 -1
- package/lib/axios/cjs/base/auth.js +107 -0
- package/lib/axios/cjs/base/auth.js.map +1 -1
- package/lib/axios/cjs/base/keypair.js +39 -0
- package/lib/axios/cjs/base/keypair.js.map +1 -1
- package/lib/axios/cjs/base/scval.js +34 -0
- package/lib/axios/cjs/base/scval.js.map +1 -1
- package/lib/axios/cjs/bindings/config.js +1 -1
- package/lib/axios/cjs/cli/index.js +1 -1
- package/lib/axios/cjs/cli/index.js.map +1 -1
- package/lib/axios/cjs/contract/assembled_transaction.js +8 -7
- package/lib/axios/cjs/contract/assembled_transaction.js.map +1 -1
- package/lib/axios/cjs/contract/client.js +56 -3
- package/lib/axios/cjs/contract/client.js.map +1 -1
- package/lib/axios/cjs/contract/spec.js +7 -3
- package/lib/axios/cjs/contract/spec.js.map +1 -1
- package/lib/axios/cjs/errors/transaction_failed.js +62 -0
- package/lib/axios/cjs/errors/transaction_failed.js.map +1 -0
- package/lib/axios/cjs/errors/wrap_http_error.js +20 -0
- package/lib/axios/cjs/errors/wrap_http_error.js.map +1 -0
- package/lib/axios/cjs/federation/server.js +14 -15
- package/lib/axios/cjs/federation/server.js.map +1 -1
- package/lib/axios/cjs/horizon/call_builder.js +20 -0
- package/lib/axios/cjs/horizon/call_builder.js.map +1 -1
- package/lib/axios/cjs/horizon/horizon_api.js +5 -0
- package/lib/axios/cjs/horizon/horizon_api.js.map +1 -1
- package/lib/axios/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/cjs/horizon/server.js +20 -26
- package/lib/axios/cjs/horizon/server.js.map +1 -1
- package/lib/axios/cjs/horizon/trade_aggregation_call_builder.js +20 -0
- package/lib/axios/cjs/horizon/trade_aggregation_call_builder.js.map +1 -1
- package/lib/axios/cjs/index.js +4 -0
- package/lib/axios/cjs/index.js.map +1 -1
- package/lib/axios/cjs/rpc/api.js.map +1 -1
- package/lib/axios/cjs/rpc/axios.js +1 -1
- package/lib/axios/cjs/rpc/server.js +163 -8
- package/lib/axios/cjs/rpc/server.js.map +1 -1
- package/lib/axios/esm/base/auth.d.ts +141 -0
- package/lib/axios/esm/base/auth.js +106 -1
- package/lib/axios/esm/base/auth.js.map +1 -1
- package/lib/axios/esm/base/index.d.ts +2 -2
- package/lib/axios/esm/base/keypair.d.ts +27 -0
- package/lib/axios/esm/base/keypair.js +39 -0
- package/lib/axios/esm/base/keypair.js.map +1 -1
- package/lib/axios/esm/base/scval.d.ts +4 -0
- package/lib/axios/esm/base/scval.js +34 -0
- package/lib/axios/esm/base/scval.js.map +1 -1
- package/lib/axios/esm/bindings/config.js +1 -1
- package/lib/axios/esm/cli/index.js +1 -1
- package/lib/axios/esm/cli/index.js.map +1 -1
- package/lib/axios/esm/contract/assembled_transaction.d.ts +1 -1
- package/lib/axios/esm/contract/assembled_transaction.js +9 -8
- package/lib/axios/esm/contract/assembled_transaction.js.map +1 -1
- package/lib/axios/esm/contract/client.d.ts +49 -3
- package/lib/axios/esm/contract/client.js +56 -3
- package/lib/axios/esm/contract/client.js.map +1 -1
- package/lib/axios/esm/contract/spec.js +7 -3
- package/lib/axios/esm/contract/spec.js.map +1 -1
- package/lib/axios/esm/errors/index.d.ts +1 -0
- package/lib/axios/esm/errors/transaction_failed.d.ts +55 -0
- package/lib/axios/esm/errors/transaction_failed.js +60 -0
- package/lib/axios/esm/errors/transaction_failed.js.map +1 -0
- package/lib/axios/esm/errors/wrap_http_error.d.ts +20 -0
- package/lib/axios/esm/errors/wrap_http_error.js +18 -0
- package/lib/axios/esm/errors/wrap_http_error.js.map +1 -0
- package/lib/axios/esm/federation/server.js +14 -15
- package/lib/axios/esm/federation/server.js.map +1 -1
- package/lib/axios/esm/horizon/call_builder.js +20 -0
- package/lib/axios/esm/horizon/call_builder.js.map +1 -1
- package/lib/axios/esm/horizon/horizon_api.d.ts +12 -1
- package/lib/axios/esm/horizon/horizon_api.js +5 -0
- package/lib/axios/esm/horizon/horizon_api.js.map +1 -1
- package/lib/axios/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/axios/esm/horizon/server.d.ts +10 -4
- package/lib/axios/esm/horizon/server.js +20 -26
- package/lib/axios/esm/horizon/server.js.map +1 -1
- package/lib/axios/esm/horizon/trade_aggregation_call_builder.js +20 -0
- package/lib/axios/esm/horizon/trade_aggregation_call_builder.js.map +1 -1
- package/lib/axios/esm/index.js +2 -1
- package/lib/axios/esm/index.js.map +1 -1
- package/lib/axios/esm/node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/package.json +3 -0
- package/lib/axios/esm/rpc/api.d.ts +21 -0
- package/lib/axios/esm/rpc/api.js.map +1 -1
- package/lib/axios/esm/rpc/axios.js +1 -1
- package/lib/axios/esm/rpc/server.d.ts +104 -1
- package/lib/axios/esm/rpc/server.js +163 -8
- package/lib/axios/esm/rpc/server.js.map +1 -1
- package/lib/cjs/base/auth.js +107 -0
- package/lib/cjs/base/auth.js.map +1 -1
- package/lib/cjs/base/keypair.js +39 -0
- package/lib/cjs/base/keypair.js.map +1 -1
- package/lib/cjs/base/scval.js +34 -0
- package/lib/cjs/base/scval.js.map +1 -1
- package/lib/cjs/bindings/config.js +1 -1
- package/lib/cjs/cli/index.js +1 -1
- package/lib/cjs/cli/index.js.map +1 -1
- package/lib/cjs/contract/assembled_transaction.js +8 -7
- package/lib/cjs/contract/assembled_transaction.js.map +1 -1
- package/lib/cjs/contract/client.js +56 -3
- package/lib/cjs/contract/client.js.map +1 -1
- package/lib/cjs/contract/spec.js +7 -3
- package/lib/cjs/contract/spec.js.map +1 -1
- package/lib/cjs/errors/transaction_failed.js +62 -0
- package/lib/cjs/errors/transaction_failed.js.map +1 -0
- package/lib/cjs/errors/wrap_http_error.js +20 -0
- package/lib/cjs/errors/wrap_http_error.js.map +1 -0
- package/lib/cjs/federation/server.js +14 -15
- package/lib/cjs/federation/server.js.map +1 -1
- package/lib/cjs/horizon/call_builder.js +20 -0
- package/lib/cjs/horizon/call_builder.js.map +1 -1
- package/lib/cjs/horizon/horizon_api.js +5 -0
- package/lib/cjs/horizon/horizon_api.js.map +1 -1
- package/lib/cjs/horizon/horizon_axios_client.js +1 -1
- package/lib/cjs/horizon/server.js +20 -26
- package/lib/cjs/horizon/server.js.map +1 -1
- package/lib/cjs/horizon/trade_aggregation_call_builder.js +20 -0
- package/lib/cjs/horizon/trade_aggregation_call_builder.js.map +1 -1
- package/lib/cjs/index.js +4 -0
- package/lib/cjs/index.js.map +1 -1
- package/lib/cjs/rpc/api.js.map +1 -1
- package/lib/cjs/rpc/axios.js +1 -1
- package/lib/cjs/rpc/server.js +163 -8
- package/lib/cjs/rpc/server.js.map +1 -1
- package/lib/esm/base/auth.d.ts +141 -0
- package/lib/esm/base/auth.js +106 -1
- package/lib/esm/base/auth.js.map +1 -1
- package/lib/esm/base/index.d.ts +2 -2
- package/lib/esm/base/keypair.d.ts +27 -0
- package/lib/esm/base/keypair.js +39 -0
- package/lib/esm/base/keypair.js.map +1 -1
- package/lib/esm/base/scval.d.ts +4 -0
- package/lib/esm/base/scval.js +34 -0
- package/lib/esm/base/scval.js.map +1 -1
- package/lib/esm/bindings/config.js +1 -1
- package/lib/esm/cli/index.js +1 -1
- package/lib/esm/cli/index.js.map +1 -1
- package/lib/esm/contract/assembled_transaction.d.ts +1 -1
- package/lib/esm/contract/assembled_transaction.js +9 -8
- package/lib/esm/contract/assembled_transaction.js.map +1 -1
- package/lib/esm/contract/client.d.ts +49 -3
- package/lib/esm/contract/client.js +56 -3
- package/lib/esm/contract/client.js.map +1 -1
- package/lib/esm/contract/spec.js +7 -3
- package/lib/esm/contract/spec.js.map +1 -1
- package/lib/esm/errors/index.d.ts +1 -0
- package/lib/esm/errors/transaction_failed.d.ts +55 -0
- package/lib/esm/errors/transaction_failed.js +60 -0
- package/lib/esm/errors/transaction_failed.js.map +1 -0
- package/lib/esm/errors/wrap_http_error.d.ts +20 -0
- package/lib/esm/errors/wrap_http_error.js +18 -0
- package/lib/esm/errors/wrap_http_error.js.map +1 -0
- package/lib/esm/federation/server.js +14 -15
- package/lib/esm/federation/server.js.map +1 -1
- package/lib/esm/horizon/call_builder.js +20 -0
- package/lib/esm/horizon/call_builder.js.map +1 -1
- package/lib/esm/horizon/horizon_api.d.ts +12 -1
- package/lib/esm/horizon/horizon_api.js +5 -0
- package/lib/esm/horizon/horizon_api.js.map +1 -1
- package/lib/esm/horizon/horizon_axios_client.js +1 -1
- package/lib/esm/horizon/server.d.ts +10 -4
- package/lib/esm/horizon/server.js +20 -26
- package/lib/esm/horizon/server.js.map +1 -1
- package/lib/esm/horizon/trade_aggregation_call_builder.js +20 -0
- package/lib/esm/horizon/trade_aggregation_call_builder.js.map +1 -1
- package/lib/esm/index.js +2 -1
- package/lib/esm/index.js.map +1 -1
- package/lib/esm/node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/package.json +3 -0
- package/lib/esm/rpc/api.d.ts +21 -0
- package/lib/esm/rpc/api.js.map +1 -1
- package/lib/esm/rpc/axios.js +1 -1
- package/lib/esm/rpc/server.d.ts +104 -1
- package/lib/esm/rpc/server.js +163 -8
- package/lib/esm/rpc/server.js.map +1 -1
- package/package.json +27 -30
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sources":["../../../../src/federation/server.ts"],"sourcesContent":["import { StrKey } from \"../base/index.js\";\n\nimport { Config } from \"../config.js\";\nimport { BadResponseError } from \"../errors/index.js\";\nimport { Resolver } from \"../stellartoml/index.js\";\n\nimport type { Api } from \"./api.js\";\nimport { httpClient } from \"../http-client/index.js\";\nimport { validateDomain } from \"./utils.js\";\n\n/**\n * The maximum size of response from a federation server\n * @defaultValue 102400\n */\nexport const FEDERATION_RESPONSE_MAX_SIZE: number = 100 * 1024;\n\n/**\n * Federation.Server handles a network connection to a\n * [federation server](https://developers.stellar.org/docs/learn/encyclopedia/federation)\n * instance and exposes an interface for requests to that instance.\n *\n * @param serverURL - The federation server URL (ex. `https://acme.com/federation`).\n * @param domain - Domain this server represents\n * @param opts - (optional) Options object\n * @returns */\nexport class FederationServer {\n /**\n * The federation server URL (ex. `https://acme.com/federation`).\n */\n private readonly serverURL: URL; // TODO: public or private? readonly?\n\n /**\n * Domain this server represents.\n */\n private readonly domain: string; // TODO: public or private? readonly?\n\n /**\n * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue.\n */\n private readonly timeout: number; // TODO: public or private? readonly?\n\n /**\n * A helper method for handling user inputs that contain `destination` value.\n * It accepts two types of values:\n *\n * * For Stellar address (ex. `bob*stellar.org`) it splits Stellar address and then tries to find information about\n * federation server in `stellar.toml` file for a given domain. It returns a `Promise` which resolves if federation\n * server exists and user has been found and rejects in all other cases.\n * * For Account ID (ex. `GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS`) it returns a `Promise` which\n * resolves if Account ID is valid and rejects in all other cases. Please note that this method does not check\n * if the account actually exists in a ledger.\n *\n * @example\n * ```ts\n * StellarSdk.FederationServer.resolve('bob*stellar.org')\n * .then(federationRecord => {\n * // {\n * // account_id: 'GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS',\n * // memo_type: 'id',\n * // memo: 100\n * // }\n * });\n * ```\n *\n * @see <a href=\"https://developers.stellar.org/docs/learn/encyclopedia/federation\" target=\"_blank\">Federation doc</a>\n * @see <a href=\"https://developers.stellar.org/docs/issuing-assets/publishing-asset-info\" target=\"_blank\">Stellar.toml doc</a>\n * @param value - Stellar Address (ex. `bob*stellar.org`)\n * @param opts - (optional) Options object\n * @returns A promise that resolves to the federation record\n * @throws Will throw an error if the provided account ID is not a valid Ed25519 public key.\n */\n public static async resolve(\n value: string,\n opts: Api.Options = {},\n ): Promise<Api.Record> {\n // Check if `value` is in account ID format\n if (value.indexOf(\"*\") < 0) {\n if (!StrKey.isValidEd25519PublicKey(value)) {\n return Promise.reject(new Error(\"Invalid Account ID\"));\n }\n return Promise.resolve({ account_id: value });\n }\n\n const addressParts = value.split(\"*\");\n const [, domain] = addressParts;\n\n if (addressParts.length !== 2 || !domain) {\n return Promise.reject(new Error(\"Invalid Stellar address\"));\n }\n\n const federationServer = await FederationServer.createForDomain(\n domain,\n opts,\n );\n return federationServer.resolveAddress(value);\n }\n\n /**\n * Creates a `FederationServer` instance based on information from\n * [stellar.toml](https://developers.stellar.org/docs/issuing-assets/publishing-asset-info)\n * file for a given domain.\n *\n * If `stellar.toml` file does not exist for a given domain or it does not\n * contain information about a federation server Promise will reject.\n *\n * @example\n * ```ts\n * StellarSdk.FederationServer.createForDomain('acme.com')\n * .then(federationServer => {\n * // federationServer.resolveAddress('bob').then(...)\n * })\n * .catch(error => {\n * // stellar.toml does not exist or it does not contain information about federation server.\n * });\n * ```\n *\n * @see <a href=\"https://developers.stellar.org/docs/issuing-assets/publishing-asset-info\" target=\"_blank\">Stellar.toml doc</a>\n * @param domain - Domain to get federation server for\n * @param opts - (optional) Options object\n * @returns A promise that resolves to the federation record\n * @throws Will throw an error if the domain's stellar.toml file does not contain a federation server field.\n */\n public static async createForDomain(\n domain: string,\n opts: Api.Options = {},\n ): Promise<FederationServer> {\n validateDomain(domain);\n const tomlObject = await Resolver.resolve(domain, opts);\n if (!tomlObject.FEDERATION_SERVER) {\n return Promise.reject(\n new Error(\"stellar.toml does not contain FEDERATION_SERVER field\"),\n );\n }\n return new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts);\n }\n\n public constructor(\n serverURL: string,\n domain: string,\n opts: Api.Options = {},\n ) {\n this.serverURL = new URL(serverURL);\n this.domain = domain;\n validateDomain(domain);\n\n const allowHttp =\n typeof opts.allowHttp === \"undefined\"\n ? Config.isAllowHttp()\n : opts.allowHttp;\n\n this.timeout =\n typeof opts.timeout === \"undefined\" ? Config.getTimeout() : opts.timeout;\n\n if (this.serverURL.protocol !== \"https:\" && !allowHttp) {\n throw new Error(\"Cannot connect to insecure federation server\");\n }\n }\n\n /**\n * Get the federation record if the user was found for a given Stellar address\n * @see <a href=\"https://developers.stellar.org/docs/encyclopedia/federation\" target=\"_blank\">Federation doc</a>\n * @param address - Stellar address (ex. `bob*stellar.org`). If `FederationServer` was instantiated with `domain` param only username (ex. `bob`) can be passed.\n * @returns A promise that resolves to the federation record\n * @throws Will throw an error if the federated address does not contain a domain, or if the server object was not instantiated with a `domain` parameter\n */\n public async resolveAddress(address: string): Promise<Api.Record> {\n let stellarAddress = address;\n if (address.indexOf(\"*\") < 0) {\n if (!this.domain) {\n return Promise.reject(\n new Error(\n \"Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object.\",\n ),\n );\n }\n stellarAddress = `${address}*${this.domain}`;\n }\n const url = new URL(this.serverURL);\n url.search = \"\";\n url.searchParams.set(\"type\", \"name\");\n url.searchParams.set(\"q\", stellarAddress);\n return this._sendRequest(url);\n }\n\n /**\n * Given an account ID, get their federation record if the user was found\n * @see <a href=\"https://developers.stellar.org/docs/encyclopedia/federation\" target=\"_blank\">Federation doc</a>\n * @param accountId - Account ID (ex. `GBYNR2QJXLBCBTRN44MRORCMI4YO7FZPFBCNOKTOBCAAFC7KC3LNPRYS`)\n * @returns A promise that resolves to the federation record\n * @throws Will throw an error if the federation server returns an invalid memo value.\n * @throws Will throw an error if the federation server's response exceeds the allowed maximum size.\n * @throws Will throw an error if the server query fails with an improper response.\n */\n public async resolveAccountId(accountId: string): Promise<Api.Record> {\n const url = new URL(this.serverURL);\n url.search = \"\";\n url.searchParams.set(\"type\", \"id\");\n url.searchParams.set(\"q\", accountId);\n return this._sendRequest(url);\n }\n\n /**\n * Given a transactionId, get the federation record if the sender of the transaction was found\n * @see <a href=\"https://developers.stellar.org/docs/glossary/federation/\" target=\"_blank\">Federation doc</a>\n * @param transactionId - Transaction ID (ex. `3389e9f0f1a65f19736cacf544c2e825313e8447f569233bb8db39aa607c8889`)\n * @returns A promise that resolves to the federation record\n * @throws Will throw an error if the federation server returns an invalid memo value.\n * @throws Will throw an error if the federation server's response exceeds the allowed maximum size.\n * @throws Will throw an error if the server query fails with an improper response.\n */\n public async resolveTransactionId(\n transactionId: string,\n ): Promise<Api.Record> {\n const url = new URL(this.serverURL);\n url.search = \"\";\n url.searchParams.set(\"type\", \"txid\");\n url.searchParams.set(\"q\", transactionId);\n return this._sendRequest(url);\n }\n\n private async _sendRequest(url: URL) {\n const timeout = this.timeout;\n\n return httpClient\n .get(url.toString(), {\n maxContentLength: FEDERATION_RESPONSE_MAX_SIZE,\n timeout,\n })\n .then((response) => {\n if (\n typeof response.data.memo !== \"undefined\" &&\n typeof response.data.memo !== \"string\"\n ) {\n throw new Error(\"memo value should be of type string\");\n }\n return response.data;\n })\n .catch((response) => {\n if (response instanceof Error) {\n if (response.message.match(/^maxContentLength size/)) {\n throw new Error(\n `federation response exceeds allowed size of ${FEDERATION_RESPONSE_MAX_SIZE}`,\n );\n } else {\n return Promise.reject(response);\n }\n } else {\n return Promise.reject(\n new BadResponseError(\n `Server query failed. Server responded: ${response.status} ${response.statusText}`,\n response.data,\n ),\n );\n }\n });\n }\n}\n"],"names":["httpClient"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAcO,MAAM,+BAAuC,GAAA,GAAM;AAWnD,MAAM,gBAAA,CAAiB;AAAA;AAAA;AAAA;AAAA,EAIX,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,MAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,OAAA;AAAA;AAAA;AAAA;AAAA;AAAA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aAAa,GAAG,CAAA;AAAA,EAC9B;AAAA,EAEA,MAAc,aAAa,GAAA,EAAU;AACnC,IAAA,MAAM,UAAU,IAAA,CAAK,OAAA;AAErB,IAAA,OAAOA,WAAA,CACJ,GAAA,CAAI,GAAA,CAAI,QAAA,EAAS,EAAG;AAAA,MACnB,gBAAA,EAAkB,4BAAA;AAAA,MAClB;AAAA,KACD,CAAA,CACA,IAAA,CAAK,CAAC,QAAA,KAAa;AAClB,MAAA,IACE,OAAO,SAAS,IAAA,CAAK,IAAA,KAAS,eAC9B,OAAO,QAAA,CAAS,IAAA,CAAK,IAAA,KAAS,QAAA,EAC9B;AACA,QAAA,MAAM,IAAI,MAAM,qCAAqC,CAAA;AAAA,MACvD;AACA,MAAA,OAAO,QAAA,CAAS,IAAA;AAAA,IAClB,CAAC,CAAA,CACA,KAAA,CAAM,CAAC,QAAA,KAAa;AACnB,MAAA,IAAI,oBAAoB,KAAA,EAAO;AAC7B,QAAA,IAAI,QAAA,CAAS,OAAA,CAAQ,KAAA,CAAM,wBAAwB,CAAA,EAAG;AACpD,UAAA,MAAM,IAAI,KAAA;AAAA,YACR,+CAA+C,4BAA4B,CAAA;AAAA,WAC7E;AAAA,QACF,CAAA,MAAO;AACL,UAAA,OAAO,OAAA,CAAQ,OAAO,QAAQ,CAAA;AAAA,QAChC;AAAA,MACF,CAAA,MAAO;AACL,QAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,UACb,IAAI,gBAAA;AAAA,YACF,CAAA,uCAAA,EAA0C,QAAA,CAAS,MAAM,CAAA,CAAA,EAAI,SAAS,UAAU,CAAA,CAAA;AAAA,YAChF,QAAA,CAAS;AAAA;AACX,SACF;AAAA,MACF;AAAA,IACF,CAAC,CAAA;AAAA,EACL;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"server.js","sources":["../../../../src/federation/server.ts"],"sourcesContent":["import { StrKey } from \"../base/index.js\";\n\nimport { Config } from \"../config.js\";\nimport { BadResponseError } from \"../errors/index.js\";\nimport { wrapHttpError } from \"../errors/wrap_http_error.js\";\nimport { Resolver } from \"../stellartoml/index.js\";\n\nimport type { Api } from \"./api.js\";\nimport { httpClient } from \"../http-client/index.js\";\nimport { validateDomain } from \"./utils.js\";\n\n/**\n * The maximum size of response from a federation server\n * @defaultValue 102400\n */\nexport const FEDERATION_RESPONSE_MAX_SIZE: number = 100 * 1024;\n\n/**\n * Federation.Server handles a network connection to a\n * [federation server](https://developers.stellar.org/docs/learn/encyclopedia/federation)\n * instance and exposes an interface for requests to that instance.\n *\n * @param serverURL - The federation server URL (ex. `https://acme.com/federation`).\n * @param domain - Domain this server represents\n * @param opts - (optional) Options object\n * @returns */\nexport class FederationServer {\n /**\n * The federation server URL (ex. `https://acme.com/federation`).\n */\n private readonly serverURL: URL; // TODO: public or private? readonly?\n\n /**\n * Domain this server represents.\n */\n private readonly domain: string; // TODO: public or private? readonly?\n\n /**\n * Allow a timeout, default: 0. Allows user to avoid nasty lag due to TOML resolve issue.\n */\n private readonly timeout: number; // TODO: public or private? readonly?\n\n /**\n * A helper method for handling user inputs that contain `destination` value.\n * It accepts two types of values:\n *\n * * For Stellar address (ex. `bob*stellar.org`) it splits Stellar address and then tries to find information about\n * federation server in `stellar.toml` file for a given domain. It returns a `Promise` which resolves if federation\n * server exists and user has been found and rejects in all other cases.\n * * For Account ID (ex. `GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS`) it returns a `Promise` which\n * resolves if Account ID is valid and rejects in all other cases. Please note that this method does not check\n * if the account actually exists in a ledger.\n *\n * @example\n * ```ts\n * StellarSdk.FederationServer.resolve('bob*stellar.org')\n * .then(federationRecord => {\n * // {\n * // account_id: 'GB5XVAABEQMY63WTHDQ5RXADGYF345VWMNPTN2GFUDZT57D57ZQTJ7PS',\n * // memo_type: 'id',\n * // memo: 100\n * // }\n * });\n * ```\n *\n * @see <a href=\"https://developers.stellar.org/docs/learn/encyclopedia/federation\" target=\"_blank\">Federation doc</a>\n * @see <a href=\"https://developers.stellar.org/docs/issuing-assets/publishing-asset-info\" target=\"_blank\">Stellar.toml doc</a>\n * @param value - Stellar Address (ex. `bob*stellar.org`)\n * @param opts - (optional) Options object\n * @returns A promise that resolves to the federation record\n * @throws Will throw an error if the provided account ID is not a valid Ed25519 public key.\n */\n public static async resolve(\n value: string,\n opts: Api.Options = {},\n ): Promise<Api.Record> {\n // Check if `value` is in account ID format\n if (value.indexOf(\"*\") < 0) {\n if (!StrKey.isValidEd25519PublicKey(value)) {\n return Promise.reject(new Error(\"Invalid Account ID\"));\n }\n return Promise.resolve({ account_id: value });\n }\n\n const addressParts = value.split(\"*\");\n const [, domain] = addressParts;\n\n if (addressParts.length !== 2 || !domain) {\n return Promise.reject(new Error(\"Invalid Stellar address\"));\n }\n\n const federationServer = await FederationServer.createForDomain(\n domain,\n opts,\n );\n return federationServer.resolveAddress(value);\n }\n\n /**\n * Creates a `FederationServer` instance based on information from\n * [stellar.toml](https://developers.stellar.org/docs/issuing-assets/publishing-asset-info)\n * file for a given domain.\n *\n * If `stellar.toml` file does not exist for a given domain or it does not\n * contain information about a federation server Promise will reject.\n *\n * @example\n * ```ts\n * StellarSdk.FederationServer.createForDomain('acme.com')\n * .then(federationServer => {\n * // federationServer.resolveAddress('bob').then(...)\n * })\n * .catch(error => {\n * // stellar.toml does not exist or it does not contain information about federation server.\n * });\n * ```\n *\n * @see <a href=\"https://developers.stellar.org/docs/issuing-assets/publishing-asset-info\" target=\"_blank\">Stellar.toml doc</a>\n * @param domain - Domain to get federation server for\n * @param opts - (optional) Options object\n * @returns A promise that resolves to the federation record\n * @throws Will throw an error if the domain's stellar.toml file does not contain a federation server field.\n */\n public static async createForDomain(\n domain: string,\n opts: Api.Options = {},\n ): Promise<FederationServer> {\n validateDomain(domain);\n const tomlObject = await Resolver.resolve(domain, opts);\n if (!tomlObject.FEDERATION_SERVER) {\n return Promise.reject(\n new Error(\"stellar.toml does not contain FEDERATION_SERVER field\"),\n );\n }\n return new FederationServer(tomlObject.FEDERATION_SERVER, domain, opts);\n }\n\n public constructor(\n serverURL: string,\n domain: string,\n opts: Api.Options = {},\n ) {\n this.serverURL = new URL(serverURL);\n this.domain = domain;\n validateDomain(domain);\n\n const allowHttp =\n typeof opts.allowHttp === \"undefined\"\n ? Config.isAllowHttp()\n : opts.allowHttp;\n\n this.timeout =\n typeof opts.timeout === \"undefined\" ? Config.getTimeout() : opts.timeout;\n\n if (this.serverURL.protocol !== \"https:\" && !allowHttp) {\n throw new Error(\"Cannot connect to insecure federation server\");\n }\n }\n\n /**\n * Get the federation record if the user was found for a given Stellar address\n * @see <a href=\"https://developers.stellar.org/docs/encyclopedia/federation\" target=\"_blank\">Federation doc</a>\n * @param address - Stellar address (ex. `bob*stellar.org`). If `FederationServer` was instantiated with `domain` param only username (ex. `bob`) can be passed.\n * @returns A promise that resolves to the federation record\n * @throws Will throw an error if the federated address does not contain a domain, or if the server object was not instantiated with a `domain` parameter\n */\n public async resolveAddress(address: string): Promise<Api.Record> {\n let stellarAddress = address;\n if (address.indexOf(\"*\") < 0) {\n if (!this.domain) {\n return Promise.reject(\n new Error(\n \"Unknown domain. Make sure `address` contains a domain (ex. `bob*stellar.org`) or pass `domain` parameter when instantiating the server object.\",\n ),\n );\n }\n stellarAddress = `${address}*${this.domain}`;\n }\n const url = new URL(this.serverURL);\n url.search = \"\";\n url.searchParams.set(\"type\", \"name\");\n url.searchParams.set(\"q\", stellarAddress);\n return this._sendRequest(url);\n }\n\n /**\n * Given an account ID, get their federation record if the user was found\n * @see <a href=\"https://developers.stellar.org/docs/encyclopedia/federation\" target=\"_blank\">Federation doc</a>\n * @param accountId - Account ID (ex. `GBYNR2QJXLBCBTRN44MRORCMI4YO7FZPFBCNOKTOBCAAFC7KC3LNPRYS`)\n * @returns A promise that resolves to the federation record\n * @throws Will throw an error if the federation server returns an invalid memo value.\n * @throws Will throw an error if the federation server's response exceeds the allowed maximum size.\n * @throws Will throw an error if the server query fails with an improper response.\n */\n public async resolveAccountId(accountId: string): Promise<Api.Record> {\n const url = new URL(this.serverURL);\n url.search = \"\";\n url.searchParams.set(\"type\", \"id\");\n url.searchParams.set(\"q\", accountId);\n return this._sendRequest(url);\n }\n\n /**\n * Given a transactionId, get the federation record if the sender of the transaction was found\n * @see <a href=\"https://developers.stellar.org/docs/glossary/federation/\" target=\"_blank\">Federation doc</a>\n * @param transactionId - Transaction ID (ex. `3389e9f0f1a65f19736cacf544c2e825313e8447f569233bb8db39aa607c8889`)\n * @returns A promise that resolves to the federation record\n * @throws Will throw an error if the federation server returns an invalid memo value.\n * @throws Will throw an error if the federation server's response exceeds the allowed maximum size.\n * @throws Will throw an error if the server query fails with an improper response.\n */\n public async resolveTransactionId(\n transactionId: string,\n ): Promise<Api.Record> {\n const url = new URL(this.serverURL);\n url.search = \"\";\n url.searchParams.set(\"type\", \"txid\");\n url.searchParams.set(\"q\", transactionId);\n return this._sendRequest(url);\n }\n\n private async _sendRequest(url: URL) {\n const timeout = this.timeout;\n\n return httpClient\n .get(url.toString(), {\n maxContentLength: FEDERATION_RESPONSE_MAX_SIZE,\n timeout,\n })\n .then((response) => {\n if (\n typeof response.data.memo !== \"undefined\" &&\n typeof response.data.memo !== \"string\"\n ) {\n throw new Error(\"memo value should be of type string\");\n }\n return response.data;\n })\n .catch((error) => {\n if (\n error instanceof Error &&\n error.message.match(/^maxContentLength size/)\n ) {\n throw new Error(\n `federation response exceeds allowed size of ${FEDERATION_RESPONSE_MAX_SIZE}`,\n );\n }\n return Promise.reject(\n wrapHttpError(\n error,\n (details) =>\n new BadResponseError(\n `Server query failed. Server responded: ${details.status} ${details.statusText}`,\n details,\n ),\n ),\n );\n });\n }\n}\n"],"names":["httpClient"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAeO,MAAM,+BAAuC,GAAA,GAAM;AAWnD,MAAM,gBAAA,CAAiB;AAAA;AAAA;AAAA;AAAA,EAIX,SAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,MAAA;AAAA;A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AA,CAAI,GAAA,EAAK,aAAa,CAAA;AACvC,IAAA,OAAO,IAAA,CAAK,aAAa,GAAG,CAAA;AAAA,EAC9B;AAAA,EAEA,MAAc,aAAa,GAAA,EAAU;AACnC,IAAA,MAAM,UAAU,IAAA,CAAK,OAAA;AAErB,IAAA,OAAOA,WAAA,CACJ,GAAA,CAAI,GAAA,CAAI,QAAA,EAAS,EAAG;AAAA,MACnB,gBAAA,EAAkB,4BAAA;AAAA,MAClB;AAAA,KACD,CAAA,CACA,IAAA,CAAK,CAAC,QAAA,KAAa;AAClB,MAAA,IACE,OAAO,SAAS,IAAA,CAAK,IAAA,KAAS,eAC9B,OAAO,QAAA,CAAS,IAAA,CAAK,IAAA,KAAS,QAAA,EAC9B;AACA,QAAA,MAAM,IAAI,MAAM,qCAAqC,CAAA;AAAA,MACvD;AACA,MAAA,OAAO,QAAA,CAAS,IAAA;AAAA,IAClB,CAAC,CAAA,CACA,KAAA,CAAM,CAAC,KAAA,KAAU;AAChB,MAAA,IACE,iBAAiB,KAAA,IACjB,KAAA,CAAM,OAAA,CAAQ,KAAA,CAAM,wBAAwB,CAAA,EAC5C;AACA,QAAA,MAAM,IAAI,KAAA;AAAA,UACR,+CAA+C,4BAA4B,CAAA;AAAA,SAC7E;AAAA,MACF;AACA,MAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,QACb,aAAA;AAAA,UACE,KAAA;AAAA,UACA,CAAC,YACC,IAAI,gBAAA;AAAA,YACF,CAAA,uCAAA,EAA0C,OAAA,CAAQ,MAAM,CAAA,CAAA,EAAI,QAAQ,UAAU,CAAA,CAAA;AAAA,YAC9E;AAAA;AACF;AACJ,OACF;AAAA,IACF,CAAC,CAAA;AAAA,EACL;AACF;;;;"}
|
|
@@ -2,6 +2,26 @@ import { EventSource } from 'eventsource';
|
|
|
2
2
|
import { NetworkError } from '../errors/network.js';
|
|
3
3
|
import { NotFoundError } from '../errors/not_found.js';
|
|
4
4
|
import { BadRequestError } from '../errors/bad_request.js';
|
|
5
|
+
import '../node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/src/int.js';
|
|
6
|
+
import '../node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/src/hyper.js';
|
|
7
|
+
import '../node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/src/unsigned-int.js';
|
|
8
|
+
import '../node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/src/unsigned-hyper.js';
|
|
9
|
+
import '../node_modules/.pnpm/@stellar_js-xdr@4.0.0/node_modules/@stellar/js-xdr/src/xdr-type.js';
|
|
10
|
+
import 'buffer';
|
|
11
|
+
import '../base/generated/curr_generated.js';
|
|
12
|
+
import '@noble/hashes/sha2.js';
|
|
13
|
+
import '../base/signing.js';
|
|
14
|
+
import '../base/keypair.js';
|
|
15
|
+
import 'base32.js';
|
|
16
|
+
import '../base/util/continued_fraction.js';
|
|
17
|
+
import '../base/util/bignumber.js';
|
|
18
|
+
import '../base/transaction_builder.js';
|
|
19
|
+
import '../base/muxed_account.js';
|
|
20
|
+
import '../base/scval.js';
|
|
21
|
+
import '../base/numbers/uint128.js';
|
|
22
|
+
import '../base/numbers/uint256.js';
|
|
23
|
+
import '../base/numbers/int128.js';
|
|
24
|
+
import '../base/numbers/int256.js';
|
|
5
25
|
import { version } from './horizon_axios_client.js';
|
|
6
26
|
import { expandUriTemplate } from '../utils/url.js';
|
|
7
27
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"call_builder.js","sources":["../../../../src/horizon/call_builder.ts"],"sourcesContent":["import { EventSource } from \"eventsource\";\n\nimport {\n BadRequestError,\n NetworkError,\n NotFoundError,\n} from \"../errors/index.js\";\nimport { HorizonApi } from \"./horizon_api.js\";\nimport { version } from \"./horizon_axios_client.js\";\nimport type { HttpClient } from \"../http-client/index.js\";\nimport { ServerApi } from \"./server_api.js\";\nimport type { Server } from \"../federation/index.js\";\nimport { expandUriTemplate } from \"../utils/url.js\";\n\n// Resources which can be included in the Horizon response via the `join`\n// query-param.\nconst JOINABLE = [\"transaction\"];\n\nexport interface EventSourceOptions<T> {\n onmessage?: (\n value: T extends ServerApi.CollectionPage<infer U> ? U : T,\n ) => void;\n onerror?: (event: MessageEvent) => void;\n reconnectTimeout?: number;\n}\n\n/**\n * Creates a new {@link CallBuilder} pointed to server defined by serverUrl.\n *\n * This is an **abstract** class. Do not create this object directly, use {@link Server} class.\n * @param serverUrl - URL of Horizon server\n */\nexport class CallBuilder<\n T extends\n | HorizonApi.FeeStatsResponse\n | HorizonApi.BaseResponse\n | HorizonApi.RootResponse\n | ServerApi.CollectionPage<HorizonApi.BaseResponse>,\n> {\n protected url: URL;\n\n public filter: string[][];\n\n protected originalSegments: string[];\n\n protected neighborRoot: string;\n\n protected httpClient: HttpClient;\n\n constructor(\n serverUrl: URL,\n httpClient: HttpClient,\n neighborRoot: string = \"\",\n ) {\n this.url = new URL(serverUrl);\n this.filter = [];\n\n this.originalSegments = this.url.pathname\n .split(\"/\")\n .filter((s) => s.length > 0);\n this.neighborRoot = neighborRoot;\n this.httpClient = httpClient;\n }\n\n protected setPath(...segments: string[]): void {\n const endpointSegments = segments.flatMap((segment) =>\n segment.split(\"/\").filter((s) => s.length > 0),\n );\n this.url.pathname = this.originalSegments\n .concat(endpointSegments)\n .join(\"/\");\n }\n\n /**\n * Triggers a HTTP request using this builder's current configuration.\n * @returns a Promise that resolves to the server's response.\n */\n public call(): Promise<T> {\n this.checkFilter();\n return this._sendNormalRequest(this.url).then((r) =>\n this._parseResponse(r),\n );\n }\n //// TODO: Migrate to async, BUT that's a change in behavior and tests \"rejects two filters\" will fail.\n //// It's because async will check within promise, which makes more sense when using awaits instead of Promises.\n // public async call(): Promise<T> {\n // this.checkFilter();\n // const r = await this._sendNormalRequest(this.url);\n // return this._parseResponse(r);\n // }\n //// /* actually equals */\n //// public call(): Promise<T> {\n //// return Promise.resolve().then(() => {\n //// this.checkFilter();\n //// return this._sendNormalRequest(this.url)\n //// }).then((r) => {\n //// this._parseResponse(r)\n //// });\n //// }\n\n /**\n * Creates an EventSource that listens for incoming messages from the server. To stop listening for new\n * events call the function returned by this method.\n * @see [Horizon Response Format](https://developers.stellar.org/api/introduction/response-format/)\n * @see [MDN EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)\n * @param options - (optional) EventSource options.\n * - `onmessage` (optional): Callback function to handle incoming messages.\n * - `onerror` (optional): Callback function to handle errors.\n * - `reconnectTimeout` (optional): Custom stream connection timeout in ms, default is 15 seconds.\n * @returns Close function. Run to close the connection and stop listening for new events.\n */\n public stream(\n options: EventSourceOptions<\n T extends ServerApi.CollectionPage<infer U> ? U : T\n > = {},\n ): () => void {\n this.checkFilter();\n\n const streamUrl = new URL(this.url);\n streamUrl.searchParams.set(\"X-Client-Name\", \"js-stellar-sdk\");\n streamUrl.searchParams.set(\"X-Client-Version\", version);\n\n // Extract custom app headers from httpClient defaults and add as query params\n // (EventSource doesn't support custom headers, so we use query params)\n const { headers } = this.httpClient.defaults;\n if (headers) {\n const headerNames = [\"X-App-Name\", \"X-App-Version\"];\n headerNames.forEach((name) => {\n let value: string | undefined;\n if (headers instanceof Headers) {\n value = headers.get(name) ?? undefined;\n } else if (Array.isArray(headers)) {\n const entry = headers.find(([key]) => key === name);\n value = entry?.[1];\n } else {\n value = headers[name];\n }\n if (value) {\n streamUrl.searchParams.set(name, value);\n }\n });\n }\n\n // EventSource object\n let es: EventSource;\n // timeout is the id of the timeout to be triggered if there were no new messages\n // in the last 15 seconds. The timeout is reset when a new message arrive.\n // It prevents closing EventSource object in case of 504 errors as `readyState`\n // property is not reliable.\n let timeout: ReturnType<typeof setTimeout>;\n\n const createTimeout = () => {\n timeout = setTimeout(\n () => {\n es?.close();\n\n es = createEventSource();\n },\n options.reconnectTimeout || 15 * 1000,\n );\n };\n\n const createEventSource = (): EventSource => {\n try {\n es = new EventSource(streamUrl.toString());\n } catch (err) {\n if (options.onerror) {\n options.onerror(err as MessageEvent);\n }\n }\n\n createTimeout();\n if (!es) {\n return es;\n }\n\n // when receiving the close message from Horizon we should close the\n // connection and recreate the event source (basically retrying forever)\n let closed = false;\n const onClose = () => {\n if (closed) {\n return;\n }\n\n clearTimeout(timeout);\n\n es.close();\n createEventSource();\n closed = true;\n };\n\n const onMessage = (message: any) => {\n if (message.type === \"close\") {\n onClose();\n return;\n }\n\n const result = message.data\n ? this._parseRecord(JSON.parse(message.data))\n : message;\n if (result.paging_token) {\n streamUrl.searchParams.set(\"cursor\", result.paging_token);\n }\n clearTimeout(timeout);\n createTimeout();\n if (typeof options.onmessage !== \"undefined\") {\n options.onmessage(result);\n }\n };\n\n const onError = (error: any) => {\n if (options.onerror) {\n options.onerror(error as MessageEvent);\n }\n };\n\n if (es.addEventListener) {\n es.addEventListener(\"message\", onMessage.bind(this));\n es.addEventListener(\"error\", onError.bind(this));\n es.addEventListener(\"close\", onClose.bind(this));\n } else {\n es.onmessage = onMessage.bind(this);\n es.onerror = onError.bind(this);\n }\n\n return es;\n };\n\n createEventSource();\n return () => {\n clearTimeout(timeout);\n es?.close();\n };\n }\n\n /**\n * Sets `cursor` parameter for the current call. Returns the CallBuilder object on which this method has been called.\n * @see [Paging](https://developers.stellar.org/api/introduction/pagination/)\n * @param cursor - A cursor is a value that points to a specific location in a collection of resources.\n * @returns current CallBuilder instance\n */\n public cursor(cursor: string): this {\n this.url.searchParams.set(\"cursor\", cursor);\n return this;\n }\n\n /**\n * Sets `limit` parameter for the current call. Returns the CallBuilder object on which this method has been called.\n * @see [Paging](https://developers.stellar.org/api/introduction/pagination/)\n * @param recordsNumber - Number of records the server should return.\n * @returns current CallBuilder instance\n */\n public limit(recordsNumber: number): this {\n this.url.searchParams.set(\"limit\", recordsNumber.toString());\n return this;\n }\n\n /**\n * Sets `order` parameter for the current call. Returns the CallBuilder object on which this method has been called.\n * @param direction - Sort direction\n * @returns current CallBuilder instance\n */\n public order(direction: \"asc\" | \"desc\"): this {\n this.url.searchParams.set(\"order\", direction);\n return this;\n }\n\n /**\n * Sets `join` parameter for the current call. The `join` parameter\n * includes the requested resource in the response. Currently, the\n * only valid value for the parameter is `transactions` and is only\n * supported on the operations and payments endpoints. The response\n * will include a `transaction` field for each operation in the\n * response.\n *\n * @param include - join Records to be included in the response.\n * @returns current CallBuilder instance.\n */\n public join(include: \"transactions\"): this {\n this.url.searchParams.set(\"join\", include);\n return this;\n }\n\n /**\n * A helper method to craft queries to \"neighbor\" endpoints.\n *\n * For example, we have an `/effects` suffix endpoint on many different\n * \"root\" endpoints, such as `/transactions/:id` and `/accounts/:id`. So,\n * it's helpful to be able to conveniently create queries to the\n * `/accounts/:id/effects` endpoint:\n *\n * `this.forEndpoint(\"accounts\", accountId)`.\n *\n * @param endpoint - neighbor endpoint in question, like /operations\n * @param param - filter parameter, like an operation ID\n *\n * @returns this CallBuilder instance\n */\n protected forEndpoint(endpoint: string, param: string): this {\n if (this.neighborRoot === \"\") {\n throw new Error(\"Invalid usage: neighborRoot not set in constructor\");\n }\n this.filter.push([endpoint, param, this.neighborRoot]);\n return this;\n }\n\n /**\n * @hidden\n * @returns */\n private checkFilter(): void {\n if (this.filter.length >= 2) {\n throw new BadRequestError(\"Too many filters specified\", this.filter);\n }\n\n if (this.filter.length === 1) {\n // append filters to original segments\n const newSegment = this.originalSegments.concat(this.filter[0]);\n this.url.pathname = newSegment.join(\"/\");\n }\n }\n\n /**\n * Convert a link object to a function that fetches that link.\n * @hidden\n * @param link - A link object\n * - `href`: the URI of the link\n * - `templated` (optional): Whether the link is templated\n * @returns A function that requests the link\n */\n private _requestFnForLink(\n link: HorizonApi.ResponseLink,\n ): (opts?: any) => any {\n return async (opts: any = {}) => {\n let uri;\n\n if (link.templated) {\n uri = new URL(expandUriTemplate(link.href, opts), this.url);\n } else {\n uri = new URL(link.href, this.url);\n }\n\n const r = await this._sendNormalRequest(uri);\n return this._parseResponse(r);\n };\n }\n\n /**\n * Given the json response, find and convert each link into a function that\n * calls that link.\n * @hidden\n * @param json - JSON response\n * @returns JSON response with string links replaced with functions\n */\n private _parseRecord(json: any): any {\n if (!json._links) {\n return json;\n }\n Object.keys(json._links).forEach((key) => {\n const n = json._links[key];\n let included = false;\n // If the key with the link name already exists, create a copy\n if (typeof json[key] !== \"undefined\") {\n json[`${key}_attr`] = json[key];\n included = true;\n }\n\n /*\n If the resource can be side-loaded using `join` query-param then don't\n try to load from the server. We need to whitelist the keys which are\n joinable, since there are other keys like `ledger` which is included in\n some payloads, but doesn't represent the ledger resource, in that\n scenario we want to make the call to the server using the URL from links.\n */\n if (included && JOINABLE.indexOf(key) >= 0) {\n const record = this._parseRecord(json[key]);\n // Maintain a promise based API so the behavior is the same whether you\n // are loading from the server or in-memory (via join).\n // eslint-disable-next-line @typescript-eslint/require-await\n json[key] = async () => record;\n } else {\n json[key] = this._requestFnForLink(n as HorizonApi.ResponseLink);\n }\n });\n return json;\n }\n\n private async _sendNormalRequest(initialUrl: URL) {\n const url = new URL(initialUrl);\n\n // Always use the configured server's authority and protocol.\n // Horizon returns absolute URLs in _links that would bypass reverse proxies.\n url.protocol = this.url.protocol;\n url.host = this.url.host;\n\n return this.httpClient\n .get(url.toString())\n .then((response) => response.data)\n .catch(this._handleNetworkError);\n }\n\n /**\n * @hidden\n * @param json - Response object\n * @returns Extended response\n */\n private _parseResponse(json: any) {\n if (json._embedded && json._embedded.records) {\n return this._toCollectionPage(json);\n }\n return this._parseRecord(json);\n }\n\n /**\n * @hidden\n * @param json - Response object\n * @returns Extended response object\n */\n private _toCollectionPage(json: any): any {\n for (let i = 0; i < json._embedded.records.length; i += 1) {\n json._embedded.records[i] = this._parseRecord(json._embedded.records[i]);\n }\n return {\n records: json._embedded.records,\n next: async () => {\n const r = await this._sendNormalRequest(\n new URL(json._links.next.href, this.url),\n );\n return this._toCollectionPage(r);\n },\n prev: async () => {\n const r = await this._sendNormalRequest(\n new URL(json._links.prev.href, this.url),\n );\n return this._toCollectionPage(r);\n },\n };\n }\n\n /**\n * @hidden\n * @param error - Network error object\n * @returns Promise that rejects with a human-readable error\n */\n private async _handleNetworkError(error: NetworkError): Promise<void> {\n if (error.response && error.response.status) {\n switch (error.response.status) {\n case 404:\n return Promise.reject(\n new NotFoundError(\n error.response.statusText ?? \"Not Found\",\n error.response.data,\n ),\n );\n default:\n return Promise.reject(\n new NetworkError(\n error.response.statusText ?? \"Unknown\",\n error.response.data,\n ),\n );\n }\n } else {\n return Promise.reject(new Error(error.message));\n }\n }\n}\n"],"names":[],"mappings":";;;;;;;AAgBA,MAAM,QAAA,GAAW,CAAC,aAAa,CAAA;AAgBxB,MAAM,WAAA,CAMX;AAAA,EACU,GAAA;AAAA,EAEH,MAAA;AAAA,EAEG,gBAAA;AAAA,EAEA,YAAA;AAAA,EAEA,UAAA;AAAA,EAEV,WAAA,CACE,SAAA,EACA,UAAA,EACA,YAAA,GAAuB,EAAA,EACvB;AACA,IAAA,IAAA,CAAK,GAAA,GAAM,IAAI,GAAA,CAAI,SAAS,CAAA;AAC5B,IAAA,IAAA,CAAK,SAAS,EAAC;AAEf,IAAA,IAAA,CAAK,gBAAA,GAAmB,IAAA,CAAK,GAAA,CAAI,QAAA,CAC9B,KAAA,CAAM,GAAG,CAAA,CACT,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,MAAA,GAAS,CAAC,CAAA;AAC7B,IAAA,IAAA,CAAK,YAAA,GAAe,YAAA;AACpB,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA;AAAA,EACpB;AAAA,EAEU,WAAW,QAAA,EAA0B;AAC7C,IAAA,MAAM,mBAAmB,QAAA,CAAS,OAAA;AAAA,MAAQ,CAAC,OAAA,KACzC,OAAA,CAAQ,KAAA,CAAM,GAAG,CAAA,CAAE,MAAA,CAAO,CAAC,CAAA,KAAM,CAAA,CAAE,MAAA,GAAS,CAAC;AAAA,KAC/C;AACA,IAAA,IAAA,CAAK,GAAA,CAAI,WAAW,IAAA,CAAK,gBAAA,CACtB,OAAO,gBAAgB,CA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AA,KACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAc,oBAAoB,KAAA,EAAoC;AACpE,IAAA,IAAI,KAAA,CAAM,QAAA,IAAY,KAAA,CAAM,QAAA,CAAS,MAAA,EAAQ;AAC3C,MAAA,QAAQ,KAAA,CAAM,SAAS,MAAA;AAAQ,QAC7B,KAAK,GAAA;AACH,UAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,YACb,IAAI,aAAA;AAAA,cACF,KAAA,CAAM,SAAS,UAAA,IAAc,WAAA;AAAA,cAC7B,MAAM,QAAA,CAAS;AAAA;AACjB,WACF;AAAA,QACF;AACE,UAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,YACb,IAAI,YAAA;AAAA,cACF,KAAA,CAAM,SAAS,UAAA,IAAc,SAAA;AAAA,cAC7B,MAAM,QAAA,CAAS;AAAA;AACjB,WACF;AAAA;AACJ,IACF,CAAA,MAAO;AACL,MAAA,OAAO,QAAQ,MAAA,CAAO,IAAI,KAAA,CAAM,KAAA,CAAM,OAAO,CAAC,CAAA;AAAA,IAChD;AAAA,EACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"call_builder.js","sources":["../../../../src/horizon/call_builder.ts"],"sourcesContent":["import { EventSource } from \"eventsource\";\n\nimport {\n BadRequestError,\n NetworkError,\n NotFoundError,\n} from \"../errors/index.js\";\nimport { HorizonApi } from \"./horizon_api.js\";\nimport { version } from \"./horizon_axios_client.js\";\nimport type { HttpClient } from \"../http-client/index.js\";\nimport { ServerApi } from \"./server_api.js\";\nimport type { Server } from \"../federation/index.js\";\nimport { expandUriTemplate } from \"../utils/url.js\";\n\n// Resources which can be included in the Horizon response via the `join`\n// query-param.\nconst JOINABLE = [\"transaction\"];\n\nexport interface EventSourceOptions<T> {\n onmessage?: (\n value: T extends ServerApi.CollectionPage<infer U> ? U : T,\n ) => void;\n onerror?: (event: MessageEvent) => void;\n reconnectTimeout?: number;\n}\n\n/**\n * Creates a new {@link CallBuilder} pointed to server defined by serverUrl.\n *\n * This is an **abstract** class. Do not create this object directly, use {@link Server} class.\n * @param serverUrl - URL of Horizon server\n */\nexport class CallBuilder<\n T extends\n | HorizonApi.FeeStatsResponse\n | HorizonApi.BaseResponse\n | HorizonApi.RootResponse\n | ServerApi.CollectionPage<HorizonApi.BaseResponse>,\n> {\n protected url: URL;\n\n public filter: string[][];\n\n protected originalSegments: string[];\n\n protected neighborRoot: string;\n\n protected httpClient: HttpClient;\n\n constructor(\n serverUrl: URL,\n httpClient: HttpClient,\n neighborRoot: string = \"\",\n ) {\n this.url = new URL(serverUrl);\n this.filter = [];\n\n this.originalSegments = this.url.pathname\n .split(\"/\")\n .filter((s) => s.length > 0);\n this.neighborRoot = neighborRoot;\n this.httpClient = httpClient;\n }\n\n protected setPath(...segments: string[]): void {\n const endpointSegments = segments.flatMap((segment) =>\n segment.split(\"/\").filter((s) => s.length > 0),\n );\n this.url.pathname = this.originalSegments\n .concat(endpointSegments)\n .join(\"/\");\n }\n\n /**\n * Triggers a HTTP request using this builder's current configuration.\n * @returns a Promise that resolves to the server's response.\n */\n public call(): Promise<T> {\n this.checkFilter();\n return this._sendNormalRequest(this.url).then((r) =>\n this._parseResponse(r),\n );\n }\n //// TODO: Migrate to async, BUT that's a change in behavior and tests \"rejects two filters\" will fail.\n //// It's because async will check within promise, which makes more sense when using awaits instead of Promises.\n // public async call(): Promise<T> {\n // this.checkFilter();\n // const r = await this._sendNormalRequest(this.url);\n // return this._parseResponse(r);\n // }\n //// /* actually equals */\n //// public call(): Promise<T> {\n //// return Promise.resolve().then(() => {\n //// this.checkFilter();\n //// return this._sendNormalRequest(this.url)\n //// }).then((r) => {\n //// this._parseResponse(r)\n //// });\n //// }\n\n /**\n * Creates an EventSource that listens for incoming messages from the server. To stop listening for new\n * events call the function returned by this method.\n * @see [Horizon Response Format](https://developers.stellar.org/api/introduction/response-format/)\n * @see [MDN EventSource](https://developer.mozilla.org/en-US/docs/Web/API/EventSource)\n * @param options - (optional) EventSource options.\n * - `onmessage` (optional): Callback function to handle incoming messages.\n * - `onerror` (optional): Callback function to handle errors.\n * - `reconnectTimeout` (optional): Custom stream connection timeout in ms, default is 15 seconds.\n * @returns Close function. Run to close the connection and stop listening for new events.\n */\n public stream(\n options: EventSourceOptions<\n T extends ServerApi.CollectionPage<infer U> ? U : T\n > = {},\n ): () => void {\n this.checkFilter();\n\n const streamUrl = new URL(this.url);\n streamUrl.searchParams.set(\"X-Client-Name\", \"js-stellar-sdk\");\n streamUrl.searchParams.set(\"X-Client-Version\", version);\n\n // Extract custom app headers from httpClient defaults and add as query params\n // (EventSource doesn't support custom headers, so we use query params)\n const { headers } = this.httpClient.defaults;\n if (headers) {\n const headerNames = [\"X-App-Name\", \"X-App-Version\"];\n headerNames.forEach((name) => {\n let value: string | undefined;\n if (headers instanceof Headers) {\n value = headers.get(name) ?? undefined;\n } else if (Array.isArray(headers)) {\n const entry = headers.find(([key]) => key === name);\n value = entry?.[1];\n } else {\n value = headers[name];\n }\n if (value) {\n streamUrl.searchParams.set(name, value);\n }\n });\n }\n\n // EventSource object\n let es: EventSource;\n // timeout is the id of the timeout to be triggered if there were no new messages\n // in the last 15 seconds. The timeout is reset when a new message arrive.\n // It prevents closing EventSource object in case of 504 errors as `readyState`\n // property is not reliable.\n let timeout: ReturnType<typeof setTimeout>;\n\n const createTimeout = () => {\n timeout = setTimeout(\n () => {\n es?.close();\n\n es = createEventSource();\n },\n options.reconnectTimeout || 15 * 1000,\n );\n };\n\n const createEventSource = (): EventSource => {\n try {\n es = new EventSource(streamUrl.toString());\n } catch (err) {\n if (options.onerror) {\n options.onerror(err as MessageEvent);\n }\n }\n\n createTimeout();\n if (!es) {\n return es;\n }\n\n // when receiving the close message from Horizon we should close the\n // connection and recreate the event source (basically retrying forever)\n let closed = false;\n const onClose = () => {\n if (closed) {\n return;\n }\n\n clearTimeout(timeout);\n\n es.close();\n createEventSource();\n closed = true;\n };\n\n const onMessage = (message: any) => {\n if (message.type === \"close\") {\n onClose();\n return;\n }\n\n const result = message.data\n ? this._parseRecord(JSON.parse(message.data))\n : message;\n if (result.paging_token) {\n streamUrl.searchParams.set(\"cursor\", result.paging_token);\n }\n clearTimeout(timeout);\n createTimeout();\n if (typeof options.onmessage !== \"undefined\") {\n options.onmessage(result);\n }\n };\n\n const onError = (error: any) => {\n if (options.onerror) {\n options.onerror(error as MessageEvent);\n }\n };\n\n if (es.addEventListener) {\n es.addEventListener(\"message\", onMessage.bind(this));\n es.addEventListener(\"error\", onError.bind(this));\n es.addEventListener(\"close\", onClose.bind(this));\n } else {\n es.onmessage = onMessage.bind(this);\n es.onerror = onError.bind(this);\n }\n\n return es;\n };\n\n createEventSource();\n return () => {\n clearTimeout(timeout);\n es?.close();\n };\n }\n\n /**\n * Sets `cursor` parameter for the current call. Returns the CallBuilder object on which this method has been called.\n * @see [Paging](https://developers.stellar.org/api/introduction/pagination/)\n * @param cursor - A cursor is a value that points to a specific location in a collection of resources.\n * @returns current CallBuilder instance\n */\n public cursor(cursor: string): this {\n this.url.searchParams.set(\"cursor\", cursor);\n return this;\n }\n\n /**\n * Sets `limit` parameter for the current call. Returns the CallBuilder object on which this method has been called.\n * @see [Paging](https://developers.stellar.org/api/introduction/pagination/)\n * @param recordsNumber - Number of records the server should return.\n * @returns current CallBuilder instance\n */\n public limit(recordsNumber: number): this {\n this.url.searchParams.set(\"limit\", recordsNumber.toString());\n return this;\n }\n\n /**\n * Sets `order` parameter for the current call. Returns the CallBuilder object on which this method has been called.\n * @param direction - Sort direction\n * @returns current CallBuilder instance\n */\n public order(direction: \"asc\" | \"desc\"): this {\n this.url.searchParams.set(\"order\", direction);\n return this;\n }\n\n /**\n * Sets `join` parameter for the current call. The `join` parameter\n * includes the requested resource in the response. Currently, the\n * only valid value for the parameter is `transactions` and is only\n * supported on the operations and payments endpoints. The response\n * will include a `transaction` field for each operation in the\n * response.\n *\n * @param include - join Records to be included in the response.\n * @returns current CallBuilder instance.\n */\n public join(include: \"transactions\"): this {\n this.url.searchParams.set(\"join\", include);\n return this;\n }\n\n /**\n * A helper method to craft queries to \"neighbor\" endpoints.\n *\n * For example, we have an `/effects` suffix endpoint on many different\n * \"root\" endpoints, such as `/transactions/:id` and `/accounts/:id`. So,\n * it's helpful to be able to conveniently create queries to the\n * `/accounts/:id/effects` endpoint:\n *\n * `this.forEndpoint(\"accounts\", accountId)`.\n *\n * @param endpoint - neighbor endpoint in question, like /operations\n * @param param - filter parameter, like an operation ID\n *\n * @returns this CallBuilder instance\n */\n protected forEndpoint(endpoint: string, param: string): this {\n if (this.neighborRoot === \"\") {\n throw new Error(\"Invalid usage: neighborRoot not set in constructor\");\n }\n this.filter.push([endpoint, param, this.neighborRoot]);\n return this;\n }\n\n /**\n * @hidden\n * @returns */\n private checkFilter(): void {\n if (this.filter.length >= 2) {\n throw new BadRequestError(\"Too many filters specified\", this.filter);\n }\n\n if (this.filter.length === 1) {\n // append filters to original segments\n const newSegment = this.originalSegments.concat(this.filter[0]);\n this.url.pathname = newSegment.join(\"/\");\n }\n }\n\n /**\n * Convert a link object to a function that fetches that link.\n * @hidden\n * @param link - A link object\n * - `href`: the URI of the link\n * - `templated` (optional): Whether the link is templated\n * @returns A function that requests the link\n */\n private _requestFnForLink(\n link: HorizonApi.ResponseLink,\n ): (opts?: any) => any {\n return async (opts: any = {}) => {\n let uri;\n\n if (link.templated) {\n uri = new URL(expandUriTemplate(link.href, opts), this.url);\n } else {\n uri = new URL(link.href, this.url);\n }\n\n const r = await this._sendNormalRequest(uri);\n return this._parseResponse(r);\n };\n }\n\n /**\n * Given the json response, find and convert each link into a function that\n * calls that link.\n * @hidden\n * @param json - JSON response\n * @returns JSON response with string links replaced with functions\n */\n private _parseRecord(json: any): any {\n if (!json._links) {\n return json;\n }\n Object.keys(json._links).forEach((key) => {\n const n = json._links[key];\n let included = false;\n // If the key with the link name already exists, create a copy\n if (typeof json[key] !== \"undefined\") {\n json[`${key}_attr`] = json[key];\n included = true;\n }\n\n /*\n If the resource can be side-loaded using `join` query-param then don't\n try to load from the server. We need to whitelist the keys which are\n joinable, since there are other keys like `ledger` which is included in\n some payloads, but doesn't represent the ledger resource, in that\n scenario we want to make the call to the server using the URL from links.\n */\n if (included && JOINABLE.indexOf(key) >= 0) {\n const record = this._parseRecord(json[key]);\n // Maintain a promise based API so the behavior is the same whether you\n // are loading from the server or in-memory (via join).\n // eslint-disable-next-line @typescript-eslint/require-await\n json[key] = async () => record;\n } else {\n json[key] = this._requestFnForLink(n as HorizonApi.ResponseLink);\n }\n });\n return json;\n }\n\n private async _sendNormalRequest(initialUrl: URL) {\n const url = new URL(initialUrl);\n\n // Always use the configured server's authority and protocol.\n // Horizon returns absolute URLs in _links that would bypass reverse proxies.\n url.protocol = this.url.protocol;\n url.host = this.url.host;\n\n return this.httpClient\n .get(url.toString())\n .then((response) => response.data)\n .catch(this._handleNetworkError);\n }\n\n /**\n * @hidden\n * @param json - Response object\n * @returns Extended response\n */\n private _parseResponse(json: any) {\n if (json._embedded && json._embedded.records) {\n return this._toCollectionPage(json);\n }\n return this._parseRecord(json);\n }\n\n /**\n * @hidden\n * @param json - Response object\n * @returns Extended response object\n */\n private _toCollectionPage(json: any): any {\n for (let i = 0; i < json._embedded.records.length; i += 1) {\n json._embedded.records[i] = this._parseRecord(json._embedded.records[i]);\n }\n return {\n records: json._embedded.records,\n next: async () => {\n const r = await this._sendNormalRequest(\n new URL(json._links.next.href, this.url),\n );\n return this._toCollectionPage(r);\n },\n prev: async () => {\n const r = await this._sendNormalRequest(\n new URL(json._links.prev.href, this.url),\n );\n return this._toCollectionPage(r);\n },\n };\n }\n\n /**\n * @hidden\n * @param error - Network error object\n * @returns Promise that rejects with a human-readable error\n */\n private async _handleNetworkError(error: NetworkError): Promise<void> {\n if (error.response && error.response.status) {\n switch (error.response.status) {\n case 404:\n return Promise.reject(\n new NotFoundError(\n error.response.statusText ?? \"Not Found\",\n error.response.data,\n ),\n );\n default:\n return Promise.reject(\n new NetworkError(\n error.response.statusText ?? \"Unkn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A;AAAQ,QAC7B,KAAK,GAAA;AACH,UAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,YACb,IAAI,aAAA;AAAA,cACF,KAAA,CAAM,SAAS,UAAA,IAAc,WAAA;AAAA,cAC7B,MAAM,QAAA,CAAS;AAAA;AACjB,WACF;AAAA,QACF;AACE,UAAA,OAAO,OAAA,CAAQ,MAAA;AAAA,YACb,IAAI,YAAA;AAAA,cACF,KAAA,CAAM,SAAS,UAAA,IAAc,SAAA;AAAA,cAC7B,MAAM,QAAA,CAAS;AAAA;AACjB,WACF;AAAA;AACJ,IACF,CAAA,MAAO;AACL,MAAA,OAAO,QAAQ,MAAA,CAAO,IAAI,KAAA,CAAM,KAAA,CAAM,OAAO,CAAC,CAAA;AAAA,IAChD;AAAA,EACF;AACF;;;;"}
|
|
@@ -517,12 +517,23 @@ export declare namespace HorizonApi {
|
|
|
517
517
|
TX_INSUFFICIENT_BALANCE = "tx_insufficient_balance",
|
|
518
518
|
TX_NO_SOURCE_ACCOUNT = "tx_no_source_account",
|
|
519
519
|
TX_INSUFFICIENT_FEE = "tx_insufficient_fee",
|
|
520
|
-
TX_INTERNAL_ERROR = "tx_internal_error"
|
|
520
|
+
TX_INTERNAL_ERROR = "tx_internal_error",
|
|
521
|
+
TX_BAD_SPONSORSHIP = "tx_bad_sponsorship",
|
|
522
|
+
TX_BAD_MIN_SEQ_AGE_OR_GAP = "tx_bad_min_seq_age_or_gap",
|
|
523
|
+
TX_MALFORMED = "tx_malformed",
|
|
524
|
+
TX_SOROBAN_INVALID = "tx_soroban_invalid",
|
|
525
|
+
TX_FROZEN_KEY_ACCESSED = "tx_frozen_key_accessed"
|
|
521
526
|
}
|
|
522
527
|
interface TransactionFailedExtras {
|
|
523
528
|
envelope_xdr: string;
|
|
524
529
|
result_codes: {
|
|
525
530
|
transaction: TransactionFailedResultCodes;
|
|
531
|
+
/** Omitted by Horizon when the transaction failed a transaction-level
|
|
532
|
+
* check (e.g. `tx_bad_seq`) and no operations were evaluated. Typed as
|
|
533
|
+
* required for backwards compatibility; treat as possibly undefined
|
|
534
|
+
* when reading the raw response, or use
|
|
535
|
+
* `TransactionFailedError.getResultCodes()` which normalizes it.
|
|
536
|
+
* TODO(next major): make this `operations?: string[]`. */
|
|
526
537
|
operations: string[];
|
|
527
538
|
};
|
|
528
539
|
result_xdr: string;
|
|
@@ -77,6 +77,11 @@ var HorizonApi;
|
|
|
77
77
|
TransactionFailedResultCodes2["TX_NO_SOURCE_ACCOUNT"] = "tx_no_source_account";
|
|
78
78
|
TransactionFailedResultCodes2["TX_INSUFFICIENT_FEE"] = "tx_insufficient_fee";
|
|
79
79
|
TransactionFailedResultCodes2["TX_INTERNAL_ERROR"] = "tx_internal_error";
|
|
80
|
+
TransactionFailedResultCodes2["TX_BAD_SPONSORSHIP"] = "tx_bad_sponsorship";
|
|
81
|
+
TransactionFailedResultCodes2["TX_BAD_MIN_SEQ_AGE_OR_GAP"] = "tx_bad_min_seq_age_or_gap";
|
|
82
|
+
TransactionFailedResultCodes2["TX_MALFORMED"] = "tx_malformed";
|
|
83
|
+
TransactionFailedResultCodes2["TX_SOROBAN_INVALID"] = "tx_soroban_invalid";
|
|
84
|
+
TransactionFailedResultCodes2["TX_FROZEN_KEY_ACCESSED"] = "tx_frozen_key_accessed";
|
|
80
85
|
})(HorizonApi2.TransactionFailedResultCodes || (HorizonApi2.TransactionFailedResultCodes = {}));
|
|
81
86
|
})(HorizonApi || (HorizonApi = {}));
|
|
82
87
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"horizon_api.js","sources":["../../../../src/horizon/horizon_api.ts"],"sourcesContent":["import type { AssetType, MemoType } from \"../base/index.js\";\n\n/* tslint:disable-next-line:no-namespace */\nexport namespace HorizonApi {\n export interface ResponseLink {\n href: string;\n templated?: boolean;\n }\n export interface BaseResponse<T extends string = never> {\n _links: { [key in T | \"self\"]: ResponseLink };\n }\n\n export interface SubmitTransactionResponse {\n hash: string;\n ledger: number;\n successful: boolean;\n envelope_xdr: string;\n result_xdr: string;\n result_meta_xdr: string;\n paging_token: string;\n }\n\n export interface SubmitAsyncTransactionResponse {\n hash: string;\n tx_status: string;\n error_result_xdr: string;\n }\n\n export interface FeeBumpTransactionResponse {\n hash: string;\n signatures: string[];\n }\n\n export interface InnerTransactionResponse {\n hash: string;\n signatures: string[];\n max_fee: string;\n }\n\n export interface TransactionPreconditions {\n timebounds?: {\n min_time: string;\n max_time: string;\n };\n ledgerbounds?: {\n min_ledger: number;\n max_ledger: number;\n };\n min_account_sequence?: string;\n min_account_sequence_age?: string;\n min_account_sequence_ledger_gap?: number;\n extra_signers?: string[];\n }\n\n export interface TransactionResponse\n extends\n SubmitTransactionResponse,\n BaseResponse<\n | \"account\"\n | \"ledger\"\n | \"operations\"\n | \"effects\"\n | \"succeeds\"\n | \"precedes\"\n > {\n created_at: string;\n fee_meta_xdr: string;\n fee_charged: number | string;\n max_fee: number | string;\n id: string;\n memo_type: MemoType;\n memo?: string;\n memo_bytes?: string;\n operation_count: number;\n paging_token: string;\n signatures: string[];\n source_account: string;\n source_account_sequence: string;\n fee_account: string;\n inner_transaction?: InnerTransactionResponse;\n fee_bump_transaction?: FeeBumpTransactionResponse;\n preconditions?: TransactionPreconditions;\n }\n\n export interface BalanceLineNative {\n balance: string;\n asset_type: AssetType.native;\n buying_liabilities: string;\n selling_liabilities: string;\n }\n export interface BalanceLineLiquidityPool {\n liquidity_pool_id: string;\n asset_type: AssetType.liquidityPoolShares;\n balance: string;\n limit: string;\n last_modified_ledger: number;\n is_authorized: boolean;\n is_authorized_to_maintain_liabilities: boolean;\n is_clawback_enabled: boolean;\n sponsor?: string;\n }\n export interface BalanceLineAsset<\n T extends AssetType.credit4 | AssetType.credit12 =\n | AssetType.credit4\n | AssetType.credit12,\n > {\n balance: string;\n limit: string;\n asset_type: T;\n asset_code: string;\n asset_issuer: string;\n buying_liabilities: string;\n selling_liabilities: string;\n last_modified_ledger: number;\n is_authorized: boolean;\n is_authorized_to_maintain_liabilities: boolean;\n is_clawback_enabled: boolean;\n sponsor?: string;\n }\n export type BalanceLine<T extends AssetType = AssetType> =\n T extends AssetType.native\n ? BalanceLineNative\n : T extends AssetType.credit4 | AssetType.credit12\n ? BalanceLineAsset<T>\n : T extends AssetType.liquidityPoolShares\n ? BalanceLineLiquidityPool\n : BalanceLineNative | BalanceLineAsset | BalanceLineLiquidityPool;\n\n export interface AssetAccounts {\n authorized: number;\n authorized_to_maintain_liabilities: number;\n unauthorized: number;\n }\n export interface AssetBalances {\n authorized: string;\n authorized_to_maintain_liabilities: string;\n unauthorized: string;\n }\n\n export interface PriceR {\n numerator: number;\n denominator: number;\n }\n\n export interface PriceRShorthand {\n n: number;\n d: number;\n }\n\n export interface AccountThresholds {\n low_threshold: number;\n med_threshold: number;\n high_threshold: number;\n }\n export interface Flags {\n auth_immutable: boolean;\n auth_required: boolean;\n auth_revocable: boolean;\n auth_clawback_enabled: boolean;\n }\n export interface AccountSigner {\n key: string;\n weight: number;\n type: string;\n sponsor?: string;\n }\n export interface AccountResponse extends BaseResponse<\n | \"transactions\"\n | \"operations\"\n | \"payments\"\n | \"effects\"\n | \"offers\"\n | \"trades\"\n | \"data\"\n > {\n id: string;\n paging_token: string;\n account_id: string;\n sequence: string;\n sequence_ledger?: number;\n sequence_time?: string;\n subentry_count: number;\n thresholds: AccountThresholds;\n last_modified_ledger: number;\n last_modified_time: string;\n flags: Flags;\n balances: BalanceLine[];\n signers: AccountSigner[];\n data: {\n [key: string]: string;\n };\n sponsor?: string;\n num_sponsoring: number;\n num_sponsored: number;\n }\n\n export enum LiquidityPoolType {\n constantProduct = \"constant_product\",\n }\n\n export enum OperationResponseType {\n createAccount = \"create_account\",\n payment = \"payment\",\n pathPayment = \"path_payment_strict_receive\",\n createPassiveOffer = \"create_passive_sell_offer\",\n manageOffer = \"manage_sell_offer\",\n setOptions = \"set_options\",\n changeTrust = \"change_trust\",\n allowTrust = \"allow_trust\",\n accountMerge = \"account_merge\",\n inflation = \"inflation\",\n manageData = \"manage_data\",\n bumpSequence = \"bump_sequence\",\n manageBuyOffer = \"manage_buy_offer\",\n pathPaymentStrictSend = \"path_payment_strict_send\",\n createClaimableBalance = \"create_claimable_balance\",\n claimClaimableBalance = \"claim_claimable_balance\",\n beginSponsoringFutureReserves = \"begin_sponsoring_future_reserves\",\n endSponsoringFutureReserves = \"end_sponsoring_future_reserves\",\n revokeSponsorship = \"revoke_sponsorship\",\n clawback = \"clawback\",\n clawbackClaimableBalance = \"clawback_claimable_balance\",\n setTrustLineFlags = \"set_trust_line_flags\",\n liquidityPoolDeposit = \"liquidity_pool_deposit\",\n liquidityPoolWithdraw = \"liquidity_pool_withdraw\",\n invokeHostFunction = \"invoke_host_function\",\n bumpFootprintExpiration = \"bump_footprint_expiration\",\n restoreFootprint = \"restore_footprint\",\n }\n export enum OperationResponseTypeI {\n createAccount = 0,\n payment = 1,\n pathPayment = 2,\n createPassiveOffer = 3,\n manageOffer = 4,\n setOptions = 5,\n changeTrust = 6,\n allowTrust = 7,\n accountMerge = 8,\n inflation = 9,\n manageData = 10,\n bumpSequence = 11,\n manageBuyOffer = 12,\n pathPaymentStrictSend = 13,\n createClaimableBalance = 14,\n claimClaimableBalance = 15,\n beginSponsoringFutureReserves = 16,\n endSponsoringFutureReserves = 17,\n revokeSponsorship = 18,\n clawback = 19,\n clawbackClaimableBalance = 20,\n setTrustLineFlags = 21,\n liquidityPoolDeposit = 22,\n liquidityPoolWithdraw = 23,\n invokeHostFunction = 24,\n bumpFootprintExpiration = 25,\n restoreFootprint = 26,\n }\n export interface BaseOperationResponse<\n T extends OperationResponseType = OperationResponseType,\n TI extends OperationResponseTypeI = OperationResponseTypeI,\n > extends BaseResponse<\"succeeds\" | \"precedes\" | \"effects\" | \"transaction\"> {\n id: string;\n paging_token: string;\n source_account: string;\n type: T;\n type_i: TI;\n created_at: string;\n transaction_hash: string;\n transaction_successful: boolean;\n }\n export interface CreateAccountOperationResponse extends BaseOperationResponse<\n OperationResponseType.createAccount,\n OperationResponseTypeI.createAccount\n > {\n account: string;\n funder: string;\n starting_balance: string;\n }\n export interface PaymentOperationResponse extends BaseOperationResponse<\n OperationResponseType.payment,\n OperationResponseTypeI.payment\n > {\n from: string;\n to: string;\n asset_type: AssetType;\n asset_code?: string;\n asset_issuer?: string;\n amount: string;\n to_muxed?: string;\n to_muxed_id?: string;\n }\n export interface PathPaymentOperationResponse extends BaseOperationResponse<\n OperationResponseType.pathPayment,\n OperationResponseTypeI.pathPayment\n > {\n amount: string;\n asset_code?: string;\n asset_issuer?: string;\n asset_type: AssetType;\n from: string;\n path: Array<{\n asset_code: string;\n asset_issuer: string;\n asset_type: AssetType;\n }>;\n source_amount: string;\n source_asset_code?: string;\n source_asset_issuer?: string;\n source_asset_type: AssetType;\n source_max: string;\n to: string;\n }\n export interface PathPaymentStrictSendOperationResponse extends BaseOperationResponse<\n OperationResponseType.pathPaymentStrictSend,\n OperationResponseTypeI.pathPaymentStrictSend\n > {\n amount: string;\n asset_code?: string;\n asset_issuer?: string;\n asset_type: AssetType;\n destination_min: string;\n from: string;\n path: Array<{\n asset_code: string;\n asset_issuer: string;\n asset_type: AssetType;\n }>;\n source_amount: string;\n source_asset_code?: string;\n source_asset_issuer?: string;\n source_asset_type: AssetType;\n to: string;\n }\n export interface ManageOfferOperationResponse extends BaseOperationResponse<\n OperationResponseType.manageOffer,\n OperationResponseTypeI.manageOffer\n > {\n offer_id: number | string;\n amount: string;\n buying_asset_type: AssetType;\n buying_asset_code?: string;\n buying_asset_issuer?: string;\n price: string;\n price_r: PriceR;\n selling_asset_type: AssetType;\n selling_asset_code?: string;\n selling_asset_issuer?: string;\n }\n export interface PassiveOfferOperationResponse extends BaseOperationResponse<\n OperationResponseType.createPassiveOffer,\n OperationResponseTypeI.createPassiveOffer\n > {\n offer_id: number | string;\n amount: string;\n buying_asset_type: AssetType;\n buying_asset_code?: string;\n buying_asset_issuer?: string;\n price: string;\n price_r: PriceR;\n selling_asset_type: AssetType;\n selling_asset_code?: string;\n selling_asset_issuer?: string;\n }\n export interface SetOptionsOperationResponse extends BaseOperationResponse<\n OperationResponseType.setOptions,\n OperationResponseTypeI.setOptions\n > {\n signer_key?: string;\n signer_weight?: number;\n master_key_weight?: number;\n low_threshold?: number;\n med_threshold?: number;\n high_threshold?: number;\n home_domain?: string;\n set_flags: Array<1 | 2 | 4>;\n set_flags_s: Array<\n | \"auth_required_flag\"\n | \"auth_revocable_flag\"\n | \"auth_clawback_enabled_flag\"\n >;\n clear_flags: Array<1 | 2 | 4>;\n clear_flags_s: Array<\n | \"auth_required_flag\"\n | \"auth_revocable_flag\"\n | \"auth_clawback_enabled_flag\"\n >;\n }\n export interface ChangeTrustOperationResponse extends BaseOperationResponse<\n OperationResponseType.changeTrust,\n OperationResponseTypeI.changeTrust\n > {\n asset_type:\n | AssetType.credit4\n | AssetType.credit12\n | AssetType.liquidityPoolShares;\n asset_code?: string;\n asset_issuer?: string;\n liquidity_pool_id?: string;\n trustee?: string;\n trustor: string;\n limit: string;\n }\n export interface AllowTrustOperationResponse extends BaseOperationResponse<\n OperationResponseType.allowTrust,\n OperationResponseTypeI.allowTrust\n > {\n asset_type: AssetType;\n asset_code: string;\n asset_issuer: string;\n authorize: boolean;\n authorize_to_maintain_liabilities: boolean;\n trustee: string;\n trustor: string;\n }\n export interface AccountMergeOperationResponse extends BaseOperationResponse<\n OperationResponseType.accountMerge,\n OperationResponseTypeI.accountMerge\n > {\n into: string;\n }\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- empty interface names a public API response type\n export interface InflationOperationResponse extends BaseOperationResponse<\n OperationResponseType.inflation,\n OperationResponseTypeI.inflation\n > {}\n export interface ManageDataOperationResponse extends BaseOperationResponse<\n OperationResponseType.manageData,\n OperationResponseTypeI.manageData\n > {\n name: string;\n value: Buffer;\n }\n export interface BumpSequenceOperationResponse extends BaseOperationResponse<\n OperationResponseType.bumpSequence,\n OperationResponseTypeI.bumpSequence\n > {\n bump_to: string;\n }\n export interface Predicate {\n and?: Predicate[];\n or?: Predicate[];\n not?: Predicate;\n abs_before?: string;\n rel_before?: string;\n }\n\n export interface Claimant {\n destination: string;\n predicate: Predicate;\n }\n\n export interface CreateClaimableBalanceOperationResponse extends BaseOperationResponse<\n OperationResponseType.createClaimableBalance,\n OperationResponseTypeI.createClaimableBalance\n > {\n asset: string;\n amount: string;\n sponsor: string;\n claimants: Claimant[];\n }\n\n export interface ClaimClaimableBalanceOperationResponse extends BaseOperationResponse<\n OperationResponseType.claimClaimableBalance,\n OperationResponseTypeI.claimClaimableBalance\n > {\n balance_id: string;\n claimant: string;\n }\n\n export interface BeginSponsoringFutureReservesOperationResponse extends BaseOperationResponse<\n OperationResponseType.beginSponsoringFutureReserves,\n OperationResponseTypeI.beginSponsoringFutureReserves\n > {\n sponsored_id: string;\n }\n\n export interface EndSponsoringFutureReservesOperationResponse extends BaseOperationResponse<\n OperationResponseType.endSponsoringFutureReserves,\n OperationResponseTypeI.endSponsoringFutureReserves\n > {\n begin_sponsor: string;\n }\n\n export interface RevokeSponsorshipOperationResponse extends BaseOperationResponse<\n OperationResponseType.revokeSponsorship,\n OperationResponseTypeI.revokeSponsorship\n > {\n account_id?: string;\n claimable_balance_id?: string;\n data_account_id?: string;\n data_name?: string;\n offer_id?: string;\n trustline_account_id?: string;\n trustline_asset?: string;\n trustline_liquidity_pool_id?: string;\n signer_account_id?: string;\n signer_key?: string;\n }\n\n export interface ClawbackOperationResponse extends BaseOperationResponse<\n OperationResponseType.clawback,\n OperationResponseTypeI.clawback\n > {\n asset_type: AssetType;\n asset_code: string;\n asset_issuer: string;\n from: string;\n amount: string;\n }\n\n export interface ClawbackClaimableBalanceOperationResponse extends BaseOperationResponse<\n OperationResponseType.clawbackClaimableBalance,\n OperationResponseTypeI.clawbackClaimableBalance\n > {\n balance_id: string;\n }\n\n export interface SetTrustLineFlagsOperationResponse extends BaseOperationResponse<\n OperationResponseType.setTrustLineFlags,\n OperationResponseTypeI.setTrustLineFlags\n > {\n asset_type: AssetType;\n asset_code: string;\n asset_issuer: string;\n trustor: string;\n set_flags: Array<1 | 2 | 4>;\n clear_flags: Array<1 | 2 | 4>;\n }\n export interface Reserve {\n asset: string;\n amount: string;\n }\n export interface DepositLiquidityOperationResponse extends BaseOperationResponse<\n OperationResponseType.liquidityPoolDeposit,\n OperationResponseTypeI.liquidityPoolDeposit\n > {\n liquidity_pool_id: string;\n reserves_max: Reserve[];\n min_price: string;\n min_price_r: PriceRShorthand;\n max_price: string;\n max_price_r: PriceRShorthand;\n reserves_deposited: Reserve[];\n shares_received: string;\n }\n export interface WithdrawLiquidityOperationResponse extends BaseOperationResponse<\n OperationResponseType.liquidityPoolWithdraw,\n OperationResponseTypeI.liquidityPoolWithdraw\n > {\n liquidity_pool_id: string;\n reserves_min: Reserve[];\n shares: string;\n reserves_received: Reserve[];\n }\n\n export interface BalanceChange {\n asset_type: string;\n asset_code?: string;\n asset_issuer?: string;\n\n type: string;\n from: string;\n to: string;\n amount: string;\n destination_muxed_id?: string;\n }\n\n export interface InvokeHostFunctionOperationResponse extends BaseOperationResponse<\n OperationResponseType.invokeHostFunction,\n OperationResponseTypeI.invokeHostFunction\n > {\n function: string;\n parameters: {\n value: string;\n type: string;\n }[];\n address: string;\n salt: string;\n asset_balance_changes: BalanceChange[];\n }\n\n export interface BumpFootprintExpirationOperationResponse extends BaseOperationResponse<\n OperationResponseType.bumpFootprintExpiration,\n OperationResponseTypeI.bumpFootprintExpiration\n > {\n ledgers_to_expire: number;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- empty interface names a public API response type\n export interface RestoreFootprintOperationResponse extends BaseOperationResponse<\n OperationResponseType.restoreFootprint,\n OperationResponseTypeI.restoreFootprint\n > {}\n\n export interface ResponseCollection<T extends BaseResponse = BaseResponse> {\n _links: {\n self: ResponseLink;\n next: ResponseLink;\n prev: ResponseLink;\n };\n _embedded: {\n records: T[];\n };\n }\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- empty interface names a public API response type\n export interface TransactionResponseCollection extends ResponseCollection<TransactionResponse> {}\n\n export interface FeeDistribution {\n max: string;\n min: string;\n mode: string;\n p10: string;\n p20: string;\n p30: string;\n p40: string;\n p50: string;\n p60: string;\n p70: string;\n p80: string;\n p90: string;\n p95: string;\n p99: string;\n }\n export interface FeeStatsResponse {\n last_ledger: string;\n last_ledger_base_fee: string;\n ledger_capacity_usage: string;\n fee_charged: FeeDistribution;\n max_fee: FeeDistribution;\n }\n\n export type ErrorResponseData =\n | ErrorResponseData.RateLimitExceeded\n | ErrorResponseData.InternalServerError\n | ErrorResponseData.TransactionFailed;\n\n export namespace ErrorResponseData {\n export interface Base {\n status: number;\n title: string;\n type: string; // TODO\n details: string; // TODO\n instance: string; // TODO\n }\n\n export interface RateLimitExceeded extends Base {\n status: 429;\n title: \"Rate Limit Exceeded\";\n }\n export interface InternalServerError extends Base {\n status: 500;\n title: \"Internal Server Error\";\n }\n export interface TransactionFailed extends Base {\n status: 400;\n title: \"Transaction Failed\";\n extras: TransactionFailedExtras;\n }\n }\n\n export enum TransactionFailedResultCodes {\n TX_FAILED = \"tx_failed\",\n TX_BAD_SEQ = \"tx_bad_seq\",\n TX_BAD_AUTH = \"tx_bad_auth\",\n TX_BAD_AUTH_EXTRA = \"tx_bad_auth_extra\",\n TX_FEE_BUMP_INNER_SUCCESS = \"tx_fee_bump_inner_success\",\n TX_FEE_BUMP_INNER_FAILED = \"tx_fee_bump_inner_failed\",\n TX_NOT_SUPPORTED = \"tx_not_supported\",\n TX_SUCCESS = \"tx_success\",\n TX_TOO_EARLY = \"tx_too_early\",\n TX_TOO_LATE = \"tx_too_late\",\n TX_MISSING_OPERATION = \"tx_missing_operation\",\n TX_INSUFFICIENT_BALANCE = \"tx_insufficient_balance\",\n TX_NO_SOURCE_ACCOUNT = \"tx_no_source_account\",\n TX_INSUFFICIENT_FEE = \"tx_insufficient_fee\",\n TX_INTERNAL_ERROR = \"tx_internal_error\",\n }\n\n export interface TransactionFailedExtras {\n envelope_xdr: string; // base64\n result_codes: {\n transaction: TransactionFailedResultCodes;\n operations: string[];\n };\n result_xdr: string;\n }\n\n export interface RootResponse {\n horizon_version: string;\n core_version: string;\n ingest_latest_ledger: number;\n history_latest_ledger: number;\n history_latest_ledger_closed_at: string;\n history_elder_ledger: number;\n core_latest_ledger: number;\n network_passphrase: string;\n current_protocol_version: number;\n supported_protocol_version: number;\n core_supported_protocol_version: number;\n }\n}\n"],"names":["HorizonApi","LiquidityPoolType","OperationResponseType","OperationResponseTypeI","TransactionFailedResultCodes"],"mappings":"AAGO,IAAU;AAAA,CAAV,CAAUA,WAAAA,KAAV;AAiME,EAAA,CAAA,CAAKC,kBAAAA,KAAL;AACL,IAAAA,mBAAA,iBAAA,CAAA,GAAkB,kBAAA;AAAA,EAAA,CAAA,EADRD,WAAAA,CAAA,iBAAA,KAAAA,WAAAA,CAAA,iBAAA,GAAA,EAAA,CAAA,CAAA;AAIL,EAAA,CAAA,CAAKE,sBAAAA,KAAL;AACL,IAAAA,uBAAA,eAAA,CAAA,GAAgB,gBAAA;AAChB,IAAAA,uBAAA,SAAA,CAAA,GAAU,SAAA;AACV,IAAAA,uBAAA,aAAA,CAAA,GAAc,6BAAA;AACd,IAAAA,uBAAA,oBAAA,CAAA,GAAqB,2BAAA;AACrB,IAAAA,uBAAA,aAAA,CAAA,GAAc,mBAAA;AACd,IAAAA,uBAAA,YAAA,CAAA,GAAa,aAAA;AACb,IAAAA,uBAAA,aAAA,CAAA,GAAc,cAAA;AACd,IAAAA,uBAAA,YAAA,CAAA,GAAa,aAAA;AACb,IAAAA,uBAAA,cAAA,CAAA,GAAe,eAAA;AACf,IAAAA,uBAAA,WAAA,CAAA,GAAY,WAAA;AACZ,IAAAA,uBAAA,YAAA,CAAA,GAAa,aAAA;AACb,IAAAA,uBAAA,cAAA,CAAA,GAAe,eAAA;AACf,IAAAA,uBAAA,gBAAA,CAAA,GAAiB,kBAAA;AACjB,IAAAA,uBAAA,uBAAA,CAAA,GAAwB,0BAAA;AACxB,I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A,GAAA,EAAA,CAAA,CAAA;AAAA,CAAA,EAlpBG,UAAA,KAAA,UAAA,GAAA,EAAA,CAAA,CAAA;;;;"}
|
|
1
|
+
{"version":3,"file":"horizon_api.js","sources":["../../../../src/horizon/horizon_api.ts"],"sourcesContent":["import type { AssetType, MemoType } from \"../base/index.js\";\n\n/* tslint:disable-next-line:no-namespace */\nexport namespace HorizonApi {\n export interface ResponseLink {\n href: string;\n templated?: boolean;\n }\n export interface BaseResponse<T extends string = never> {\n _links: { [key in T | \"self\"]: ResponseLink };\n }\n\n export interface SubmitTransactionResponse {\n hash: string;\n ledger: number;\n successful: boolean;\n envelope_xdr: string;\n result_xdr: string;\n result_meta_xdr: string;\n paging_token: string;\n }\n\n export interface SubmitAsyncTransactionResponse {\n hash: string;\n tx_status: string;\n error_result_xdr: string;\n }\n\n export interface FeeBumpTransactionResponse {\n hash: string;\n signatures: string[];\n }\n\n export interface InnerTransactionResponse {\n hash: string;\n signatures: string[];\n max_fee: string;\n }\n\n export interface TransactionPreconditions {\n timebounds?: {\n min_time: string;\n max_time: string;\n };\n ledgerbounds?: {\n min_ledger: number;\n max_ledger: number;\n };\n min_account_sequence?: string;\n min_account_sequence_age?: string;\n min_account_sequence_ledger_gap?: number;\n extra_signers?: string[];\n }\n\n export interface TransactionResponse\n extends\n SubmitTransactionResponse,\n BaseResponse<\n | \"account\"\n | \"ledger\"\n | \"operations\"\n | \"effects\"\n | \"succeeds\"\n | \"precedes\"\n > {\n created_at: string;\n fee_meta_xdr: string;\n fee_charged: number | string;\n max_fee: number | string;\n id: string;\n memo_type: MemoType;\n memo?: string;\n memo_bytes?: string;\n operation_count: number;\n paging_token: string;\n signatures: string[];\n source_account: string;\n source_account_sequence: string;\n fee_account: string;\n inner_transaction?: InnerTransactionResponse;\n fee_bump_transaction?: FeeBumpTransactionResponse;\n preconditions?: TransactionPreconditions;\n }\n\n export interface BalanceLineNative {\n balance: string;\n asset_type: AssetType.native;\n buying_liabilities: string;\n selling_liabilities: string;\n }\n export interface BalanceLineLiquidityPool {\n liquidity_pool_id: string;\n asset_type: AssetType.liquidityPoolShares;\n balance: string;\n limit: string;\n last_modified_ledger: number;\n is_authorized: boolean;\n is_authorized_to_maintain_liabilities: boolean;\n is_clawback_enabled: boolean;\n sponsor?: string;\n }\n export interface BalanceLineAsset<\n T extends AssetType.credit4 | AssetType.credit12 =\n | AssetType.credit4\n | AssetType.credit12,\n > {\n balance: string;\n limit: string;\n asset_type: T;\n asset_code: string;\n asset_issuer: string;\n buying_liabilities: string;\n selling_liabilities: string;\n last_modified_ledger: number;\n is_authorized: boolean;\n is_authorized_to_maintain_liabilities: boolean;\n is_clawback_enabled: boolean;\n sponsor?: string;\n }\n export type BalanceLine<T extends AssetType = AssetType> =\n T extends AssetType.native\n ? BalanceLineNative\n : T extends AssetType.credit4 | AssetType.credit12\n ? BalanceLineAsset<T>\n : T extends AssetType.liquidityPoolShares\n ? BalanceLineLiquidityPool\n : BalanceLineNative | BalanceLineAsset | BalanceLineLiquidityPool;\n\n export interface AssetAccounts {\n authorized: number;\n authorized_to_maintain_liabilities: number;\n unauthorized: number;\n }\n export interface AssetBalances {\n authorized: string;\n authorized_to_maintain_liabilities: string;\n unauthorized: string;\n }\n\n export interface PriceR {\n numerator: number;\n denominator: number;\n }\n\n export interface PriceRShorthand {\n n: number;\n d: number;\n }\n\n export interface AccountThresholds {\n low_threshold: number;\n med_threshold: number;\n high_threshold: number;\n }\n export interface Flags {\n auth_immutable: boolean;\n auth_required: boolean;\n auth_revocable: boolean;\n auth_clawback_enabled: boolean;\n }\n export interface AccountSigner {\n key: string;\n weight: number;\n type: string;\n sponsor?: string;\n }\n export interface AccountResponse extends BaseResponse<\n | \"transactions\"\n | \"operations\"\n | \"payments\"\n | \"effects\"\n | \"offers\"\n | \"trades\"\n | \"data\"\n > {\n id: string;\n paging_token: string;\n account_id: string;\n sequence: string;\n sequence_ledger?: number;\n sequence_time?: string;\n subentry_count: number;\n thresholds: AccountThresholds;\n last_modified_ledger: number;\n last_modified_time: string;\n flags: Flags;\n balances: BalanceLine[];\n signers: AccountSigner[];\n data: {\n [key: string]: string;\n };\n sponsor?: string;\n num_sponsoring: number;\n num_sponsored: number;\n }\n\n export enum LiquidityPoolType {\n constantProduct = \"constant_product\",\n }\n\n export enum OperationResponseType {\n createAccount = \"create_account\",\n payment = \"payment\",\n pathPayment = \"path_payment_strict_receive\",\n createPassiveOffer = \"create_passive_sell_offer\",\n manageOffer = \"manage_sell_offer\",\n setOptions = \"set_options\",\n changeTrust = \"change_trust\",\n allowTrust = \"allow_trust\",\n accountMerge = \"account_merge\",\n inflation = \"inflation\",\n manageData = \"manage_data\",\n bumpSequence = \"bump_sequence\",\n manageBuyOffer = \"manage_buy_offer\",\n pathPaymentStrictSend = \"path_payment_strict_send\",\n createClaimableBalance = \"create_claimable_balance\",\n claimClaimableBalance = \"claim_claimable_balance\",\n beginSponsoringFutureReserves = \"begin_sponsoring_future_reserves\",\n endSponsoringFutureReserves = \"end_sponsoring_future_reserves\",\n revokeSponsorship = \"revoke_sponsorship\",\n clawback = \"clawback\",\n clawbackClaimableBalance = \"clawback_claimable_balance\",\n setTrustLineFlags = \"set_trust_line_flags\",\n liquidityPoolDeposit = \"liquidity_pool_deposit\",\n liquidityPoolWithdraw = \"liquidity_pool_withdraw\",\n invokeHostFunction = \"invoke_host_function\",\n bumpFootprintExpiration = \"bump_footprint_expiration\",\n restoreFootprint = \"restore_footprint\",\n }\n export enum OperationResponseTypeI {\n createAccount = 0,\n payment = 1,\n pathPayment = 2,\n createPassiveOffer = 3,\n manageOffer = 4,\n setOptions = 5,\n changeTrust = 6,\n allowTrust = 7,\n accountMerge = 8,\n inflation = 9,\n manageData = 10,\n bumpSequence = 11,\n manageBuyOffer = 12,\n pathPaymentStrictSend = 13,\n createClaimableBalance = 14,\n claimClaimableBalance = 15,\n beginSponsoringFutureReserves = 16,\n endSponsoringFutureReserves = 17,\n revokeSponsorship = 18,\n clawback = 19,\n clawbackClaimableBalance = 20,\n setTrustLineFlags = 21,\n liquidityPoolDeposit = 22,\n liquidityPoolWithdraw = 23,\n invokeHostFunction = 24,\n bumpFootprintExpiration = 25,\n restoreFootprint = 26,\n }\n export interface BaseOperationResponse<\n T extends OperationResponseType = OperationResponseType,\n TI extends OperationResponseTypeI = OperationResponseTypeI,\n > extends BaseResponse<\"succeeds\" | \"precedes\" | \"effects\" | \"transaction\"> {\n id: string;\n paging_token: string;\n source_account: string;\n type: T;\n type_i: TI;\n created_at: string;\n transaction_hash: string;\n transaction_successful: boolean;\n }\n export interface CreateAccountOperationResponse extends BaseOperationResponse<\n OperationResponseType.createAccount,\n OperationResponseTypeI.createAccount\n > {\n account: string;\n funder: string;\n starting_balance: string;\n }\n export interface PaymentOperationResponse extends BaseOperationResponse<\n OperationResponseType.payment,\n OperationResponseTypeI.payment\n > {\n from: string;\n to: string;\n asset_type: AssetType;\n asset_code?: string;\n asset_issuer?: string;\n amount: string;\n to_muxed?: string;\n to_muxed_id?: string;\n }\n export interface PathPaymentOperationResponse extends BaseOperationResponse<\n OperationResponseType.pathPayment,\n OperationResponseTypeI.pathPayment\n > {\n amount: string;\n asset_code?: string;\n asset_issuer?: string;\n asset_type: AssetType;\n from: string;\n path: Array<{\n asset_code: string;\n asset_issuer: string;\n asset_type: AssetType;\n }>;\n source_amount: string;\n source_asset_code?: string;\n source_asset_issuer?: string;\n source_asset_type: AssetType;\n source_max: string;\n to: string;\n }\n export interface PathPaymentStrictSendOperationResponse extends BaseOperationResponse<\n OperationResponseType.pathPaymentStrictSend,\n OperationResponseTypeI.pathPaymentStrictSend\n > {\n amount: string;\n asset_code?: string;\n asset_issuer?: string;\n asset_type: AssetType;\n destination_min: string;\n from: string;\n path: Array<{\n asset_code: string;\n asset_issuer: string;\n asset_type: AssetType;\n }>;\n source_amount: string;\n source_asset_code?: string;\n source_asset_issuer?: string;\n source_asset_type: AssetType;\n to: string;\n }\n export interface ManageOfferOperationResponse extends BaseOperationResponse<\n OperationResponseType.manageOffer,\n OperationResponseTypeI.manageOffer\n > {\n offer_id: number | string;\n amount: string;\n buying_asset_type: AssetType;\n buying_asset_code?: string;\n buying_asset_issuer?: string;\n price: string;\n price_r: PriceR;\n selling_asset_type: AssetType;\n selling_asset_code?: string;\n selling_asset_issuer?: string;\n }\n export interface PassiveOfferOperationResponse extends BaseOperationResponse<\n OperationResponseType.createPassiveOffer,\n OperationResponseTypeI.createPassiveOffer\n > {\n offer_id: number | string;\n amount: string;\n buying_asset_type: AssetType;\n buying_asset_code?: string;\n buying_asset_issuer?: string;\n price: string;\n price_r: PriceR;\n selling_asset_type: AssetType;\n selling_asset_code?: string;\n selling_asset_issuer?: string;\n }\n export interface SetOptionsOperationResponse extends BaseOperationResponse<\n OperationResponseType.setOptions,\n OperationResponseTypeI.setOptions\n > {\n signer_key?: string;\n signer_weight?: number;\n master_key_weight?: number;\n low_threshold?: number;\n med_threshold?: number;\n high_threshold?: number;\n home_domain?: string;\n set_flags: Array<1 | 2 | 4>;\n set_flags_s: Array<\n | \"auth_required_flag\"\n | \"auth_revocable_flag\"\n | \"auth_clawback_enabled_flag\"\n >;\n clear_flags: Array<1 | 2 | 4>;\n clear_flags_s: Array<\n | \"auth_required_flag\"\n | \"auth_revocable_flag\"\n | \"auth_clawback_enabled_flag\"\n >;\n }\n export interface ChangeTrustOperationResponse extends BaseOperationResponse<\n OperationResponseType.changeTrust,\n OperationResponseTypeI.changeTrust\n > {\n asset_type:\n | AssetType.credit4\n | AssetType.credit12\n | AssetType.liquidityPoolShares;\n asset_code?: string;\n asset_issuer?: string;\n liquidity_pool_id?: string;\n trustee?: string;\n trustor: string;\n limit: string;\n }\n export interface AllowTrustOperationResponse extends BaseOperationResponse<\n OperationResponseType.allowTrust,\n OperationResponseTypeI.allowTrust\n > {\n asset_type: AssetType;\n asset_code: string;\n asset_issuer: string;\n authorize: boolean;\n authorize_to_maintain_liabilities: boolean;\n trustee: string;\n trustor: string;\n }\n export interface AccountMergeOperationResponse extends BaseOperationResponse<\n OperationResponseType.accountMerge,\n OperationResponseTypeI.accountMerge\n > {\n into: string;\n }\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- empty interface names a public API response type\n export interface InflationOperationResponse extends BaseOperationResponse<\n OperationResponseType.inflation,\n OperationResponseTypeI.inflation\n > {}\n export interface ManageDataOperationResponse extends BaseOperationResponse<\n OperationResponseType.manageData,\n OperationResponseTypeI.manageData\n > {\n name: string;\n value: Buffer;\n }\n export interface BumpSequenceOperationResponse extends BaseOperationResponse<\n OperationResponseType.bumpSequence,\n OperationResponseTypeI.bumpSequence\n > {\n bump_to: string;\n }\n export interface Predicate {\n and?: Predicate[];\n or?: Predicate[];\n not?: Predicate;\n abs_before?: string;\n rel_before?: string;\n }\n\n export interface Claimant {\n destination: string;\n predicate: Predicate;\n }\n\n export interface CreateClaimableBalanceOperationResponse extends BaseOperationResponse<\n OperationResponseType.createClaimableBalance,\n OperationResponseTypeI.createClaimableBalance\n > {\n asset: string;\n amount: string;\n sponsor: string;\n claimants: Claimant[];\n }\n\n export interface ClaimClaimableBalanceOperationResponse extends BaseOperationResponse<\n OperationResponseType.claimClaimableBalance,\n OperationResponseTypeI.claimClaimableBalance\n > {\n balance_id: string;\n claimant: string;\n }\n\n export interface BeginSponsoringFutureReservesOperationResponse extends BaseOperationResponse<\n OperationResponseType.beginSponsoringFutureReserves,\n OperationResponseTypeI.beginSponsoringFutureReserves\n > {\n sponsored_id: string;\n }\n\n export interface EndSponsoringFutureReservesOperationResponse extends BaseOperationResponse<\n OperationResponseType.endSponsoringFutureReserves,\n OperationResponseTypeI.endSponsoringFutureReserves\n > {\n begin_sponsor: string;\n }\n\n export interface RevokeSponsorshipOperationResponse extends BaseOperationResponse<\n OperationResponseType.revokeSponsorship,\n OperationResponseTypeI.revokeSponsorship\n > {\n account_id?: string;\n claimable_balance_id?: string;\n data_account_id?: string;\n data_name?: string;\n offer_id?: string;\n trustline_account_id?: string;\n trustline_asset?: string;\n trustline_liquidity_pool_id?: string;\n signer_account_id?: string;\n signer_key?: string;\n }\n\n export interface ClawbackOperationResponse extends BaseOperationResponse<\n OperationResponseType.clawback,\n OperationResponseTypeI.clawback\n > {\n asset_type: AssetType;\n asset_code: string;\n asset_issuer: string;\n from: string;\n amount: string;\n }\n\n export interface ClawbackClaimableBalanceOperationResponse extends BaseOperationResponse<\n OperationResponseType.clawbackClaimableBalance,\n OperationResponseTypeI.clawbackClaimableBalance\n > {\n balance_id: string;\n }\n\n export interface SetTrustLineFlagsOperationResponse extends BaseOperationResponse<\n OperationResponseType.setTrustLineFlags,\n OperationResponseTypeI.setTrustLineFlags\n > {\n asset_type: AssetType;\n asset_code: string;\n asset_issuer: string;\n trustor: string;\n set_flags: Array<1 | 2 | 4>;\n clear_flags: Array<1 | 2 | 4>;\n }\n export interface Reserve {\n asset: string;\n amount: string;\n }\n export interface DepositLiquidityOperationResponse extends BaseOperationResponse<\n OperationResponseType.liquidityPoolDeposit,\n OperationResponseTypeI.liquidityPoolDeposit\n > {\n liquidity_pool_id: string;\n reserves_max: Reserve[];\n min_price: string;\n min_price_r: PriceRShorthand;\n max_price: string;\n max_price_r: PriceRShorthand;\n reserves_deposited: Reserve[];\n shares_received: string;\n }\n export interface WithdrawLiquidityOperationResponse extends BaseOperationResponse<\n OperationResponseType.liquidityPoolWithdraw,\n OperationResponseTypeI.liquidityPoolWithdraw\n > {\n liquidity_pool_id: string;\n reserves_min: Reserve[];\n shares: string;\n reserves_received: Reserve[];\n }\n\n export interface BalanceChange {\n asset_type: string;\n asset_code?: string;\n asset_issuer?: string;\n\n type: string;\n from: string;\n to: string;\n amount: string;\n destination_muxed_id?: string;\n }\n\n export interface InvokeHostFunctionOperationResponse extends BaseOperationResponse<\n OperationResponseType.invokeHostFunction,\n OperationResponseTypeI.invokeHostFunction\n > {\n function: string;\n parameters: {\n value: string;\n type: string;\n }[];\n address: string;\n salt: string;\n asset_balance_changes: BalanceChange[];\n }\n\n export interface BumpFootprintExpirationOperationResponse extends BaseOperationResponse<\n OperationResponseType.bumpFootprintExpiration,\n OperationResponseTypeI.bumpFootprintExpiration\n > {\n ledgers_to_expire: number;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- empty interface names a public API response type\n export interface RestoreFootprintOperationResponse extends BaseOperationResponse<\n OperationResponseType.restoreFootprint,\n OperationResponseTypeI.restoreFootprint\n > {}\n\n export interface ResponseCollection<T extends BaseResponse = BaseResponse> {\n _links: {\n self: ResponseLink;\n next: ResponseLink;\n prev: ResponseLink;\n };\n _embedded: {\n records: T[];\n };\n }\n // eslint-disable-next-line @typescript-eslint/no-empty-object-type -- empty interface names a public API response type\n export interface TransactionResponseCollection extends ResponseCollection<TransactionResponse> {}\n\n export interface FeeDistribution {\n max: string;\n min: string;\n mode: string;\n p10: string;\n p20: string;\n p30: string;\n p40: string;\n p50: string;\n p60: string;\n p70: string;\n p80: string;\n p90: string;\n p95: string;\n p99: string;\n }\n export interface FeeStatsResponse {\n last_ledger: string;\n last_ledger_base_fee: string;\n ledger_capacity_usage: string;\n fee_charged: FeeDistribution;\n max_fee: FeeDistribution;\n }\n\n export type ErrorResponseData =\n | ErrorResponseData.RateLimitExceeded\n | ErrorResponseData.InternalServerError\n | ErrorResponseData.TransactionFailed;\n\n export namespace ErrorResponseData {\n export interface Base {\n status: number;\n title: string;\n type: string; // TODO\n details: string; // TODO\n instance: string; // TODO\n }\n\n export interface RateLimitExceeded extends Base {\n status: 429;\n title: \"Rate Limit Exceeded\";\n }\n export interface InternalServerError extends Base {\n status: 500;\n title: \"Internal Server Error\";\n }\n export interface TransactionFailed extends Base {\n status: 400;\n title: \"Transaction Failed\";\n extras: TransactionFailedExtras;\n }\n }\n\n export enum TransactionFailedResultCodes {\n TX_FAILED = \"tx_failed\",\n TX_BAD_SEQ = \"tx_bad_seq\",\n TX_BAD_AUTH = \"tx_bad_auth\",\n TX_BAD_AUTH_EXTRA = \"tx_bad_auth_extra\",\n TX_FEE_BUMP_INNER_SUCCESS = \"tx_fee_bump_inner_success\",\n TX_FEE_BUMP_INNER_FAILED = \"tx_fee_bump_inner_failed\",\n TX_NOT_SUPPORTED = \"tx_not_supported\",\n TX_SUCCESS = \"tx_success\",\n TX_TOO_EARLY = \"tx_too_early\",\n TX_TOO_LATE = \"tx_too_late\",\n TX_MISSING_OPERATION = \"tx_missing_operation\",\n TX_INSUFFICIENT_BALANCE = \"tx_insufficient_balance\",\n TX_NO_SOURCE_ACCOUNT = \"tx_no_source_account\",\n TX_INSUFFICIENT_FEE = \"tx_insufficient_fee\",\n TX_INTERNAL_ERROR = \"tx_internal_error\",\n TX_BAD_SPONSORSHIP = \"tx_bad_sponsorship\",\n TX_BAD_MIN_SEQ_AGE_OR_GAP = \"tx_bad_min_seq_age_or_gap\",\n TX_MALFORMED = \"tx_malformed\",\n TX_SOROBAN_INVALID = \"tx_soroban_invalid\",\n TX_FROZEN_KEY_ACCESSED = \"tx_frozen_key_accessed\",\n }\n\n export interface TransactionFailedExtras {\n envelope_xdr: string; // base64\n result_codes: {\n transaction: TransactionFailedResultCodes;\n /** Omitted by Horizon when the transaction failed a transaction-level\n * check (e.g. `tx_bad_seq`) and no operations were evaluated. Typed as\n * required for backwards compatibility; treat as possibly undefined\n * when reading the raw response, or use\n * `TransactionFailedError.getResultCodes()` which normalizes it.\n * TODO(next major): make this `operations?: string[]`. */\n operations: string[];\n };\n result_xdr: string;\n }\n\n export interface RootResponse {\n horizon_version: string;\n core_version: string;\n ingest_latest_ledger: number;\n history_latest_ledger: number;\n history_latest_ledger_closed_at: string;\n history_elder_ledger: number;\n core_latest_ledger: number;\n network_passphrase: string;\n current_protocol_version: number;\n supported_protocol_version: number;\n core_supported_protocol_version: number;\n }\n}\n"],"names":["HorizonApi","LiquidityPoolType","OperationResponseType","OperationResponseTypeI","TransactionFailedResultCodes"],"mappings":"AAGO,IAAU;AAAA,CAAV,CAAUA,WAAAA,KAAV;AAiME,EAAA,CAAA,CAAKC,kBAAAA,KAAL;AACL,IAAAA,mBAAA,iBAAA,CAAA,GAAkB,k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,KAAL;AACL,IAAAA,8BAAA,WAAA,CAAA,GAAY,WAAA;AACZ,IAAAA,8BAAA,YAAA,CAAA,GAAa,YAAA;AACb,IAAAA,8BAAA,aAAA,CAAA,GAAc,aAAA;AACd,IAAAA,8BAAA,mBAAA,CAAA,GAAoB,mBAAA;AACpB,IAAAA,8BAAA,2BAAA,CAAA,GAA4B,2BAAA;AAC5B,IAAAA,8BAAA,0BAAA,CAAA,GAA2B,0BAAA;AAC3B,IAAAA,8BAAA,kBAAA,CAAA,GAAmB,kBAAA;AACnB,IAAAA,8BAAA,YAAA,CAAA,GAAa,YAAA;AACb,IAAAA,8BAAA,cAAA,CAAA,GAAe,cAAA;AACf,IAAAA,8BAAA,aAAA,CAAA,GAAc,aAAA;AACd,IAAAA,8BAAA,sBAAA,CAAA,GAAuB,sBAAA;AACvB,IAAAA,8BAAA,yBAAA,CAAA,GAA0B,yBAAA;AAC1B,IAAAA,8BAAA,sBAAA,CAAA,GAAuB,sBAAA;AACvB,IAAAA,8BAAA,qBAAA,CAAA,GAAsB,qBAAA;AACtB,IAAAA,8BAAA,mBAAA,CAAA,GAAoB,mBAAA;AACpB,IAAAA,8BAAA,oBAAA,CAAA,GAAqB,oBAAA;AACrB,IAAAA,8BAAA,2BAAA,CAAA,GAA4B,2BAAA;AAC5B,IAAAA,8BAAA,cAAA,CAAA,GAAe,cAAA;AACf,IAAAA,8BAAA,oBAAA,CAAA,GAAqB,oBAAA;AACrB,IAAAA,8BAAA,wBAAA,CAAA,GAAyB,wBAAA;AAAA,EAAA,CAAA,EApBfJ,WAAAA,CAAA,4BAAA,KAAAA,WAAAA,CAAA,4BAAA,GAAA,EAAA,CAAA,CAAA;AAAA,CAAA,EAlpBG,UAAA,KAAA,UAAA,GAAA,EAAA,CAAA,CAAA;;;;"}
|
|
@@ -203,8 +203,11 @@ export declare class HorizonServer {
|
|
|
203
203
|
* - `skipMemoRequiredCheck` (optional): Allow skipping memo
|
|
204
204
|
* required check, default: `false`. See
|
|
205
205
|
* [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md).
|
|
206
|
-
* @returns Promise that resolves
|
|
207
|
-
*
|
|
206
|
+
* @returns Promise that resolves with the response from Horizon. Rejects
|
|
207
|
+
* with a {@link TransactionFailedError} when Horizon reports transaction
|
|
208
|
+
* result codes, a {@link BadResponseError} for any other HTTP error
|
|
209
|
+
* response (the underlying client error is preserved as `cause` on both),
|
|
210
|
+
* or the original error for network-level failures.
|
|
208
211
|
*/
|
|
209
212
|
submitTransaction(transaction: Transaction | FeeBumpTransaction, opts?: HorizonServer.SubmitTransactionOptions): Promise<HorizonApi.SubmitTransactionResponse>;
|
|
210
213
|
/**
|
|
@@ -221,8 +224,11 @@ export declare class HorizonServer {
|
|
|
221
224
|
* - `skipMemoRequiredCheck` (optional): Allow skipping memo
|
|
222
225
|
* required check, default: `false`. See
|
|
223
226
|
* [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md).
|
|
224
|
-
* @returns Promise that resolves
|
|
225
|
-
*
|
|
227
|
+
* @returns Promise that resolves with the response from Horizon. Rejects
|
|
228
|
+
* with a {@link TransactionFailedError} when Horizon reports transaction
|
|
229
|
+
* result codes, a {@link BadResponseError} for any other HTTP error
|
|
230
|
+
* response (the underlying client error is preserved as `cause` on both),
|
|
231
|
+
* or the original error for network-level failures.
|
|
226
232
|
*/
|
|
227
233
|
submitAsyncTransaction(transaction: Transaction | FeeBumpTransaction, opts?: HorizonServer.SubmitTransactionOptions): Promise<HorizonApi.SubmitAsyncTransactionResponse>;
|
|
228
234
|
/**
|
|
@@ -24,7 +24,9 @@ import { CallBuilder } from './call_builder.js';
|
|
|
24
24
|
import { Config } from '../config.js';
|
|
25
25
|
import { NotFoundError } from '../errors/not_found.js';
|
|
26
26
|
import { BadResponseError } from '../errors/bad_response.js';
|
|
27
|
+
import { TransactionFailedError } from '../errors/transaction_failed.js';
|
|
27
28
|
import { AccountRequiresMemoError } from '../errors/account_requires_memo.js';
|
|
29
|
+
import { wrapHttpError } from '../errors/wrap_http_error.js';
|
|
28
30
|
import { AccountCallBuilder } from './account_call_builder.js';
|
|
29
31
|
import { AccountResponse } from './account_response.js';
|
|
30
32
|
import { AssetsCallBuilder } from './assets_call_builder.js';
|
|
@@ -50,6 +52,12 @@ const ACCOUNT_REQUIRES_MEMO = "MQ==";
|
|
|
50
52
|
function getAmountInLumens(amt) {
|
|
51
53
|
return new BigNumber(amt).div(STROOPS_IN_LUMEN).toString();
|
|
52
54
|
}
|
|
55
|
+
function toSubmissionError(error) {
|
|
56
|
+
return wrapHttpError(error, (details) => {
|
|
57
|
+
const message = `Transaction submission failed. Server responded: ${details.status} ${details.statusText}`;
|
|
58
|
+
return details.data?.extras?.result_codes ? new TransactionFailedError(message, details) : new BadResponseError(message, details);
|
|
59
|
+
});
|
|
60
|
+
}
|
|
53
61
|
class HorizonServer {
|
|
54
62
|
/**
|
|
55
63
|
* Horizon Server URL (ex. `https://horizon-testnet.stellar.org`)
|
|
@@ -278,8 +286,11 @@ class HorizonServer {
|
|
|
278
286
|
* - `skipMemoRequiredCheck` (optional): Allow skipping memo
|
|
279
287
|
* required check, default: `false`. See
|
|
280
288
|
* [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md).
|
|
281
|
-
* @returns Promise that resolves
|
|
282
|
-
*
|
|
289
|
+
* @returns Promise that resolves with the response from Horizon. Rejects
|
|
290
|
+
* with a {@link TransactionFailedError} when Horizon reports transaction
|
|
291
|
+
* result codes, a {@link BadResponseError} for any other HTTP error
|
|
292
|
+
* response (the underlying client error is preserved as `cause` on both),
|
|
293
|
+
* or the original error for network-level failures.
|
|
283
294
|
*/
|
|
284
295
|
async submitTransaction(transaction, opts = {
|
|
285
296
|
skipMemoRequiredCheck: false
|
|
@@ -419,17 +430,7 @@ class HorizonServer {
|
|
|
419
430
|
...response.data,
|
|
420
431
|
offerResults: hasManageOffer ? offerResults : void 0
|
|
421
432
|
};
|
|
422
|
-
}).catch((
|
|
423
|
-
if (response instanceof Error) {
|
|
424
|
-
return Promise.reject(response);
|
|
425
|
-
}
|
|
426
|
-
return Promise.reject(
|
|
427
|
-
new BadResponseError(
|
|
428
|
-
`Transaction submission failed. Server responded: ${response.status} ${response.statusText}`,
|
|
429
|
-
response.data
|
|
430
|
-
)
|
|
431
|
-
);
|
|
432
|
-
});
|
|
433
|
+
}).catch((error) => Promise.reject(toSubmissionError(error)));
|
|
433
434
|
}
|
|
434
435
|
/**
|
|
435
436
|
* Submits an asynchronous transaction to the network. Unlike the synchronous version, which blocks
|
|
@@ -445,8 +446,11 @@ class HorizonServer {
|
|
|
445
446
|
* - `skipMemoRequiredCheck` (optional): Allow skipping memo
|
|
446
447
|
* required check, default: `false`. See
|
|
447
448
|
* [SEP0029](https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0029.md).
|
|
448
|
-
* @returns Promise that resolves
|
|
449
|
-
*
|
|
449
|
+
* @returns Promise that resolves with the response from Horizon. Rejects
|
|
450
|
+
* with a {@link TransactionFailedError} when Horizon reports transaction
|
|
451
|
+
* result codes, a {@link BadResponseError} for any other HTTP error
|
|
452
|
+
* response (the underlying client error is preserved as `cause` on both),
|
|
453
|
+
* or the original error for network-level failures.
|
|
450
454
|
*/
|
|
451
455
|
async submitAsyncTransaction(transaction, opts = {
|
|
452
456
|
skipMemoRequiredCheck: false
|
|
@@ -461,17 +465,7 @@ class HorizonServer {
|
|
|
461
465
|
url.pathname = url.pathname.split("/").concat(["transactions_async"]).filter((value) => value.length > 0).join("/");
|
|
462
466
|
return this.httpClient.post(url.toString(), `tx=${tx}`, {
|
|
463
467
|
headers: { "Content-Type": "application/x-www-form-urlencoded" }
|
|
464
|
-
}).then((response) => response.data).catch((
|
|
465
|
-
if (response instanceof Error) {
|
|
466
|
-
return Promise.reject(response);
|
|
467
|
-
}
|
|
468
|
-
return Promise.reject(
|
|
469
|
-
new BadResponseError(
|
|
470
|
-
`Transaction submission failed. Server responded: ${response.status} ${response.statusText}`,
|
|
471
|
-
response.data
|
|
472
|
-
)
|
|
473
|
-
);
|
|
474
|
-
});
|
|
468
|
+
}).then((response) => response.data).catch((error) => Promise.reject(toSubmissionError(error)));
|
|
475
469
|
}
|
|
476
470
|
/**
|
|
477
471
|
* @returns New {@link AccountCallBuilder} object configured by a current Horizon server configuration.
|