@lifi/sdk 4.2.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/cjs/actions/getContractCallsQuote.js.map +1 -1
  3. package/dist/cjs/actions/getTokenBalances.js +3 -2
  4. package/dist/cjs/actions/getTokenBalances.js.map +1 -1
  5. package/dist/cjs/actions/getTokenBalancesByChain.js.map +1 -1
  6. package/dist/cjs/actions/index.d.ts +1 -8
  7. package/dist/cjs/actions/index.js +0 -2
  8. package/dist/cjs/actions/index.js.map +1 -1
  9. package/dist/cjs/client/getClientStorage.js +3 -2
  10. package/dist/cjs/client/getClientStorage.js.map +1 -1
  11. package/dist/cjs/core/BaseStepExecutor.js +11 -9
  12. package/dist/cjs/core/BaseStepExecutor.js.map +1 -1
  13. package/dist/cjs/core/StatusManager.js +1 -4
  14. package/dist/cjs/core/StatusManager.js.map +1 -1
  15. package/dist/cjs/core/execution.js.map +1 -1
  16. package/dist/cjs/core/tasks/CheckBalanceTask.js +2 -1
  17. package/dist/cjs/core/tasks/CheckBalanceTask.js.map +1 -1
  18. package/dist/cjs/core/tasks/PrepareTransactionTask.d.ts +7 -0
  19. package/dist/cjs/core/tasks/PrepareTransactionTask.js +12 -2
  20. package/dist/cjs/core/tasks/PrepareTransactionTask.js.map +1 -1
  21. package/dist/cjs/core/tasks/helpers/checkBalance.js +1 -1
  22. package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
  23. package/dist/cjs/index.d.ts +1 -2
  24. package/dist/cjs/index.js +0 -2
  25. package/dist/cjs/utils/checkPackageUpdates.js +1 -1
  26. package/dist/cjs/version.d.ts +1 -1
  27. package/dist/cjs/version.js +1 -1
  28. package/dist/cjs/version.js.map +1 -1
  29. package/dist/esm/actions/getTokenBalances.js +3 -2
  30. package/dist/esm/actions/getTokenBalances.js.map +1 -1
  31. package/dist/esm/actions/getTokenBalancesByChain.d.ts.map +1 -1
  32. package/dist/esm/actions/getTokenBalancesByChain.js.map +1 -1
  33. package/dist/esm/actions/index.d.ts +1 -8
  34. package/dist/esm/actions/index.d.ts.map +1 -1
  35. package/dist/esm/actions/index.js +0 -2
  36. package/dist/esm/actions/index.js.map +1 -1
  37. package/dist/esm/client/getClientStorage.js +3 -2
  38. package/dist/esm/client/getClientStorage.js.map +1 -1
  39. package/dist/esm/core/BaseStepExecutor.js +11 -9
  40. package/dist/esm/core/BaseStepExecutor.js.map +1 -1
  41. package/dist/esm/core/StatusManager.js +1 -4
  42. package/dist/esm/core/StatusManager.js.map +1 -1
  43. package/dist/esm/core/execution.js.map +1 -1
  44. package/dist/esm/core/tasks/CheckBalanceTask.js +2 -1
  45. package/dist/esm/core/tasks/CheckBalanceTask.js.map +1 -1
  46. package/dist/esm/core/tasks/PrepareTransactionTask.d.ts +7 -0
  47. package/dist/esm/core/tasks/PrepareTransactionTask.d.ts.map +1 -1
  48. package/dist/esm/core/tasks/PrepareTransactionTask.js +12 -2
  49. package/dist/esm/core/tasks/PrepareTransactionTask.js.map +1 -1
  50. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js +2 -1
  51. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  52. package/dist/esm/core/tasks/helpers/checkBalance.js +1 -1
  53. package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
  54. package/dist/esm/index.d.ts +1 -2
  55. package/dist/esm/index.js +1 -2
  56. package/dist/esm/utils/checkPackageUpdates.js +1 -1
  57. package/dist/esm/version.d.ts +1 -1
  58. package/dist/esm/version.js +1 -1
  59. package/dist/esm/version.js.map +1 -1
  60. package/package.json +2 -2
  61. package/src/actions/index.ts +0 -15
  62. package/src/client/getClientStorage.ts +1 -0
  63. package/src/core/tasks/PrepareTransactionTask.ts +11 -1
  64. package/src/index.ts +0 -1
  65. package/src/version.ts +1 -1
  66. package/dist/cjs/actions/getWalletBalances.d.ts +0 -15
  67. package/dist/cjs/actions/getWalletBalances.js +0 -20
  68. package/dist/cjs/actions/getWalletBalances.js.map +0 -1
  69. package/dist/esm/actions/getWalletBalances.d.ts +0 -15
  70. package/dist/esm/actions/getWalletBalances.d.ts.map +0 -1
  71. package/dist/esm/actions/getWalletBalances.js +0 -19
  72. package/dist/esm/actions/getWalletBalances.js.map +0 -1
  73. package/src/actions/getWalletBalances.ts +0 -36
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @lifi/sdk
2
2
 
3
+ ## 4.4.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [`fd1e9b5`](https://github.com/lifinance/sdk/commit/fd1e9b5ff481b35683d7b8557011c9c726446cdd) Thanks [@chybisov](https://github.com/chybisov)! - Add Stellar (STL) ecosystem support. Introduces the `@lifi/sdk-provider-stellar` package — address validation, Federation resolution, SAC-based balance reads, and route execution via `StellarStepExecutor` — and registers `ChainType.STL` in the SDK client's chain fetching so Stellar chains and RPC URLs load.
8
+
9
+ Execution signs the backend-generated Soroban envelope with the connected wallet, submits it over Stellar RPC, waits for on-chain confirmation, then tracks the transfer through the LI.FI status API. Because a Stellar envelope embeds the sender's account sequence number and a short-lived set of timebounds, the provider always requests a freshly built transaction immediately before signing rather than reusing the one attached to the quote. SAC allowances are granted first when a step requires one, and the approval is confirmed on-chain before the route transaction is requested.
10
+
11
+ `PrepareTransactionTask` gains a `shouldRefetchTransaction` hook. It defaults to the previous behaviour — fetch only when the step carries no transaction request — and the Stellar task overrides it, because a Stellar envelope embeds the sender's sequence number and cannot be reused.
12
+
13
+ `StellarProviderOptions.horizonUrl` is gone — nothing read it — and `StellarWallet.signAuthEntry` is now optional, because the router routes use source-account auth and the SDK never calls it. The provider also exports `DEFAULT_NETWORK_PASSPHRASE`, and refuses to sign when the connected wallet's network disagrees with the configured one.
14
+
15
+ ## 4.3.0
16
+
17
+ ### Minor Changes
18
+
19
+ - [#431](https://github.com/lifinance/sdk/pull/431) [`08b54da`](https://github.com/lifinance/sdk/commit/08b54dadebef063bc20af06630f0e43ec5850dca) Thanks [@chybisov](https://github.com/chybisov)! - Remove the `getWalletBalances` action and client method — the underlying `/wallets/{address}/balances` API endpoint is deprecated. Use `getTokenBalances`/`getTokenBalancesByChain` to fetch balances directly from RPCs instead.
20
+
21
+ ### Patch Changes
22
+
23
+ - [#435](https://github.com/lifinance/sdk/pull/435) [`d8b7adb`](https://github.com/lifinance/sdk/commit/d8b7adb6f797734f25d8c7d458121752a2567998) Thanks [@chybisov](https://github.com/chybisov)! - Bump runtime dependencies: @lifi/types to 17.86.0 (sdk), viem to 2.55.8 (ethereum), and @mysten/sui to 2.22.1 (sui).
24
+
3
25
  ## 4.2.0
4
26
 
5
27
  ### Minor Changes
@@ -1 +1 @@
1
- {"version":3,"file":"getContractCallsQuote.js","names":["SDKError","ValidationError","request"],"sources":["../../../src/actions/getContractCallsQuote.ts"],"sourcesContent":["import type {\n ContractCallsQuoteRequest,\n LiFiStep,\n RequestOptions,\n} from '@lifi/types'\nimport {\n isContractCallsRequestWithFromAmount,\n isContractCallsRequestWithToAmount,\n} from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\n\n/**\n * Get a quote for a destination contract call\n * @param client - The SDK client\n * @param params - The configuration of the requested destination call\n * @param options - Request options\n * @throws {LiFiError} - Throws a LiFiError if request fails\n * @returns - Returns step.\n */\nexport const getContractCallsQuote = async (\n client: SDKClient,\n params: ContractCallsQuoteRequest,\n options?: RequestOptions\n): Promise<LiFiStep> => {\n // validation\n const requiredParameters: Array<keyof ContractCallsQuoteRequest> = [\n 'fromChain',\n 'fromToken',\n 'fromAddress',\n 'toChain',\n 'toToken',\n 'contractCalls',\n ]\n for (const requiredParameter of requiredParameters) {\n if (!params[requiredParameter]) {\n throw new SDKError(\n new ValidationError(\n `Required parameter \"${requiredParameter}\" is missing.`\n )\n )\n }\n }\n if (\n !isContractCallsRequestWithFromAmount(params) &&\n !isContractCallsRequestWithToAmount(params)\n ) {\n throw new SDKError(\n new ValidationError(\n `Required parameter \"fromAmount\" or \"toAmount\" is missing.`\n )\n )\n }\n // apply defaults\n // option.order is not used in this endpoint\n params.integrator ??= client.config.integrator\n params.slippage ??= client.config.routeOptions?.slippage\n params.referrer ??= client.config.routeOptions?.referrer\n params.fee ??= client.config.routeOptions?.fee\n params.allowBridges ??= client.config.routeOptions?.bridges?.allow\n params.denyBridges ??= client.config.routeOptions?.bridges?.deny\n params.preferBridges ??= client.config.routeOptions?.bridges?.prefer\n params.allowExchanges ??= client.config.routeOptions?.exchanges?.allow\n params.denyExchanges ??= client.config.routeOptions?.exchanges?.deny\n params.preferExchanges ??= client.config.routeOptions?.exchanges?.prefer\n // send request\n return await request<LiFiStep>(\n client.config,\n `${client.config.apiUrl}/quote/contractCalls`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(params),\n signal: options?.signal,\n }\n )\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,wBAAwB,OACnC,QACA,QACA,YACsB;CAUtB,KAAK,MAAM,qBAAqB;EAP9B;EACA;EACA;EACA;EACA;EACA;CAE+C,GAC/C,IAAI,CAAC,OAAO,oBACV,MAAM,IAAIA,wBAAAA,SACR,IAAIC,sBAAAA,gBACF,uBAAuB,kBAAkB,cAC3C,CACF;CAGJ,IACE,EAAA,GAAA,YAAA,qCAAA,CAAsC,MAAM,KAC5C,EAAA,GAAA,YAAA,mCAAA,CAAoC,MAAM,GAE1C,MAAM,IAAID,wBAAAA,SACR,IAAIC,sBAAAA,gBACF,2DACF,CACF;CAIF,OAAO,eAAe,OAAO,OAAO;CACpC,OAAO,aAAa,OAAO,OAAO,cAAc;CAChD,OAAO,aAAa,OAAO,OAAO,cAAc;CAChD,OAAO,QAAQ,OAAO,OAAO,cAAc;CAC3C,OAAO,iBAAiB,OAAO,OAAO,cAAc,SAAS;CAC7D,OAAO,gBAAgB,OAAO,OAAO,cAAc,SAAS;CAC5D,OAAO,kBAAkB,OAAO,OAAO,cAAc,SAAS;CAC9D,OAAO,mBAAmB,OAAO,OAAO,cAAc,WAAW;CACjE,OAAO,kBAAkB,OAAO,OAAO,cAAc,WAAW;CAChE,OAAO,oBAAoB,OAAO,OAAO,cAAc,WAAW;CAElE,OAAO,MAAMC,sBAAAA,QACX,OAAO,QACP,GAAG,OAAO,OAAO,OAAO,uBACxB;EACE,QAAQ;EACR,SAAS,EACP,gBAAgB,mBAClB;EACA,MAAM,KAAK,UAAU,MAAM;EAC3B,QAAQ,SAAS;CACnB,CACF;AACF"}
1
+ {"version":3,"file":"getContractCallsQuote.js","names":["SDKError","ValidationError","isContractCallsRequestWithFromAmount","isContractCallsRequestWithToAmount","request"],"sources":["../../../src/actions/getContractCallsQuote.ts"],"sourcesContent":["import type {\n ContractCallsQuoteRequest,\n LiFiStep,\n RequestOptions,\n} from '@lifi/types'\nimport {\n isContractCallsRequestWithFromAmount,\n isContractCallsRequestWithToAmount,\n} from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\n\n/**\n * Get a quote for a destination contract call\n * @param client - The SDK client\n * @param params - The configuration of the requested destination call\n * @param options - Request options\n * @throws {LiFiError} - Throws a LiFiError if request fails\n * @returns - Returns step.\n */\nexport const getContractCallsQuote = async (\n client: SDKClient,\n params: ContractCallsQuoteRequest,\n options?: RequestOptions\n): Promise<LiFiStep> => {\n // validation\n const requiredParameters: Array<keyof ContractCallsQuoteRequest> = [\n 'fromChain',\n 'fromToken',\n 'fromAddress',\n 'toChain',\n 'toToken',\n 'contractCalls',\n ]\n for (const requiredParameter of requiredParameters) {\n if (!params[requiredParameter]) {\n throw new SDKError(\n new ValidationError(\n `Required parameter \"${requiredParameter}\" is missing.`\n )\n )\n }\n }\n if (\n !isContractCallsRequestWithFromAmount(params) &&\n !isContractCallsRequestWithToAmount(params)\n ) {\n throw new SDKError(\n new ValidationError(\n `Required parameter \"fromAmount\" or \"toAmount\" is missing.`\n )\n )\n }\n // apply defaults\n // option.order is not used in this endpoint\n params.integrator ??= client.config.integrator\n params.slippage ??= client.config.routeOptions?.slippage\n params.referrer ??= client.config.routeOptions?.referrer\n params.fee ??= client.config.routeOptions?.fee\n params.allowBridges ??= client.config.routeOptions?.bridges?.allow\n params.denyBridges ??= client.config.routeOptions?.bridges?.deny\n params.preferBridges ??= client.config.routeOptions?.bridges?.prefer\n params.allowExchanges ??= client.config.routeOptions?.exchanges?.allow\n params.denyExchanges ??= client.config.routeOptions?.exchanges?.deny\n params.preferExchanges ??= client.config.routeOptions?.exchanges?.prefer\n // send request\n return await request<LiFiStep>(\n client.config,\n `${client.config.apiUrl}/quote/contractCalls`,\n {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(params),\n signal: options?.signal,\n }\n )\n}\n"],"mappings":";;;;;;;;;;;;;;AAsBA,MAAa,wBAAwB,OACnC,QACA,QACA,YACsB;CAUtB,KAAK,MAAM,qBAAqB;EAP9B;EACA;EACA;EACA;EACA;EACA;CAE+C,GAC/C,IAAI,CAAC,OAAO,oBACV,MAAM,IAAIA,wBAAAA,SACR,IAAIC,sBAAAA,gBACF,uBAAuB,kBAAkB,cAC3C,CACF;CAGJ,IACE,EAAA,GAACC,YAAAA,qCAAAA,CAAqC,MAAM,KAC5C,EAAA,GAACC,YAAAA,mCAAAA,CAAmC,MAAM,GAE1C,MAAM,IAAIH,wBAAAA,SACR,IAAIC,sBAAAA,gBACF,2DACF,CACF;CAIF,OAAO,eAAe,OAAO,OAAO;CACpC,OAAO,aAAa,OAAO,OAAO,cAAc;CAChD,OAAO,aAAa,OAAO,OAAO,cAAc;CAChD,OAAO,QAAQ,OAAO,OAAO,cAAc;CAC3C,OAAO,iBAAiB,OAAO,OAAO,cAAc,SAAS;CAC7D,OAAO,gBAAgB,OAAO,OAAO,cAAc,SAAS;CAC5D,OAAO,kBAAkB,OAAO,OAAO,cAAc,SAAS;CAC9D,OAAO,mBAAmB,OAAO,OAAO,cAAc,WAAW;CACjE,OAAO,kBAAkB,OAAO,OAAO,cAAc,WAAW;CAChE,OAAO,oBAAoB,OAAO,OAAO,cAAc,WAAW;CAElE,OAAO,MAAMG,sBAAAA,QACX,OAAO,QACP,GAAG,OAAO,OAAO,OAAO,uBACxB;EACE,QAAQ;EACR,SAAS,EACP,gBAAgB,mBAClB;EACA,MAAM,KAAK,UAAU,MAAM;EAC3B,QAAQ,SAAS;CACnB,CACF;AACF"}
@@ -2,11 +2,12 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_actions_getTokenBalancesByChain = require("./getTokenBalancesByChain.js");
3
3
  //#region src/actions/getTokenBalances.ts
4
4
  async function getTokenBalances(client, walletAddress, tokens) {
5
- const tokenAmountsByChain = await require_actions_getTokenBalancesByChain.getTokenBalancesByChain(client, walletAddress, tokens.reduce((tokens, token) => {
5
+ const tokensByChain = tokens.reduce((tokens, token) => {
6
6
  if (!tokens[token.chainId]) tokens[token.chainId] = [];
7
7
  tokens[token.chainId].push(token);
8
8
  return tokens;
9
- }, {}));
9
+ }, {});
10
+ const tokenAmountsByChain = await require_actions_getTokenBalancesByChain.getTokenBalancesByChain(client, walletAddress, tokensByChain);
10
11
  return Object.values(tokenAmountsByChain).flat();
11
12
  }
12
13
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"getTokenBalances.js","names":["getTokenBalancesByChain"],"sources":["../../../src/actions/getTokenBalances.ts"],"sourcesContent":["import type {\n Token,\n TokenAmount,\n TokenAmountExtended,\n TokenExtended,\n} from '@lifi/types'\nimport type { SDKClient } from '../types/core.js'\nimport { getTokenBalancesByChain } from './getTokenBalancesByChain.js'\n\n/**\n * Returns the balances for a list tokens a wallet holds across all aggregated chains.\n * @param client - The SDK client.\n * @param walletAddress - A wallet address.\n * @param tokens - A list of Token (or TokenExtended) objects.\n * @returns A list of objects containing the tokens and the amounts on different chains.\n * @throws {ValidationError} Throws a ValidationError if validation fails.\n * @throws {Error} Throws an Error if the SDK Provider for the wallet address is not found.\n */\nexport async function getTokenBalances(\n client: SDKClient,\n walletAddress: string,\n tokens: Token[]\n): Promise<TokenAmount[]>\nexport async function getTokenBalances(\n client: SDKClient,\n walletAddress: string,\n tokens: TokenExtended[]\n): Promise<TokenAmountExtended[]> {\n // split by chain\n const tokensByChain = tokens.reduce(\n (tokens, token) => {\n if (!tokens[token.chainId]) {\n tokens[token.chainId] = []\n }\n tokens[token.chainId].push(token)\n return tokens\n },\n {} as { [chainId: number]: Token[] | TokenExtended[] }\n )\n\n const tokenAmountsByChain = await getTokenBalancesByChain(\n client,\n walletAddress,\n tokensByChain\n )\n return Object.values(tokenAmountsByChain).flat()\n}\n"],"mappings":";;;AAuBA,eAAsB,iBACpB,QACA,eACA,QACgC;CAahC,MAAM,sBAAsB,MAAMA,wCAAAA,wBAChC,QACA,eAboB,OAAO,QAC1B,QAAQ,UAAU;EACjB,IAAI,CAAC,OAAO,MAAM,UAChB,OAAO,MAAM,WAAW,CAAC;EAE3B,OAAO,MAAM,QAAQ,CAAC,KAAK,KAAK;EAChC,OAAO;CACT,GACA,CAAC,CAMW,CACd;CACA,OAAO,OAAO,OAAO,mBAAmB,CAAC,CAAC,KAAK;AACjD"}
1
+ {"version":3,"file":"getTokenBalances.js","names":["getTokenBalancesByChain"],"sources":["../../../src/actions/getTokenBalances.ts"],"sourcesContent":["import type {\n Token,\n TokenAmount,\n TokenAmountExtended,\n TokenExtended,\n} from '@lifi/types'\nimport type { SDKClient } from '../types/core.js'\nimport { getTokenBalancesByChain } from './getTokenBalancesByChain.js'\n\n/**\n * Returns the balances for a list tokens a wallet holds across all aggregated chains.\n * @param client - The SDK client.\n * @param walletAddress - A wallet address.\n * @param tokens - A list of Token (or TokenExtended) objects.\n * @returns A list of objects containing the tokens and the amounts on different chains.\n * @throws {ValidationError} Throws a ValidationError if validation fails.\n * @throws {Error} Throws an Error if the SDK Provider for the wallet address is not found.\n */\nexport async function getTokenBalances(\n client: SDKClient,\n walletAddress: string,\n tokens: Token[]\n): Promise<TokenAmount[]>\nexport async function getTokenBalances(\n client: SDKClient,\n walletAddress: string,\n tokens: TokenExtended[]\n): Promise<TokenAmountExtended[]> {\n // split by chain\n const tokensByChain = tokens.reduce(\n (tokens, token) => {\n if (!tokens[token.chainId]) {\n tokens[token.chainId] = []\n }\n tokens[token.chainId].push(token)\n return tokens\n },\n {} as { [chainId: number]: Token[] | TokenExtended[] }\n )\n\n const tokenAmountsByChain = await getTokenBalancesByChain(\n client,\n walletAddress,\n tokensByChain\n )\n return Object.values(tokenAmountsByChain).flat()\n}\n"],"mappings":";;;AAuBA,eAAsB,iBACpB,QACA,eACA,QACgC;CAEhC,MAAM,gBAAgB,OAAO,QAC1B,QAAQ,UAAU;EACjB,IAAI,CAAC,OAAO,MAAM,UAChB,OAAO,MAAM,WAAW,CAAC;EAE3B,OAAO,MAAM,QAAQ,CAAC,KAAK,KAAK;EAChC,OAAO;CACT,GACA,CAAC,CACH;CAEA,MAAM,sBAAsB,MAAMA,wCAAAA,wBAChC,QACA,eACA,aACF;CACA,OAAO,OAAO,OAAO,mBAAmB,CAAC,CAAC,KAAK;AACjD"}
@@ -1 +1 @@
1
- {"version":3,"file":"getTokenBalancesByChain.js","names":["ValidationError","isToken"],"sources":["../../../src/actions/getTokenBalancesByChain.ts"],"sourcesContent":["import type {\n Token,\n TokenAmount,\n TokenAmountExtended,\n TokenExtended,\n} from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport type { SDKClient } from '../types/core.js'\nimport { isToken } from '../utils/isToken.js'\n\n/**\n * This method queries the balances of tokens for a specific list of chains for a given wallet.\n * @param client - The SDK client.\n * @param walletAddress - A wallet address.\n * @param tokensByChain - A list of token objects organized by chain ids.\n * @returns A list of objects containing the tokens and the amounts on different chains organized by the chosen chains.\n * @throws {ValidationError} Throws a ValidationError if validation fails.\n * @throws {Error} Throws an Error if the SDK Provider for the wallet address is not found.\n */\nexport async function getTokenBalancesByChain(\n client: SDKClient,\n walletAddress: string,\n tokensByChain: { [chainId: number]: Token[] }\n): Promise<{ [chainId: number]: TokenAmount[] }>\nexport async function getTokenBalancesByChain(\n client: SDKClient,\n walletAddress: string,\n tokensByChain: { [chainId: number]: TokenExtended[] }\n): Promise<{ [chainId: number]: TokenAmountExtended[] }> {\n if (!walletAddress) {\n throw new ValidationError('Missing walletAddress.')\n }\n\n const tokenList = Object.values(tokensByChain).flat()\n const invalidTokens = tokenList.filter((token) => !isToken(token))\n if (invalidTokens.length) {\n throw new ValidationError('Invalid tokens passed.')\n }\n\n const provider = client.providers.find((provider) =>\n provider.isAddress(walletAddress)\n )\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const tokenAmountsByChain: {\n [chainId: number]: TokenAmount[] | TokenAmountExtended[]\n } = {}\n const tokenAmountsSettled = await Promise.allSettled(\n Object.keys(tokensByChain).map(async (chainIdStr) => {\n const chainId = Number.parseInt(chainIdStr, 10)\n const chain = await client.getChainById(chainId)\n if (provider.type === chain.chainType) {\n const tokenAmounts = await provider.getBalance(\n client,\n walletAddress,\n tokensByChain[chainId]\n )\n tokenAmountsByChain[chainId] = tokenAmounts\n } else {\n // if the provider is not the same as the chain type,\n // return the tokens as is\n tokenAmountsByChain[chainId] = tokensByChain[chainId]\n }\n })\n )\n if (client.config.debug) {\n for (const result of tokenAmountsSettled) {\n if (result.status === 'rejected') {\n console.warn(\"Couldn't fetch token balance.\", result.reason)\n }\n }\n }\n return tokenAmountsByChain\n}\n"],"mappings":";;;;AAwBA,eAAsB,wBACpB,QACA,eACA,eACuD;CACvD,IAAI,CAAC,eACH,MAAM,IAAIA,sBAAAA,gBAAgB,wBAAwB;CAKpD,IAFkB,OAAO,OAAO,aAAa,CAAC,CAAC,KACjB,CAAC,CAAC,QAAQ,UAAU,CAACC,sBAAAA,QAAQ,KAAK,CAChD,CAAC,CAAC,QAChB,MAAM,IAAID,sBAAAA,gBAAgB,wBAAwB;CAGpD,MAAM,WAAW,OAAO,UAAU,MAAM,aACtC,SAAS,UAAU,aAAa,CAClC;CACA,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,0BAA0B,cAAc,eAAe;CAGzE,MAAM,sBAEF,CAAC;CACL,MAAM,sBAAsB,MAAM,QAAQ,WACxC,OAAO,KAAK,aAAa,CAAC,CAAC,IAAI,OAAO,eAAe;EACnD,MAAM,UAAU,OAAO,SAAS,YAAY,EAAE;EAC9C,MAAM,QAAQ,MAAM,OAAO,aAAa,OAAO;EAC/C,IAAI,SAAS,SAAS,MAAM,WAAW;GACrC,MAAM,eAAe,MAAM,SAAS,WAClC,QACA,eACA,cAAc,QAChB;GACA,oBAAoB,WAAW;EACjC,OAGE,oBAAoB,WAAW,cAAc;CAEjD,CAAC,CACH;CACA,IAAI,OAAO,OAAO;OACX,MAAM,UAAU,qBACnB,IAAI,OAAO,WAAW,YACpB,QAAQ,KAAK,iCAAiC,OAAO,MAAM;CAAA;CAIjE,OAAO;AACT"}
1
+ {"version":3,"file":"getTokenBalancesByChain.js","names":["ValidationError","isToken"],"sources":["../../../src/actions/getTokenBalancesByChain.ts"],"sourcesContent":["import type {\n Token,\n TokenAmount,\n TokenAmountExtended,\n TokenExtended,\n} from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport type { SDKClient } from '../types/core.js'\nimport { isToken } from '../utils/isToken.js'\n\n/**\n * This method queries the balances of tokens for a specific list of chains for a given wallet.\n * @param client - The SDK client.\n * @param walletAddress - A wallet address.\n * @param tokensByChain - A list of token objects organized by chain ids.\n * @returns A list of objects containing the tokens and the amounts on different chains organized by the chosen chains.\n * @throws {ValidationError} Throws a ValidationError if validation fails.\n * @throws {Error} Throws an Error if the SDK Provider for the wallet address is not found.\n */\nexport async function getTokenBalancesByChain(\n client: SDKClient,\n walletAddress: string,\n tokensByChain: { [chainId: number]: Token[] }\n): Promise<{ [chainId: number]: TokenAmount[] }>\nexport async function getTokenBalancesByChain(\n client: SDKClient,\n walletAddress: string,\n tokensByChain: { [chainId: number]: TokenExtended[] }\n): Promise<{ [chainId: number]: TokenAmountExtended[] }> {\n if (!walletAddress) {\n throw new ValidationError('Missing walletAddress.')\n }\n\n const tokenList = Object.values(tokensByChain).flat()\n const invalidTokens = tokenList.filter((token) => !isToken(token))\n if (invalidTokens.length) {\n throw new ValidationError('Invalid tokens passed.')\n }\n\n const provider = client.providers.find((provider) =>\n provider.isAddress(walletAddress)\n )\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const tokenAmountsByChain: {\n [chainId: number]: TokenAmount[] | TokenAmountExtended[]\n } = {}\n const tokenAmountsSettled = await Promise.allSettled(\n Object.keys(tokensByChain).map(async (chainIdStr) => {\n const chainId = Number.parseInt(chainIdStr, 10)\n const chain = await client.getChainById(chainId)\n if (provider.type === chain.chainType) {\n const tokenAmounts = await provider.getBalance(\n client,\n walletAddress,\n tokensByChain[chainId]\n )\n tokenAmountsByChain[chainId] = tokenAmounts\n } else {\n // if the provider is not the same as the chain type,\n // return the tokens as is\n tokenAmountsByChain[chainId] = tokensByChain[chainId]\n }\n })\n )\n if (client.config.debug) {\n for (const result of tokenAmountsSettled) {\n if (result.status === 'rejected') {\n console.warn(\"Couldn't fetch token balance.\", result.reason)\n }\n }\n }\n return tokenAmountsByChain\n}\n"],"mappings":";;;;AAwBA,eAAsB,wBACpB,QACA,eACA,eACuD;CACvD,IAAI,CAAC,eACH,MAAM,IAAIA,sBAAAA,gBAAgB,wBAAwB;CAKpD,IAFkB,OAAO,OAAO,aAAa,CAAC,CAAC,KACjB,CAAC,CAAC,QAAQ,UAAU,CAACC,sBAAAA,QAAQ,KAAK,CAChD,CAAC,CAAC,QAChB,MAAM,IAAID,sBAAAA,gBAAgB,wBAAwB;CAGpD,MAAM,WAAW,OAAO,UAAU,MAAM,aACtC,SAAS,UAAU,aAAa,CAClC;CACA,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,0BAA0B,cAAc,eAAe;CAGzE,MAAM,sBAEF,CAAC;CACL,MAAM,sBAAsB,MAAM,QAAQ,WACxC,OAAO,KAAK,aAAa,CAAC,CAAC,IAAI,OAAO,eAAe;EACnD,MAAM,UAAU,OAAO,SAAS,YAAY,EAAE;EAC9C,MAAM,QAAQ,MAAM,OAAO,aAAa,OAAO;EAC/C,IAAI,SAAS,SAAS,MAAM,WAAW;GACrC,MAAM,eAAe,MAAM,SAAS,WAClC,QACA,eACA,cAAc,QAChB;GACA,oBAAoB,WAAW;EACjC,OAGE,oBAAoB,WAAW,cAAc;CAEjD,CAAC,CACH;CACA,IAAI,OAAO,OAAO,OACX;OAAA,MAAM,UAAU,qBACnB,IAAI,OAAO,WAAW,YACpB,QAAQ,KAAK,iCAAiC,OAAO,MAAM;CAAA;CAIjE,OAAO;AACT"}
@@ -2,7 +2,7 @@ import { SDKClient } from "../types/core.js";
2
2
  import { GetStatusRequestExtended, LiFiStepRequest, QuoteRequestFromAmount, RoutesRequest as RoutesRequest$1 } from "../types/actions.js";
3
3
  import { getQuote } from "./getQuote.js";
4
4
  import { PatchContractCallsResponse } from "./patchContractCalls.js";
5
- import { ChainId, ChainKey, ChainType, ChainsRequest, ConnectionsRequest, ConnectionsResponse, ContractCallsQuoteRequest, ExtendedChain, GasRecommendationRequest, GasRecommendationResponse, LiFiStep, PatchCallDataRequest, RelayRequest, RelayResponseData, RelayStatusRequest, RelayStatusResponseData, RequestOptions, RoutesResponse, StatusResponse, Token, TokenAmount, TokenExtended, TokensExtendedResponse, TokensRequest, TokensResponse, ToolsRequest, ToolsResponse, TransactionAnalyticsRequest, TransactionAnalyticsResponse, WalletTokenExtended } from "@lifi/types";
5
+ import { ChainId, ChainKey, ChainType, ChainsRequest, ConnectionsRequest, ConnectionsResponse, ContractCallsQuoteRequest, ExtendedChain, GasRecommendationRequest, GasRecommendationResponse, LiFiStep, PatchCallDataRequest, RelayRequest, RelayResponseData, RelayStatusRequest, RelayStatusResponseData, RequestOptions, RoutesResponse, StatusResponse, Token, TokenAmount, TokenExtended, TokensExtendedResponse, TokensRequest, TokensResponse, ToolsRequest, ToolsResponse, TransactionAnalyticsRequest, TransactionAnalyticsResponse } from "@lifi/types";
6
6
  //#region src/actions/index.d.ts
7
7
  type Actions = {
8
8
  /**
@@ -146,13 +146,6 @@ type Actions = {
146
146
  * @returns Transaction history
147
147
  */
148
148
  getTransactionHistory: (params: TransactionAnalyticsRequest, options?: RequestOptions) => Promise<TransactionAnalyticsResponse>;
149
- /**
150
- * Get wallet balances
151
- * @param params - The configuration of the requested wallet balances
152
- * @param options - Request options
153
- * @returns Wallet balances
154
- */
155
- getWalletBalances: (walletAddress: string, options?: RequestOptions) => Promise<Record<number, WalletTokenExtended[]>>;
156
149
  /**
157
150
  * Relay a transaction through the relayer service
158
151
  * @param params - The configuration for the relay request
@@ -17,7 +17,6 @@ const require_actions_getTokenBalance = require("./getTokenBalance.js");
17
17
  const require_actions_getTokens = require("./getTokens.js");
18
18
  const require_actions_getTools = require("./getTools.js");
19
19
  const require_actions_getTransactionHistory = require("./getTransactionHistory.js");
20
- const require_actions_getWalletBalances = require("./getWalletBalances.js");
21
20
  const require_actions_patchContractCalls = require("./patchContractCalls.js");
22
21
  const require_actions_relayTransaction = require("./relayTransaction.js");
23
22
  //#region src/actions/index.ts
@@ -41,7 +40,6 @@ function actions(client) {
41
40
  getTokenBalances: (walletAddress, tokens) => require_actions_getTokenBalances.getTokenBalances(client, walletAddress, tokens),
42
41
  getTokenBalancesByChain: (walletAddress, tokensByChain) => require_actions_getTokenBalancesByChain.getTokenBalancesByChain(client, walletAddress, tokensByChain),
43
42
  getTransactionHistory: (params, options) => require_actions_getTransactionHistory.getTransactionHistory(client, params, options),
44
- getWalletBalances: (walletAddress, options) => require_actions_getWalletBalances.getWalletBalances(client, walletAddress, options),
45
43
  relayTransaction: (params, options) => require_actions_relayTransaction.relayTransaction(client, params, options),
46
44
  patchContractCalls: (params, options) => require_actions_patchContractCalls.patchContractCalls(client, params, options)
47
45
  };
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["getChains","getConnections","getContractCallsQuote","getGasRecommendation","getNameServiceAddress","getTokens","getTools","getQuote","getRelayedTransactionStatus","getRelayerQuote","getRoutes","getStatus","getStepTransaction","getToken","getTokenBalance","getTokenBalances","getTokenBalancesByChain","getTransactionHistory","getWalletBalances","relayTransaction","patchContractCalls"],"sources":["../../../src/actions/index.ts"],"sourcesContent":["import type {\n ChainId,\n ChainKey,\n ChainsRequest,\n ChainType,\n ConnectionsRequest,\n ConnectionsResponse,\n ContractCallsQuoteRequest,\n ExtendedChain,\n GasRecommendationRequest,\n GasRecommendationResponse,\n LiFiStep,\n PatchCallDataRequest,\n RelayRequest,\n RelayResponseData,\n RelayStatusRequest,\n RelayStatusResponseData,\n RequestOptions,\n RoutesResponse,\n StatusResponse,\n Token,\n TokenAmount,\n TokenExtended,\n TokensExtendedResponse,\n TokensRequest,\n TokensResponse,\n ToolsRequest,\n ToolsResponse,\n TransactionAnalyticsRequest,\n TransactionAnalyticsResponse,\n WalletTokenExtended,\n} from '@lifi/types'\nimport type {\n GetStatusRequestExtended,\n LiFiStepRequest,\n QuoteRequestFromAmount,\n RoutesRequest,\n} from '../types/actions.js'\nimport type { SDKClient } from '../types/core.js'\nimport { getChains } from './getChains.js'\nimport { getConnections } from './getConnections.js'\nimport { getContractCallsQuote } from './getContractCallsQuote.js'\nimport { getGasRecommendation } from './getGasRecommendation.js'\nimport { getNameServiceAddress } from './getNameServiceAddress.js'\nimport { getQuote } from './getQuote.js'\nimport { getRelayedTransactionStatus } from './getRelayedTransactionStatus.js'\nimport { getRelayerQuote } from './getRelayerQuote.js'\nimport { getRoutes } from './getRoutes.js'\nimport { getStatus } from './getStatus.js'\nimport { getStepTransaction } from './getStepTransaction.js'\nimport { getToken } from './getToken.js'\nimport { getTokenBalance } from './getTokenBalance.js'\nimport { getTokenBalances } from './getTokenBalances.js'\nimport { getTokenBalancesByChain } from './getTokenBalancesByChain.js'\nimport { getTokens } from './getTokens.js'\nimport { getTools } from './getTools.js'\nimport { getTransactionHistory } from './getTransactionHistory.js'\nimport { getWalletBalances } from './getWalletBalances.js'\nimport {\n type PatchContractCallsResponse,\n patchContractCalls,\n} from './patchContractCalls.js'\nimport { relayTransaction } from './relayTransaction.js'\n\nexport type Actions = {\n /**\n * Get all available chains\n * @param params - The configuration of the requested chains\n * @param options - Request options\n * @returns A list of all available chains\n */\n getChains: (\n params?: ChainsRequest,\n options?: RequestOptions\n ) => Promise<ExtendedChain[]>\n\n /**\n * Get connections between chains\n * @param params - The configuration of the requested connections\n * @param options - Request options\n * @returns A list of connections\n */\n getConnections: (\n params: ConnectionsRequest,\n options?: RequestOptions\n ) => Promise<ConnectionsResponse>\n\n /**\n * Get a quote for contract calls\n * @param params - The configuration of the requested contract calls quote\n * @param options - Request options\n * @returns Quote for contract calls\n */\n getContractCallsQuote: (\n params: ContractCallsQuoteRequest,\n options?: RequestOptions\n ) => Promise<LiFiStep>\n\n /**\n * Get gas recommendation for a chain\n * @param params - The configuration of the requested gas recommendation\n * @param options - Request options\n * @returns Gas recommendation\n */\n getGasRecommendation: (\n params: GasRecommendationRequest,\n options?: RequestOptions\n ) => Promise<GasRecommendationResponse>\n\n /**\n * Get the address of a name service\n * @param name - The name to resolve\n * @param chainType - The chain type to resolve the name on\n * @returns The address of the name service\n */\n getNameServiceAddress: (\n name: string,\n chainType?: ChainType\n ) => Promise<string | undefined>\n\n /**\n * Get a quote for a token transfer\n * @param params - The configuration of the requested quote\n * @param options - Request options\n * @returns Quote for a token transfer\n */\n getQuote: (\n params: Parameters<typeof getQuote>[1],\n options?: RequestOptions\n ) => Promise<LiFiStep>\n\n /**\n * Get the status of a relayed transaction\n * @param params - The configuration of the requested relay status\n * @param options - Request options\n * @returns Status of the relayed transaction\n */\n getRelayedTransactionStatus: (\n params: RelayStatusRequest,\n options?: RequestOptions\n ) => Promise<RelayStatusResponseData>\n\n /**\n * Get a quote from a relayer\n * @param params - The configuration of the requested relayer quote\n * @param options - Request options\n * @returns Quote from a relayer\n */\n getRelayerQuote: (\n params: QuoteRequestFromAmount,\n options?: RequestOptions\n ) => Promise<LiFiStep>\n\n /**\n * Get a set of routes for a request that describes a transfer of tokens.\n * Optional limit-order fields (`toAmount`, `validUntil`, `partiallyFillable`)\n * may be supplied and are resolved on the backend.\n * @param params - A description of the transfer\n * @param options - Request options\n * @returns The resulting routes that can be used to realize the described transfer\n */\n getRoutes: (\n params: RoutesRequest,\n options?: RequestOptions\n ) => Promise<RoutesResponse>\n\n /**\n * Get the status of a transaction\n * @param params - The configuration of the requested status\n * @param options - Request options\n * @returns Status of the transaction\n */\n getStatus: (\n params: GetStatusRequestExtended,\n options?: RequestOptions\n ) => Promise<StatusResponse>\n\n /**\n * Get a step transaction. The step's `action` may carry the optional\n * limit-order fields, which are resolved on the backend.\n * @param params - The configuration of the requested step transaction\n * @param options - Request options\n * @returns Step transaction\n */\n getStepTransaction: (\n params: LiFiStepRequest,\n options?: RequestOptions\n ) => Promise<LiFiStep>\n\n /**\n * Get a specific token\n * @param chain - Id or key of the chain that contains the token\n * @param token - Address or symbol of the token on the requested chain\n * @param options - Request options\n * @returns Token information\n */\n getToken: (\n chain: ChainKey | ChainId,\n token: string,\n options?: RequestOptions\n ) => Promise<TokenExtended>\n\n /**\n * Get token balance for a specific token\n * @param walletAddress - A wallet address\n * @param token - A Token object\n * @returns Token balance\n */\n getTokenBalance: (\n walletAddress: string,\n token: Token\n ) => Promise<TokenAmount | null>\n\n /**\n * Get token balances for multiple tokens\n * @param walletAddress - A wallet address\n * @param tokens - A list of Token objects\n * @returns Token balances\n */\n getTokenBalances: (\n walletAddress: string,\n tokens: Token[]\n ) => Promise<TokenAmount[]>\n\n /**\n * Get token balances by chain\n * @param walletAddress - A wallet address\n * @param tokensByChain - A list of token objects organized by chain ids\n * @returns Token balances by chain\n */\n getTokenBalancesByChain: (\n walletAddress: string,\n tokensByChain: { [chainId: number]: Token[] }\n ) => Promise<{\n [chainId: number]: TokenAmount[]\n }>\n\n /**\n * Get all available tokens\n * @param params - The configuration of the requested tokens\n * @param options - Request options\n * @returns A list of all available tokens\n */\n getTokens: {\n (\n params?: TokensRequest & { extended?: false | undefined },\n options?: RequestOptions\n ): Promise<TokensResponse>\n (\n params: TokensRequest & { extended: true },\n options?: RequestOptions\n ): Promise<TokensExtendedResponse>\n }\n\n /**\n * Get all available tools (bridges and exchanges)\n * @param params - The configuration of the requested tools\n * @param options - Request options\n * @returns A list of all available tools\n */\n getTools: (\n params?: ToolsRequest,\n options?: RequestOptions\n ) => Promise<ToolsResponse>\n\n /**\n * Get transaction history\n * @param params - The configuration of the requested transaction history\n * @param options - Request options\n * @returns Transaction history\n */\n getTransactionHistory: (\n params: TransactionAnalyticsRequest,\n options?: RequestOptions\n ) => Promise<TransactionAnalyticsResponse>\n\n /**\n * Get wallet balances\n * @param params - The configuration of the requested wallet balances\n * @param options - Request options\n * @returns Wallet balances\n */\n getWalletBalances: (\n walletAddress: string,\n options?: RequestOptions\n ) => Promise<Record<number, WalletTokenExtended[]>>\n\n /**\n * Relay a transaction through the relayer service\n * @param params - The configuration for the relay request\n * @param options - Request options\n * @returns Task ID and transaction link for the relayed transaction\n */\n relayTransaction: (\n params: RelayRequest,\n options?: RequestOptions\n ) => Promise<RelayResponseData>\n\n /**\n * Patch contract calls\n * @param params - The configuration for the patch contract calls request\n * @param options - Request options\n * @returns Patched contract calls\n */\n patchContractCalls: (\n params: PatchCallDataRequest,\n options?: RequestOptions\n ) => Promise<PatchContractCallsResponse[]>\n}\n\nexport function actions(client: SDKClient): Actions {\n return {\n getChains: (params, options) => getChains(client, params, options),\n getConnections: (params, options) =>\n getConnections(client, params, options),\n getContractCallsQuote: (params, options) =>\n getContractCallsQuote(client, params, options),\n getGasRecommendation: (params, options) =>\n getGasRecommendation(client, params, options),\n getNameServiceAddress: (name, chainType) =>\n getNameServiceAddress(client, name, chainType),\n getTokens: (params, options) => getTokens(client, params as any, options),\n getTools: (params, options) => getTools(client, params, options),\n getQuote: (params, options) => getQuote(client, params, options),\n getRelayedTransactionStatus: (params, options) =>\n getRelayedTransactionStatus(client, params, options),\n getRelayerQuote: (params, options) =>\n getRelayerQuote(client, params, options),\n getRoutes: (params, options) => getRoutes(client, params, options),\n getStatus: (params, options) => getStatus(client, params, options),\n getStepTransaction: (params, options) =>\n getStepTransaction(client, params, options),\n getToken: (chain, token, options) =>\n getToken(client, chain, token, options),\n getTokenBalance: (walletAddress, token) =>\n getTokenBalance(client, walletAddress, token),\n getTokenBalances: (walletAddress, tokens) =>\n getTokenBalances(client, walletAddress, tokens),\n getTokenBalancesByChain: (walletAddress, tokensByChain) =>\n getTokenBalancesByChain(client, walletAddress, tokensByChain),\n getTransactionHistory: (params, options) =>\n getTransactionHistory(client, params, options),\n getWalletBalances: (walletAddress, options) =>\n getWalletBalances(client, walletAddress, options),\n relayTransaction: (params, options) =>\n relayTransaction(client, params, options),\n patchContractCalls: (params, options) =>\n patchContractCalls(client, params, options),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAsTA,SAAgB,QAAQ,QAA4B;CAClD,OAAO;EACL,YAAY,QAAQ,YAAYA,0BAAAA,UAAU,QAAQ,QAAQ,OAAO;EACjE,iBAAiB,QAAQ,YACvBC,+BAAAA,eAAe,QAAQ,QAAQ,OAAO;EACxC,wBAAwB,QAAQ,YAC9BC,sCAAAA,sBAAsB,QAAQ,QAAQ,OAAO;EAC/C,uBAAuB,QAAQ,YAC7BC,qCAAAA,qBAAqB,QAAQ,QAAQ,OAAO;EAC9C,wBAAwB,MAAM,cAC5BC,sCAAAA,sBAAsB,QAAQ,MAAM,SAAS;EAC/C,YAAY,QAAQ,YAAYC,0BAAAA,UAAU,QAAQ,QAAe,OAAO;EACxE,WAAW,QAAQ,YAAYC,yBAAAA,SAAS,QAAQ,QAAQ,OAAO;EAC/D,WAAW,QAAQ,YAAYC,yBAAAA,SAAS,QAAQ,QAAQ,OAAO;EAC/D,8BAA8B,QAAQ,YACpCC,4CAAAA,4BAA4B,QAAQ,QAAQ,OAAO;EACrD,kBAAkB,QAAQ,YACxBC,gCAAAA,gBAAgB,QAAQ,QAAQ,OAAO;EACzC,YAAY,QAAQ,YAAYC,0BAAAA,UAAU,QAAQ,QAAQ,OAAO;EACjE,YAAY,QAAQ,YAAYC,0BAAAA,UAAU,QAAQ,QAAQ,OAAO;EACjE,qBAAqB,QAAQ,YAC3BC,mCAAAA,mBAAmB,QAAQ,QAAQ,OAAO;EAC5C,WAAW,OAAO,OAAO,YACvBC,yBAAAA,SAAS,QAAQ,OAAO,OAAO,OAAO;EACxC,kBAAkB,eAAe,UAC/BC,gCAAAA,gBAAgB,QAAQ,eAAe,KAAK;EAC9C,mBAAmB,eAAe,WAChCC,iCAAAA,iBAAiB,QAAQ,eAAe,MAAM;EAChD,0BAA0B,eAAe,kBACvCC,wCAAAA,wBAAwB,QAAQ,eAAe,aAAa;EAC9D,wBAAwB,QAAQ,YAC9BC,sCAAAA,sBAAsB,QAAQ,QAAQ,OAAO;EAC/C,oBAAoB,eAAe,YACjCC,kCAAAA,kBAAkB,QAAQ,eAAe,OAAO;EAClD,mBAAmB,QAAQ,YACzBC,iCAAAA,iBAAiB,QAAQ,QAAQ,OAAO;EAC1C,qBAAqB,QAAQ,YAC3BC,mCAAAA,mBAAmB,QAAQ,QAAQ,OAAO;CAC9C;AACF"}
1
+ {"version":3,"file":"index.js","names":["getChains","getConnections","getContractCallsQuote","getGasRecommendation","getNameServiceAddress","getTokens","getTools","getQuote","getRelayedTransactionStatus","getRelayerQuote","getRoutes","getStatus","getStepTransaction","getToken","getTokenBalance","getTokenBalances","getTokenBalancesByChain","getTransactionHistory","relayTransaction","patchContractCalls"],"sources":["../../../src/actions/index.ts"],"sourcesContent":["import type {\n ChainId,\n ChainKey,\n ChainsRequest,\n ChainType,\n ConnectionsRequest,\n ConnectionsResponse,\n ContractCallsQuoteRequest,\n ExtendedChain,\n GasRecommendationRequest,\n GasRecommendationResponse,\n LiFiStep,\n PatchCallDataRequest,\n RelayRequest,\n RelayResponseData,\n RelayStatusRequest,\n RelayStatusResponseData,\n RequestOptions,\n RoutesResponse,\n StatusResponse,\n Token,\n TokenAmount,\n TokenExtended,\n TokensExtendedResponse,\n TokensRequest,\n TokensResponse,\n ToolsRequest,\n ToolsResponse,\n TransactionAnalyticsRequest,\n TransactionAnalyticsResponse,\n} from '@lifi/types'\nimport type {\n GetStatusRequestExtended,\n LiFiStepRequest,\n QuoteRequestFromAmount,\n RoutesRequest,\n} from '../types/actions.js'\nimport type { SDKClient } from '../types/core.js'\nimport { getChains } from './getChains.js'\nimport { getConnections } from './getConnections.js'\nimport { getContractCallsQuote } from './getContractCallsQuote.js'\nimport { getGasRecommendation } from './getGasRecommendation.js'\nimport { getNameServiceAddress } from './getNameServiceAddress.js'\nimport { getQuote } from './getQuote.js'\nimport { getRelayedTransactionStatus } from './getRelayedTransactionStatus.js'\nimport { getRelayerQuote } from './getRelayerQuote.js'\nimport { getRoutes } from './getRoutes.js'\nimport { getStatus } from './getStatus.js'\nimport { getStepTransaction } from './getStepTransaction.js'\nimport { getToken } from './getToken.js'\nimport { getTokenBalance } from './getTokenBalance.js'\nimport { getTokenBalances } from './getTokenBalances.js'\nimport { getTokenBalancesByChain } from './getTokenBalancesByChain.js'\nimport { getTokens } from './getTokens.js'\nimport { getTools } from './getTools.js'\nimport { getTransactionHistory } from './getTransactionHistory.js'\nimport {\n type PatchContractCallsResponse,\n patchContractCalls,\n} from './patchContractCalls.js'\nimport { relayTransaction } from './relayTransaction.js'\n\nexport type Actions = {\n /**\n * Get all available chains\n * @param params - The configuration of the requested chains\n * @param options - Request options\n * @returns A list of all available chains\n */\n getChains: (\n params?: ChainsRequest,\n options?: RequestOptions\n ) => Promise<ExtendedChain[]>\n\n /**\n * Get connections between chains\n * @param params - The configuration of the requested connections\n * @param options - Request options\n * @returns A list of connections\n */\n getConnections: (\n params: ConnectionsRequest,\n options?: RequestOptions\n ) => Promise<ConnectionsResponse>\n\n /**\n * Get a quote for contract calls\n * @param params - The configuration of the requested contract calls quote\n * @param options - Request options\n * @returns Quote for contract calls\n */\n getContractCallsQuote: (\n params: ContractCallsQuoteRequest,\n options?: RequestOptions\n ) => Promise<LiFiStep>\n\n /**\n * Get gas recommendation for a chain\n * @param params - The configuration of the requested gas recommendation\n * @param options - Request options\n * @returns Gas recommendation\n */\n getGasRecommendation: (\n params: GasRecommendationRequest,\n options?: RequestOptions\n ) => Promise<GasRecommendationResponse>\n\n /**\n * Get the address of a name service\n * @param name - The name to resolve\n * @param chainType - The chain type to resolve the name on\n * @returns The address of the name service\n */\n getNameServiceAddress: (\n name: string,\n chainType?: ChainType\n ) => Promise<string | undefined>\n\n /**\n * Get a quote for a token transfer\n * @param params - The configuration of the requested quote\n * @param options - Request options\n * @returns Quote for a token transfer\n */\n getQuote: (\n params: Parameters<typeof getQuote>[1],\n options?: RequestOptions\n ) => Promise<LiFiStep>\n\n /**\n * Get the status of a relayed transaction\n * @param params - The configuration of the requested relay status\n * @param options - Request options\n * @returns Status of the relayed transaction\n */\n getRelayedTransactionStatus: (\n params: RelayStatusRequest,\n options?: RequestOptions\n ) => Promise<RelayStatusResponseData>\n\n /**\n * Get a quote from a relayer\n * @param params - The configuration of the requested relayer quote\n * @param options - Request options\n * @returns Quote from a relayer\n */\n getRelayerQuote: (\n params: QuoteRequestFromAmount,\n options?: RequestOptions\n ) => Promise<LiFiStep>\n\n /**\n * Get a set of routes for a request that describes a transfer of tokens.\n * Optional limit-order fields (`toAmount`, `validUntil`, `partiallyFillable`)\n * may be supplied and are resolved on the backend.\n * @param params - A description of the transfer\n * @param options - Request options\n * @returns The resulting routes that can be used to realize the described transfer\n */\n getRoutes: (\n params: RoutesRequest,\n options?: RequestOptions\n ) => Promise<RoutesResponse>\n\n /**\n * Get the status of a transaction\n * @param params - The configuration of the requested status\n * @param options - Request options\n * @returns Status of the transaction\n */\n getStatus: (\n params: GetStatusRequestExtended,\n options?: RequestOptions\n ) => Promise<StatusResponse>\n\n /**\n * Get a step transaction. The step's `action` may carry the optional\n * limit-order fields, which are resolved on the backend.\n * @param params - The configuration of the requested step transaction\n * @param options - Request options\n * @returns Step transaction\n */\n getStepTransaction: (\n params: LiFiStepRequest,\n options?: RequestOptions\n ) => Promise<LiFiStep>\n\n /**\n * Get a specific token\n * @param chain - Id or key of the chain that contains the token\n * @param token - Address or symbol of the token on the requested chain\n * @param options - Request options\n * @returns Token information\n */\n getToken: (\n chain: ChainKey | ChainId,\n token: string,\n options?: RequestOptions\n ) => Promise<TokenExtended>\n\n /**\n * Get token balance for a specific token\n * @param walletAddress - A wallet address\n * @param token - A Token object\n * @returns Token balance\n */\n getTokenBalance: (\n walletAddress: string,\n token: Token\n ) => Promise<TokenAmount | null>\n\n /**\n * Get token balances for multiple tokens\n * @param walletAddress - A wallet address\n * @param tokens - A list of Token objects\n * @returns Token balances\n */\n getTokenBalances: (\n walletAddress: string,\n tokens: Token[]\n ) => Promise<TokenAmount[]>\n\n /**\n * Get token balances by chain\n * @param walletAddress - A wallet address\n * @param tokensByChain - A list of token objects organized by chain ids\n * @returns Token balances by chain\n */\n getTokenBalancesByChain: (\n walletAddress: string,\n tokensByChain: { [chainId: number]: Token[] }\n ) => Promise<{\n [chainId: number]: TokenAmount[]\n }>\n\n /**\n * Get all available tokens\n * @param params - The configuration of the requested tokens\n * @param options - Request options\n * @returns A list of all available tokens\n */\n getTokens: {\n (\n params?: TokensRequest & { extended?: false | undefined },\n options?: RequestOptions\n ): Promise<TokensResponse>\n (\n params: TokensRequest & { extended: true },\n options?: RequestOptions\n ): Promise<TokensExtendedResponse>\n }\n\n /**\n * Get all available tools (bridges and exchanges)\n * @param params - The configuration of the requested tools\n * @param options - Request options\n * @returns A list of all available tools\n */\n getTools: (\n params?: ToolsRequest,\n options?: RequestOptions\n ) => Promise<ToolsResponse>\n\n /**\n * Get transaction history\n * @param params - The configuration of the requested transaction history\n * @param options - Request options\n * @returns Transaction history\n */\n getTransactionHistory: (\n params: TransactionAnalyticsRequest,\n options?: RequestOptions\n ) => Promise<TransactionAnalyticsResponse>\n\n /**\n * Relay a transaction through the relayer service\n * @param params - The configuration for the relay request\n * @param options - Request options\n * @returns Task ID and transaction link for the relayed transaction\n */\n relayTransaction: (\n params: RelayRequest,\n options?: RequestOptions\n ) => Promise<RelayResponseData>\n\n /**\n * Patch contract calls\n * @param params - The configuration for the patch contract calls request\n * @param options - Request options\n * @returns Patched contract calls\n */\n patchContractCalls: (\n params: PatchCallDataRequest,\n options?: RequestOptions\n ) => Promise<PatchContractCallsResponse[]>\n}\n\nexport function actions(client: SDKClient): Actions {\n return {\n getChains: (params, options) => getChains(client, params, options),\n getConnections: (params, options) =>\n getConnections(client, params, options),\n getContractCallsQuote: (params, options) =>\n getContractCallsQuote(client, params, options),\n getGasRecommendation: (params, options) =>\n getGasRecommendation(client, params, options),\n getNameServiceAddress: (name, chainType) =>\n getNameServiceAddress(client, name, chainType),\n getTokens: (params, options) => getTokens(client, params as any, options),\n getTools: (params, options) => getTools(client, params, options),\n getQuote: (params, options) => getQuote(client, params, options),\n getRelayedTransactionStatus: (params, options) =>\n getRelayedTransactionStatus(client, params, options),\n getRelayerQuote: (params, options) =>\n getRelayerQuote(client, params, options),\n getRoutes: (params, options) => getRoutes(client, params, options),\n getStatus: (params, options) => getStatus(client, params, options),\n getStepTransaction: (params, options) =>\n getStepTransaction(client, params, options),\n getToken: (chain, token, options) =>\n getToken(client, chain, token, options),\n getTokenBalance: (walletAddress, token) =>\n getTokenBalance(client, walletAddress, token),\n getTokenBalances: (walletAddress, tokens) =>\n getTokenBalances(client, walletAddress, tokens),\n getTokenBalancesByChain: (walletAddress, tokensByChain) =>\n getTokenBalancesByChain(client, walletAddress, tokensByChain),\n getTransactionHistory: (params, options) =>\n getTransactionHistory(client, params, options),\n relayTransaction: (params, options) =>\n relayTransaction(client, params, options),\n patchContractCalls: (params, options) =>\n patchContractCalls(client, params, options),\n }\n}\n"],"mappings":";;;;;;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C/C,mBAAmB,QAAQ,YACzBC,iCAAAA,iBAAiB,QAAQ,QAAQ,OAAO;EAC1C,qBAAqB,QAAQ,YAC3BC,mCAAAA,mBAAmB,QAAQ,QAAQ,OAAO;CAC9C;AACF"}
@@ -3,7 +3,7 @@ const require_actions_getChains = require("../actions/getChains.js");
3
3
  const require_core_utils = require("../core/utils.js");
4
4
  let _lifi_types = require("@lifi/types");
5
5
  //#region src/client/getClientStorage.ts
6
- const chainsRefreshInterval = 1e3 * 60 * 60 * 6;
6
+ const chainsRefreshInterval = 216e5;
7
7
  const getClientStorage = (config) => {
8
8
  let _chains = [];
9
9
  let _rpcUrls = { ...config.rpcUrls };
@@ -29,7 +29,8 @@ const getClientStorage = (config) => {
29
29
  _lifi_types.ChainType.SVM,
30
30
  _lifi_types.ChainType.UTXO,
31
31
  _lifi_types.ChainType.MVM,
32
- _lifi_types.ChainType.TVM
32
+ _lifi_types.ChainType.TVM,
33
+ _lifi_types.ChainType.STL
33
34
  ] });
34
35
  _chainsUpdatedAt = Date.now();
35
36
  updateRpcUrls();
@@ -1 +1 @@
1
- {"version":3,"file":"getClientStorage.js","names":["getRpcUrlsFromChains","ChainId","_getChains","ChainType"],"sources":["../../../src/client/getClientStorage.ts"],"sourcesContent":["import { ChainId, ChainType, type ExtendedChain } from '@lifi/types'\nimport { _getChains } from '../actions/getChains.js'\nimport { getRpcUrlsFromChains } from '../core/utils.js'\nimport type { RPCUrls, SDKBaseConfig } from '../types/core.js'\n\n// 6 hours in milliseconds\nconst chainsRefreshInterval = 1000 * 60 * 60 * 6\n\nexport interface ClientStorage {\n readonly needReset: boolean\n setChains(chains: ExtendedChain[]): void\n getChains(): Promise<ExtendedChain[]>\n getRpcUrls(): Promise<RPCUrls>\n}\n\nexport const getClientStorage = (config: SDKBaseConfig): ClientStorage => {\n let _chains = [] as ExtendedChain[]\n let _rpcUrls = { ...config.rpcUrls } as RPCUrls\n let _chainsUpdatedAt: number | undefined\n\n const updateRpcUrls = () => {\n _rpcUrls = { ...config.rpcUrls }\n _rpcUrls = getRpcUrlsFromChains(_rpcUrls, _chains, [ChainId.SOL])\n }\n\n return {\n get needReset() {\n return (\n !_chainsUpdatedAt ||\n Date.now() - _chainsUpdatedAt >= chainsRefreshInterval\n )\n },\n setChains(chains: ExtendedChain[]) {\n _chains = chains\n _chainsUpdatedAt = Date.now()\n updateRpcUrls()\n },\n async getChains() {\n // When preloadChains is false, SDK does not auto-fetch chains\n // External consumer is responsible for calling setChains\n if (!config.preloadChains) {\n return _chains\n }\n\n if (this.needReset || !_chains.length) {\n _chains = await _getChains(config, {\n chainTypes: [\n ChainType.EVM,\n ChainType.SVM,\n ChainType.UTXO,\n ChainType.MVM,\n ChainType.TVM,\n ],\n })\n _chainsUpdatedAt = Date.now()\n updateRpcUrls()\n }\n return _chains\n },\n async getRpcUrls() {\n await this.getChains() // _rpcUrls is updated when needed\n return _rpcUrls\n },\n }\n}\n"],"mappings":";;;;;AAMA,MAAM,wBAAwB,MAAO,KAAK,KAAK;AAS/C,MAAa,oBAAoB,WAAyC;CACxE,IAAI,UAAU,CAAC;CACf,IAAI,WAAW,EAAE,GAAG,OAAO,QAAQ;CACnC,IAAI;CAEJ,MAAM,sBAAsB;EAC1B,WAAW,EAAE,GAAG,OAAO,QAAQ;EAC/B,WAAWA,mBAAAA,qBAAqB,UAAU,SAAS,CAACC,YAAAA,QAAQ,GAAG,CAAC;CAClE;CAEA,OAAO;EACL,IAAI,YAAY;GACd,OACE,CAAC,oBACD,KAAK,IAAI,IAAI,oBAAoB;EAErC;EACA,UAAU,QAAyB;GACjC,UAAU;GACV,mBAAmB,KAAK,IAAI;GAC5B,cAAc;EAChB;EACA,MAAM,YAAY;GAGhB,IAAI,CAAC,OAAO,eACV,OAAO;GAGT,IAAI,KAAK,aAAa,CAAC,QAAQ,QAAQ;IACrC,UAAU,MAAMC,0BAAAA,WAAW,QAAQ,EACjC,YAAY;KACVC,YAAAA,UAAU;KACVA,YAAAA,UAAU;KACVA,YAAAA,UAAU;KACVA,YAAAA,UAAU;KACVA,YAAAA,UAAU;IACZ,EACF,CAAC;IACD,mBAAmB,KAAK,IAAI;IAC5B,cAAc;GAChB;GACA,OAAO;EACT;EACA,MAAM,aAAa;GACjB,MAAM,KAAK,UAAU;GACrB,OAAO;EACT;CACF;AACF"}
1
+ {"version":3,"file":"getClientStorage.js","names":["getRpcUrlsFromChains","ChainId","_getChains","ChainType"],"sources":["../../../src/client/getClientStorage.ts"],"sourcesContent":["import { ChainId, ChainType, type ExtendedChain } from '@lifi/types'\nimport { _getChains } from '../actions/getChains.js'\nimport { getRpcUrlsFromChains } from '../core/utils.js'\nimport type { RPCUrls, SDKBaseConfig } from '../types/core.js'\n\n// 6 hours in milliseconds\nconst chainsRefreshInterval = 1000 * 60 * 60 * 6\n\nexport interface ClientStorage {\n readonly needReset: boolean\n setChains(chains: ExtendedChain[]): void\n getChains(): Promise<ExtendedChain[]>\n getRpcUrls(): Promise<RPCUrls>\n}\n\nexport const getClientStorage = (config: SDKBaseConfig): ClientStorage => {\n let _chains = [] as ExtendedChain[]\n let _rpcUrls = { ...config.rpcUrls } as RPCUrls\n let _chainsUpdatedAt: number | undefined\n\n const updateRpcUrls = () => {\n _rpcUrls = { ...config.rpcUrls }\n _rpcUrls = getRpcUrlsFromChains(_rpcUrls, _chains, [ChainId.SOL])\n }\n\n return {\n get needReset() {\n return (\n !_chainsUpdatedAt ||\n Date.now() - _chainsUpdatedAt >= chainsRefreshInterval\n )\n },\n setChains(chains: ExtendedChain[]) {\n _chains = chains\n _chainsUpdatedAt = Date.now()\n updateRpcUrls()\n },\n async getChains() {\n // When preloadChains is false, SDK does not auto-fetch chains\n // External consumer is responsible for calling setChains\n if (!config.preloadChains) {\n return _chains\n }\n\n if (this.needReset || !_chains.length) {\n _chains = await _getChains(config, {\n chainTypes: [\n ChainType.EVM,\n ChainType.SVM,\n ChainType.UTXO,\n ChainType.MVM,\n ChainType.TVM,\n ChainType.STL,\n ],\n })\n _chainsUpdatedAt = Date.now()\n updateRpcUrls()\n }\n return _chains\n },\n async getRpcUrls() {\n await this.getChains() // _rpcUrls is updated when needed\n return _rpcUrls\n },\n }\n}\n"],"mappings":";;;;;AAMA,MAAM,wBAAwB;AAS9B,MAAa,oBAAoB,WAAyC;CACxE,IAAI,UAAU,CAAC;CACf,IAAI,WAAW,EAAE,GAAG,OAAO,QAAQ;CACnC,IAAI;CAEJ,MAAM,sBAAsB;EAC1B,WAAW,EAAE,GAAG,OAAO,QAAQ;EAC/B,WAAWA,mBAAAA,qBAAqB,UAAU,SAAS,CAACC,YAAAA,QAAQ,GAAG,CAAC;CAClE;CAEA,OAAO;EACL,IAAI,YAAY;GACd,OACE,CAAC,oBACD,KAAK,IAAI,IAAI,oBAAoB;EAErC;EACA,UAAU,QAAyB;GACjC,UAAU;GACV,mBAAmB,KAAK,IAAI;GAC5B,cAAc;EAChB;EACA,MAAM,YAAY;GAGhB,IAAI,CAAC,OAAO,eACV,OAAO;GAGT,IAAI,KAAK,aAAa,CAAC,QAAQ,QAAQ;IACrC,UAAU,MAAMC,0BAAAA,WAAW,QAAQ,EACjC,YAAY;KACVC,YAAAA,UAAU;KACVA,YAAAA,UAAU;KACVA,YAAAA,UAAU;KACVA,YAAAA,UAAU;KACVA,YAAAA,UAAU;KACVA,YAAAA,UAAU;IACZ,EACF,CAAC;IACD,mBAAmB,KAAK,IAAI;IAC5B,cAAc;GAChB;GACA,OAAO;EACT;EACA,MAAM,aAAa;GACjB,MAAM,KAAK,UAAU;GACrB,OAAO;EACT;CACF;AACF"}
@@ -50,17 +50,19 @@ var BaseStepExecutor = class {
50
50
  } catch (error) {
51
51
  const action = step.execution?.actions?.at(-1);
52
52
  const parsed = await this.parseErrors(error, step, action, retryParams);
53
- if (!(parsed instanceof require_errors_errors.ExecuteStepRetryError)) if (action) this.statusManager.updateAction(step, action.type, "FAILED", { error: {
54
- message: parsed.cause?.message,
55
- code: parsed.code
56
- } });
57
- else this.statusManager.updateExecution(step, {
58
- status: "FAILED",
59
- error: {
53
+ if (!(parsed instanceof require_errors_errors.ExecuteStepRetryError)) {
54
+ if (action) this.statusManager.updateAction(step, action.type, "FAILED", { error: {
60
55
  message: parsed.cause?.message,
61
56
  code: parsed.code
62
- }
63
- });
57
+ } });
58
+ else this.statusManager.updateExecution(step, {
59
+ status: "FAILED",
60
+ error: {
61
+ message: parsed.cause?.message,
62
+ code: parsed.code
63
+ }
64
+ });
65
+ }
64
66
  throw parsed;
65
67
  }
66
68
  };
@@ -1 +1 @@
1
- {"version":3,"file":"BaseStepExecutor.js","names":["StatusManager","ExecuteStepRetryError"],"sources":["../../../src/core/BaseStepExecutor.ts"],"sourcesContent":["import { ExecuteStepRetryError } from '../errors/errors.js'\nimport type { SDKError } from '../errors/SDKError.js'\nimport type {\n ExecuteStepRetryParams,\n ExecutionAction,\n ExecutionOptions,\n InteractionSettings,\n LiFiStepExtended,\n SDKClient,\n StepExecutor,\n StepExecutorOptions,\n} from '../types/core.js'\nimport type {\n StepExecutorBaseContext,\n StepExecutorContext,\n} from '../types/execution.js'\nimport { StatusManager } from './StatusManager.js'\nimport type { TaskPipeline } from './TaskPipeline.js'\n\n// Please be careful when changing the defaults as it may break the behavior (e.g., background execution)\nconst defaultInteractionSettings = {\n allowInteraction: true,\n allowUpdates: true,\n allowExecution: true,\n}\n\nexport abstract class BaseStepExecutor implements StepExecutor {\n protected executionOptions?: ExecutionOptions\n protected statusManager: StatusManager\n\n public allowUserInteraction = true\n public allowExecution = true\n\n constructor(options: StepExecutorOptions) {\n this.statusManager = new StatusManager(options.routeId)\n this.executionOptions = options.executionOptions\n }\n\n setInteraction = (settings?: InteractionSettings): void => {\n const interactionSettings = {\n ...defaultInteractionSettings,\n ...settings,\n }\n this.allowUserInteraction = interactionSettings.allowInteraction\n this.statusManager.allowUpdates(interactionSettings.allowUpdates)\n this.allowExecution = interactionSettings.allowExecution\n }\n\n private createBaseContext = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams\n ): Promise<StepExecutorBaseContext> => {\n const fromChain = await client.getChainById(step.action.fromChainId)\n const toChain = await client.getChainById(step.action.toChainId)\n\n const isBridgeExecution = fromChain.id !== toChain.id\n\n return {\n client,\n step,\n fromChain,\n toChain,\n isBridgeExecution,\n retryParams,\n statusManager: this.statusManager,\n executionOptions: this.executionOptions,\n allowUserInteraction: this.allowUserInteraction,\n }\n }\n\n abstract createContext(\n baseContext: StepExecutorBaseContext\n ): Promise<StepExecutorContext>\n\n abstract createPipeline(context: StepExecutorContext): TaskPipeline\n\n abstract parseErrors(\n error: Error,\n step?: LiFiStepExtended,\n action?: ExecutionAction,\n retryParams?: ExecuteStepRetryParams\n ): Promise<SDKError | ExecuteStepRetryError>\n\n executeStep = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams\n ): Promise<LiFiStepExtended> => {\n try {\n step.execution = this.statusManager.initializeExecution(step)\n\n const baseContext = await this.createBaseContext(\n client,\n step,\n retryParams\n )\n const context = await this.createContext(baseContext)\n const pipeline = this.createPipeline(context)\n\n await pipeline.run(context)\n\n return step\n } catch (error: any) {\n // Derive failing action from last in execution.actions\n const action = step.execution?.actions?.at(-1)\n const parsed = await this.parseErrors(error, step, action, retryParams)\n if (!(parsed instanceof ExecuteStepRetryError)) {\n if (action) {\n this.statusManager.updateAction(step, action.type, 'FAILED', {\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n } else {\n this.statusManager.updateExecution(step, {\n status: 'FAILED',\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n }\n }\n throw parsed\n }\n }\n}\n"],"mappings":";;;;AAoBA,MAAM,6BAA6B;CACjC,kBAAkB;CAClB,cAAc;CACd,gBAAgB;AAClB;AAEA,IAAsB,mBAAtB,MAA+D;CAC7D;CACA;CAEA,uBAA8B;CAC9B,iBAAwB;CAExB,YAAY,SAA8B;EACxC,KAAK,gBAAgB,IAAIA,2BAAAA,cAAc,QAAQ,OAAO;EACtD,KA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etryError"],"sources":["../../../src/core/BaseStepExecutor.ts"],"sourcesContent":["import { ExecuteStepRetryError } from '../errors/errors.js'\nimport type { SDKError } from '../errors/SDKError.js'\nimport type {\n ExecuteStepRetryParams,\n ExecutionAction,\n ExecutionOptions,\n InteractionSettings,\n LiFiStepExtended,\n SDKClient,\n StepExecutor,\n StepExecutorOptions,\n} from '../types/core.js'\nimport type {\n StepExecutorBaseContext,\n StepExecutorContext,\n} from '../types/execution.js'\nimport { StatusManager } from './StatusManager.js'\nimport type { TaskPipeline } from './TaskPipeline.js'\n\n// Please be careful when changing the defaults as it may break the behavior (e.g., background execution)\nconst defaultInteractionSettings = {\n allowInteraction: true,\n allowUpdates: true,\n allowExecution: true,\n}\n\nexport abstract class BaseStepExecutor implements StepExecutor {\n protected executionOptions?: ExecutionOptions\n protected statusManager: StatusManager\n\n public allowUserInteraction = true\n public allowExecution = true\n\n constructor(options: StepExecutorOptions) {\n this.statusManager = new StatusManager(options.routeId)\n this.executionOptions = options.executionOptions\n }\n\n setInteraction = (settings?: InteractionSettings): void => {\n const interactionSettings = {\n ...defaultInteractionSettings,\n ...settings,\n }\n this.allowUserInteraction = interactionSettings.allowInteraction\n this.statusManager.allowUpdates(interactionSettings.allowUpdates)\n this.allowExecution = interactionSettings.allowExecution\n }\n\n private createBaseContext = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams\n ): Promise<StepExecutorBaseContext> => {\n const fromChain = await client.getChainById(step.action.fromChainId)\n const toChain = await client.getChainById(step.action.toChainId)\n\n const isBridgeExecution = fromChain.id !== toChain.id\n\n return {\n client,\n step,\n fromChain,\n toChain,\n isBridgeExecution,\n retryParams,\n statusManager: this.statusManager,\n executionOptions: this.executionOptions,\n allowUserInteraction: this.allowUserInteraction,\n }\n }\n\n abstract createContext(\n baseContext: StepExecutorBaseContext\n ): Promise<StepExecutorContext>\n\n abstract createPipeline(context: StepExecutorContext): TaskPipeline\n\n abstract parseErrors(\n error: Error,\n step?: LiFiStepExtended,\n action?: ExecutionAction,\n retryParams?: ExecuteStepRetryParams\n ): Promise<SDKError | ExecuteStepRetryError>\n\n executeStep = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams\n ): Promise<LiFiStepExtended> => {\n try {\n step.execution = this.statusManager.initializeExecution(step)\n\n const baseContext = await this.createBaseContext(\n client,\n step,\n retryParams\n )\n const context = await this.createContext(baseContext)\n const pipeline = this.createPipeline(context)\n\n await pipeline.run(context)\n\n return step\n } catch (error: any) {\n // Derive failing action from last in execution.actions\n const action = step.execution?.actions?.at(-1)\n const parsed = await this.parseErrors(error, step, action, retryParams)\n if (!(parsed instanceof ExecuteStepRetryError)) {\n if (action) {\n this.statusManager.updateAction(step, action.type, 'FAILED', {\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n } else {\n this.statusManager.updateExecution(step, {\n status: 'FAILED',\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n }\n }\n throw parsed\n }\n }\n}\n"],"mappings":";;;;AAoBA,MAAM,6BAA6B;CACjC,kBAAkB;CAClB,cAAc;CACd,gBAAgB;AAClB;AAEA,IAAsB,mBAAtB,MAA+D;CAC7D;CACA;CAEA,uBAA8B;CAC9B,iBAAwB;CAExB,YAAY,SAA8B;EACxC,KAAK,gBAAgB,IAAIA,2BAAAA,cAAc,QAAQ,OAAO;EACtD,KAAK,mBAAmB,QAAQ;CAClC;CAEA,kBAAkB,aAAyC;EACzD,MAAM,sBAAsB;GAC1B,GAAG;GACH,GAAG;EACL;EACA,KAAK,uBAAuB,oBAAoB;EAChD,KAAK,cAAc,aAAa,oBAAoB,YAAY;EAChE,KAAK,iBAAiB,oBAAoB;CAC5C;CAEA,oBAA4B,OAC1B,QACA,MACA,gBACqC;EACrC,MAAM,YAAY,MAAM,OAAO,aAAa,KAAK,OAAO,WAAW;EACnE,MAAM,UAAU,MAAM,OAAO,aAAa,KAAK,OAAO,SAAS;EAI/D,OAAO;GACL;GACA;GACA;GACA;GACA,mBAPwB,UAAU,OAAO,QAAQ;GAQjD;GACA,eAAe,KAAK;GACpB,kBAAkB,KAAK;GACvB,sBAAsB,KAAK;EAC7B;CACF;CAeA,cAAc,OACZ,QACA,MACA,gBAC8B;EAC9B,IAAI;GACF,KAAK,YAAY,KAAK,cAAc,oBAAoB,IAAI;GAE5D,MAAM,cAAc,MAAM,KAAK,kBAC7B,QACA,MACA,WACF;GACA,MAAM,UAAU,MAAM,KAAK,cAAc,WAAW;GAGpD,MAFiB,KAAK,eAAe,OAExB,CAAC,CAAC,IAAI,OAAO;GAE1B,OAAO;EACT,SAAS,OAAY;GAEnB,MAAM,SAAS,KAAK,WAAW,SAAS,GAAG,EAAE;GAC7C,MAAM,SAAS,MAAM,KAAK,YAAY,OAAO,MAAM,QAAQ,WAAW;GACtE,IAAI,EAAE,kBAAkBC,sBAAAA,wBAAwB;IAC9C,IAAI,QACF,KAAK,cAAc,aAAa,MAAM,OAAO,MAAM,UAAU,EAC3D,OAAO;KACL,SAAS,OAAO,OAAO;KACvB,MAAM,OAAO;IACf,EACF,CAAC;SAED,KAAK,cAAc,gBAAgB,MAAM;KACvC,QAAQ;KACR,OAAO;MACL,SAAS,OAAO,OAAO;MACvB,MAAM,OAAO;KACf;IACF,CAAC;GAEL;GACA,MAAM;EACR;CACF;AACF"}
@@ -122,10 +122,7 @@ var StatusManager = class {
122
122
  break;
123
123
  case "RESET_REQUIRED":
124
124
  case "MESSAGE_REQUIRED":
125
- case "ACTION_REQUIRED":
126
- step.execution.status = "ACTION_REQUIRED";
127
- break;
128
- default: break;
125
+ case "ACTION_REQUIRED": step.execution.status = "ACTION_REQUIRED";
129
126
  }
130
127
  currentAction.status = status;
131
128
  currentAction.message = require_core_actionMessages.getActionMessage(type, status);
@@ -1 +1 @@
1
- {"version":3,"file":"StatusManager.js","names":["getActionMessage","executionState"],"sources":["../../../src/core/StatusManager.ts"],"sourcesContent":["import type { ChainId, LiFiStep } from '@lifi/types'\nimport type {\n Execution,\n ExecutionAction,\n ExecutionActionStatus,\n ExecutionActionType,\n LiFiStepExtended,\n} from '../types/core.js'\nimport { getActionMessage } from './actionMessages.js'\nimport { executionState } from './executionState.js'\n\ntype ActionProps = {\n step: LiFiStepExtended\n type: ExecutionActionType\n chainId: ChainId\n status: ExecutionActionStatus\n}\n\n/**\n * Manages status updates of a route and provides various functions for tracking actions.\n */\nexport class StatusManager {\n private readonly routeId: string\n private shouldUpdate = true\n\n constructor(routeId: string) {\n this.routeId = routeId\n }\n\n /**\n * Initializes the execution object of a Step.\n * @param step The current step in execution\n * @returns The initialized execution object for this step\n */\n initializeExecution = (step: LiFiStepExtended): Execution => {\n if (!step.execution) {\n step.execution = {\n startedAt: Date.now(),\n status: 'PENDING',\n actions: [],\n }\n this.updateStepInRoute(step)\n }\n\n // Change status to PENDING after resuming from FAILED\n if (step.execution.status === 'FAILED') {\n step.execution.startedAt = Date.now()\n step.execution.status = 'PENDING'\n step.execution.signedAt = undefined\n step.execution.error = undefined\n this.updateStepInRoute(step)\n }\n\n return step.execution\n }\n\n /**\n * Updates the execution object of a Step.\n * @param step The current step in execution\n * @param execution Partial execution data to merge\n * @returns The step with the updated execution object\n */\n updateExecution(\n step: LiFiStepExtended,\n execution: Partial<Execution>\n ): LiFiStep {\n if (!step.execution) {\n throw Error(\"Can't update empty execution.\")\n }\n step.execution = {\n ...step.execution,\n ...execution,\n }\n this.updateStepInRoute(step)\n return step\n }\n\n /**\n * Finds an action of the specified type in the step's execution\n * @param step The step to search in\n * @param type The action type to find\n * @returns The found action or undefined if not found\n */\n findAction(\n step: LiFiStepExtended,\n type: ExecutionActionType\n ): ExecutionAction | undefined {\n if (!step.execution?.actions) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const action = step.execution.actions.find((p) => p.type === type)\n\n return action\n }\n\n /**\n * Create and push a new action into the execution.\n * Caller is responsible for ensuring an action of this type does not already exist.\n * @param step The step that should contain the new action.\n * @param type Type of the action.\n * @param chainId Chain Id of the action.\n * @param status The initial status for the new action.\n * @returns The created action.\n */\n createAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const newAction: ExecutionAction = {\n type,\n message: getActionMessage(type, status),\n status,\n chainId,\n }\n\n step.execution.actions.push(newAction)\n this.updateStepInRoute(step)\n return newAction\n }\n\n /**\n * Find an existing action by type and update it, or create a new one if none exists.\n * @param step The step that should contain the action.\n * @param type Type of the action. Used to identify already existing actions.\n * @param chainId Chain Id of the action (used when creating).\n * @param status The status to set on the found or newly created action.\n * @returns The updated or newly created action.\n */\n initializeAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n const action = this.findAction(step, type)\n\n if (action) {\n return this.updateAction(step, type, status, {\n error: undefined,\n })\n }\n\n return this.createAction({ step, type, chainId, status })\n }\n\n /**\n * Update an action object.\n * @param step The step where the action should be updated\n * @param type The action type to update\n * @param status The status the action gets.\n * @param [params] Additional parameters to append to the action.\n * @returns The updated action\n */\n updateAction = (\n step: LiFiStepExtended,\n type: ExecutionActionType,\n status: ExecutionActionStatus,\n params?: Partial<ExecutionAction & { signedAt?: number }>\n ): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Can't update an empty step execution.\")\n }\n const currentAction = this.findAction(step, type)\n\n if (!currentAction) {\n throw new Error(\"Can't find an action for the given type.\")\n }\n\n switch (status) {\n case 'CANCELLED':\n break\n case 'FAILED':\n step.execution.status = 'FAILED'\n if (params?.error) {\n step.execution.error = params.error\n }\n break\n case 'DONE':\n break\n case 'PENDING':\n step.execution.status = 'PENDING'\n if (params?.signedAt) {\n step.execution.signedAt = params.signedAt\n }\n break\n case 'RESET_REQUIRED':\n case 'MESSAGE_REQUIRED':\n case 'ACTION_REQUIRED':\n step.execution.status = 'ACTION_REQUIRED'\n break\n default:\n break\n }\n\n currentAction.status = status\n currentAction.message = getActionMessage(type, status)\n // set extra parameters or overwrite the standard params set in the switch statement\n if (params) {\n const { signedAt: _signedAt, ...rest } = params\n Object.assign(currentAction, rest)\n }\n // Sort actions, the ones with DONE status go first\n step.execution.actions = [\n ...step.execution.actions.filter((action) => action.status === 'DONE'),\n ...step.execution.actions.filter((action) => action.status !== 'DONE'),\n ]\n this.updateStepInRoute(step) // updates the step in the route\n return currentAction\n }\n\n updateStepInRoute = (step: LiFiStep): LiFiStep => {\n if (!this.shouldUpdate) {\n return step\n }\n const data = executionState.get(this.routeId)\n\n if (!data) {\n throw new Error('Execution data not found.')\n }\n\n const stepIndex = data.route.steps.findIndex(\n (routeStep) => routeStep.id === step.id\n )\n\n if (stepIndex === -1) {\n throw new Error(\"Couldn't find a step to update.\")\n }\n\n data.route.steps[stepIndex] = { ...data.route.steps[stepIndex], ...step }\n\n data.executionOptions?.updateRouteHook?.(data.route)\n return data.route.steps[stepIndex]\n }\n\n allowUpdates(value: boolean): void {\n this.shouldUpdate = value\n }\n}\n"],"mappings":";;;;;;;AAqBA,IAAa,gBAAb,MAA2B;CACzB;CACA,eAAuB;CAEvB,YAAY,SAAiB;EAC3B,KAAK,UAAU;CACjB;;;;;;CAOA,uBAAuB,SAAsC;EAC3D,IAAI,CAAC,KAAK,WAAW;GACnB,KAAK,YAAY;IACf,WAAW,KAAK,IAAI;IACpB,QAAQ;IACR,SAAS,CAAC;GACZ;GACA,KAAK,kBAAkB,IAAI;EAC7B;EAGA,IAAI,KAAK,UAAU,WAAW,UAAU;GACtC,KAAK,UAAU,YAAY,KAAK,IAAI;GACpC,KAAK,UAAU,SAAS;GACxB,KAAK,UAAU,WAAW,KAAA;GAC1B,KAAK,UAAU,QAAQ,KAAA;GACvB,KAAK,kBAAkB,IAAI;EAC7B;EAEA,OAAO,KAAK;CACd;;;;;;;CAQA,gBACE,MACA,WACU;EACV,IAAI,CAAC,KAAK,WACR,MAAM,MAAM,+BAA+B;EAE7C,KAAK,YAAY;GACf,GAAG,KAAK;GACR,GAAG;EACL;EACA,KAAK,kBAAkB,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iBAAiB,MAAM,MAAM;EAErD,IAAI,QAAQ;GACV,MAAM,EAAE,UAAU,WAAW,GAAG,SAAS;GACzC,OAAO,OAAO,eAAe,IAAI;EACnC;EAEA,KAAK,UAAU,UAAU,CACvB,GAAG,KAAK,UAAU,QAAQ,QAAQ,WAAW,OAAO,WAAW,MAAM,GACrE,GAAG,KAAK,UAAU,QAAQ,QAAQ,WAAW,OAAO,WAAW,MAAM,CACvE;EACA,KAAK,kBAAkB,IAAI;EAC3B,OAAO;CACT;CAEA,qBAAqB,SAA6B;EAChD,IAAI,CAAC,KAAK,cACR,OAAO;EAET,MAAM,OAAOC,4BAAAA,eAAe,IAAI,KAAK,OAAO;EAE5C,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,2BAA2B;EAG7C,MAAM,YAAY,KAAK,MAAM,MAAM,WAChC,cAAc,UAAU,OAAO,KAAK,EACvC;EAEA,IAAI,cAAc,IAChB,MAAM,IAAI,MAAM,iCAAiC;EAGnD,KAAK,MAAM,MAAM,aAAa;GAAE,GAAG,KAAK,MAAM,MAAM;GAAY,GAAG;EAAK;EAExE,KAAK,kBAAkB,kBAAkB,KAAK,KAAK;EACnD,OAAO,KAAK,MAAM,MAAM;CAC1B;CAEA,aAAa,OAAsB;EACjC,KAAK,eAAe;CACtB;AACF"}
1
+ {"version":3,"file":"StatusManager.js","names":["getActionMessage","executionState"],"sources":["../../../src/core/StatusManager.ts"],"sourcesContent":["import type { ChainId, LiFiStep } from '@lifi/types'\nimport type {\n Execution,\n ExecutionAction,\n ExecutionActionStatus,\n ExecutionActionType,\n LiFiStepExtended,\n} from '../types/core.js'\nimport { getActionMessage } from './actionMessages.js'\nimport { executionState } from './executionState.js'\n\ntype ActionProps = {\n step: LiFiStepExtended\n type: ExecutionActionType\n chainId: ChainId\n status: ExecutionActionStatus\n}\n\n/**\n * Manages status updates of a route and provides various functions for tracking actions.\n */\nexport class StatusManager {\n private readonly routeId: string\n private shouldUpdate = true\n\n constructor(routeId: string) {\n this.routeId = routeId\n }\n\n /**\n * Initializes the execution object of a Step.\n * @param step The current step in execution\n * @returns The initialized execution object for this step\n */\n initializeExecution = (step: LiFiStepExtended): Execution => {\n if (!step.execution) {\n step.execution = {\n startedAt: Date.now(),\n status: 'PENDING',\n actions: [],\n }\n this.updateStepInRoute(step)\n }\n\n // Change status to PENDING after resuming from FAILED\n if (step.execution.status === 'FAILED') {\n step.execution.startedAt = Date.now()\n step.execution.status = 'PENDING'\n step.execution.signedAt = undefined\n step.execution.error = undefined\n this.updateStepInRoute(step)\n }\n\n return step.execution\n }\n\n /**\n * Updates the execution object of a Step.\n * @param step The current step in execution\n * @param execution Partial execution data to merge\n * @returns The step with the updated execution object\n */\n updateExecution(\n step: LiFiStepExtended,\n execution: Partial<Execution>\n ): LiFiStep {\n if (!step.execution) {\n throw Error(\"Can't update empty execution.\")\n }\n step.execution = {\n ...step.execution,\n ...execution,\n }\n this.updateStepInRoute(step)\n return step\n }\n\n /**\n * Finds an action of the specified type in the step's execution\n * @param step The step to search in\n * @param type The action type to find\n * @returns The found action or undefined if not found\n */\n findAction(\n step: LiFiStepExtended,\n type: ExecutionActionType\n ): ExecutionAction | undefined {\n if (!step.execution?.actions) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const action = step.execution.actions.find((p) => p.type === type)\n\n return action\n }\n\n /**\n * Create and push a new action into the execution.\n * Caller is responsible for ensuring an action of this type does not already exist.\n * @param step The step that should contain the new action.\n * @param type Type of the action.\n * @param chainId Chain Id of the action.\n * @param status The initial status for the new action.\n * @returns The created action.\n */\n createAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const newAction: ExecutionAction = {\n type,\n message: getActionMessage(type, status),\n status,\n chainId,\n }\n\n step.execution.actions.push(newAction)\n this.updateStepInRoute(step)\n return newAction\n }\n\n /**\n * Find an existing action by type and update it, or create a new one if none exists.\n * @param step The step that should contain the action.\n * @param type Type of the action. Used to identify already existing actions.\n * @param chainId Chain Id of the action (used when creating).\n * @param status The status to set on the found or newly created action.\n * @returns The updated or newly created action.\n */\n initializeAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n const action = this.findAction(step, type)\n\n if (action) {\n return this.updateAction(step, type, status, {\n error: undefined,\n })\n }\n\n return this.createAction({ step, type, chainId, status })\n }\n\n /**\n * Update an action object.\n * @param step The step where the action should be updated\n * @param type The action type to update\n * @param status The status the action gets.\n * @param [params] Additional parameters to append to the action.\n * @returns The updated action\n */\n updateAction = (\n step: LiFiStepExtended,\n type: ExecutionActionType,\n status: ExecutionActionStatus,\n params?: Partial<ExecutionAction & { signedAt?: number }>\n ): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Can't update an empty step execution.\")\n }\n const currentAction = this.findAction(step, type)\n\n if (!currentAction) {\n throw new Error(\"Can't find an action for the given type.\")\n }\n\n switch (status) {\n case 'CANCELLED':\n break\n case 'FAILED':\n step.execution.status = 'FAILED'\n if (params?.error) {\n step.execution.error = params.error\n }\n break\n case 'DONE':\n break\n case 'PENDING':\n step.execution.status = 'PENDING'\n if (params?.signedAt) {\n step.execution.signedAt = params.signedAt\n }\n break\n case 'RESET_REQUIRED':\n case 'MESSAGE_REQUIRED':\n case 'ACTION_REQUIRED':\n step.execution.status = 'ACTION_REQUIRED'\n break\n default:\n break\n }\n\n currentAction.status = status\n currentAction.message = getActionMessage(type, status)\n // set extra parameters or overwrite the standard params set in the switch statement\n if (params) {\n const { signedAt: _signedAt, ...rest } = params\n Object.assign(currentAction, rest)\n }\n // Sort actions, the ones with DONE status go first\n step.execution.actions = [\n ...step.execution.actions.filter((action) => action.status === 'DONE'),\n ...step.execution.actions.filter((action) => action.status !== 'DONE'),\n ]\n this.updateStepInRoute(step) // updates the step in the route\n return currentAction\n }\n\n updateStepInRoute = (step: LiFiStep): LiFiStep => {\n if (!this.shouldUpdate) {\n return step\n }\n const data = executionState.get(this.routeId)\n\n if (!data) {\n throw new Error('Execution data not found.')\n }\n\n const stepIndex = data.route.steps.findIndex(\n (routeStep) => routeStep.id === step.id\n )\n\n if (stepIndex === -1) {\n throw new Error(\"Couldn't find a step to update.\")\n }\n\n data.route.steps[stepIndex] = { ...data.route.steps[stepIndex], ...step }\n\n data.executionOptions?.updateRouteHook?.(data.route)\n return data.route.steps[stepIndex]\n }\n\n allowUpdates(value: boolean): void {\n this.shouldUpdate = value\n }\n}\n"],"mappings":";;;;;;;AAqBA,IAAa,gBAAb,MAA2B;CACzB;CACA,eAAuB;CAEvB,YAAY,SAAiB;EAC3B,KAAK,UAAU;CACjB;;;;;;CAOA,uBAAuB,SAAsC;EAC3D,IAAI,CAAC,KAAK,WAAW;GACnB,KAAK,YAAY;IACf,WAAW,KAAK,IAAI;IACpB,QAAQ;IACR,SAAS,CAAC;GACZ;GACA,KAAK,kBAAkB,IAAI;EAC7B;EAGA,IAAI,KAAK,UAAU,WAAW,UAAU;GACtC,KAAK,UAAU,YAAY,KAAK,IAAI;GACpC,KAAK,UAAU,SAAS;GACxB,KAAK,UAAU,WAAW,KAAA;GAC1B,KAAK,UAAU,QAAQ,KAAA;GACvB,KAAK,kBAAkB,IAAI;EAC7B;EAEA,OAAO,KAAK;CACd;;;;;;;CAQA,gBACE,MACA,WACU;EACV,IAAI,CAAC,KAAK,WACR,MAAM,MAAM,+BAA+B;EAE7C,KAAK,YAAY;GACf,GAAG,KAAK;GACR,GAAG;EACL;EACA,KAAK,kBAAkB,IAAI;EAC3B,OAAO;CACT;;;;;;;CAQA,WACE,MACA,MAC6B;EAC7B,IAAI,CAAC,KAAK,WAAW,SACnB,MAAM,IAAI,MAAM,oCAAoC;EAKtD,OAFe,KAAK,UAAU,QAAQ,MAAM,MAAM,EAAE,SAAS,IAEjD;CACd;;;;;;;;;;CAWA,gBAAgB,EACd,MACA,MACA,SACA,aACkC;EAClC,IAAI,CAAC,KAAK,WACR,MAAM,IAAI,MAAM,oCAAoC;EAGtD,MAAM,YAA6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AAqB,SAA6B;EAChD,IAAI,CAAC,KAAK,cACR,OAAO;EAET,MAAM,OAAOC,4BAAAA,eAAe,IAAI,KAAK,OAAO;EAE5C,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,2BAA2B;EAG7C,MAAM,YAAY,KAAK,MAAM,MAAM,WAChC,cAAc,UAAU,OAAO,KAAK,EACvC;EAEA,IAAI,cAAc,IAChB,MAAM,IAAI,MAAM,iCAAiC;EAGnD,KAAK,MAAM,MAAM,aAAa;GAAE,GAAG,KAAK,MAAM,MAAM;GAAY,GAAG;EAAK;EAExE,KAAK,kBAAkB,kBAAkB,KAAK,KAAK;EACnD,OAAO,KAAK,MAAM,MAAM;CAC1B;CAEA,aAAa,OAAsB;EACjC,KAAK,eAAe;CACtB;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"execution.js","names":["executionState","ProviderError","ExecuteStepRetryError"],"sources":["../../../src/core/execution.ts"],"sourcesContent":["import type { Route } from '@lifi/types'\nimport { LiFiErrorCode } from '../errors/constants.js'\nimport { ExecuteStepRetryError, ProviderError } from '../errors/errors.js'\nimport type {\n ExecutionOptions,\n LiFiStepExtended,\n RouteExtended,\n SDKClient,\n SDKProvider,\n} from '../types/core.js'\nimport { executionState } from './executionState.js'\nimport { prepareRestart } from './prepareRestart.js'\n\n/**\n * Execute a route.\n * @param client - The SDK client.\n * @param route - The route that should be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const executeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n // Deep clone to prevent side effects\n const clonedRoute = structuredClone<Route>(route)\n\n let executionPromise = executionState.get(clonedRoute.id)?.promise\n // Check if route is already running\n if (executionPromise) {\n return executionPromise\n }\n\n executionState.create({ route: clonedRoute, executionOptions })\n executionPromise = executeSteps(client, clonedRoute)\n executionState.update({\n route: clonedRoute,\n promise: executionPromise,\n })\n\n return executionPromise\n}\n\n/**\n * Resume the execution of a route that has been stopped or had an error while executing.\n * @param client - The SDK client.\n * @param route - The route that is to be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const resumeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n const execution = executionState.get(route.id)\n\n if (execution) {\n const executionHalted = execution.executors.some(\n (executor) => !executor.allowExecution\n )\n if (!executionHalted) {\n // Check if we want to resume route execution in the background\n updateRouteExecution(route, {\n executeInBackground: executionOptions?.executeInBackground,\n })\n if (!execution.promise) {\n // We should never reach this point if we do clean-up properly\n throw new Error('Route execution promise not found.')\n }\n return execution.promise\n }\n }\n\n prepareRestart(route)\n\n return executeRoute(client, route, executionOptions)\n}\n\nconst executeSteps = async (\n client: SDKClient,\n route: RouteExtended\n): Promise<RouteExtended> => {\n // Loop over steps and execute them\n for (let index = 0; index < route.steps.length; index++) {\n const execution = executionState.get(route.id)\n // Check if execution has stopped in the meantime\n if (!execution) {\n break\n }\n\n const step = route.steps[index]\n const previousStep = route.steps[index - 1]\n // Check if the step is already done\n if (step.execution?.status === 'DONE') {\n continue\n }\n\n // Update step fromAmount using output of the previous step execution. In the future this should be handled by calling `updateRoute`\n if (previousStep?.execution?.toAmount) {\n step.action.fromAmount = previousStep.execution.toAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount =\n previousStep.execution.toAmount\n }\n }\n\n try {\n const fromAddress = step.action.fromAddress\n if (!fromAddress) {\n throw new Error('Action fromAddress is not specified.')\n }\n\n const provider = client.providers.find((provider: SDKProvider) =>\n provider.isAddress(fromAddress)\n )\n\n if (!provider) {\n throw new ProviderError(\n LiFiErrorCode.ProviderUnavailable,\n 'SDK Execution Provider not found.'\n )\n }\n\n const stepExecutor = await provider.getStepExecutor({\n routeId: route.id,\n executionOptions: execution.executionOptions,\n })\n execution.executors.push(stepExecutor)\n\n // Check if we want to execute this step in the background\n if (execution.executionOptions) {\n updateRouteExecution(route, execution.executionOptions)\n }\n\n let executedStep: LiFiStepExtended\n try {\n executedStep = await stepExecutor.executeStep(client, step)\n } catch (e) {\n if (e instanceof ExecuteStepRetryError) {\n step.execution = undefined\n executedStep = await stepExecutor.executeStep(\n client,\n step,\n e.retryParams\n )\n } else {\n throw e\n }\n }\n\n // We may reach this point if user interaction isn't allowed. We want to stop execution until we resume it\n if (executedStep.execution?.status !== 'DONE') {\n stopRouteExecution(route)\n }\n\n // Execution stopped during the current step, we don't want to continue to the next step so we return already\n if (!stepExecutor.allowExecution) {\n return route\n }\n } catch (e) {\n stopRouteExecution(route)\n throw e\n }\n }\n\n // Clean up after the execution\n executionState.delete(route.id)\n return route\n}\n\n/**\n * Updates route execution to background or foreground state.\n * @param route - A route that is currently in execution.\n * @param options - An object with execution settings.\n */\nexport const updateRouteExecution = (\n route: Route,\n options: ExecutionOptions\n): void => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return\n }\n\n if ('executeInBackground' in options) {\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: !options?.executeInBackground,\n allowUpdates: true,\n })\n }\n }\n // Update active route settings so we know what the current state of execution is\n execution.executionOptions = {\n ...execution.executionOptions,\n ...options,\n }\n}\n\n/**\n * Stops the execution of an active route.\n * @param route - A route that is currently in execution.\n * @returns The stopped route.\n */\nexport const stopRouteExecution = (route: Route): Route => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return route\n }\n\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: false,\n allowUpdates: false,\n allowExecution: false,\n })\n }\n executionState.delete(route.id)\n return execution.route\n}\n\n/**\n * Get the list of active routes.\n * @returns A list of routes.\n */\nexport const getActiveRoutes = (): RouteExtended[] => {\n return Object.values(executionState.state)\n .map((dict) => dict?.route)\n .filter(Boolean) as RouteExtended[]\n}\n\n/**\n * Return the current route information for given route. The route has to be active.\n * @param routeId - A route id.\n * @returns The updated route.\n */\nexport const getActiveRoute = (routeId: string): RouteExtended | undefined => {\n return executionState.get(routeId)?.route\n}\n"],"mappings":";;;;;;;;;;;;;;AAqBA,MAAa,eAAe,OAC1B,QACA,OACA,qBAC2B;CAE3B,MAAM,cAAc,gBAAuB,KAAK;CAEhD,IAAI,mBAAmBA,4BAAAA,eAAe,IAAI,YAAY,EAAE,CAAC,EAAE;CAE3D,IAAI,kBACF,OAAO;CAGT,4BAAA,eAAe,OAAO;EAAE,OAAO;EAAa;CAAiB,CAAC;CAC9D,mBAAmB,aAAa,QAAQ,WAAW;CACnD,4BAAA,eAAe,OAAO;EACpB,OAAO;EACP,SAAS;CACX,CAAC;CAED,OAAO;AACT;;;;;;;;;AAUA,MAAa,cAAc,OACzB,QACA,OACA,qBAC2B;CAC3B,MAAM,YAAYA,4BAAAA,eAAe,IAAI,MAAM,EAAE;CAE7C,IAAI;MAIE,CAHoB,UAAU,UAAU,MACzC,aAAa,CAAC,SAAS,cAEP,GAAG;GAEpB,qBAAqB,OAAO,EAC1B,qBAAqB,kBAAkB,oBACzC,CAAC;GACD,IAAI,CAAC,UAAU,SAEb,MAAM,IAAI,MAAM,oCAAoC;GAEtD,OAAO,UAAU;EACnB;;CAGF,4BAAA,eAAe,KAAK;CAEpB,OAAO,aAAa,QAAQ,OAAO,gBAAgB;AACrD;AAEA,MAAM,eAAe,OACnB,QACA,UAC2B;CAE3B,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,MAAM,QAAQ,SAAS;EACvD,MAAM,YAAYA,4BAAAA,eAAe,IAAI,MAAM,EAAE;EAE7C,IAAI,CAAC,WACH;EAGF,MAAM,OAAO,MAAM,MAAM;EACzB,MAAM,eAAe,MAAM,MAAM,QAAQ;EAEzC,IAAI,KAAK,WAAW,WAAW,QAC7B;EAIF,IAAI,cAAc,WAAW,UAAU;GACrC,KAAK,OAAO,aAAa,aAAa,UAAU;GAChD,IAAI,KAAK,eAAe,QACtB,KAAK,cAAc,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AAE;CAC7C,IAAI,CAAC,WACH,OAAO;CAGT,KAAK,MAAM,YAAY,UAAU,WAC/B,SAAS,eAAe;EACtB,kBAAkB;EAClB,cAAc;EACd,gBAAgB;CAClB,CAAC;CAEH,4BAAA,eAAe,OAAO,MAAM,EAAE;CAC9B,OAAO,UAAU;AACnB;;;;;AAMA,MAAa,wBAAyC;CACpD,OAAO,OAAO,OAAOA,4BAAAA,eAAe,KAAK,CAAC,CACvC,KAAK,SAAS,MAAM,KAAK,CAAC,CAC1B,OAAO,OAAO;AACnB;;;;;;AAOA,MAAa,kBAAkB,YAA+C;CAC5E,OAAOA,4BAAAA,eAAe,IAAI,OAAO,CAAC,EAAE;AACtC"}
1
+ {"version":3,"file":"execution.js","names":["executionState","ProviderError","ExecuteStepRetryError"],"sources":["../../../src/core/execution.ts"],"sourcesContent":["import type { Route } from '@lifi/types'\nimport { LiFiErrorCode } from '../errors/constants.js'\nimport { ExecuteStepRetryError, ProviderError } from '../errors/errors.js'\nimport type {\n ExecutionOptions,\n LiFiStepExtended,\n RouteExtended,\n SDKClient,\n SDKProvider,\n} from '../types/core.js'\nimport { executionState } from './executionState.js'\nimport { prepareRestart } from './prepareRestart.js'\n\n/**\n * Execute a route.\n * @param client - The SDK client.\n * @param route - The route that should be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const executeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n // Deep clone to prevent side effects\n const clonedRoute = structuredClone<Route>(route)\n\n let executionPromise = executionState.get(clonedRoute.id)?.promise\n // Check if route is already running\n if (executionPromise) {\n return executionPromise\n }\n\n executionState.create({ route: clonedRoute, executionOptions })\n executionPromise = executeSteps(client, clonedRoute)\n executionState.update({\n route: clonedRoute,\n promise: executionPromise,\n })\n\n return executionPromise\n}\n\n/**\n * Resume the execution of a route that has been stopped or had an error while executing.\n * @param client - The SDK client.\n * @param route - The route that is to be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const resumeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n const execution = executionState.get(route.id)\n\n if (execution) {\n const executionHalted = execution.executors.some(\n (executor) => !executor.allowExecution\n )\n if (!executionHalted) {\n // Check if we want to resume route execution in the background\n updateRouteExecution(route, {\n executeInBackground: executionOptions?.executeInBackground,\n })\n if (!execution.promise) {\n // We should never reach this point if we do clean-up properly\n throw new Error('Route execution promise not found.')\n }\n return execution.promise\n }\n }\n\n prepareRestart(route)\n\n return executeRoute(client, route, executionOptions)\n}\n\nconst executeSteps = async (\n client: SDKClient,\n route: RouteExtended\n): Promise<RouteExtended> => {\n // Loop over steps and execute them\n for (let index = 0; index < route.steps.length; index++) {\n const execution = executionState.get(route.id)\n // Check if execution has stopped in the meantime\n if (!execution) {\n break\n }\n\n const step = route.steps[index]\n const previousStep = route.steps[index - 1]\n // Check if the step is already done\n if (step.execution?.status === 'DONE') {\n continue\n }\n\n // Update step fromAmount using output of the previous step execution. In the future this should be handled by calling `updateRoute`\n if (previousStep?.execution?.toAmount) {\n step.action.fromAmount = previousStep.execution.toAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount =\n previousStep.execution.toAmount\n }\n }\n\n try {\n const fromAddress = step.action.fromAddress\n if (!fromAddress) {\n throw new Error('Action fromAddress is not specified.')\n }\n\n const provider = client.providers.find((provider: SDKProvider) =>\n provider.isAddress(fromAddress)\n )\n\n if (!provider) {\n throw new ProviderError(\n LiFiErrorCode.ProviderUnavailable,\n 'SDK Execution Provider not found.'\n )\n }\n\n const stepExecutor = await provider.getStepExecutor({\n routeId: route.id,\n executionOptions: execution.executionOptions,\n })\n execution.executors.push(stepExecutor)\n\n // Check if we want to execute this step in the background\n if (execution.executionOptions) {\n updateRouteExecution(route, execution.executionOptions)\n }\n\n let executedStep: LiFiStepExtended\n try {\n executedStep = await stepExecutor.executeStep(client, step)\n } catch (e) {\n if (e instanceof ExecuteStepRetryError) {\n step.execution = undefined\n executedStep = await stepExecutor.executeStep(\n client,\n step,\n e.retryParams\n )\n } else {\n throw e\n }\n }\n\n // We may reach this point if user interaction isn't allowed. We want to stop execution until we resume it\n if (executedStep.execution?.status !== 'DONE') {\n stopRouteExecution(route)\n }\n\n // Execution stopped during the current step, we don't want to continue to the next step so we return already\n if (!stepExecutor.allowExecution) {\n return route\n }\n } catch (e) {\n stopRouteExecution(route)\n throw e\n }\n }\n\n // Clean up after the execution\n executionState.delete(route.id)\n return route\n}\n\n/**\n * Updates route execution to background or foreground state.\n * @param route - A route that is currently in execution.\n * @param options - An object with execution settings.\n */\nexport const updateRouteExecution = (\n route: Route,\n options: ExecutionOptions\n): void => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return\n }\n\n if ('executeInBackground' in options) {\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: !options?.executeInBackground,\n allowUpdates: true,\n })\n }\n }\n // Update active route settings so we know what the current state of execution is\n execution.executionOptions = {\n ...execution.executionOptions,\n ...options,\n }\n}\n\n/**\n * Stops the execution of an active route.\n * @param route - A route that is currently in execution.\n * @returns The stopped route.\n */\nexport const stopRouteExecution = (route: Route): Route => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return route\n }\n\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: false,\n allowUpdates: false,\n allowExecution: false,\n })\n }\n executionState.delete(route.id)\n return execution.route\n}\n\n/**\n * Get the list of active routes.\n * @returns A list of routes.\n */\nexport const getActiveRoutes = (): RouteExtended[] => {\n return Object.values(executionState.state)\n .map((dict) => dict?.route)\n .filter(Boolean) as RouteExtended[]\n}\n\n/**\n * Return the current route information for given route. The route has to be active.\n * @param routeId - A route id.\n * @returns The updated route.\n */\nexport const getActiveRoute = (routeId: string): RouteExtended | undefined => {\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Y,UAAU,WAC/B,SAAS,eAAe;EACtB,kBAAkB;EAClB,cAAc;EACd,gBAAgB;CAClB,CAAC;CAEH,4BAAA,eAAe,OAAO,MAAM,EAAE;CAC9B,OAAO,UAAU;AACnB;;;;;AAMA,MAAa,wBAAyC;CACpD,OAAO,OAAO,OAAOA,4BAAAA,eAAe,KAAK,CAAC,CACvC,KAAK,SAAS,MAAM,KAAK,CAAC,CAC1B,OAAO,OAAO;AACnB;;;;;;AAOA,MAAa,kBAAkB,YAA+C;CAC5E,OAAOA,4BAAAA,eAAe,IAAI,OAAO,CAAC,EAAE;AACtC"}
@@ -25,7 +25,8 @@ var CheckBalanceTask = class extends require_core_BaseStepExecutionTask.BaseStep
25
25
  });
26
26
  const walletAddress = step.action.fromAddress;
27
27
  if (!walletAddress) throw new require_errors_errors.TransactionError(1e3, "The wallet address is undefined.");
28
- await require_core_tasks_helpers_checkBalance.checkBalance(client, walletAddress, step, await this.getCheckBalanceOptions(context));
28
+ const options = await this.getCheckBalanceOptions(context);
29
+ await require_core_tasks_helpers_checkBalance.checkBalance(client, walletAddress, step, options);
29
30
  return { status: "COMPLETED" };
30
31
  }
31
32
  };
@@ -1 +1 @@
1
- {"version":3,"file":"CheckBalanceTask.js","names":["BaseStepExecutionTask","TransactionError","checkBalance"],"sources":["../../../../src/core/tasks/CheckBalanceTask.ts"],"sourcesContent":["import { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport {\n type CheckBalanceOptions,\n checkBalance,\n} from './helpers/checkBalance.js'\n\nexport class CheckBalanceTask extends BaseStepExecutionTask {\n /**\n * Per-step options hook for chain-specific subclasses (e.g. skip the\n * gas check for smart-contract wallets or relayed steps). Default `{}`\n * keeps behavior unchanged for every provider that doesn't override.\n * Resolved lazily inside `run()` — pipelines that resume past\n * `CheckBalance` pay no cost.\n */\n protected getCheckBalanceOptions(\n _context: StepExecutorContext\n ): Promise<CheckBalanceOptions> {\n return Promise.resolve({})\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const { client, step, statusManager, isBridgeExecution } = context\n\n statusManager.initializeAction({\n step,\n type: isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP',\n chainId: step.action.fromChainId,\n status: 'STARTED',\n })\n\n const walletAddress = step.action.fromAddress\n if (!walletAddress) {\n throw new TransactionError(\n LiFiErrorCode.InternalError,\n 'The wallet address is undefined.'\n )\n }\n\n const options = await this.getCheckBalanceOptions(context)\n await checkBalance(client, walletAddress, step, options)\n return { status: 'COMPLETED' }\n }\n}\n"],"mappings":";;;;;;AASA,IAAa,mBAAb,cAAsCA,mCAAAA,sBAAsB;;;;;;;;CAQ1D,uBACE,UAC8B;EAC9B,OAAO,QAAQ,QAAQ,CAAC,CAAC;CAC3B;CAEA,MAAM,IAAI,SAAmD;EAC3D,MAAM,EAAE,QAAQ,MAAM,eAAe,sBAAsB;EAE3D,cAAc,iBAAiB;GAC7B;GACA,MAAM,oBAAoB,gBAAgB;GAC1C,SAAS,KAAK,OAAO;GACrB,QAAQ;EACV,CAAC;EAED,MAAM,gBAAgB,KAAK,OAAO;EAClC,IAAI,CAAC,eACH,MAAM,IAAIC,sBAAAA,iBAAAA,KAER,kCACF;EAIF,MAAMC,wCAAAA,aAAa,QAAQ,eAAe,MAAM,MAD1B,KAAK,uBAAuB,OAAO,CACF;EACvD,OAAO,EAAE,QAAQ,YAAY;CAC/B;AACF"}
1
+ {"version":3,"file":"CheckBalanceTask.js","names":["BaseStepExecutionTask","TransactionError","checkBalance"],"sources":["../../../../src/core/tasks/CheckBalanceTask.ts"],"sourcesContent":["import { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport {\n type CheckBalanceOptions,\n checkBalance,\n} from './helpers/checkBalance.js'\n\nexport class CheckBalanceTask extends BaseStepExecutionTask {\n /**\n * Per-step options hook for chain-specific subclasses (e.g. skip the\n * gas check for smart-contract wallets or relayed steps). Default `{}`\n * keeps behavior unchanged for every provider that doesn't override.\n * Resolved lazily inside `run()` — pipelines that resume past\n * `CheckBalance` pay no cost.\n */\n protected getCheckBalanceOptions(\n _context: StepExecutorContext\n ): Promise<CheckBalanceOptions> {\n return Promise.resolve({})\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const { client, step, statusManager, isBridgeExecution } = context\n\n statusManager.initializeAction({\n step,\n type: isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP',\n chainId: step.action.fromChainId,\n status: 'STARTED',\n })\n\n const walletAddress = step.action.fromAddress\n if (!walletAddress) {\n throw new TransactionError(\n LiFiErrorCode.InternalError,\n 'The wallet address is undefined.'\n )\n }\n\n const options = await this.getCheckBalanceOptions(context)\n await checkBalance(client, walletAddress, step, options)\n return { status: 'COMPLETED' }\n }\n}\n"],"mappings":";;;;;;AASA,IAAa,mBAAb,cAAsCA,mCAAAA,sBAAsB;;;;;;;;CAQ1D,uBACE,UAC8B;EAC9B,OAAO,QAAQ,QAAQ,CAAC,CAAC;CAC3B;CAEA,MAAM,IAAI,SAAmD;EAC3D,MAAM,EAAE,QAAQ,MAAM,eAAe,sBAAsB;EAE3D,cAAc,iBAAiB;GAC7B;GACA,MAAM,oBAAoB,gBAAgB;GAC1C,SAAS,KAAK,OAAO;GACrB,QAAQ;EACV,CAAC;EAED,MAAM,gBAAgB,KAAK,OAAO;EAClC,IAAI,CAAC,eACH,MAAM,IAAIC,sBAAAA,iBAAAA,KAER,kCACF;EAGF,MAAM,UAAU,MAAM,KAAK,uBAAuB,OAAO;EACzD,MAAMC,wCAAAA,aAAa,QAAQ,eAAe,MAAM,OAAO;EACvD,OAAO,EAAE,QAAQ,YAAY;CAC/B;AACF"}
@@ -2,6 +2,13 @@ import { StepExecutorContext, TaskResult } from "../../types/execution.js";
2
2
  import { BaseStepExecutionTask } from "../BaseStepExecutionTask.js";
3
3
  //#region src/core/tasks/PrepareTransactionTask.d.ts
4
4
  declare class PrepareTransactionTask extends BaseStepExecutionTask {
5
+ /**
6
+ * Whether `run()` has to fetch a fresh transaction request. The default asks
7
+ * only when the step carries none, which keeps every existing provider
8
+ * unchanged. Chains whose payload cannot be reused override it — see
9
+ * `StellarPrepareTransactionTask`.
10
+ */
11
+ protected shouldRefetchTransaction(context: StepExecutorContext): boolean;
5
12
  run(context: StepExecutorContext): Promise<TaskResult>;
6
13
  }
7
14
  //#endregion
@@ -6,13 +6,23 @@ const require_core_BaseStepExecutionTask = require("../BaseStepExecutionTask.js"
6
6
  const require_core_tasks_helpers_stepComparison = require("./helpers/stepComparison.js");
7
7
  //#region src/core/tasks/PrepareTransactionTask.ts
8
8
  var PrepareTransactionTask = class extends require_core_BaseStepExecutionTask.BaseStepExecutionTask {
9
+ /**
10
+ * Whether `run()` has to fetch a fresh transaction request. The default asks
11
+ * only when the step carries none, which keeps every existing provider
12
+ * unchanged. Chains whose payload cannot be reused override it — see
13
+ * `StellarPrepareTransactionTask`.
14
+ */
15
+ shouldRefetchTransaction(context) {
16
+ return !context.step.transactionRequest;
17
+ }
9
18
  async run(context) {
10
19
  const { client, step, statusManager, allowUserInteraction, executionOptions, isBridgeExecution } = context;
11
20
  const action = statusManager.findAction(step, isBridgeExecution ? "CROSS_CHAIN" : "SWAP");
12
21
  if (!action) throw new require_errors_errors.TransactionError(1008, "Unable to prepare transaction. Action not found.");
13
- if (!step.transactionRequest) {
22
+ if (this.shouldRefetchTransaction(context)) {
14
23
  const { execution, ...stepBase } = step;
15
- const comparedStep = await require_core_tasks_helpers_stepComparison.stepComparison(statusManager, step, await require_actions_getStepTransaction.getStepTransaction(client, stepBase), allowUserInteraction, executionOptions);
24
+ const updatedStep = await require_actions_getStepTransaction.getStepTransaction(client, stepBase);
25
+ const comparedStep = await require_core_tasks_helpers_stepComparison.stepComparison(statusManager, step, updatedStep, allowUserInteraction, executionOptions);
16
26
  Object.assign(step, {
17
27
  ...comparedStep,
18
28
  execution: step.execution
@@ -1 +1 @@
1
- {"version":3,"file":"PrepareTransactionTask.js","names":["BaseStepExecutionTask","TransactionError","stepComparison","getStepTransaction"],"sources":["../../../../src/core/tasks/PrepareTransactionTask.ts"],"sourcesContent":["import { getStepTransaction } from '../../actions/getStepTransaction.js'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport { stepComparison } from './helpers/stepComparison.js'\n\nexport class PrepareTransactionTask extends BaseStepExecutionTask {\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const {\n client,\n step,\n statusManager,\n allowUserInteraction,\n executionOptions,\n isBridgeExecution,\n } = context\n\n const action = statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n\n if (!action) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Action not found.'\n )\n }\n\n if (!step.transactionRequest) {\n const { execution, ...stepBase } = step\n const updatedStep = await getStepTransaction(client, stepBase)\n const comparedStep = await stepComparison(\n statusManager,\n step,\n updatedStep,\n allowUserInteraction,\n executionOptions\n )\n Object.assign(step, {\n ...comparedStep,\n execution: step.execution,\n })\n }\n\n if (!step.transactionRequest?.data) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Transaction request data is not found.'\n )\n }\n\n statusManager.updateAction(step, action.type, 'ACTION_REQUIRED')\n\n if (!allowUserInteraction) {\n return { status: 'PAUSED' }\n }\n\n return { status: 'COMPLETED' }\n }\n}\n"],"mappings":";;;;;;;AAOA,IAAa,yBAAb,cAA4CA,mCAAAA,sBAAsB;CAChE,MAAM,IAAI,SAAmD;EAC3D,MAAM,EACJ,QACA,MACA,eACA,sBACA,kBACA,sBACE;EAEJ,MAAM,SAAS,cAAc,WAC3B,MACA,oBAAoB,gBAAgB,MACtC;EAEA,IAAI,CAAC,QACH,MAAM,IAAIC,sBAAAA,iBAAAA,MAER,kDACF;EAGF,IAAI,CAAC,KAAK,oBAAoB;GAC5B,MAAM,EAAE,WAAW,GAAG,aAAa;GAEnC,MAAM,eAAe,MAAMC,0CAAAA,eACzB,eACA,MACA,MAJwBC,mCAAAA,mBAAmB,QAAQ,QAAQ,GAK3D,sBACA,gBACF;GACA,OAAO,OAAO,MAAM;IAClB,GAAG;IACH,WAAW,KAAK;GAClB,CAAC;EACH;EAEA,IAAI,CAAC,KAAK,oBAAoB,MAC5B,MAAM,IAAIF,sBAAAA,iBAAAA,MAER,uEACF;EAGF,cAAc,aAAa,MAAM,OAAO,MAAM,iBAAiB;EAE/D,IAAI,CAAC,sBACH,OAAO,EAAE,QAAQ,SAAS;EAG5B,OAAO,EAAE,QAAQ,YAAY;CAC/B;AACF"}
1
+ {"version":3,"file":"PrepareTransactionTask.js","names":["BaseStepExecutionTask","TransactionError","getStepTransaction","stepComparison"],"sources":["../../../../src/core/tasks/PrepareTransactionTask.ts"],"sourcesContent":["import { getStepTransaction } from '../../actions/getStepTransaction.js'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport { stepComparison } from './helpers/stepComparison.js'\n\nexport class PrepareTransactionTask extends BaseStepExecutionTask {\n /**\n * Whether `run()` has to fetch a fresh transaction request. The default asks\n * only when the step carries none, which keeps every existing provider\n * unchanged. Chains whose payload cannot be reused override it — see\n * `StellarPrepareTransactionTask`.\n */\n protected shouldRefetchTransaction(context: StepExecutorContext): boolean {\n return !context.step.transactionRequest\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const {\n client,\n step,\n statusManager,\n allowUserInteraction,\n executionOptions,\n isBridgeExecution,\n } = context\n\n const action = statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n\n if (!action) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Action not found.'\n )\n }\n\n if (this.shouldRefetchTransaction(context)) {\n const { execution, ...stepBase } = step\n const updatedStep = await getStepTransaction(client, stepBase)\n const comparedStep = await stepComparison(\n statusManager,\n step,\n updatedStep,\n allowUserInteraction,\n executionOptions\n )\n Object.assign(step, {\n ...comparedStep,\n execution: step.execution,\n })\n }\n\n if (!step.transactionRequest?.data) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Transaction request data is not found.'\n )\n }\n\n statusManager.updateAction(step, action.type, 'ACTION_REQUIRED')\n\n if (!allowUserInteraction) {\n return { status: 'PAUSED' }\n }\n\n return { status: 'COMPLETED' }\n }\n}\n"],"mappings":";;;;;;;AAOA,IAAa,yBAAb,cAA4CA,mCAAAA,sBAAsB;;;;;;;CAOhE,yBAAmC,SAAuC;EACxE,OAAO,CAAC,QAAQ,KAAK;CACvB;CAEA,MAAM,IAAI,SAAmD;EAC3D,MAAM,EACJ,QACA,MACA,eACA,sBACA,kBACA,sBACE;EAEJ,MAAM,SAAS,cAAc,WAC3B,MACA,oBAAoB,gBAAgB,MACtC;EAEA,IAAI,CAAC,QACH,MAAM,IAAIC,sBAAAA,iBAAAA,MAER,kDACF;EAGF,IAAI,KAAK,yBAAyB,OAAO,GAAG;GAC1C,MAAM,EAAE,WAAW,GAAG,aAAa;GACnC,MAAM,cAAc,MAAMC,mCAAAA,mBAAmB,QAAQ,QAAQ;GAC7D,MAAM,eAAe,MAAMC,0CAAAA,eACzB,eACA,MACA,aACA,sBACA,gBACF;GACA,OAAO,OAAO,MAAM;IAClB,GAAG;IACH,WAAW,KAAK;GAClB,CAAC;EACH;EAEA,IAAI,CAAC,KAAK,oBAAoB,MAC5B,MAAM,IAAIF,sBAAAA,iBAAAA,MAER,uEACF;EAGF,cAAc,aAAa,MAAM,OAAO,MAAM,iBAAiB;EAE/D,IAAI,CAAC,sBACH,OAAO,EAAE,QAAQ,SAAS;EAG5B,OAAO,EAAE,QAAQ,YAAY;CAC/B;AACF"}
@@ -54,7 +54,7 @@ const checkBalance = async (client, walletAddress, step, options = {}) => {
54
54
  const slippageScaled = BigInt(Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION)));
55
55
  await require_utils_withTimeout.withTimeout(async () => {
56
56
  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
57
- const isFinal = attempt === MAX_ATTEMPTS - 1;
57
+ const isFinal = attempt === 5;
58
58
  let balances;
59
59
  try {
60
60
  balances = await provider.getBalance(client, walletAddress, tokens);
@@ -1 +1 @@
1
- {"version":3,"file":"checkBalance.js","names":["withTimeout","BalanceError","sleep","formatUnits"],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"sourcesContent":["import type { LiFiStep, Token, TokenAmount } from '@lifi/types'\nimport { BalanceError } from '../../../errors/errors.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { formatUnits } from '../../../utils/formatUnits.js'\nimport { sleep } from '../../../utils/sleep.js'\nimport { withTimeout } from '../../../utils/withTimeout.js'\n\nconst MAX_ATTEMPTS = 6\n// Exponential backoff: 150, 300, 600, 1200, 2400 → ≈4.65s of sleep total.\nconst BACKOFF_BASE_MS = 150\nconst OVERALL_TIMEOUT_MS = 10_000\nconst SLIPPAGE_PRECISION = 1_000_000_000n\n\ntype Bucket = 'source' | 'gas' | 'fee'\n\ntype Requirement = {\n token: Token\n sourcePart: bigint // step.action.fromAmount\n gasPart: bigint // step.estimate.gasCosts in this token\n feePart: bigint // non-included step.estimate.feeCosts in this token\n}\n\nexport type CheckBalanceOptions = {\n /**\n * Set to `false` when outer-tx gas is paid by something other than\n * `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):\n * `gasPart` is excluded from the sufficiency check and slippage rescue.\n * Source amount and non-included fees (e.g. LZ `msg.value`) are still\n * verified. Defaults to `true` (strict, today's behavior).\n */\n walletPaysGas?: boolean\n}\n\n/**\n * Verifies that the wallet holds enough of every token required to execute\n * the step on its source chain — the source-token amount, any gas costs, and\n * any non-included fee costs. Reads all balances in one batched provider\n * call, retries within a bounded budget to absorb transient RPC failures and\n * post-confirmation propagation lag, and applies slippage to the source-token\n * portion only as a last resort (overhead is never trimmed).\n *\n * Throws BalanceError(\"The balance is too low.\") on a genuine shortfall, or\n * BalanceError(\"Could not read wallet balance.\") if the balance can't be read\n * after retries.\n */\nexport const checkBalance = async (\n client: SDKClient,\n walletAddress: string,\n step: LiFiStep,\n options: CheckBalanceOptions = {}\n): Promise<void> => {\n const fromChainId = step.action.fromChainId\n // Chains with non-standard native decimals (e.g. Tempo, Stable) report\n // gas costs in units that don't align with wallet balances — drop the\n // gas portion of the check on those chains.\n const fromChain = await client.getChainById(fromChainId)\n const walletPaysGas =\n (options.walletPaysGas ?? true) && !fromChain.nonStandardNativeDecimals\n const requirements = new Map<string, Requirement>()\n const add = (token: Token, amount: bigint, bucket: Bucket): void => {\n if (token.chainId !== fromChainId || amount === 0n) {\n return\n }\n const key = token.address.toLowerCase()\n const req = requirements.get(key) ?? {\n token,\n sourcePart: 0n,\n gasPart: 0n,\n feePart: 0n,\n }\n if (bucket === 'source') {\n req.sourcePart += amount\n } else if (bucket === 'gas') {\n req.gasPart += amount\n } else {\n req.feePart += amount\n }\n requirements.set(key, req)\n }\n add(step.action.fromToken, BigInt(step.action.fromAmount), 'source')\n for (const gas of step.estimate?.gasCosts ?? []) {\n add(gas.token, BigInt(gas.amount), 'gas')\n }\n for (const fee of step.estimate?.feeCosts ?? []) {\n // Included fees are already part of fromAmount — don't count twice.\n if (!fee.included) {\n add(fee.token, BigInt(fee.amount), 'fee')\n }\n }\n\n const reservedOverhead = (r: Requirement): bigint =>\n r.feePart + (walletPaysGas ? r.gasPart : 0n)\n const need = (r: Requirement): bigint => r.sourcePart + reservedOverhead(r)\n\n // Drop pure-gas entries when `walletPaysGas` is false (e.g. native ETH\n // on Safe Apps with only `gasPart`) — saves one balance read each.\n for (const [key, req] of requirements) {\n if (need(req) === 0n) {\n requirements.delete(key)\n }\n }\n\n if (requirements.size === 0) {\n return\n }\n\n // Provider is dispatched by wallet address; all requirements share the\n // source chain, which matches this provider by virtue of the address.\n const provider = client.providers.find((p) => p.isAddress(walletAddress))\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const reqs = Array.from(requirements.values())\n const tokens = reqs.map((r) => r.token)\n const slippage = step.action.slippage ?? 0\n const slippageScaled = BigInt(\n Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))\n )\n\n await withTimeout(\n async () => {\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n const isFinal = attempt === MAX_ATTEMPTS - 1\n\n let balances: TokenAmount[]\n try {\n balances = await provider.getBalance(client, walletAddress, tokens)\n } catch (error) {\n if (isFinal) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n error as Error\n )\n }\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n continue\n }\n\n const balanceByAddress = new Map(\n balances.map((b) => [b.address.toLowerCase(), b.amount] as const)\n )\n\n const unknown: Token[] = []\n const insufficient: { req: Requirement; have: bigint }[] = []\n for (const req of reqs) {\n const have = balanceByAddress.get(req.token.address.toLowerCase())\n if (have === undefined) {\n unknown.push(req.token)\n } else if (have < need(req)) {\n insufficient.push({ req, have })\n }\n }\n\n if (unknown.length === 0 && insufficient.length === 0) {\n return\n }\n\n // Final-attempt slippage rescue: only when the sole shortfall is\n // the source-token portion. Trim source to (balance − reserved\n // overhead) so the overhead reserve is preserved.\n if (\n isFinal &&\n unknown.length === 0 &&\n insufficient.length === 1 &&\n insufficient[0].req.sourcePart > 0n\n ) {\n const { req, have } = insufficient[0]\n const reserved = reservedOverhead(req)\n const minAcceptable =\n (req.sourcePart * slippageScaled) / SLIPPAGE_PRECISION + reserved\n if (have >= minAcceptable) {\n const newFromAmount = (have - reserved).toString()\n step.action.fromAmount = newFromAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount = newFromAmount\n }\n return\n }\n }\n\n if (isFinal) {\n if (unknown.length > 0) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n new Error(\n `Could not read balance for: ${unknown\n .map((t) => t.symbol || t.address)\n .join(', ')}.`\n )\n )\n }\n const lines = insufficient.map(({ req, have }) => {\n const needed = formatUnits(need(req), req.token.decimals)\n const current = formatUnits(have, req.token.decimals)\n const symbol = req.token.symbol\n // The \"fees\" branch covers pure-overhead tokens; with\n // walletPaysGas=false, gas is excluded from `need(req)` so it\n // only fires for genuine fee shortfalls.\n return req.sourcePart > 0n\n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.`\n : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`\n })\n throw new BalanceError(\n 'The balance is too low.',\n new Error(`${lines.join(' ')} No funds have been sent.`)\n )\n }\n\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n }\n },\n {\n timeout: OVERALL_TIMEOUT_MS,\n errorInstance: new BalanceError('Could not read wallet balance.'),\n }\n )\n}\n"],"mappings":";;;;;;AAOA,MAAM,eAAe;AAErB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;;;;;;;;;;;;;AAkC3B,MAAa,eAAe,OAC1B,QACA,eACA,MACA,UAA+B,CAAC,MACd;CAClB,MAAM,cAAc,KAAK,OAAO;CAIhC,MAAM,YAAY,MAAM,OAAO,aAAa,WAAW;CACvD,MAAM,iBACH,QAAQ,iBAAiB,SAAS,CAAC,UAAU;CAChD,MAAM,+BAAe,IAAI,IAAyB;CAClD,MAAM,OAAO,OAAc,QAAgB,WAAyB;EAClE,IAAI,MAAM,YAAY,eAAe,WAAW,IAC9C;EAEF,MAAM,MAAM,MAAM,QAAQ,YAAY;EACtC,MAAM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,GAAG,IAAI,MAAM,QAAQ;KACxD,MAAM,UAAUA,0BAAAA,YAAY,MAAM,IAAI,MAAM,QAAQ;KACpD,MAAM,SAAS,IAAI,MAAM;KAIzB,OAAO,IAAI,aAAa,KACpB,QAAQ,OAAO,2CAA2C,OAAO,GAAG,OAAO,+BAA+B,QAAQ,GAAG,OAAO,KAC5H,gBAAgB,OAAO,kBAAkB,OAAO,GAAG,OAAO,SAAS,QAAQ,GAAG,OAAO;IAC3F,CAAC;IACD,MAAM,IAAIF,sBAAAA,aACR,2CACA,IAAI,MAAM,GAAG,MAAM,KAAK,GAAG,EAAE,0BAA0B,CACzD;GACF;GAEA,MAAMC,oBAAAA,MAAM,kBAAkB,KAAK,OAAO;EAC5C;CACF,GACA;EACE,SAAS;EACT,eAAe,IAAID,sBAAAA,aAAa,gCAAgC;CAClE,CACF;AACF"}
1
+ {"version":3,"file":"checkBalance.js","names":["withTimeout","BalanceError","sleep","formatUnits"],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"sourcesContent":["import type { LiFiStep, Token, TokenAmount } from '@lifi/types'\nimport { BalanceError } from '../../../errors/errors.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { formatUnits } from '../../../utils/formatUnits.js'\nimport { sleep } from '../../../utils/sleep.js'\nimport { withTimeout } from '../../../utils/withTimeout.js'\n\nconst MAX_ATTEMPTS = 6\n// Exponential backoff: 150, 300, 600, 1200, 2400 → ≈4.65s of sleep total.\nconst BACKOFF_BASE_MS = 150\nconst OVERALL_TIMEOUT_MS = 10_000\nconst SLIPPAGE_PRECISION = 1_000_000_000n\n\ntype Bucket = 'source' | 'gas' | 'fee'\n\ntype Requirement = {\n token: Token\n sourcePart: bigint // step.action.fromAmount\n gasPart: bigint // step.estimate.gasCosts in this token\n feePart: bigint // non-included step.estimate.feeCosts in this token\n}\n\nexport type CheckBalanceOptions = {\n /**\n * Set to `false` when outer-tx gas is paid by something other than\n * `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):\n * `gasPart` is excluded from the sufficiency check and slippage rescue.\n * Source amount and non-included fees (e.g. LZ `msg.value`) are still\n * verified. Defaults to `true` (strict, today's behavior).\n */\n walletPaysGas?: boolean\n}\n\n/**\n * Verifies that the wallet holds enough of every token required to execute\n * the step on its source chain — the source-token amount, any gas costs, and\n * any non-included fee costs. Reads all balances in one batched provider\n * call, retries within a bounded budget to absorb transient RPC failures and\n * post-confirmation propagation lag, and applies slippage to the source-token\n * portion only as a last resort (overhead is never trimmed).\n *\n * Throws BalanceError(\"The balance is too low.\") on a genuine shortfall, or\n * BalanceError(\"Could not read wallet balance.\") if the balance can't be read\n * after retries.\n */\nexport const checkBalance = async (\n client: SDKClient,\n walletAddress: string,\n step: LiFiStep,\n options: CheckBalanceOptions = {}\n): Promise<void> => {\n const fromChainId = step.action.fromChainId\n // Chains with non-standard native decimals (e.g. Tempo, Stable) report\n // gas costs in units that don't align with wallet balances — drop the\n // gas portion of the check on those chains.\n const fromChain = await client.getChainById(fromChainId)\n const walletPaysGas =\n (options.walletPaysGas ?? true) && !fromChain.nonStandardNativeDecimals\n const requirements = new Map<string, Requirement>()\n const add = (token: Token, amount: bigint, bucket: Bucket): void => {\n if (token.chainId !== fromChainId || amount === 0n) {\n return\n }\n const key = token.address.toLowerCase()\n const req = requirements.get(key) ?? {\n token,\n sourcePart: 0n,\n gasPart: 0n,\n feePart: 0n,\n }\n if (bucket === 'source') {\n req.sourcePart += amount\n } else if (bucket === 'gas') {\n req.gasPart += amount\n } else {\n req.feePart += amount\n }\n requirements.set(key, req)\n }\n add(step.action.fromToken, BigInt(step.action.fromAmount), 'source')\n for (const gas of step.estimate?.gasCosts ?? []) {\n add(gas.token, BigInt(gas.amount), 'gas')\n }\n for (const fee of step.estimate?.feeCosts ?? []) {\n // Included fees are already part of fromAmount — don't count twice.\n if (!fee.included) {\n add(fee.token, BigInt(fee.amount), 'fee')\n }\n }\n\n const reservedOverhead = (r: Requirement): bigint =>\n r.feePart + (walletPaysGas ? r.gasPart : 0n)\n const need = (r: Requirement): bigint => r.sourcePart + reservedOverhead(r)\n\n // Drop pure-gas entries when `walletPaysGas` is false (e.g. native ETH\n // on Safe Apps with only `gasPart`) — saves one balance read each.\n for (const [key, req] of requirements) {\n if (need(req) === 0n) {\n requirements.delete(key)\n }\n }\n\n if (requirements.size === 0) {\n return\n }\n\n // Provider is dispatched by wallet address; all requirements share the\n // source chain, which matches this provider by virtue of the address.\n const provider = client.providers.find((p) => p.isAddress(walletAddress))\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const reqs = Array.from(requirements.values())\n const tokens = reqs.map((r) => r.token)\n const slippage = step.action.slippage ?? 0\n const slippageScaled = BigInt(\n Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))\n )\n\n await withTimeout(\n async () => {\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n const isFinal = attempt === MAX_ATTEMPTS - 1\n\n let balances: TokenAmount[]\n try {\n balances = await provider.getBalance(client, walletAddress, tokens)\n } catch (error) {\n if (isFinal) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n error as Error\n )\n }\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n continue\n }\n\n const balanceByAddress = new Map(\n balances.map((b) => [b.address.toLowerCase(), b.amount] as const)\n )\n\n const unknown: Token[] = []\n const insufficient: { req: Requirement; have: bigint }[] = []\n for (const req of reqs) {\n const have = balanceByAddress.get(req.token.address.toLowerCase())\n if (have === undefined) {\n unknown.push(req.token)\n } else if (have < need(req)) {\n insufficient.push({ req, have })\n }\n }\n\n if (unknown.length === 0 && insufficient.length === 0) {\n return\n }\n\n // Final-attempt slippage rescue: only when the sole shortfall is\n // the source-token portion. Trim source to (balance − reserved\n // overhead) so the overhead reserve is preserved.\n if (\n isFinal &&\n unknown.length === 0 &&\n insufficient.length === 1 &&\n insufficient[0].req.sourcePart > 0n\n ) {\n const { req, have } = insufficient[0]\n const reserved = reservedOverhead(req)\n const minAcceptable =\n (req.sourcePart * slippageScaled) / SLIPPAGE_PRECISION + reserved\n if (have >= minAcceptable) {\n const newFromAmount = (have - reserved).toString()\n step.action.fromAmount = newFromAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount = newFromAmount\n }\n return\n }\n }\n\n if (isFinal) {\n if (unknown.length > 0) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n new Error(\n `Could not read balance for: ${unknown\n .map((t) => t.symbol || t.address)\n .join(', ')}.`\n )\n )\n }\n const lines = insufficient.map(({ req, have }) => {\n const needed = formatUnits(need(req), req.token.decimals)\n const current = formatUnits(have, req.token.decimals)\n const symbol = req.token.symbol\n // The \"fees\" branch covers pure-overhead tokens; with\n // walletPaysGas=false, gas is excluded from `need(req)` so it\n // only fires for genuine fee shortfalls.\n return req.sourcePart > 0n\n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.`\n : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`\n })\n throw new BalanceError(\n 'The balance is too low.',\n new Error(`${lines.join(' ')} No funds have been sent.`)\n )\n }\n\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n }\n },\n {\n timeout: OVERALL_TIMEOUT_MS,\n errorInstance: new BalanceError('Could not read wallet balance.'),\n }\n )\n}\n"],"mappings":";;;;;;AAOA,MAAM,eAAe;AAErB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;;;;;;;;;;;;;AAkC3B,MAAa,eAAe,OAC1B,QACA,eACA,MACA,UAA+B,CAAC,MACd;CAClB,MAAM,cAAc,KAAK,OAAO;CAIhC,MAAM,YAAY,MAAM,OAAO,aAAa,WAAW;CACvD,MAAM,iBACH,QAAQ,iBAAiB,SAAS,CAAC,UAAU;CAChD,MAAM,+BAAe,IAAI,IAAyB;CAClD,MAAM,OAAO,OAAc,QAAgB,WAAyB;EAClE,IAAI,MAAM,YAAY,eAAe,WAAW,IAC9C;E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