@lifi/sdk 4.0.0 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/cjs/actions/getChains.js.map +1 -1
- package/dist/cjs/actions/getContractCallsQuote.js.map +1 -1
- package/dist/cjs/actions/getRelayedTransactionStatus.js.map +1 -1
- package/dist/cjs/actions/getTokenBalances.js.map +1 -1
- package/dist/cjs/actions/getTokenBalancesByChain.js.map +1 -1
- package/dist/cjs/actions/getTokens.js.map +1 -1
- package/dist/cjs/actions/getWalletBalances.js.map +1 -1
- package/dist/cjs/client/createClient.js.map +1 -1
- package/dist/cjs/core/BaseStepExecutor.js.map +1 -1
- package/dist/cjs/core/actionMessages.js.map +1 -1
- package/dist/cjs/core/execution.js.map +1 -1
- package/dist/cjs/core/executionState.js.map +1 -1
- package/dist/cjs/core/prepareRestart.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
- package/dist/cjs/core/utils.js.map +1 -1
- package/dist/cjs/utils/checkPackageUpdates.js +1 -1
- package/dist/cjs/utils/checkPackageUpdates.js.map +1 -1
- package/dist/cjs/utils/convertQuoteToRoute.js.map +1 -1
- package/dist/cjs/utils/decode.js.map +1 -1
- package/dist/cjs/utils/fetchTxErrorDetails.js.map +1 -1
- package/dist/cjs/utils/getTransactionMessage.js.map +1 -1
- package/dist/cjs/utils/isStep.js.map +1 -1
- package/dist/cjs/utils/withDedupe.js.map +1 -1
- package/dist/cjs/utils/withTimeout.js.map +1 -1
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/version.js.map +1 -1
- package/dist/esm/actions/getChains.js.map +1 -1
- package/dist/esm/actions/getRelayedTransactionStatus.js.map +1 -1
- package/dist/esm/actions/getTokenBalances.js.map +1 -1
- package/dist/esm/actions/getTokenBalancesByChain.js.map +1 -1
- package/dist/esm/actions/getTokens.js.map +1 -1
- package/dist/esm/actions/getWalletBalances.js.map +1 -1
- package/dist/esm/client/createClient.js.map +1 -1
- package/dist/esm/core/BaseStepExecutor.js.map +1 -1
- package/dist/esm/core/actionMessages.js.map +1 -1
- package/dist/esm/core/execution.js.map +1 -1
- package/dist/esm/core/executionState.js.map +1 -1
- package/dist/esm/core/prepareRestart.js.map +1 -1
- package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
- package/dist/esm/core/utils.js.map +1 -1
- package/dist/esm/utils/checkPackageUpdates.js +1 -1
- package/dist/esm/utils/checkPackageUpdates.js.map +1 -1
- package/dist/esm/utils/convertQuoteToRoute.js.map +1 -1
- package/dist/esm/utils/decode.js.map +1 -1
- package/dist/esm/utils/fetchTxErrorDetails.js.map +1 -1
- package/dist/esm/utils/getTransactionMessage.js.map +1 -1
- package/dist/esm/utils/isStep.js.map +1 -1
- package/dist/esm/utils/withDedupe.js.map +1 -1
- package/dist/esm/utils/withTimeout.js.map +1 -1
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.map +1 -1
- package/package.json +2 -2
- package/src/version.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @lifi/sdk
|
|
2
2
|
|
|
3
|
+
## 4.0.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#402](https://github.com/lifinance/sdk/pull/402) [`bf3d047`](https://github.com/lifinance/sdk/commit/bf3d047ebdc9a8b3a5a6362f65d25aa1eb652ffa) Thanks [@chybisov](https://github.com/chybisov)! - Bump runtime dependencies: @lifi/types to 17.85.0, viem to 2.52.2, @solana/kit to 6.10.0 (with @solana/wallet-standard-features and @wallet-standard/base), @mysten/sui to 2.19.0, and @tronweb3/tronwallet-abstract-adapter to 1.2.0.
|
|
8
|
+
|
|
3
9
|
## 4.0.0
|
|
4
10
|
|
|
5
11
|
> **Pre-Changesets history (aggregated, repo-wide).** The entries below are
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getChains.js","names":["withDedupe","request"],"sources":["../../../src/actions/getChains.ts"],"sourcesContent":["import type {\n ChainsRequest,\n ChainsResponse,\n ExtendedChain,\n RequestOptions,\n} from '@lifi/types'\nimport type { SDKBaseConfig, SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\nimport { withDedupe } from '../utils/withDedupe.js'\n\n/**\n * Get all available chains\n * @param client - The SDK client\n * @param params - The configuration of the requested chains\n * @param options - Request options\n * @returns A list of all available chains\n * @throws {LiFiError} Throws a LiFiError if request fails.\n */\nexport const getChains = async (\n client: SDKClient,\n params?: ChainsRequest,\n options?: RequestOptions\n): Promise<ExtendedChain[]> => {\n return await _getChains(client.config, params, options)\n}\n\nexport const _getChains = async (\n config: SDKBaseConfig,\n params?: ChainsRequest,\n options?: RequestOptions\n): Promise<ExtendedChain[]> => {\n if (params) {\n for (const key of Object.keys(params)) {\n const value = params[key as keyof ChainsRequest]\n if (value === undefined || value === null) {\n delete params[key as keyof ChainsRequest]\n }\n }\n }\n const urlSearchParams = new URLSearchParams(\n params as Record<string, string>\n ).toString()\n const response = await withDedupe(\n () =>\n request<ChainsResponse>(\n config,\n `${config.apiUrl}/chains?${urlSearchParams}`,\n {\n signal: options?.signal,\n }\n ),\n { id: `${getChains.name}.${urlSearchParams}` }\n )\n return response.chains\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAa,YAAY,OACvB,QACA,QACA,YAC6B;CAC7B,OAAO,MAAM,WAAW,OAAO,QAAQ,QAAQ,OAAO;AACxD;AAEA,MAAa,aAAa,OACxB,QACA,QACA,YAC6B;CAC7B,IAAI,QACF,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;EACrC,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO,OAAO;CAElB;CAEF,MAAM,kBAAkB,IAAI,gBAC1B,MACF,
|
|
1
|
+
{"version":3,"file":"getChains.js","names":["withDedupe","request"],"sources":["../../../src/actions/getChains.ts"],"sourcesContent":["import type {\n ChainsRequest,\n ChainsResponse,\n ExtendedChain,\n RequestOptions,\n} from '@lifi/types'\nimport type { SDKBaseConfig, SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\nimport { withDedupe } from '../utils/withDedupe.js'\n\n/**\n * Get all available chains\n * @param client - The SDK client\n * @param params - The configuration of the requested chains\n * @param options - Request options\n * @returns A list of all available chains\n * @throws {LiFiError} Throws a LiFiError if request fails.\n */\nexport const getChains = async (\n client: SDKClient,\n params?: ChainsRequest,\n options?: RequestOptions\n): Promise<ExtendedChain[]> => {\n return await _getChains(client.config, params, options)\n}\n\nexport const _getChains = async (\n config: SDKBaseConfig,\n params?: ChainsRequest,\n options?: RequestOptions\n): Promise<ExtendedChain[]> => {\n if (params) {\n for (const key of Object.keys(params)) {\n const value = params[key as keyof ChainsRequest]\n if (value === undefined || value === null) {\n delete params[key as keyof ChainsRequest]\n }\n }\n }\n const urlSearchParams = new URLSearchParams(\n params as Record<string, string>\n ).toString()\n const response = await withDedupe(\n () =>\n request<ChainsResponse>(\n config,\n `${config.apiUrl}/chains?${urlSearchParams}`,\n {\n signal: options?.signal,\n }\n ),\n { id: `${getChains.name}.${urlSearchParams}` }\n )\n return response.chains\n}\n"],"mappings":";;;;;;;;;;;;AAkBA,MAAa,YAAY,OACvB,QACA,QACA,YAC6B;CAC7B,OAAO,MAAM,WAAW,OAAO,QAAQ,QAAQ,OAAO;AACxD;AAEA,MAAa,aAAa,OACxB,QACA,QACA,YAC6B;CAC7B,IAAI,QACF,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;EACrC,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO,OAAO;CAElB;CAEF,MAAM,kBAAkB,IAAI,gBAC1B,MACF,CAAC,CAAC,SAAS;CAYX,QAAO,MAXgBA,yBAAAA,iBAEnBC,sBAAAA,QACE,QACA,GAAG,OAAO,OAAO,UAAU,mBAC3B,EACE,QAAQ,SAAS,OACnB,CACF,GACF,EAAE,IAAI,GAAG,UAAU,KAAK,GAAG,kBAAkB,CAC/C,EAAA,CACgB;AAClB"}
|
|
@@ -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,
|
|
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getRelayedTransactionStatus.js","names":["SDKError","ValidationError","decodeTaskId","getStatus","request","BaseError"],"sources":["../../../src/actions/getRelayedTransactionStatus.ts"],"sourcesContent":["import type {\n RelayStatusRequest,\n RelayStatusResponse,\n RelayStatusResponseData,\n RequestOptions,\n} from '@lifi/types'\nimport { BaseError } from '../errors/baseError.js'\nimport { ErrorName } from '../errors/constants.js'\nimport { ValidationError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport type { SDKClient } from '../types/core.js'\nimport { decodeTaskId } from '../utils/decode.js'\nimport { request } from '../utils/request.js'\nimport { getStatus } from './getStatus.js'\n\n/**\n * Get the status of a relayed transaction\n * @param client - The SDK client\n * @param params - Parameters for the relay status request\n * @param options - Request options\n * @throws {LiFiError} - Throws a LiFiError if request fails\n * @returns Status of the relayed transaction\n */\nexport const getRelayedTransactionStatus = async (\n client: SDKClient,\n params: RelayStatusRequest,\n options?: RequestOptions\n): Promise<RelayStatusResponseData> => {\n if (!params.taskId) {\n throw new SDKError(\n new ValidationError('Required parameter \"taskId\" is missing.')\n )\n }\n\n const { taskId, ...otherParams } = params\n const queryParams = new URLSearchParams(\n otherParams as unknown as Record<string, string>\n )\n\n const decodedTaskId = decodeTaskId(taskId)\n // Temporary solution during the transition between status endpoints\n if (decodedTaskId.length >= 3) {\n return (await getStatus(\n client,\n params,\n options\n )) as unknown as RelayStatusResponseData\n }\n\n const result = await request<RelayStatusResponse>(\n client.config,\n `${client.config.apiUrl}/relayer/status/${taskId}?${queryParams}`,\n {\n signal: options?.signal,\n }\n )\n\n if (result.status === 'error') {\n throw new BaseError(\n ErrorName.ServerError,\n result.data.code,\n result.data.message\n )\n }\n\n return result.data\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAuBA,MAAa,8BAA8B,OACzC,QACA,QACA,YACqC;CACrC,IAAI,CAAC,OAAO,QACV,MAAM,IAAIA,wBAAAA,SACR,IAAIC,sBAAAA,gBAAgB,2CAAyC,CAC/D;CAGF,MAAM,EAAE,QAAQ,GAAG,gBAAgB;CACnC,MAAM,cAAc,IAAI,gBACtB,WACF;CAIA,IAFsBC,qBAAAA,aAAa,MAEnB,
|
|
1
|
+
{"version":3,"file":"getRelayedTransactionStatus.js","names":["SDKError","ValidationError","decodeTaskId","getStatus","request","BaseError"],"sources":["../../../src/actions/getRelayedTransactionStatus.ts"],"sourcesContent":["import type {\n RelayStatusRequest,\n RelayStatusResponse,\n RelayStatusResponseData,\n RequestOptions,\n} from '@lifi/types'\nimport { BaseError } from '../errors/baseError.js'\nimport { ErrorName } from '../errors/constants.js'\nimport { ValidationError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport type { SDKClient } from '../types/core.js'\nimport { decodeTaskId } from '../utils/decode.js'\nimport { request } from '../utils/request.js'\nimport { getStatus } from './getStatus.js'\n\n/**\n * Get the status of a relayed transaction\n * @param client - The SDK client\n * @param params - Parameters for the relay status request\n * @param options - Request options\n * @throws {LiFiError} - Throws a LiFiError if request fails\n * @returns Status of the relayed transaction\n */\nexport const getRelayedTransactionStatus = async (\n client: SDKClient,\n params: RelayStatusRequest,\n options?: RequestOptions\n): Promise<RelayStatusResponseData> => {\n if (!params.taskId) {\n throw new SDKError(\n new ValidationError('Required parameter \"taskId\" is missing.')\n )\n }\n\n const { taskId, ...otherParams } = params\n const queryParams = new URLSearchParams(\n otherParams as unknown as Record<string, string>\n )\n\n const decodedTaskId = decodeTaskId(taskId)\n // Temporary solution during the transition between status endpoints\n if (decodedTaskId.length >= 3) {\n return (await getStatus(\n client,\n params,\n options\n )) as unknown as RelayStatusResponseData\n }\n\n const result = await request<RelayStatusResponse>(\n client.config,\n `${client.config.apiUrl}/relayer/status/${taskId}?${queryParams}`,\n {\n signal: options?.signal,\n }\n )\n\n if (result.status === 'error') {\n throw new BaseError(\n ErrorName.ServerError,\n result.data.code,\n result.data.message\n )\n }\n\n return result.data\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAuBA,MAAa,8BAA8B,OACzC,QACA,QACA,YACqC;CACrC,IAAI,CAAC,OAAO,QACV,MAAM,IAAIA,wBAAAA,SACR,IAAIC,sBAAAA,gBAAgB,2CAAyC,CAC/D;CAGF,MAAM,EAAE,QAAQ,GAAG,gBAAgB;CACnC,MAAM,cAAc,IAAI,gBACtB,WACF;CAIA,IAFsBC,qBAAAA,aAAa,MAEnB,CAAC,CAAC,UAAU,GAC1B,OAAQ,MAAMC,0BAAAA,UACZ,QACA,QACA,OACF;CAGF,MAAM,SAAS,MAAMC,sBAAAA,QACnB,OAAO,QACP,GAAG,OAAO,OAAO,OAAO,kBAAkB,OAAO,GAAG,eACpD,EACE,QAAQ,SAAS,OACnB,CACF;CAEA,IAAI,OAAO,WAAW,SACpB,MAAM,IAAIC,yBAAAA,UAAAA,eAER,OAAO,KAAK,MACZ,OAAO,KAAK,OACd;CAGF,OAAO,OAAO;AAChB"}
|
|
@@ -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,
|
|
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 +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,
|
|
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,WAM1B,oBAAoB,WAAW,MALJ,SAAS,WAClC,QACA,eACA,cAAc,QAChB;OAKA,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTokens.js","names":["withDedupe","request"],"sources":["../../../src/actions/getTokens.ts"],"sourcesContent":["import type {\n RequestOptions,\n TokensExtendedResponse,\n TokensRequest,\n TokensResponse,\n} from '@lifi/types'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\nimport { withDedupe } from '../utils/withDedupe.js'\n\n/**\n * Get all known tokens.\n * @param client - The SDK client\n * @param params - The configuration of the requested tokens\n * @param options - Request options\n * @returns The tokens that are available on the requested chains\n */\nexport async function getTokens(\n client: SDKClient,\n params?: TokensRequest & { extended?: false | undefined },\n options?: RequestOptions\n): Promise<TokensResponse>\nexport async function getTokens(\n client: SDKClient,\n params: TokensRequest & { extended: true },\n options?: RequestOptions\n): Promise<TokensExtendedResponse>\nexport async function getTokens(\n client: SDKClient,\n params?: TokensRequest,\n options?: RequestOptions\n): Promise<TokensResponse> {\n if (params) {\n for (const key of Object.keys(params)) {\n const value = params[key as keyof TokensRequest]\n if (value === undefined || value === null) {\n delete params[key as keyof TokensRequest]\n }\n }\n }\n const urlSearchParams = new URLSearchParams(\n params as Record<string, string>\n ).toString()\n const _isExtended = params?.extended === true\n const response = await withDedupe(\n () =>\n request<\n typeof _isExtended extends true\n ? TokensExtendedResponse\n : TokensResponse\n >(client.config, `${client.config.apiUrl}/tokens?${urlSearchParams}`, {\n signal: options?.signal,\n }),\n { id: `${getTokens.name}.${urlSearchParams}` }\n )\n return response\n}\n"],"mappings":";;;;AA2BA,eAAsB,UACpB,QACA,QACA,SACyB;CACzB,IAAI,QACF,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;EACrC,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO,OAAO;CAElB;CAEF,MAAM,kBAAkB,IAAI,gBAC1B,MACF,
|
|
1
|
+
{"version":3,"file":"getTokens.js","names":["withDedupe","request"],"sources":["../../../src/actions/getTokens.ts"],"sourcesContent":["import type {\n RequestOptions,\n TokensExtendedResponse,\n TokensRequest,\n TokensResponse,\n} from '@lifi/types'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\nimport { withDedupe } from '../utils/withDedupe.js'\n\n/**\n * Get all known tokens.\n * @param client - The SDK client\n * @param params - The configuration of the requested tokens\n * @param options - Request options\n * @returns The tokens that are available on the requested chains\n */\nexport async function getTokens(\n client: SDKClient,\n params?: TokensRequest & { extended?: false | undefined },\n options?: RequestOptions\n): Promise<TokensResponse>\nexport async function getTokens(\n client: SDKClient,\n params: TokensRequest & { extended: true },\n options?: RequestOptions\n): Promise<TokensExtendedResponse>\nexport async function getTokens(\n client: SDKClient,\n params?: TokensRequest,\n options?: RequestOptions\n): Promise<TokensResponse> {\n if (params) {\n for (const key of Object.keys(params)) {\n const value = params[key as keyof TokensRequest]\n if (value === undefined || value === null) {\n delete params[key as keyof TokensRequest]\n }\n }\n }\n const urlSearchParams = new URLSearchParams(\n params as Record<string, string>\n ).toString()\n const _isExtended = params?.extended === true\n const response = await withDedupe(\n () =>\n request<\n typeof _isExtended extends true\n ? TokensExtendedResponse\n : TokensResponse\n >(client.config, `${client.config.apiUrl}/tokens?${urlSearchParams}`, {\n signal: options?.signal,\n }),\n { id: `${getTokens.name}.${urlSearchParams}` }\n )\n return response\n}\n"],"mappings":";;;;AA2BA,eAAsB,UACpB,QACA,QACA,SACyB;CACzB,IAAI,QACF,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;EACrC,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO,OAAO;CAElB;CAEF,MAAM,kBAAkB,IAAI,gBAC1B,MACF,CAAC,CAAC,SAAS;CACS,QAAQ;CAY5B,OAAO,MAXgBA,yBAAAA,iBAEnBC,sBAAAA,QAIE,OAAO,QAAQ,GAAG,OAAO,OAAO,OAAO,UAAU,mBAAmB,EACpE,QAAQ,SAAS,OACnB,CAAC,GACH,EAAE,IAAI,GAAG,UAAU,KAAK,GAAG,kBAAkB,CAC/C;AAEF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getWalletBalances.js","names":["ValidationError","request"],"sources":["../../../src/actions/getWalletBalances.ts"],"sourcesContent":["import type {\n GetWalletBalanceExtendedResponse,\n RequestOptions,\n WalletTokenExtended,\n} from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\n\n/**\n * Returns the balances of tokens a wallet holds across EVM chains.\n * @param client - The SDK client.\n * @param walletAddress - A wallet address.\n * @param options - Optional request options.\n * @returns An object containing the tokens and the amounts organized by chain ids.\n * @throws {ValidationError} Throws a ValidationError if parameters are invalid.\n */\nexport const getWalletBalances = async (\n client: SDKClient,\n walletAddress: string,\n options?: RequestOptions\n): Promise<Record<number, WalletTokenExtended[]>> => {\n if (!walletAddress) {\n throw new ValidationError('Missing walletAddress.')\n }\n\n const response = await request<GetWalletBalanceExtendedResponse>(\n client.config,\n `${client.config.apiUrl}/wallets/${walletAddress}/balances?extended=true`,\n {\n signal: options?.signal,\n }\n )\n\n return (response?.balances || {}) as Record<number, WalletTokenExtended[]>\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAa,oBAAoB,OAC/B,QACA,eACA,YACmD;CACnD,IAAI,CAAC,eACH,MAAM,IAAIA,sBAAAA,gBAAgB,wBAAwB;CAWpD,QAAQ,MAReC,sBAAAA,QACrB,OAAO,QACP,GAAG,OAAO,OAAO,OAAO,WAAW,cAAc,0BACjD,EACE,QAAQ,SAAS,OACnB,CACF,
|
|
1
|
+
{"version":3,"file":"getWalletBalances.js","names":["ValidationError","request"],"sources":["../../../src/actions/getWalletBalances.ts"],"sourcesContent":["import type {\n GetWalletBalanceExtendedResponse,\n RequestOptions,\n WalletTokenExtended,\n} from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\n\n/**\n * Returns the balances of tokens a wallet holds across EVM chains.\n * @param client - The SDK client.\n * @param walletAddress - A wallet address.\n * @param options - Optional request options.\n * @returns An object containing the tokens and the amounts organized by chain ids.\n * @throws {ValidationError} Throws a ValidationError if parameters are invalid.\n */\nexport const getWalletBalances = async (\n client: SDKClient,\n walletAddress: string,\n options?: RequestOptions\n): Promise<Record<number, WalletTokenExtended[]>> => {\n if (!walletAddress) {\n throw new ValidationError('Missing walletAddress.')\n }\n\n const response = await request<GetWalletBalanceExtendedResponse>(\n client.config,\n `${client.config.apiUrl}/wallets/${walletAddress}/balances?extended=true`,\n {\n signal: options?.signal,\n }\n )\n\n return (response?.balances || {}) as Record<number, WalletTokenExtended[]>\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAa,oBAAoB,OAC/B,QACA,eACA,YACmD;CACnD,IAAI,CAAC,eACH,MAAM,IAAIA,sBAAAA,gBAAgB,wBAAwB;CAWpD,QAAQ,MAReC,sBAAAA,QACrB,OAAO,QACP,GAAG,OAAO,OAAO,OAAO,WAAW,cAAc,0BACjD,EACE,QAAQ,SAAS,OACnB,CACF,EAAA,EAEkB,YAAY,CAAC;AACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createClient.js","names":["name","version","getClientStorage"],"sources":["../../../src/client/createClient.ts"],"sourcesContent":["import type { ChainId, ChainType, ExtendedChain } from '@lifi/types'\nimport type {\n SDKBaseConfig,\n SDKClient,\n SDKConfig,\n SDKProvider,\n} from '../types/core.js'\nimport { checkPackageUpdates } from '../utils/checkPackageUpdates.js'\nimport { name, version } from '../version.js'\nimport { getClientStorage } from './getClientStorage.js'\n\nexport function createClient(options: SDKConfig): SDKClient {\n if (!options.integrator) {\n throw new Error(\n 'Integrator not found. Please see documentation https://docs.li.fi/integrate-li.fi-js-sdk/set-up-the-sdk'\n )\n }\n\n if (!options.disableVersionCheck && process.env.NODE_ENV === 'development') {\n checkPackageUpdates(name, version)\n }\n\n const { providers, ...configOptions } = options\n\n const _config: SDKBaseConfig = {\n ...configOptions,\n apiUrl: configOptions?.apiUrl ?? 'https://li.quest/v1',\n rpcUrls: configOptions?.rpcUrls ?? {},\n debug: configOptions?.debug ?? false,\n preloadChains: configOptions?.preloadChains ?? true,\n integrator: configOptions?.integrator ?? 'lifi-sdk',\n }\n\n let _providers: SDKProvider[] = providers ?? []\n const _storage = getClientStorage(_config)\n\n const client: SDKClient = {\n get config() {\n return _config\n },\n get providers() {\n return _providers\n },\n getProvider(type: ChainType) {\n return this.providers.find((provider) => provider.type === type)\n },\n setProviders(newProviders: SDKProvider[]) {\n const providerMap = new Map(\n this.providers.map((provider) => [provider.type, provider])\n )\n for (const provider of newProviders) {\n providerMap.set(provider.type, provider)\n }\n _providers = Array.from(providerMap.values())\n },\n setChains(chains: ExtendedChain[]) {\n _storage.setChains(chains)\n },\n async getChains() {\n return await _storage.getChains()\n },\n async getChainById(chainId: ChainId) {\n const chains = await this.getChains()\n const chain = chains?.find((chain) => chain.id === chainId)\n if (!chain) {\n throw new Error(`ChainId ${chainId} not found`)\n }\n return chain\n },\n async getRpcUrls() {\n return await _storage.getRpcUrls()\n },\n async getRpcUrlsByChainId(chainId: ChainId) {\n const rpcUrls = await this.getRpcUrls()\n const chainRpcUrls = rpcUrls[chainId]\n if (!chainRpcUrls?.length) {\n throw new Error(`RPC URL not found for chainId: ${chainId}`)\n }\n return chainRpcUrls\n },\n }\n\n function extend<TClient extends SDKClient>(\n base: TClient\n ): <TExtensions extends Record<string, any>>(\n extendFn: (client: TClient) => TExtensions\n ) => TClient & TExtensions {\n return (extendFn) => {\n const extensions = extendFn(base)\n const extended = { ...base, ...extensions } as TClient & typeof extensions\n\n // Preserve the extend function for further extensions\n return Object.assign(extended, {\n extend: extend(extended),\n })\n }\n }\n\n return Object.assign(client, { extend: extend(client) })\n}\n"],"mappings":";;;;;AAWA,SAAgB,aAAa,SAA+B;CAC1D,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,yGACF;CAGF,IAAI,CAAC,QAAQ,uBAAuB,QAAQ,IAAI,aAAa,eAC3D,kCAAA,oBAAoBA,gBAAAA,MAAMC,gBAAAA,OAAO;CAGnC,MAAM,EAAE,WAAW,GAAG,kBAAkB;CAExC,MAAM,UAAyB;EAC7B,GAAG;EACH,QAAQ,eAAe,UAAU;EACjC,SAAS,eAAe,WAAW,CAAC;EACpC,OAAO,eAAe,SAAS;EAC/B,eAAe,eAAe,iBAAiB;EAC/C,YAAY,eAAe,cAAc;CAC3C;CAEA,IAAI,aAA4B,aAAa,CAAC;CAC9C,MAAM,WAAWC,gCAAAA,iBAAiB,OAAO;CAEzC,MAAM,SAAoB;EACxB,IAAI,SAAS;GACX,OAAO;EACT;EACA,IAAI,YAAY;GACd,OAAO;EACT;EACA,YAAY,MAAiB;GAC3B,OAAO,KAAK,UAAU,MAAM,aAAa,SAAS,SAAS,IAAI;EACjE;EACA,aAAa,cAA6B;GACxC,MAAM,cAAc,IAAI,IACtB,KAAK,UAAU,KAAK,aAAa,CAAC,SAAS,MAAM,QAAQ,CAAC,CAC5D;GACA,KAAK,MAAM,YAAY,cACrB,YAAY,IAAI,SAAS,MAAM,QAAQ;GAEzC,aAAa,MAAM,KAAK,YAAY,OAAO,CAAC;EAC9C;EACA,UAAU,QAAyB;GACjC,SAAS,UAAU,MAAM;EAC3B;EACA,MAAM,YAAY;GAChB,OAAO,MAAM,SAAS,UAAU;EAClC;EACA,MAAM,aAAa,SAAkB;GAEnC,MAAM,SAAQ,MADO,KAAK,UAAU,
|
|
1
|
+
{"version":3,"file":"createClient.js","names":["name","version","getClientStorage"],"sources":["../../../src/client/createClient.ts"],"sourcesContent":["import type { ChainId, ChainType, ExtendedChain } from '@lifi/types'\nimport type {\n SDKBaseConfig,\n SDKClient,\n SDKConfig,\n SDKProvider,\n} from '../types/core.js'\nimport { checkPackageUpdates } from '../utils/checkPackageUpdates.js'\nimport { name, version } from '../version.js'\nimport { getClientStorage } from './getClientStorage.js'\n\nexport function createClient(options: SDKConfig): SDKClient {\n if (!options.integrator) {\n throw new Error(\n 'Integrator not found. Please see documentation https://docs.li.fi/integrate-li.fi-js-sdk/set-up-the-sdk'\n )\n }\n\n if (!options.disableVersionCheck && process.env.NODE_ENV === 'development') {\n checkPackageUpdates(name, version)\n }\n\n const { providers, ...configOptions } = options\n\n const _config: SDKBaseConfig = {\n ...configOptions,\n apiUrl: configOptions?.apiUrl ?? 'https://li.quest/v1',\n rpcUrls: configOptions?.rpcUrls ?? {},\n debug: configOptions?.debug ?? false,\n preloadChains: configOptions?.preloadChains ?? true,\n integrator: configOptions?.integrator ?? 'lifi-sdk',\n }\n\n let _providers: SDKProvider[] = providers ?? []\n const _storage = getClientStorage(_config)\n\n const client: SDKClient = {\n get config() {\n return _config\n },\n get providers() {\n return _providers\n },\n getProvider(type: ChainType) {\n return this.providers.find((provider) => provider.type === type)\n },\n setProviders(newProviders: SDKProvider[]) {\n const providerMap = new Map(\n this.providers.map((provider) => [provider.type, provider])\n )\n for (const provider of newProviders) {\n providerMap.set(provider.type, provider)\n }\n _providers = Array.from(providerMap.values())\n },\n setChains(chains: ExtendedChain[]) {\n _storage.setChains(chains)\n },\n async getChains() {\n return await _storage.getChains()\n },\n async getChainById(chainId: ChainId) {\n const chains = await this.getChains()\n const chain = chains?.find((chain) => chain.id === chainId)\n if (!chain) {\n throw new Error(`ChainId ${chainId} not found`)\n }\n return chain\n },\n async getRpcUrls() {\n return await _storage.getRpcUrls()\n },\n async getRpcUrlsByChainId(chainId: ChainId) {\n const rpcUrls = await this.getRpcUrls()\n const chainRpcUrls = rpcUrls[chainId]\n if (!chainRpcUrls?.length) {\n throw new Error(`RPC URL not found for chainId: ${chainId}`)\n }\n return chainRpcUrls\n },\n }\n\n function extend<TClient extends SDKClient>(\n base: TClient\n ): <TExtensions extends Record<string, any>>(\n extendFn: (client: TClient) => TExtensions\n ) => TClient & TExtensions {\n return (extendFn) => {\n const extensions = extendFn(base)\n const extended = { ...base, ...extensions } as TClient & typeof extensions\n\n // Preserve the extend function for further extensions\n return Object.assign(extended, {\n extend: extend(extended),\n })\n }\n }\n\n return Object.assign(client, { extend: extend(client) })\n}\n"],"mappings":";;;;;AAWA,SAAgB,aAAa,SAA+B;CAC1D,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,yGACF;CAGF,IAAI,CAAC,QAAQ,uBAAuB,QAAQ,IAAI,aAAa,eAC3D,kCAAA,oBAAoBA,gBAAAA,MAAMC,gBAAAA,OAAO;CAGnC,MAAM,EAAE,WAAW,GAAG,kBAAkB;CAExC,MAAM,UAAyB;EAC7B,GAAG;EACH,QAAQ,eAAe,UAAU;EACjC,SAAS,eAAe,WAAW,CAAC;EACpC,OAAO,eAAe,SAAS;EAC/B,eAAe,eAAe,iBAAiB;EAC/C,YAAY,eAAe,cAAc;CAC3C;CAEA,IAAI,aAA4B,aAAa,CAAC;CAC9C,MAAM,WAAWC,gCAAAA,iBAAiB,OAAO;CAEzC,MAAM,SAAoB;EACxB,IAAI,SAAS;GACX,OAAO;EACT;EACA,IAAI,YAAY;GACd,OAAO;EACT;EACA,YAAY,MAAiB;GAC3B,OAAO,KAAK,UAAU,MAAM,aAAa,SAAS,SAAS,IAAI;EACjE;EACA,aAAa,cAA6B;GACxC,MAAM,cAAc,IAAI,IACtB,KAAK,UAAU,KAAK,aAAa,CAAC,SAAS,MAAM,QAAQ,CAAC,CAC5D;GACA,KAAK,MAAM,YAAY,cACrB,YAAY,IAAI,SAAS,MAAM,QAAQ;GAEzC,aAAa,MAAM,KAAK,YAAY,OAAO,CAAC;EAC9C;EACA,UAAU,QAAyB;GACjC,SAAS,UAAU,MAAM;EAC3B;EACA,MAAM,YAAY;GAChB,OAAO,MAAM,SAAS,UAAU;EAClC;EACA,MAAM,aAAa,SAAkB;GAEnC,MAAM,SAAQ,MADO,KAAK,UAAU,EAAA,EACd,MAAM,UAAU,MAAM,OAAO,OAAO;GAC1D,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,WAAW,QAAQ,WAAW;GAEhD,OAAO;EACT;EACA,MAAM,aAAa;GACjB,OAAO,MAAM,SAAS,WAAW;EACnC;EACA,MAAM,oBAAoB,SAAkB;GAE1C,MAAM,gBAAe,MADC,KAAK,WAAW,EAAA,CACT;GAC7B,IAAI,CAAC,cAAc,QACjB,MAAM,IAAI,MAAM,kCAAkC,SAAS;GAE7D,OAAO;EACT;CACF;CAEA,SAAS,OACP,MAGyB;EACzB,QAAQ,aAAa;GACnB,MAAM,aAAa,SAAS,IAAI;GAChC,MAAM,WAAW;IAAE,GAAG;IAAM,GAAG;GAAW;GAG1C,OAAO,OAAO,OAAO,UAAU,EAC7B,QAAQ,OAAO,QAAQ,EACzB,CAAC;EACH;CACF;CAEA,OAAO,OAAO,OAAO,QAAQ,EAAE,QAAQ,OAAO,MAAM,EAAE,CAAC;AACzD"}
|
|
@@ -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,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,
|
|
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,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,wBACtB,IAAI,QACF,KAAK,cAAc,aAAa,MAAM,OAAO,MAAM,UAAU,EAC3D,OAAO;IACL,SAAS,OAAO,OAAO;IACvB,MAAM,OAAO;GACf,EACF,CAAC;QAED,KAAK,cAAc,gBAAgB,MAAM;IACvC,QAAQ;IACR,OAAO;KACL,SAAS,OAAO,OAAO;KACvB,MAAM,OAAO;IACf;GACF,CAAC;GAGL,MAAM;EACR;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actionMessages.js","names":[],"sources":["../../../src/core/actionMessages.ts"],"sourcesContent":["import type { StatusMessage, Substatus } from '@lifi/types'\nimport type {\n ExecutionActionStatus,\n ExecutionActionType,\n} from '../types/core.js'\n\nconst actionMessages: Record<\n ExecutionActionType,\n Partial<Record<ExecutionActionStatus, string>>\n> = {\n CHECK_ALLOWANCE: {\n STARTED: 'Checking token allowance',\n PENDING: 'Waiting for token allowance check',\n DONE: 'Token allowance checked',\n },\n RESET_ALLOWANCE: {\n STARTED: 'Resetting token allowance',\n RESET_REQUIRED: 'Resetting token allowance',\n PENDING: 'Waiting for token allowance reset',\n DONE: 'Token allowance reset',\n },\n SET_ALLOWANCE: {\n STARTED: 'Setting token allowance',\n ACTION_REQUIRED: 'Set token allowance',\n PENDING: 'Waiting for token allowance',\n DONE: 'Token allowance set',\n },\n SWAP: {\n STARTED: 'Preparing swap transaction',\n ACTION_REQUIRED: 'Sign swap transaction',\n MESSAGE_REQUIRED: 'Sign swap message',\n PENDING: 'Waiting for swap transaction',\n DONE: 'Swap completed',\n },\n CROSS_CHAIN: {\n STARTED: 'Preparing bridge transaction',\n ACTION_REQUIRED: 'Sign bridge transaction',\n MESSAGE_REQUIRED: 'Sign bridge message',\n PENDING: 'Waiting for bridge transaction',\n DONE: 'Bridge transaction confirmed',\n },\n RECEIVING_CHAIN: {\n STARTED: 'Waiting for destination chain',\n PENDING: 'Waiting for destination chain',\n DONE: 'Bridge completed',\n },\n PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n NATIVE_PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n}\n\nconst substatusMessages: Record<\n StatusMessage,\n Partial<Record<Substatus, string>>\n> = {\n PENDING: {\n BRIDGE_NOT_AVAILABLE: 'Bridge communication is temporarily unavailable.',\n CHAIN_NOT_AVAILABLE: 'RPC communication is temporarily unavailable.',\n UNKNOWN_ERROR:\n 'An unexpected error occurred. Please seek assistance in the LI.FI discord server.',\n WAIT_SOURCE_CONFIRMATIONS:\n 'The bridge deposit has been received. The bridge is waiting for more confirmations to start the off-chain logic.',\n WAIT_DESTINATION_TRANSACTION:\n 'The bridge off-chain logic is being executed. Wait for the transaction to appear on the destination chain.',\n },\n DONE: {\n PARTIAL:\n 'Some of the received tokens are not the requested destination tokens.',\n REFUNDED: 'The tokens were refunded to the sender address.',\n COMPLETED: 'The transfer is complete.',\n },\n FAILED: {},\n INVALID: {},\n NOT_FOUND: {},\n}\n\nexport function getActionMessage(\n type: ExecutionActionType,\n status: ExecutionActionStatus\n): string | undefined {\n const actionMessage = actionMessages[type][status]\n return actionMessage\n}\n\nexport function getSubstatusMessage(\n status: StatusMessage,\n substatus?: Substatus\n): string | undefined {\n if (!substatus) {\n return\n }\n const message = substatusMessages[status][substatus]\n return message\n}\n"],"mappings":";;AAMA,MAAM,iBAGF;CACF,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;CACR;CACA,iBAAiB;EACf,SAAS;EACT,gBAAgB;EAChB,SAAS;EACT,MAAM;CACR;CACA,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;CACA,MAAM;EACJ,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;CACR;CACA,aAAa;EACX,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;CACR;CACA,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;CACR;CACA,QAAQ;EACN,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;CACA,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;AACF;AAEA,MAAM,oBAGF;CACF,SAAS;EACP,sBAAsB;EACtB,qBAAqB;EACrB,eACE;EACF,2BACE;EACF,8BACE;CACJ;CACA,MAAM;EACJ,SACE;EACF,UAAU;EACV,WAAW;CACb;CACA,QAAQ,CAAC;CACT,SAAS,CAAC;CACV,WAAW,CAAC;AACd;AAEA,SAAgB,iBACd,MACA,QACoB;CAEpB,OADsB,eAAe,
|
|
1
|
+
{"version":3,"file":"actionMessages.js","names":[],"sources":["../../../src/core/actionMessages.ts"],"sourcesContent":["import type { StatusMessage, Substatus } from '@lifi/types'\nimport type {\n ExecutionActionStatus,\n ExecutionActionType,\n} from '../types/core.js'\n\nconst actionMessages: Record<\n ExecutionActionType,\n Partial<Record<ExecutionActionStatus, string>>\n> = {\n CHECK_ALLOWANCE: {\n STARTED: 'Checking token allowance',\n PENDING: 'Waiting for token allowance check',\n DONE: 'Token allowance checked',\n },\n RESET_ALLOWANCE: {\n STARTED: 'Resetting token allowance',\n RESET_REQUIRED: 'Resetting token allowance',\n PENDING: 'Waiting for token allowance reset',\n DONE: 'Token allowance reset',\n },\n SET_ALLOWANCE: {\n STARTED: 'Setting token allowance',\n ACTION_REQUIRED: 'Set token allowance',\n PENDING: 'Waiting for token allowance',\n DONE: 'Token allowance set',\n },\n SWAP: {\n STARTED: 'Preparing swap transaction',\n ACTION_REQUIRED: 'Sign swap transaction',\n MESSAGE_REQUIRED: 'Sign swap message',\n PENDING: 'Waiting for swap transaction',\n DONE: 'Swap completed',\n },\n CROSS_CHAIN: {\n STARTED: 'Preparing bridge transaction',\n ACTION_REQUIRED: 'Sign bridge transaction',\n MESSAGE_REQUIRED: 'Sign bridge message',\n PENDING: 'Waiting for bridge transaction',\n DONE: 'Bridge transaction confirmed',\n },\n RECEIVING_CHAIN: {\n STARTED: 'Waiting for destination chain',\n PENDING: 'Waiting for destination chain',\n DONE: 'Bridge completed',\n },\n PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n NATIVE_PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n}\n\nconst substatusMessages: Record<\n StatusMessage,\n Partial<Record<Substatus, string>>\n> = {\n PENDING: {\n BRIDGE_NOT_AVAILABLE: 'Bridge communication is temporarily unavailable.',\n CHAIN_NOT_AVAILABLE: 'RPC communication is temporarily unavailable.',\n UNKNOWN_ERROR:\n 'An unexpected error occurred. Please seek assistance in the LI.FI discord server.',\n WAIT_SOURCE_CONFIRMATIONS:\n 'The bridge deposit has been received. The bridge is waiting for more confirmations to start the off-chain logic.',\n WAIT_DESTINATION_TRANSACTION:\n 'The bridge off-chain logic is being executed. Wait for the transaction to appear on the destination chain.',\n },\n DONE: {\n PARTIAL:\n 'Some of the received tokens are not the requested destination tokens.',\n REFUNDED: 'The tokens were refunded to the sender address.',\n COMPLETED: 'The transfer is complete.',\n },\n FAILED: {},\n INVALID: {},\n NOT_FOUND: {},\n}\n\nexport function getActionMessage(\n type: ExecutionActionType,\n status: ExecutionActionStatus\n): string | undefined {\n const actionMessage = actionMessages[type][status]\n return actionMessage\n}\n\nexport function getSubstatusMessage(\n status: StatusMessage,\n substatus?: Substatus\n): string | undefined {\n if (!substatus) {\n return\n }\n const message = substatusMessages[status][substatus]\n return message\n}\n"],"mappings":";;AAMA,MAAM,iBAGF;CACF,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;CACR;CACA,iBAAiB;EACf,SAAS;EACT,gBAAgB;EAChB,SAAS;EACT,MAAM;CACR;CACA,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;CACA,MAAM;EACJ,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;CACR;CACA,aAAa;EACX,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;CACR;CACA,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;CACR;CACA,QAAQ;EACN,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;CACA,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;AACF;AAEA,MAAM,oBAGF;CACF,SAAS;EACP,sBAAsB;EACtB,qBAAqB;EACrB,eACE;EACF,2BACE;EACF,8BACE;CACJ;CACA,MAAM;EACJ,SACE;EACF,UAAU;EACV,WAAW;CACb;CACA,QAAQ,CAAC;CACT,SAAS,CAAC;CACV,WAAW,CAAC;AACd;AAEA,SAAgB,iBACd,MACA,QACoB;CAEpB,OADsB,eAAe,KAAK,CAAC;AAE7C;AAEA,SAAgB,oBACd,QACA,WACoB;CACpB,IAAI,CAAC,WACH;CAGF,OADgB,kBAAkB,OAAO,CAAC;AAE5C"}
|
|
@@ -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,
|
|
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":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executionState.js","names":[],"sources":["../../../src/core/executionState.ts"],"sourcesContent":["import type {\n ExecutionOptions,\n RouteExtended,\n StepExecutor,\n} from '../types/core.js'\n\ninterface ExecutionData {\n route: RouteExtended\n executors: StepExecutor[]\n executionOptions?: ExecutionOptions\n promise?: Promise<RouteExtended>\n}\n\ntype ExecutionStateParams = Omit<ExecutionData, 'executors'>\n\ninterface ExecutionState {\n state: Partial<Record<string, ExecutionData>>\n get(routeId: string): ExecutionData | undefined\n create(params: ExecutionStateParams): ExecutionData\n update(params: ExecutionStateParams): void\n delete(routeId: string): void\n}\n\nexport const executionState: ExecutionState = {\n state: {},\n get(routeId: string) {\n return this.state[routeId]\n },\n create(params) {\n this.state[params.route.id] = {\n ...this.state[params.route.id],\n ...params,\n executors: this.state[params.route.id]?.executors ?? [],\n }\n return this.state[params.route.id]!\n },\n update(state) {\n if (this.state[state.route.id]) {\n this.state[state.route.id] = {\n ...this.state[state.route.id]!,\n ...state,\n }\n }\n },\n delete(routeId) {\n delete this.state[routeId]\n },\n}\n"],"mappings":";;AAuBA,MAAa,iBAAiC;CAC5C,OAAO,CAAC;CACR,IAAI,SAAiB;EACnB,OAAO,KAAK,MAAM;CACpB;CACA,OAAO,QAAQ;EACb,KAAK,MAAM,OAAO,MAAM,MAAM;GAC5B,GAAG,KAAK,MAAM,OAAO,MAAM;GAC3B,GAAG;GACH,WAAW,KAAK,MAAM,OAAO,MAAM,
|
|
1
|
+
{"version":3,"file":"executionState.js","names":[],"sources":["../../../src/core/executionState.ts"],"sourcesContent":["import type {\n ExecutionOptions,\n RouteExtended,\n StepExecutor,\n} from '../types/core.js'\n\ninterface ExecutionData {\n route: RouteExtended\n executors: StepExecutor[]\n executionOptions?: ExecutionOptions\n promise?: Promise<RouteExtended>\n}\n\ntype ExecutionStateParams = Omit<ExecutionData, 'executors'>\n\ninterface ExecutionState {\n state: Partial<Record<string, ExecutionData>>\n get(routeId: string): ExecutionData | undefined\n create(params: ExecutionStateParams): ExecutionData\n update(params: ExecutionStateParams): void\n delete(routeId: string): void\n}\n\nexport const executionState: ExecutionState = {\n state: {},\n get(routeId: string) {\n return this.state[routeId]\n },\n create(params) {\n this.state[params.route.id] = {\n ...this.state[params.route.id],\n ...params,\n executors: this.state[params.route.id]?.executors ?? [],\n }\n return this.state[params.route.id]!\n },\n update(state) {\n if (this.state[state.route.id]) {\n this.state[state.route.id] = {\n ...this.state[state.route.id]!,\n ...state,\n }\n }\n },\n delete(routeId) {\n delete this.state[routeId]\n },\n}\n"],"mappings":";;AAuBA,MAAa,iBAAiC;CAC5C,OAAO,CAAC;CACR,IAAI,SAAiB;EACnB,OAAO,KAAK,MAAM;CACpB;CACA,OAAO,QAAQ;EACb,KAAK,MAAM,OAAO,MAAM,MAAM;GAC5B,GAAG,KAAK,MAAM,OAAO,MAAM;GAC3B,GAAG;GACH,WAAW,KAAK,MAAM,OAAO,MAAM,GAAG,EAAE,aAAa,CAAC;EACxD;EACA,OAAO,KAAK,MAAM,OAAO,MAAM;CACjC;CACA,OAAO,OAAO;EACZ,IAAI,KAAK,MAAM,MAAM,MAAM,KACzB,KAAK,MAAM,MAAM,MAAM,MAAM;GAC3B,GAAG,KAAK,MAAM,MAAM,MAAM;GAC1B,GAAG;EACL;CAEJ;CACA,OAAO,SAAS;EACd,OAAO,KAAK,MAAM;CACpB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepareRestart.js","names":[],"sources":["../../../src/core/prepareRestart.ts"],"sourcesContent":["import type { RouteExtended } from '../types/core.js'\n\nexport const prepareRestart = (route: RouteExtended): void => {\n for (let index = 0; index < route.steps.length; index++) {\n const step = route.steps[index]\n if (step.execution) {\n // Find the index of the last action that has tx hash, taskId, or signed messages\n const lastValidIndex = step.execution.actions.findLastIndex(\n (action) =>\n ['SWAP', 'CROSS_CHAIN', 'RECEIVING_CHAIN'].includes(action.type) &&\n (!!action.txHash || !!action.taskId) &&\n action.status !== 'FAILED'\n )\n\n // Keep all actions up to the one with tx hash\n if (lastValidIndex >= 0) {\n step.execution.actions = step.execution.actions.slice(\n 0,\n lastValidIndex + 1\n )\n } else {\n // If no tx hash exists, reset the actions array\n step.execution.actions = []\n }\n }\n step.transactionRequest = undefined\n }\n}\n"],"mappings":";;AAEA,MAAa,kBAAkB,UAA+B;CAC5D,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,MAAM,QAAQ,SAAS;EACvD,MAAM,OAAO,MAAM,MAAM;EACzB,IAAI,KAAK,WAAW;GAElB,MAAM,iBAAiB,KAAK,UAAU,QAAQ,eAC3C,WACC;IAAC;IAAQ;IAAe;GAAiB,
|
|
1
|
+
{"version":3,"file":"prepareRestart.js","names":[],"sources":["../../../src/core/prepareRestart.ts"],"sourcesContent":["import type { RouteExtended } from '../types/core.js'\n\nexport const prepareRestart = (route: RouteExtended): void => {\n for (let index = 0; index < route.steps.length; index++) {\n const step = route.steps[index]\n if (step.execution) {\n // Find the index of the last action that has tx hash, taskId, or signed messages\n const lastValidIndex = step.execution.actions.findLastIndex(\n (action) =>\n ['SWAP', 'CROSS_CHAIN', 'RECEIVING_CHAIN'].includes(action.type) &&\n (!!action.txHash || !!action.taskId) &&\n action.status !== 'FAILED'\n )\n\n // Keep all actions up to the one with tx hash\n if (lastValidIndex >= 0) {\n step.execution.actions = step.execution.actions.slice(\n 0,\n lastValidIndex + 1\n )\n } else {\n // If no tx hash exists, reset the actions array\n step.execution.actions = []\n }\n }\n step.transactionRequest = undefined\n }\n}\n"],"mappings":";;AAEA,MAAa,kBAAkB,UAA+B;CAC5D,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,MAAM,QAAQ,SAAS;EACvD,MAAM,OAAO,MAAM,MAAM;EACzB,IAAI,KAAK,WAAW;GAElB,MAAM,iBAAiB,KAAK,UAAU,QAAQ,eAC3C,WACC;IAAC;IAAQ;IAAe;GAAiB,CAAC,CAAC,SAAS,OAAO,IAAI,MAC9D,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,WAC7B,OAAO,WAAW,QACtB;GAGA,IAAI,kBAAkB,GACpB,KAAK,UAAU,UAAU,KAAK,UAAU,QAAQ,MAC9C,GACA,iBAAiB,CACnB;QAGA,KAAK,UAAU,UAAU,CAAC;EAE9B;EACA,KAAK,qBAAqB,KAAA;CAC5B;AACF"}
|
|
@@ -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":"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"}
|
|
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":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"waitForTransactionStatus.js","names":["getStatus","getSubstatusMessage","waitForResult","ServerError"],"sources":["../../../../../src/core/tasks/helpers/waitForTransactionStatus.ts"],"sourcesContent":["import type { FullStatusData, LiFiStep, StatusResponse } from '@lifi/types'\nimport { getStatus } from '../../../actions/getStatus.js'\nimport { ServerError } from '../../../errors/errors.js'\nimport type { ExecutionActionType, SDKClient } from '../../../types/core.js'\nimport { waitForResult } from '../../../utils/waitForResult.js'\nimport { getSubstatusMessage } from '../../actionMessages.js'\nimport type { StatusManager } from '../../StatusManager.js'\n\nconst TRANSACTION_HASH_OBSERVERS: Record<string, Promise<StatusResponse>> = {}\n\nexport async function waitForTransactionStatus(\n client: SDKClient,\n statusManager: StatusManager,\n txHash: string,\n step: LiFiStep,\n actionType: ExecutionActionType,\n interval = 5_000\n): Promise<StatusResponse> {\n const _getStatus = (): Promise<StatusResponse | undefined> => {\n return getStatus(client, {\n fromChain: step.action.fromChainId,\n fromAddress: step.action.fromAddress,\n toChain: step.action.toChainId,\n txHash,\n ...(step.tool !== 'custom' && { bridge: step.tool }),\n ...(step.transactionId && { transactionId: step.transactionId }),\n })\n .then((statusResponse) => {\n switch (statusResponse.status) {\n case 'DONE':\n return statusResponse\n case 'PENDING':\n statusManager?.updateAction(step, actionType, 'PENDING', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(\n statusResponse.status,\n statusResponse.substatus\n ),\n txLink: (statusResponse as FullStatusData).bridgeExplorerLink,\n })\n return undefined\n case 'NOT_FOUND':\n return undefined\n default:\n return Promise.reject()\n }\n })\n .catch((e) => {\n if (process.env.NODE_ENV === 'development') {\n console.debug('Fetching status from backend failed.', e)\n }\n return undefined\n })\n }\n\n let status = TRANSACTION_HASH_OBSERVERS[txHash]\n\n if (!status) {\n status = waitForResult(_getStatus, interval).finally(() => {\n delete TRANSACTION_HASH_OBSERVERS[txHash]\n })\n TRANSACTION_HASH_OBSERVERS[txHash] = status\n }\n\n const resolvedStatus = await status\n\n if (!('receiving' in resolvedStatus)) {\n throw new ServerError(\n \"Status doesn't contain destination chain information.\"\n )\n }\n\n return resolvedStatus\n}\n"],"mappings":";;;;;;AAQA,MAAM,6BAAsE,CAAC;AAE7E,eAAsB,yBACpB,QACA,eACA,QACA,MACA,YACA,WAAW,KACc;CACzB,MAAM,mBAAwD;EAC5D,OAAOA,0BAAAA,UAAU,QAAQ;GACvB,WAAW,KAAK,OAAO;GACvB,aAAa,KAAK,OAAO;GACzB,SAAS,KAAK,OAAO;GACrB;GACA,GAAI,KAAK,SAAS,YAAY,EAAE,QAAQ,KAAK,KAAK;GAClD,GAAI,KAAK,iBAAiB,EAAE,eAAe,KAAK,cAAc;EAChE,CAAC,
|
|
1
|
+
{"version":3,"file":"waitForTransactionStatus.js","names":["getStatus","getSubstatusMessage","waitForResult","ServerError"],"sources":["../../../../../src/core/tasks/helpers/waitForTransactionStatus.ts"],"sourcesContent":["import type { FullStatusData, LiFiStep, StatusResponse } from '@lifi/types'\nimport { getStatus } from '../../../actions/getStatus.js'\nimport { ServerError } from '../../../errors/errors.js'\nimport type { ExecutionActionType, SDKClient } from '../../../types/core.js'\nimport { waitForResult } from '../../../utils/waitForResult.js'\nimport { getSubstatusMessage } from '../../actionMessages.js'\nimport type { StatusManager } from '../../StatusManager.js'\n\nconst TRANSACTION_HASH_OBSERVERS: Record<string, Promise<StatusResponse>> = {}\n\nexport async function waitForTransactionStatus(\n client: SDKClient,\n statusManager: StatusManager,\n txHash: string,\n step: LiFiStep,\n actionType: ExecutionActionType,\n interval = 5_000\n): Promise<StatusResponse> {\n const _getStatus = (): Promise<StatusResponse | undefined> => {\n return getStatus(client, {\n fromChain: step.action.fromChainId,\n fromAddress: step.action.fromAddress,\n toChain: step.action.toChainId,\n txHash,\n ...(step.tool !== 'custom' && { bridge: step.tool }),\n ...(step.transactionId && { transactionId: step.transactionId }),\n })\n .then((statusResponse) => {\n switch (statusResponse.status) {\n case 'DONE':\n return statusResponse\n case 'PENDING':\n statusManager?.updateAction(step, actionType, 'PENDING', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(\n statusResponse.status,\n statusResponse.substatus\n ),\n txLink: (statusResponse as FullStatusData).bridgeExplorerLink,\n })\n return undefined\n case 'NOT_FOUND':\n return undefined\n default:\n return Promise.reject()\n }\n })\n .catch((e) => {\n if (process.env.NODE_ENV === 'development') {\n console.debug('Fetching status from backend failed.', e)\n }\n return undefined\n })\n }\n\n let status = TRANSACTION_HASH_OBSERVERS[txHash]\n\n if (!status) {\n status = waitForResult(_getStatus, interval).finally(() => {\n delete TRANSACTION_HASH_OBSERVERS[txHash]\n })\n TRANSACTION_HASH_OBSERVERS[txHash] = status\n }\n\n const resolvedStatus = await status\n\n if (!('receiving' in resolvedStatus)) {\n throw new ServerError(\n \"Status doesn't contain destination chain information.\"\n )\n }\n\n return resolvedStatus\n}\n"],"mappings":";;;;;;AAQA,MAAM,6BAAsE,CAAC;AAE7E,eAAsB,yBACpB,QACA,eACA,QACA,MACA,YACA,WAAW,KACc;CACzB,MAAM,mBAAwD;EAC5D,OAAOA,0BAAAA,UAAU,QAAQ;GACvB,WAAW,KAAK,OAAO;GACvB,aAAa,KAAK,OAAO;GACzB,SAAS,KAAK,OAAO;GACrB;GACA,GAAI,KAAK,SAAS,YAAY,EAAE,QAAQ,KAAK,KAAK;GAClD,GAAI,KAAK,iBAAiB,EAAE,eAAe,KAAK,cAAc;EAChE,CAAC,CAAC,CACC,MAAM,mBAAmB;GACxB,QAAQ,eAAe,QAAvB;IACE,KAAK,QACH,OAAO;IACT,KAAK;KACH,eAAe,aAAa,MAAM,YAAY,WAAW;MACvD,WAAW,eAAe;MAC1B,kBACE,eAAe,oBACfC,4BAAAA,oBACE,eAAe,QACf,eAAe,SACjB;MACF,QAAS,eAAkC;KAC7C,CAAC;KACD;IACF,KAAK,aACH;IACF,SACE,OAAO,QAAQ,OAAO;GAC1B;EACF,CAAC,CAAC,CACD,OAAO,MAAM;GACZ,IAAI,QAAQ,IAAI,aAAa,eAC3B,QAAQ,MAAM,wCAAwC,CAAC;EAG3D,CAAC;CACL;CAEA,IAAI,SAAS,2BAA2B;CAExC,IAAI,CAAC,QAAQ;EACX,SAASC,4BAAAA,cAAc,YAAY,QAAQ,CAAC,CAAC,cAAc;GACzD,OAAO,2BAA2B;EACpC,CAAC;EACD,2BAA2B,UAAU;CACvC;CAEA,MAAM,iBAAiB,MAAM;CAE7B,IAAI,EAAE,eAAe,iBACnB,MAAM,IAAIC,sBAAAA,YACR,uDACF;CAGF,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../../src/core/utils.ts"],"sourcesContent":["import type { ChainId, ExtendedChain, LiFiStep } from '@lifi/types'\nimport type { RPCUrls } from '../types/core.js'\n\n// Standard threshold for destination amount difference (0.5%)\nconst standardThreshold = 0.005\n\n/**\n * Used to check if changed exchange rate is in the range of slippage threshold.\n * We use a slippage value as a threshold to trigger the rate change hook.\n * This can result in almost doubled slippage for the user and need to be revisited.\n * @param oldStep - old step\n * @param newStep - new step\n * @returns Boolean\n */\nexport function checkStepSlippageThreshold(\n oldStep: LiFiStep,\n newStep: LiFiStep\n): boolean {\n const setSlippage = oldStep.action.slippage || standardThreshold\n const oldEstimatedToAmount = BigInt(oldStep.estimate.toAmountMin)\n const newEstimatedToAmount = BigInt(newStep.estimate.toAmountMin)\n const amountDifference = oldEstimatedToAmount - newEstimatedToAmount\n // oldEstimatedToAmount can be 0 when we use contract calls\n let actualSlippage = 0\n if (oldEstimatedToAmount > 0) {\n actualSlippage =\n Number((amountDifference * 1_000_000_000n) / oldEstimatedToAmount) /\n 1_000_000_000\n }\n return actualSlippage <= setSlippage\n}\n\nexport function getRpcUrlsFromChains(\n existingRpcUrls: RPCUrls,\n chains: ExtendedChain[],\n skipChains?: ChainId[]\n): RPCUrls {\n const rpcUrlsFromChains = chains.reduce((rpcUrls, chain) => {\n if (chain.metamask?.rpcUrls?.length) {\n rpcUrls[chain.id as ChainId] = chain.metamask.rpcUrls\n }\n return rpcUrls\n }, {} as RPCUrls)\n const result = { ...existingRpcUrls }\n for (const rpcUrlsKey in rpcUrlsFromChains) {\n const chainId = Number(rpcUrlsKey) as ChainId\n const urls = rpcUrlsFromChains[chainId]\n if (!urls?.length) {\n continue\n }\n if (!result[chainId]?.length) {\n result[chainId] = Array.from(urls)\n } else if (!skipChains?.includes(chainId)) {\n const filteredUrls = urls.filter((url) => !result[chainId]?.includes(url))\n result[chainId].push(...filteredUrls)\n }\n }\n return result\n}\n"],"mappings":";;AAIA,MAAM,oBAAoB;;;;;;;;;AAU1B,SAAgB,2BACd,SACA,SACS;CACT,MAAM,cAAc,QAAQ,OAAO,YAAY;CAC/C,MAAM,uBAAuB,OAAO,QAAQ,SAAS,WAAW;CAEhE,MAAM,mBAAmB,uBADI,OAAO,QAAQ,SAAS,WACc;CAEnE,IAAI,iBAAiB;CACrB,IAAI,uBAAuB,GACzB,iBACE,OAAQ,mBAAmB,cAAkB,oBAAoB,IACjE;CAEJ,OAAO,kBAAkB;AAC3B;AAEA,SAAgB,qBACd,iBACA,QACA,YACS;CACT,MAAM,oBAAoB,OAAO,QAAQ,SAAS,UAAU;EAC1D,IAAI,MAAM,UAAU,SAAS,QAC3B,QAAQ,MAAM,MAAiB,MAAM,SAAS;EAEhD,OAAO;CACT,GAAG,CAAC,CAAY;CAChB,MAAM,SAAS,EAAE,GAAG,gBAAgB;CACpC,KAAK,MAAM,cAAc,mBAAmB;EAC1C,MAAM,UAAU,OAAO,UAAU;EACjC,MAAM,OAAO,kBAAkB;EAC/B,IAAI,CAAC,MAAM,QACT;EAEF,IAAI,CAAC,OAAO,
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../src/core/utils.ts"],"sourcesContent":["import type { ChainId, ExtendedChain, LiFiStep } from '@lifi/types'\nimport type { RPCUrls } from '../types/core.js'\n\n// Standard threshold for destination amount difference (0.5%)\nconst standardThreshold = 0.005\n\n/**\n * Used to check if changed exchange rate is in the range of slippage threshold.\n * We use a slippage value as a threshold to trigger the rate change hook.\n * This can result in almost doubled slippage for the user and need to be revisited.\n * @param oldStep - old step\n * @param newStep - new step\n * @returns Boolean\n */\nexport function checkStepSlippageThreshold(\n oldStep: LiFiStep,\n newStep: LiFiStep\n): boolean {\n const setSlippage = oldStep.action.slippage || standardThreshold\n const oldEstimatedToAmount = BigInt(oldStep.estimate.toAmountMin)\n const newEstimatedToAmount = BigInt(newStep.estimate.toAmountMin)\n const amountDifference = oldEstimatedToAmount - newEstimatedToAmount\n // oldEstimatedToAmount can be 0 when we use contract calls\n let actualSlippage = 0\n if (oldEstimatedToAmount > 0) {\n actualSlippage =\n Number((amountDifference * 1_000_000_000n) / oldEstimatedToAmount) /\n 1_000_000_000\n }\n return actualSlippage <= setSlippage\n}\n\nexport function getRpcUrlsFromChains(\n existingRpcUrls: RPCUrls,\n chains: ExtendedChain[],\n skipChains?: ChainId[]\n): RPCUrls {\n const rpcUrlsFromChains = chains.reduce((rpcUrls, chain) => {\n if (chain.metamask?.rpcUrls?.length) {\n rpcUrls[chain.id as ChainId] = chain.metamask.rpcUrls\n }\n return rpcUrls\n }, {} as RPCUrls)\n const result = { ...existingRpcUrls }\n for (const rpcUrlsKey in rpcUrlsFromChains) {\n const chainId = Number(rpcUrlsKey) as ChainId\n const urls = rpcUrlsFromChains[chainId]\n if (!urls?.length) {\n continue\n }\n if (!result[chainId]?.length) {\n result[chainId] = Array.from(urls)\n } else if (!skipChains?.includes(chainId)) {\n const filteredUrls = urls.filter((url) => !result[chainId]?.includes(url))\n result[chainId].push(...filteredUrls)\n }\n }\n return result\n}\n"],"mappings":";;AAIA,MAAM,oBAAoB;;;;;;;;;AAU1B,SAAgB,2BACd,SACA,SACS;CACT,MAAM,cAAc,QAAQ,OAAO,YAAY;CAC/C,MAAM,uBAAuB,OAAO,QAAQ,SAAS,WAAW;CAEhE,MAAM,mBAAmB,uBADI,OAAO,QAAQ,SAAS,WACc;CAEnE,IAAI,iBAAiB;CACrB,IAAI,uBAAuB,GACzB,iBACE,OAAQ,mBAAmB,cAAkB,oBAAoB,IACjE;CAEJ,OAAO,kBAAkB;AAC3B;AAEA,SAAgB,qBACd,iBACA,QACA,YACS;CACT,MAAM,oBAAoB,OAAO,QAAQ,SAAS,UAAU;EAC1D,IAAI,MAAM,UAAU,SAAS,QAC3B,QAAQ,MAAM,MAAiB,MAAM,SAAS;EAEhD,OAAO;CACT,GAAG,CAAC,CAAY;CAChB,MAAM,SAAS,EAAE,GAAG,gBAAgB;CACpC,KAAK,MAAM,cAAc,mBAAmB;EAC1C,MAAM,UAAU,OAAO,UAAU;EACjC,MAAM,OAAO,kBAAkB;EAC/B,IAAI,CAAC,MAAM,QACT;EAEF,IAAI,CAAC,OAAO,QAAQ,EAAE,QACpB,OAAO,WAAW,MAAM,KAAK,IAAI;OAC5B,IAAI,CAAC,YAAY,SAAS,OAAO,GAAG;GACzC,MAAM,eAAe,KAAK,QAAQ,QAAQ,CAAC,OAAO,QAAQ,EAAE,SAAS,GAAG,CAAC;GACzE,OAAO,QAAQ,CAAC,KAAK,GAAG,YAAY;EACtC;CACF;CACA,OAAO;AACT"}
|
|
@@ -5,7 +5,7 @@ const checkPackageUpdates = async (packageName, packageVersion) => {
|
|
|
5
5
|
try {
|
|
6
6
|
const pkgName = packageName ?? "@lifi/sdk";
|
|
7
7
|
const latestVersion = (await (await fetch(`https://registry.npmjs.org/${pkgName}/latest`)).json()).version;
|
|
8
|
-
const currentVersion = packageVersion ?? "4.0.
|
|
8
|
+
const currentVersion = packageVersion ?? "4.0.1";
|
|
9
9
|
if (latestVersion > currentVersion) console.warn(`${pkgName}: new package version is available. Please update as soon as possible to enjoy the newest features. Current version: ${currentVersion}. Latest version: ${latestVersion}.`);
|
|
10
10
|
} catch (_error) {}
|
|
11
11
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkPackageUpdates.js","names":[],"sources":["../../../src/utils/checkPackageUpdates.ts"],"sourcesContent":["import { name, version } from '../version.js'\n\nexport const checkPackageUpdates = async (\n packageName?: string,\n packageVersion?: string\n): Promise<void> => {\n try {\n const pkgName = packageName ?? name\n const response = await fetch(`https://registry.npmjs.org/${pkgName}/latest`)\n const reponseBody = await response.json()\n const latestVersion = reponseBody.version\n const currentVersion = packageVersion ?? version\n\n if (latestVersion > currentVersion) {\n console.warn(\n `${pkgName}: new package version is available. Please update as soon as possible to enjoy the newest features. Current version: ${currentVersion}. Latest version: ${latestVersion}.`\n )\n }\n } catch (_error) {\n // Cannot verify version, might be network error etc. We don't bother showing anything in that case\n }\n}\n"],"mappings":";;;AAEA,MAAa,sBAAsB,OACjC,aACA,mBACkB;CAClB,IAAI;EACF,MAAM,UAAU,eAAA;EAGhB,MAAM,iBAAgB,OADI,MADH,MAAM,8BAA8B,QAAQ,QAAQ,
|
|
1
|
+
{"version":3,"file":"checkPackageUpdates.js","names":[],"sources":["../../../src/utils/checkPackageUpdates.ts"],"sourcesContent":["import { name, version } from '../version.js'\n\nexport const checkPackageUpdates = async (\n packageName?: string,\n packageVersion?: string\n): Promise<void> => {\n try {\n const pkgName = packageName ?? name\n const response = await fetch(`https://registry.npmjs.org/${pkgName}/latest`)\n const reponseBody = await response.json()\n const latestVersion = reponseBody.version\n const currentVersion = packageVersion ?? version\n\n if (latestVersion > currentVersion) {\n console.warn(\n `${pkgName}: new package version is available. Please update as soon as possible to enjoy the newest features. Current version: ${currentVersion}. Latest version: ${latestVersion}.`\n )\n }\n } catch (_error) {\n // Cannot verify version, might be network error etc. We don't bother showing anything in that case\n }\n}\n"],"mappings":";;;AAEA,MAAa,sBAAsB,OACjC,aACA,mBACkB;CAClB,IAAI;EACF,MAAM,UAAU,eAAA;EAGhB,MAAM,iBAAgB,OADI,MADH,MAAM,8BAA8B,QAAQ,QAAQ,EAAA,CACxC,KAAK,EAAA,CACN;EAClC,MAAM,iBAAiB,kBAAA;EAEvB,IAAI,gBAAgB,gBAClB,QAAQ,KACN,GAAG,QAAQ,uHAAuH,eAAe,oBAAoB,cAAc,EACrL;CAEJ,SAAS,QAAQ,CAEjB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"convertQuoteToRoute.js","names":["formatUnits","SDKError","ValidationError"],"sources":["../../../src/utils/convertQuoteToRoute.ts"],"sourcesContent":["import type { LiFiStep, Route, Step } from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport { formatUnits } from './formatUnits.js'\n\ninterface ConvertQuoteToRouteOptions {\n /**\n * When true, if the quote has zero output values (toAmount, toAmountMin, toAmountUSD),\n * use the values from the previous included step that has non-zero output.\n */\n adjustZeroOutputFromPreviousStep?: boolean\n}\n\nconst parseBigInt = (value: string | undefined): bigint => {\n if (!value) {\n return 0n\n }\n try {\n return BigInt(value)\n } catch {\n return 0n\n }\n}\n\nconst parseNumber = (value: string | undefined): number => {\n if (!value) {\n return 0\n }\n const parsed = Number(value)\n return Number.isNaN(parsed) ? 0 : parsed\n}\n\nconst isZeroOutput = (\n toAmount: string,\n toAmountMin: string,\n toAmountUSD?: string\n): boolean => {\n return (\n !parseBigInt(toAmount) &&\n !parseBigInt(toAmountMin) &&\n !parseNumber(toAmountUSD)\n )\n}\n\nconst hasNonZeroOutput = (step: Step): boolean => {\n return (\n !!parseBigInt(step.estimate.toAmount) ||\n !!parseBigInt(step.estimate.toAmountMin)\n )\n}\n\nconst findPreviousNonZeroStep = (steps: Step[]): Step | undefined => {\n // Find the last step that has non-zero output (the step before the zero output step)\n for (let i = steps.length - 1; i >= 0; i--) {\n const step = steps[i]\n if (hasNonZeroOutput(step)) {\n return step\n }\n }\n return undefined\n}\n\nexport function formatTokenPrice(\n amount?: string | bigint,\n price?: string,\n decimals?: number\n): number {\n if (!amount || !price) {\n return 0\n }\n\n const formattedAmount =\n typeof amount === 'bigint' && decimals !== undefined\n ? formatUnits(amount, decimals)\n : amount.toString()\n\n if (Number.isNaN(Number(formattedAmount)) || Number.isNaN(Number(price))) {\n return 0\n }\n return Number.parseFloat(formattedAmount) * Number.parseFloat(price)\n}\n\n/**\n * Converts a quote to Route\n * @param quote - Step returned from the quote endpoint.\n * @param options - Optional configuration for handling edge cases.\n * @returns - The route to be executed.\n * @throws {BaseError} Throws a ValidationError if the step has missing values.\n */\nexport const convertQuoteToRoute = (\n quote: LiFiStep,\n options?: ConvertQuoteToRouteOptions\n): Route => {\n let toAmount = quote.estimate.toAmount\n let toAmountMin = quote.estimate.toAmountMin\n let toAmountUSD = quote.estimate.toAmountUSD\n\n // Handle zero output values by looking at previous included step\n if (\n options?.adjustZeroOutputFromPreviousStep &&\n quote.includedSteps?.length &&\n isZeroOutput(toAmount, toAmountMin, toAmountUSD)\n ) {\n const previousStep = findPreviousNonZeroStep(quote.includedSteps)\n if (previousStep) {\n toAmount = previousStep.estimate.toAmount\n toAmountMin = previousStep.estimate.toAmountMin\n toAmountUSD = formatTokenPrice(\n parseBigInt(toAmount),\n previousStep.action.toToken.priceUSD,\n previousStep.action.toToken.decimals\n ).toFixed(2)\n\n // Update the last included step's estimate with the adjusted values\n const lastStep = quote.includedSteps[quote.includedSteps.length - 1]\n if (lastStep && !hasNonZeroOutput(lastStep)) {\n lastStep.estimate.toAmount = toAmount\n lastStep.estimate.toAmountMin = toAmountMin\n }\n }\n }\n\n if (!quote.estimate.fromAmountUSD) {\n throw new SDKError(\n new ValidationError(\"Missing 'fromAmountUSD' in step estimate.\")\n )\n }\n\n if (!toAmountUSD) {\n throw new SDKError(\n new ValidationError(\"Missing 'toAmountUSD' in step estimate.\")\n )\n }\n\n const route: Route = {\n id: quote.id,\n fromChainId: quote.action.fromToken.chainId,\n fromToken: quote.action.fromToken,\n fromAmount: quote.action.fromAmount,\n fromAmountUSD: quote.estimate.fromAmountUSD,\n fromAddress: quote.action.fromAddress,\n toChainId: quote.action.toToken.chainId,\n toToken: quote.action.toToken,\n toAmount,\n toAmountMin,\n toAmountUSD,\n toAddress: quote.action.toAddress || quote.action.fromAddress,\n gasCostUSD: quote.estimate.gasCosts?.[0]?.amountUSD || '0',\n steps: [quote],\n insurance: { state: 'NOT_INSURABLE', feeAmountUsd: '0' },\n }\n\n return route\n}\n"],"mappings":";;;;;AAaA,MAAM,eAAe,UAAsC;CACzD,IAAI,CAAC,OACH,OAAO;CAET,IAAI;EACF,OAAO,OAAO,KAAK;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,eAAe,UAAsC;CACzD,IAAI,CAAC,OACH,OAAO;CAET,MAAM,SAAS,OAAO,KAAK;CAC3B,OAAO,OAAO,MAAM,MAAM,IAAI,IAAI;AACpC;AAEA,MAAM,gBACJ,UACA,aACA,gBACY;CACZ,OACE,CAAC,YAAY,QAAQ,KACrB,CAAC,YAAY,WAAW,KACxB,CAAC,YAAY,WAAW;AAE5B;AAEA,MAAM,oBAAoB,SAAwB;CAChD,OACE,CAAC,CAAC,YAAY,KAAK,SAAS,QAAQ,KACpC,CAAC,CAAC,YAAY,KAAK,SAAS,WAAW;AAE3C;AAEA,MAAM,2BAA2B,UAAoC;CAEnE,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;EAC1C,MAAM,OAAO,MAAM;EACnB,IAAI,iBAAiB,IAAI,GACvB,OAAO;CAEX;AAEF;AAEA,SAAgB,iBACd,QACA,OACA,UACQ;CACR,IAAI,CAAC,UAAU,CAAC,OACd,OAAO;CAGT,MAAM,kBACJ,OAAO,WAAW,YAAY,aAAa,KAAA,IACvCA,0BAAAA,YAAY,QAAQ,QAAQ,IAC5B,OAAO,SAAS;CAEtB,IAAI,OAAO,MAAM,OAAO,eAAe,CAAC,KAAK,OAAO,MAAM,OAAO,KAAK,CAAC,GACrE,OAAO;CAET,OAAO,OAAO,WAAW,eAAe,IAAI,OAAO,WAAW,KAAK;AACrE;;;;;;;;AASA,MAAa,uBACX,OACA,YACU;CACV,IAAI,WAAW,MAAM,SAAS;CAC9B,IAAI,cAAc,MAAM,SAAS;CACjC,IAAI,cAAc,MAAM,SAAS;CAGjC,IACE,SAAS,oCACT,MAAM,eAAe,UACrB,aAAa,UAAU,aAAa,WAAW,GAC/C;EACA,MAAM,eAAe,wBAAwB,MAAM,aAAa;EAChE,IAAI,cAAc;GAChB,WAAW,aAAa,SAAS;GACjC,cAAc,aAAa,SAAS;GACpC,cAAc,iBACZ,YAAY,QAAQ,GACpB,aAAa,OAAO,QAAQ,UAC5B,aAAa,OAAO,QAAQ,QAC9B,
|
|
1
|
+
{"version":3,"file":"convertQuoteToRoute.js","names":["formatUnits","SDKError","ValidationError"],"sources":["../../../src/utils/convertQuoteToRoute.ts"],"sourcesContent":["import type { LiFiStep, Route, Step } from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport { formatUnits } from './formatUnits.js'\n\ninterface ConvertQuoteToRouteOptions {\n /**\n * When true, if the quote has zero output values (toAmount, toAmountMin, toAmountUSD),\n * use the values from the previous included step that has non-zero output.\n */\n adjustZeroOutputFromPreviousStep?: boolean\n}\n\nconst parseBigInt = (value: string | undefined): bigint => {\n if (!value) {\n return 0n\n }\n try {\n return BigInt(value)\n } catch {\n return 0n\n }\n}\n\nconst parseNumber = (value: string | undefined): number => {\n if (!value) {\n return 0\n }\n const parsed = Number(value)\n return Number.isNaN(parsed) ? 0 : parsed\n}\n\nconst isZeroOutput = (\n toAmount: string,\n toAmountMin: string,\n toAmountUSD?: string\n): boolean => {\n return (\n !parseBigInt(toAmount) &&\n !parseBigInt(toAmountMin) &&\n !parseNumber(toAmountUSD)\n )\n}\n\nconst hasNonZeroOutput = (step: Step): boolean => {\n return (\n !!parseBigInt(step.estimate.toAmount) ||\n !!parseBigInt(step.estimate.toAmountMin)\n )\n}\n\nconst findPreviousNonZeroStep = (steps: Step[]): Step | undefined => {\n // Find the last step that has non-zero output (the step before the zero output step)\n for (let i = steps.length - 1; i >= 0; i--) {\n const step = steps[i]\n if (hasNonZeroOutput(step)) {\n return step\n }\n }\n return undefined\n}\n\nexport function formatTokenPrice(\n amount?: string | bigint,\n price?: string,\n decimals?: number\n): number {\n if (!amount || !price) {\n return 0\n }\n\n const formattedAmount =\n typeof amount === 'bigint' && decimals !== undefined\n ? formatUnits(amount, decimals)\n : amount.toString()\n\n if (Number.isNaN(Number(formattedAmount)) || Number.isNaN(Number(price))) {\n return 0\n }\n return Number.parseFloat(formattedAmount) * Number.parseFloat(price)\n}\n\n/**\n * Converts a quote to Route\n * @param quote - Step returned from the quote endpoint.\n * @param options - Optional configuration for handling edge cases.\n * @returns - The route to be executed.\n * @throws {BaseError} Throws a ValidationError if the step has missing values.\n */\nexport const convertQuoteToRoute = (\n quote: LiFiStep,\n options?: ConvertQuoteToRouteOptions\n): Route => {\n let toAmount = quote.estimate.toAmount\n let toAmountMin = quote.estimate.toAmountMin\n let toAmountUSD = quote.estimate.toAmountUSD\n\n // Handle zero output values by looking at previous included step\n if (\n options?.adjustZeroOutputFromPreviousStep &&\n quote.includedSteps?.length &&\n isZeroOutput(toAmount, toAmountMin, toAmountUSD)\n ) {\n const previousStep = findPreviousNonZeroStep(quote.includedSteps)\n if (previousStep) {\n toAmount = previousStep.estimate.toAmount\n toAmountMin = previousStep.estimate.toAmountMin\n toAmountUSD = formatTokenPrice(\n parseBigInt(toAmount),\n previousStep.action.toToken.priceUSD,\n previousStep.action.toToken.decimals\n ).toFixed(2)\n\n // Update the last included step's estimate with the adjusted values\n const lastStep = quote.includedSteps[quote.includedSteps.length - 1]\n if (lastStep && !hasNonZeroOutput(lastStep)) {\n lastStep.estimate.toAmount = toAmount\n lastStep.estimate.toAmountMin = toAmountMin\n }\n }\n }\n\n if (!quote.estimate.fromAmountUSD) {\n throw new SDKError(\n new ValidationError(\"Missing 'fromAmountUSD' in step estimate.\")\n )\n }\n\n if (!toAmountUSD) {\n throw new SDKError(\n new ValidationError(\"Missing 'toAmountUSD' in step estimate.\")\n )\n }\n\n const route: Route = {\n id: quote.id,\n fromChainId: quote.action.fromToken.chainId,\n fromToken: quote.action.fromToken,\n fromAmount: quote.action.fromAmount,\n fromAmountUSD: quote.estimate.fromAmountUSD,\n fromAddress: quote.action.fromAddress,\n toChainId: quote.action.toToken.chainId,\n toToken: quote.action.toToken,\n toAmount,\n toAmountMin,\n toAmountUSD,\n toAddress: quote.action.toAddress || quote.action.fromAddress,\n gasCostUSD: quote.estimate.gasCosts?.[0]?.amountUSD || '0',\n steps: [quote],\n insurance: { state: 'NOT_INSURABLE', feeAmountUsd: '0' },\n }\n\n return route\n}\n"],"mappings":";;;;;AAaA,MAAM,eAAe,UAAsC;CACzD,IAAI,CAAC,OACH,OAAO;CAET,IAAI;EACF,OAAO,OAAO,KAAK;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,eAAe,UAAsC;CACzD,IAAI,CAAC,OACH,OAAO;CAET,MAAM,SAAS,OAAO,KAAK;CAC3B,OAAO,OAAO,MAAM,MAAM,IAAI,IAAI;AACpC;AAEA,MAAM,gBACJ,UACA,aACA,gBACY;CACZ,OACE,CAAC,YAAY,QAAQ,KACrB,CAAC,YAAY,WAAW,KACxB,CAAC,YAAY,WAAW;AAE5B;AAEA,MAAM,oBAAoB,SAAwB;CAChD,OACE,CAAC,CAAC,YAAY,KAAK,SAAS,QAAQ,KACpC,CAAC,CAAC,YAAY,KAAK,SAAS,WAAW;AAE3C;AAEA,MAAM,2BAA2B,UAAoC;CAEnE,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;EAC1C,MAAM,OAAO,MAAM;EACnB,IAAI,iBAAiB,IAAI,GACvB,OAAO;CAEX;AAEF;AAEA,SAAgB,iBACd,QACA,OACA,UACQ;CACR,IAAI,CAAC,UAAU,CAAC,OACd,OAAO;CAGT,MAAM,kBACJ,OAAO,WAAW,YAAY,aAAa,KAAA,IACvCA,0BAAAA,YAAY,QAAQ,QAAQ,IAC5B,OAAO,SAAS;CAEtB,IAAI,OAAO,MAAM,OAAO,eAAe,CAAC,KAAK,OAAO,MAAM,OAAO,KAAK,CAAC,GACrE,OAAO;CAET,OAAO,OAAO,WAAW,eAAe,IAAI,OAAO,WAAW,KAAK;AACrE;;;;;;;;AASA,MAAa,uBACX,OACA,YACU;CACV,IAAI,WAAW,MAAM,SAAS;CAC9B,IAAI,cAAc,MAAM,SAAS;CACjC,IAAI,cAAc,MAAM,SAAS;CAGjC,IACE,SAAS,oCACT,MAAM,eAAe,UACrB,aAAa,UAAU,aAAa,WAAW,GAC/C;EACA,MAAM,eAAe,wBAAwB,MAAM,aAAa;EAChE,IAAI,cAAc;GAChB,WAAW,aAAa,SAAS;GACjC,cAAc,aAAa,SAAS;GACpC,cAAc,iBACZ,YAAY,QAAQ,GACpB,aAAa,OAAO,QAAQ,UAC5B,aAAa,OAAO,QAAQ,QAC9B,CAAC,CAAC,QAAQ,CAAC;GAGX,MAAM,WAAW,MAAM,cAAc,MAAM,cAAc,SAAS;GAClE,IAAI,YAAY,CAAC,iBAAiB,QAAQ,GAAG;IAC3C,SAAS,SAAS,WAAW;IAC7B,SAAS,SAAS,cAAc;GAClC;EACF;CACF;CAEA,IAAI,CAAC,MAAM,SAAS,eAClB,MAAM,IAAIC,wBAAAA,SACR,IAAIC,sBAAAA,gBAAgB,2CAA2C,CACjE;CAGF,IAAI,CAAC,aACH,MAAM,IAAID,wBAAAA,SACR,IAAIC,sBAAAA,gBAAgB,yCAAyC,CAC/D;CAqBF,OAAO;EAjBL,IAAI,MAAM;EACV,aAAa,MAAM,OAAO,UAAU;EACpC,WAAW,MAAM,OAAO;EACxB,YAAY,MAAM,OAAO;EACzB,eAAe,MAAM,SAAS;EAC9B,aAAa,MAAM,OAAO;EAC1B,WAAW,MAAM,OAAO,QAAQ;EAChC,SAAS,MAAM,OAAO;EACtB;EACA;EACA;EACA,WAAW,MAAM,OAAO,aAAa,MAAM,OAAO;EAClD,YAAY,MAAM,SAAS,WAAW,EAAE,EAAE,aAAa;EACvD,OAAO,CAAC,KAAK;EACb,WAAW;GAAE,OAAO;GAAiB,cAAc;EAAI;CAG9C;AACb"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decode.js","names":[],"sources":["../../../src/utils/decode.ts"],"sourcesContent":["export const decodeTaskId = (taskId: string): string[] => {\n const decoded = new TextDecoder()\n .decode(\n new Uint8Array(\n taskId\n .slice(2)\n .match(/.{1,2}/g)\n ?.map((byte) => Number.parseInt(byte, 16)) ?? []\n )\n )\n .split('|')\n return decoded\n}\n"],"mappings":";;AAAA,MAAa,gBAAgB,WAA6B;CAWxD,OAVgB,IAAI,YAAY,
|
|
1
|
+
{"version":3,"file":"decode.js","names":[],"sources":["../../../src/utils/decode.ts"],"sourcesContent":["export const decodeTaskId = (taskId: string): string[] => {\n const decoded = new TextDecoder()\n .decode(\n new Uint8Array(\n taskId\n .slice(2)\n .match(/.{1,2}/g)\n ?.map((byte) => Number.parseInt(byte, 16)) ?? []\n )\n )\n .split('|')\n return decoded\n}\n"],"mappings":";;AAAA,MAAa,gBAAgB,WAA6B;CAWxD,OAVgB,IAAI,YAAY,CAAC,CAC9B,OACC,IAAI,WACF,OACG,MAAM,CAAC,CAAC,CACR,MAAM,SAAS,CAAC,EACf,KAAK,SAAS,OAAO,SAAS,MAAM,EAAE,CAAC,KAAK,CAAC,CACnD,CACF,CAAC,CACA,MAAM,GACI;AACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchTxErrorDetails.js","names":[],"sources":["../../../src/utils/fetchTxErrorDetails.ts"],"sourcesContent":["export const fetchTxErrorDetails = async (\n txHash: string,\n chainId: number\n): Promise<unknown> => {\n try {\n const response = await fetch(\n `https://api.tenderly.co/api/v1/public-contract/${chainId}/tx/${txHash}`\n )\n const reponseBody = await response.json()\n\n return reponseBody\n } catch (_) {\n return undefined\n }\n}\n"],"mappings":";;AAAA,MAAa,sBAAsB,OACjC,QACA,YACqB;CACrB,IAAI;EAMF,OAAO,OAFmB,MAHH,MACrB,kDAAkD,QAAQ,MAAM,QAClE,
|
|
1
|
+
{"version":3,"file":"fetchTxErrorDetails.js","names":[],"sources":["../../../src/utils/fetchTxErrorDetails.ts"],"sourcesContent":["export const fetchTxErrorDetails = async (\n txHash: string,\n chainId: number\n): Promise<unknown> => {\n try {\n const response = await fetch(\n `https://api.tenderly.co/api/v1/public-contract/${chainId}/tx/${txHash}`\n )\n const reponseBody = await response.json()\n\n return reponseBody\n } catch (_) {\n return undefined\n }\n}\n"],"mappings":";;AAAA,MAAa,sBAAsB,OACjC,QACA,YACqB;CACrB,IAAI;EAMF,OAAO,OAFmB,MAHH,MACrB,kDAAkD,QAAQ,MAAM,QAClE,EAAA,CACmC,KAAK;CAG1C,SAAS,GAAG;EACV;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTransactionMessage.js","names":[],"sources":["../../../src/utils/getTransactionMessage.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport type { SDKClient } from '../types/core.js'\n\nexport const getTransactionFailedMessage = async (\n client: SDKClient,\n step: LiFiStep,\n txLink?: string\n): Promise<string> => {\n const chain = await client.getChainById(step.action.toChainId)\n\n const baseString = `It appears that your transaction may not have been successful.\n However, to confirm this, please check your ${chain.name} wallet for ${step.action.toToken.symbol}.`\n return txLink\n ? `${baseString}\n You can also check the <a href=\"${txLink}\" target=\"_blank\" rel=\"nofollow noreferrer\">block explorer</a> for more information.`\n : baseString\n}\n"],"mappings":";;AAGA,MAAa,8BAA8B,OACzC,QACA,MACA,WACoB;CAGpB,MAAM,aAAa;iDAC2B,MAH1B,OAAO,aAAa,KAAK,OAAO,SAAS,
|
|
1
|
+
{"version":3,"file":"getTransactionMessage.js","names":[],"sources":["../../../src/utils/getTransactionMessage.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport type { SDKClient } from '../types/core.js'\n\nexport const getTransactionFailedMessage = async (\n client: SDKClient,\n step: LiFiStep,\n txLink?: string\n): Promise<string> => {\n const chain = await client.getChainById(step.action.toChainId)\n\n const baseString = `It appears that your transaction may not have been successful.\n However, to confirm this, please check your ${chain.name} wallet for ${step.action.toToken.symbol}.`\n return txLink\n ? `${baseString}\n You can also check the <a href=\"${txLink}\" target=\"_blank\" rel=\"nofollow noreferrer\">block explorer</a> for more information.`\n : baseString\n}\n"],"mappings":";;AAGA,MAAa,8BAA8B,OACzC,QACA,MACA,WACoB;CAGpB,MAAM,aAAa;iDAC2B,MAH1B,OAAO,aAAa,KAAK,OAAO,SAAS,EAAA,CAGT,KAAK,cAAc,KAAK,OAAO,QAAQ,OAAO;CAClG,OAAO,SACH,GAAG,WAAW;2CACuB,OAAO,wFAC5C;AACN"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isStep.js","names":["isToken"],"sources":["../../../src/utils/isStep.ts"],"sourcesContent":["import type { Action, Estimate, LiFiStep } from '@lifi/types'\nimport { isToken } from './isToken.js'\n\nconst isAction = (action: Action): action is Action => {\n const { fromChainId, fromAmount, fromToken, toChainId, toToken } = action\n\n return (\n typeof fromChainId === 'number' &&\n typeof fromAmount === 'string' &&\n fromAmount !== '' &&\n isToken(fromToken) &&\n typeof toChainId === 'number' &&\n isToken(toToken)\n )\n}\n\nconst isEstimate = (estimate: Estimate): estimate is Estimate => {\n const { fromAmount, toAmount, toAmountMin, approvalAddress } = estimate\n\n return (\n typeof fromAmount === 'string' &&\n fromAmount !== '' &&\n typeof toAmount === 'string' &&\n toAmount !== '' &&\n typeof toAmountMin === 'string' &&\n toAmountMin !== '' &&\n (typeof approvalAddress === 'string' || approvalAddress === null)\n )\n}\n\nexport const isStep = (step: LiFiStep): step is LiFiStep => {\n const { id, type, tool, action, estimate } = step\n\n return (\n typeof id === 'string' &&\n ['swap', 'cross', 'lifi'].includes(type) &&\n typeof tool === 'string' &&\n isAction(action) &&\n isEstimate(estimate)\n )\n}\n"],"mappings":";;;AAGA,MAAM,YAAY,WAAqC;CACrD,MAAM,EAAE,aAAa,YAAY,WAAW,WAAW,YAAY;CAEnE,OACE,OAAO,gBAAgB,YACvB,OAAO,eAAe,YACtB,eAAe,MACfA,sBAAAA,QAAQ,SAAS,KACjB,OAAO,cAAc,YACrBA,sBAAAA,QAAQ,OAAO;AAEnB;AAEA,MAAM,cAAc,aAA6C;CAC/D,MAAM,EAAE,YAAY,UAAU,aAAa,oBAAoB;CAE/D,OACE,OAAO,eAAe,YACtB,eAAe,MACf,OAAO,aAAa,YACpB,aAAa,MACb,OAAO,gBAAgB,YACvB,gBAAgB,OACf,OAAO,oBAAoB,YAAY,oBAAoB;AAEhE;AAEA,MAAa,UAAU,SAAqC;CAC1D,MAAM,EAAE,IAAI,MAAM,MAAM,QAAQ,aAAa;CAE7C,OACE,OAAO,OAAO,YACd;EAAC;EAAQ;EAAS;CAAM,
|
|
1
|
+
{"version":3,"file":"isStep.js","names":["isToken"],"sources":["../../../src/utils/isStep.ts"],"sourcesContent":["import type { Action, Estimate, LiFiStep } from '@lifi/types'\nimport { isToken } from './isToken.js'\n\nconst isAction = (action: Action): action is Action => {\n const { fromChainId, fromAmount, fromToken, toChainId, toToken } = action\n\n return (\n typeof fromChainId === 'number' &&\n typeof fromAmount === 'string' &&\n fromAmount !== '' &&\n isToken(fromToken) &&\n typeof toChainId === 'number' &&\n isToken(toToken)\n )\n}\n\nconst isEstimate = (estimate: Estimate): estimate is Estimate => {\n const { fromAmount, toAmount, toAmountMin, approvalAddress } = estimate\n\n return (\n typeof fromAmount === 'string' &&\n fromAmount !== '' &&\n typeof toAmount === 'string' &&\n toAmount !== '' &&\n typeof toAmountMin === 'string' &&\n toAmountMin !== '' &&\n (typeof approvalAddress === 'string' || approvalAddress === null)\n )\n}\n\nexport const isStep = (step: LiFiStep): step is LiFiStep => {\n const { id, type, tool, action, estimate } = step\n\n return (\n typeof id === 'string' &&\n ['swap', 'cross', 'lifi'].includes(type) &&\n typeof tool === 'string' &&\n isAction(action) &&\n isEstimate(estimate)\n )\n}\n"],"mappings":";;;AAGA,MAAM,YAAY,WAAqC;CACrD,MAAM,EAAE,aAAa,YAAY,WAAW,WAAW,YAAY;CAEnE,OACE,OAAO,gBAAgB,YACvB,OAAO,eAAe,YACtB,eAAe,MACfA,sBAAAA,QAAQ,SAAS,KACjB,OAAO,cAAc,YACrBA,sBAAAA,QAAQ,OAAO;AAEnB;AAEA,MAAM,cAAc,aAA6C;CAC/D,MAAM,EAAE,YAAY,UAAU,aAAa,oBAAoB;CAE/D,OACE,OAAO,eAAe,YACtB,eAAe,MACf,OAAO,aAAa,YACpB,aAAa,MACb,OAAO,gBAAgB,YACvB,gBAAgB,OACf,OAAO,oBAAoB,YAAY,oBAAoB;AAEhE;AAEA,MAAa,UAAU,SAAqC;CAC1D,MAAM,EAAE,IAAI,MAAM,MAAM,QAAQ,aAAa;CAE7C,OACE,OAAO,OAAO,YACd;EAAC;EAAQ;EAAS;CAAM,CAAC,CAAC,SAAS,IAAI,KACvC,OAAO,SAAS,YAChB,SAAS,MAAM,KACf,WAAW,QAAQ;AAEvB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withDedupe.js","names":[],"sources":["../../../src/utils/withDedupe.ts"],"sourcesContent":["/**\n * Map with a LRU (Least recently used) policy.\n *\n * https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap<value = unknown> extends Map<string, value> {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override set(key: string, value: value): this {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n this.delete(this.keys().next().value!)\n }\n return this\n }\n}\n\n/** @internal */\nconst promiseCache = /*#__PURE__*/ new LruMap<Promise<any>>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe<T>(\n fn: () => Promise<T>,\n { enabled = true, id }: WithDedupeOptions\n): Promise<T> {\n if (!enabled || !id) {\n return fn()\n }\n if (promiseCache.get(id)) {\n return promiseCache.get(id)!\n }\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n"],"mappings":";;;;;;;AAKA,IAAa,SAAb,cAA6C,IAAmB;CAC9D;CAEA,YAAY,MAAc;EACxB,MAAM;EACN,KAAK,UAAU;CACjB;CAEA,IAAa,KAAa,OAAoB;EAC5C,MAAM,IAAI,KAAK,KAAK;EACpB,IAAI,KAAK,WAAW,KAAK,OAAO,KAAK,SACnC,KAAK,OAAO,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"withDedupe.js","names":[],"sources":["../../../src/utils/withDedupe.ts"],"sourcesContent":["/**\n * Map with a LRU (Least recently used) policy.\n *\n * https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap<value = unknown> extends Map<string, value> {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override set(key: string, value: value): this {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n this.delete(this.keys().next().value!)\n }\n return this\n }\n}\n\n/** @internal */\nconst promiseCache = /*#__PURE__*/ new LruMap<Promise<any>>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe<T>(\n fn: () => Promise<T>,\n { enabled = true, id }: WithDedupeOptions\n): Promise<T> {\n if (!enabled || !id) {\n return fn()\n }\n if (promiseCache.get(id)) {\n return promiseCache.get(id)!\n }\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n"],"mappings":";;;;;;;AAKA,IAAa,SAAb,cAA6C,IAAmB;CAC9D;CAEA,YAAY,MAAc;EACxB,MAAM;EACN,KAAK,UAAU;CACjB;CAEA,IAAa,KAAa,OAAoB;EAC5C,MAAM,IAAI,KAAK,KAAK;EACpB,IAAI,KAAK,WAAW,KAAK,OAAO,KAAK,SACnC,KAAK,OAAO,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAM;EAEvC,OAAO;CACT;AACF;;AAGA,MAAM,6BAA6B,IAAI,OAAqB,IAAI;;AAQhE,SAAgB,WACd,IACA,EAAE,UAAU,MAAM,MACN;CACZ,IAAI,CAAC,WAAW,CAAC,IACf,OAAO,GAAG;CAEZ,IAAI,aAAa,IAAI,EAAE,GACrB,OAAO,aAAa,IAAI,EAAE;CAE5B,MAAM,UAAU,GAAG,CAAC,CAAC,cAAc,aAAa,OAAO,EAAE,CAAC;CAC1D,aAAa,IAAI,IAAI,OAAO;CAC5B,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withTimeout.js","names":[],"sources":["../../../src/utils/withTimeout.ts"],"sourcesContent":["/**\n * Wraps a function in a timeout.\n * Based on viem's withTimeout implementation.\n * @param fn - The function to wrap.\n * @param timeout - The timeout in milliseconds.\n * @param errorInstance - The error instance to throw when the timeout is reached.\n * @param signal - Whether or not the timeout should use an abort signal.\n * @returns The result of the function.\n */\nexport function withTimeout<T>(\n fn: ({ signal }: { signal: AbortController['signal'] | null }) => Promise<T>,\n {\n errorInstance = new Error('Timed out after waiting for too long.'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n }\n): Promise<T> {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') {\n reject(errorInstance)\n }\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n"],"mappings":";;;;;;;;;;;AASA,SAAgB,YACd,IACA,EACE,gCAAgB,IAAI,MAAM,uCAAuC,GACjE,SACA,UASU;CACZ,OAAO,IAAI,SAAS,SAAS,WAAW;EACrC,CAAC,YAAY;GACZ,IAAI;GACJ,IAAI;IACF,MAAM,aAAa,IAAI,gBAAgB;IACvC,IAAI,UAAU,GACZ,YAAY,iBAAiB;KAC3B,IAAI,QACF,WAAW,MAAM;UAEjB,OAAO,aAAa;IAExB,GAAG,OAAO;IAEZ,QAAQ,MAAM,GAAG,EAAE,QAAQ,YAAY,UAAU,KAAK,CAAC,CAAC;GAC1D,SAAS,KAAK;IACZ,IAAK,KAAe,SAAS,cAC3B,OAAO,aAAa;IAEtB,OAAO,GAAG;GACZ,UAAU;IACR,aAAa,SAAS;GACxB;EACF,
|
|
1
|
+
{"version":3,"file":"withTimeout.js","names":[],"sources":["../../../src/utils/withTimeout.ts"],"sourcesContent":["/**\n * Wraps a function in a timeout.\n * Based on viem's withTimeout implementation.\n * @param fn - The function to wrap.\n * @param timeout - The timeout in milliseconds.\n * @param errorInstance - The error instance to throw when the timeout is reached.\n * @param signal - Whether or not the timeout should use an abort signal.\n * @returns The result of the function.\n */\nexport function withTimeout<T>(\n fn: ({ signal }: { signal: AbortController['signal'] | null }) => Promise<T>,\n {\n errorInstance = new Error('Timed out after waiting for too long.'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n }\n): Promise<T> {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') {\n reject(errorInstance)\n }\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n"],"mappings":";;;;;;;;;;;AASA,SAAgB,YACd,IACA,EACE,gCAAgB,IAAI,MAAM,uCAAuC,GACjE,SACA,UASU;CACZ,OAAO,IAAI,SAAS,SAAS,WAAW;EACrC,CAAC,YAAY;GACZ,IAAI;GACJ,IAAI;IACF,MAAM,aAAa,IAAI,gBAAgB;IACvC,IAAI,UAAU,GACZ,YAAY,iBAAiB;KAC3B,IAAI,QACF,WAAW,MAAM;UAEjB,OAAO,aAAa;IAExB,GAAG,OAAO;IAEZ,QAAQ,MAAM,GAAG,EAAE,QAAQ,YAAY,UAAU,KAAK,CAAC,CAAC;GAC1D,SAAS,KAAK;IACZ,IAAK,KAAe,SAAS,cAC3B,OAAO,aAAa;IAEtB,OAAO,GAAG;GACZ,UAAU;IACR,aAAa,SAAS;GACxB;EACF,EAAA,CAAG;CACL,CAAC;AACH"}
|
package/dist/cjs/version.d.ts
CHANGED
package/dist/cjs/version.js
CHANGED
package/dist/cjs/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk'\nexport const version = '4.0.
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk'\nexport const version = '4.0.1'\n"],"mappings":";;AAAA,MAAa,OAAO;AACpB,MAAa,UAAU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getChains.js","names":[],"sources":["../../../src/actions/getChains.ts"],"sourcesContent":["import type {\n ChainsRequest,\n ChainsResponse,\n ExtendedChain,\n RequestOptions,\n} from '@lifi/types'\nimport type { SDKBaseConfig, SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\nimport { withDedupe } from '../utils/withDedupe.js'\n\n/**\n * Get all available chains\n * @param client - The SDK client\n * @param params - The configuration of the requested chains\n * @param options - Request options\n * @returns A list of all available chains\n * @throws {LiFiError} Throws a LiFiError if request fails.\n */\nexport const getChains = async (\n client: SDKClient,\n params?: ChainsRequest,\n options?: RequestOptions\n): Promise<ExtendedChain[]> => {\n return await _getChains(client.config, params, options)\n}\n\nexport const _getChains = async (\n config: SDKBaseConfig,\n params?: ChainsRequest,\n options?: RequestOptions\n): Promise<ExtendedChain[]> => {\n if (params) {\n for (const key of Object.keys(params)) {\n const value = params[key as keyof ChainsRequest]\n if (value === undefined || value === null) {\n delete params[key as keyof ChainsRequest]\n }\n }\n }\n const urlSearchParams = new URLSearchParams(\n params as Record<string, string>\n ).toString()\n const response = await withDedupe(\n () =>\n request<ChainsResponse>(\n config,\n `${config.apiUrl}/chains?${urlSearchParams}`,\n {\n signal: options?.signal,\n }\n ),\n { id: `${getChains.name}.${urlSearchParams}` }\n )\n return response.chains\n}\n"],"mappings":";;;;;;;;;;;AAkBA,MAAa,YAAY,OACvB,QACA,QACA,YAC6B;CAC7B,OAAO,MAAM,WAAW,OAAO,QAAQ,QAAQ,OAAO;AACxD;AAEA,MAAa,aAAa,OACxB,QACA,QACA,YAC6B;CAC7B,IAAI,QACF,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;EACrC,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO,OAAO;CAElB;CAEF,MAAM,kBAAkB,IAAI,gBAC1B,MACF,
|
|
1
|
+
{"version":3,"file":"getChains.js","names":[],"sources":["../../../src/actions/getChains.ts"],"sourcesContent":["import type {\n ChainsRequest,\n ChainsResponse,\n ExtendedChain,\n RequestOptions,\n} from '@lifi/types'\nimport type { SDKBaseConfig, SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\nimport { withDedupe } from '../utils/withDedupe.js'\n\n/**\n * Get all available chains\n * @param client - The SDK client\n * @param params - The configuration of the requested chains\n * @param options - Request options\n * @returns A list of all available chains\n * @throws {LiFiError} Throws a LiFiError if request fails.\n */\nexport const getChains = async (\n client: SDKClient,\n params?: ChainsRequest,\n options?: RequestOptions\n): Promise<ExtendedChain[]> => {\n return await _getChains(client.config, params, options)\n}\n\nexport const _getChains = async (\n config: SDKBaseConfig,\n params?: ChainsRequest,\n options?: RequestOptions\n): Promise<ExtendedChain[]> => {\n if (params) {\n for (const key of Object.keys(params)) {\n const value = params[key as keyof ChainsRequest]\n if (value === undefined || value === null) {\n delete params[key as keyof ChainsRequest]\n }\n }\n }\n const urlSearchParams = new URLSearchParams(\n params as Record<string, string>\n ).toString()\n const response = await withDedupe(\n () =>\n request<ChainsResponse>(\n config,\n `${config.apiUrl}/chains?${urlSearchParams}`,\n {\n signal: options?.signal,\n }\n ),\n { id: `${getChains.name}.${urlSearchParams}` }\n )\n return response.chains\n}\n"],"mappings":";;;;;;;;;;;AAkBA,MAAa,YAAY,OACvB,QACA,QACA,YAC6B;CAC7B,OAAO,MAAM,WAAW,OAAO,QAAQ,QAAQ,OAAO;AACxD;AAEA,MAAa,aAAa,OACxB,QACA,QACA,YAC6B;CAC7B,IAAI,QACF,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;EACrC,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO,OAAO;CAElB;CAEF,MAAM,kBAAkB,IAAI,gBAC1B,MACF,CAAC,CAAC,SAAS;CAYX,QAAO,MAXgB,iBAEnB,QACE,QACA,GAAG,OAAO,OAAO,UAAU,mBAC3B,EACE,QAAQ,SAAS,OACnB,CACF,GACF,EAAE,IAAI,GAAG,UAAU,KAAK,GAAG,kBAAkB,CAC/C,EAAA,CACgB;AAClB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getRelayedTransactionStatus.js","names":[],"sources":["../../../src/actions/getRelayedTransactionStatus.ts"],"sourcesContent":["import type {\n RelayStatusRequest,\n RelayStatusResponse,\n RelayStatusResponseData,\n RequestOptions,\n} from '@lifi/types'\nimport { BaseError } from '../errors/baseError.js'\nimport { ErrorName } from '../errors/constants.js'\nimport { ValidationError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport type { SDKClient } from '../types/core.js'\nimport { decodeTaskId } from '../utils/decode.js'\nimport { request } from '../utils/request.js'\nimport { getStatus } from './getStatus.js'\n\n/**\n * Get the status of a relayed transaction\n * @param client - The SDK client\n * @param params - Parameters for the relay status request\n * @param options - Request options\n * @throws {LiFiError} - Throws a LiFiError if request fails\n * @returns Status of the relayed transaction\n */\nexport const getRelayedTransactionStatus = async (\n client: SDKClient,\n params: RelayStatusRequest,\n options?: RequestOptions\n): Promise<RelayStatusResponseData> => {\n if (!params.taskId) {\n throw new SDKError(\n new ValidationError('Required parameter \"taskId\" is missing.')\n )\n }\n\n const { taskId, ...otherParams } = params\n const queryParams = new URLSearchParams(\n otherParams as unknown as Record<string, string>\n )\n\n const decodedTaskId = decodeTaskId(taskId)\n // Temporary solution during the transition between status endpoints\n if (decodedTaskId.length >= 3) {\n return (await getStatus(\n client,\n params,\n options\n )) as unknown as RelayStatusResponseData\n }\n\n const result = await request<RelayStatusResponse>(\n client.config,\n `${client.config.apiUrl}/relayer/status/${taskId}?${queryParams}`,\n {\n signal: options?.signal,\n }\n )\n\n if (result.status === 'error') {\n throw new BaseError(\n ErrorName.ServerError,\n result.data.code,\n result.data.message\n )\n }\n\n return result.data\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAa,8BAA8B,OACzC,QACA,QACA,YACqC;CACrC,IAAI,CAAC,OAAO,QACV,MAAM,IAAI,SACR,IAAI,gBAAgB,2CAAyC,CAC/D;CAGF,MAAM,EAAE,QAAQ,GAAG,gBAAgB;CACnC,MAAM,cAAc,IAAI,gBACtB,WACF;CAIA,IAFsB,aAAa,MAEnB,
|
|
1
|
+
{"version":3,"file":"getRelayedTransactionStatus.js","names":[],"sources":["../../../src/actions/getRelayedTransactionStatus.ts"],"sourcesContent":["import type {\n RelayStatusRequest,\n RelayStatusResponse,\n RelayStatusResponseData,\n RequestOptions,\n} from '@lifi/types'\nimport { BaseError } from '../errors/baseError.js'\nimport { ErrorName } from '../errors/constants.js'\nimport { ValidationError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport type { SDKClient } from '../types/core.js'\nimport { decodeTaskId } from '../utils/decode.js'\nimport { request } from '../utils/request.js'\nimport { getStatus } from './getStatus.js'\n\n/**\n * Get the status of a relayed transaction\n * @param client - The SDK client\n * @param params - Parameters for the relay status request\n * @param options - Request options\n * @throws {LiFiError} - Throws a LiFiError if request fails\n * @returns Status of the relayed transaction\n */\nexport const getRelayedTransactionStatus = async (\n client: SDKClient,\n params: RelayStatusRequest,\n options?: RequestOptions\n): Promise<RelayStatusResponseData> => {\n if (!params.taskId) {\n throw new SDKError(\n new ValidationError('Required parameter \"taskId\" is missing.')\n )\n }\n\n const { taskId, ...otherParams } = params\n const queryParams = new URLSearchParams(\n otherParams as unknown as Record<string, string>\n )\n\n const decodedTaskId = decodeTaskId(taskId)\n // Temporary solution during the transition between status endpoints\n if (decodedTaskId.length >= 3) {\n return (await getStatus(\n client,\n params,\n options\n )) as unknown as RelayStatusResponseData\n }\n\n const result = await request<RelayStatusResponse>(\n client.config,\n `${client.config.apiUrl}/relayer/status/${taskId}?${queryParams}`,\n {\n signal: options?.signal,\n }\n )\n\n if (result.status === 'error') {\n throw new BaseError(\n ErrorName.ServerError,\n result.data.code,\n result.data.message\n )\n }\n\n return result.data\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,MAAa,8BAA8B,OACzC,QACA,QACA,YACqC;CACrC,IAAI,CAAC,OAAO,QACV,MAAM,IAAI,SACR,IAAI,gBAAgB,2CAAyC,CAC/D;CAGF,MAAM,EAAE,QAAQ,GAAG,gBAAgB;CACnC,MAAM,cAAc,IAAI,gBACtB,WACF;CAIA,IAFsB,aAAa,MAEnB,CAAC,CAAC,UAAU,GAC1B,OAAQ,MAAM,UACZ,QACA,QACA,OACF;CAGF,MAAM,SAAS,MAAM,QACnB,OAAO,QACP,GAAG,OAAO,OAAO,OAAO,kBAAkB,OAAO,GAAG,eACpD,EACE,QAAQ,SAAS,OACnB,CACF;CAEA,IAAI,OAAO,WAAW,SACpB,MAAM,IAAI,UAAA,eAER,OAAO,KAAK,MACZ,OAAO,KAAK,OACd;CAGF,OAAO,OAAO;AAChB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTokenBalances.js","names":[],"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,MAAM,wBAChC,QACA,eAboB,OAAO,QAC1B,QAAQ,UAAU;EACjB,IAAI,CAAC,OAAO,MAAM,UAChB,OAAO,MAAM,WAAW,CAAC;EAE3B,OAAO,MAAM,
|
|
1
|
+
{"version":3,"file":"getTokenBalances.js","names":[],"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,MAAM,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTokenBalancesByChain.js","names":[],"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,IAAI,gBAAgB,wBAAwB;CAKpD,IAFkB,OAAO,OAAO,aAAa,
|
|
1
|
+
{"version":3,"file":"getTokenBalancesByChain.js","names":[],"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,IAAI,gBAAgB,wBAAwB;CAKpD,IAFkB,OAAO,OAAO,aAAa,CAAC,CAAC,KACjB,CAAC,CAAC,QAAQ,UAAU,CAAC,QAAQ,KAAK,CAChD,CAAC,CAAC,QAChB,MAAM,IAAI,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,WAM1B,oBAAoB,WAAW,MALJ,SAAS,WAClC,QACA,eACA,cAAc,QAChB;OAKA,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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTokens.js","names":[],"sources":["../../../src/actions/getTokens.ts"],"sourcesContent":["import type {\n RequestOptions,\n TokensExtendedResponse,\n TokensRequest,\n TokensResponse,\n} from '@lifi/types'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\nimport { withDedupe } from '../utils/withDedupe.js'\n\n/**\n * Get all known tokens.\n * @param client - The SDK client\n * @param params - The configuration of the requested tokens\n * @param options - Request options\n * @returns The tokens that are available on the requested chains\n */\nexport async function getTokens(\n client: SDKClient,\n params?: TokensRequest & { extended?: false | undefined },\n options?: RequestOptions\n): Promise<TokensResponse>\nexport async function getTokens(\n client: SDKClient,\n params: TokensRequest & { extended: true },\n options?: RequestOptions\n): Promise<TokensExtendedResponse>\nexport async function getTokens(\n client: SDKClient,\n params?: TokensRequest,\n options?: RequestOptions\n): Promise<TokensResponse> {\n if (params) {\n for (const key of Object.keys(params)) {\n const value = params[key as keyof TokensRequest]\n if (value === undefined || value === null) {\n delete params[key as keyof TokensRequest]\n }\n }\n }\n const urlSearchParams = new URLSearchParams(\n params as Record<string, string>\n ).toString()\n const _isExtended = params?.extended === true\n const response = await withDedupe(\n () =>\n request<\n typeof _isExtended extends true\n ? TokensExtendedResponse\n : TokensResponse\n >(client.config, `${client.config.apiUrl}/tokens?${urlSearchParams}`, {\n signal: options?.signal,\n }),\n { id: `${getTokens.name}.${urlSearchParams}` }\n )\n return response\n}\n"],"mappings":";;;AA2BA,eAAsB,UACpB,QACA,QACA,SACyB;CACzB,IAAI,QACF,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;EACrC,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO,OAAO;CAElB;CAEF,MAAM,kBAAkB,IAAI,gBAC1B,MACF,
|
|
1
|
+
{"version":3,"file":"getTokens.js","names":[],"sources":["../../../src/actions/getTokens.ts"],"sourcesContent":["import type {\n RequestOptions,\n TokensExtendedResponse,\n TokensRequest,\n TokensResponse,\n} from '@lifi/types'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\nimport { withDedupe } from '../utils/withDedupe.js'\n\n/**\n * Get all known tokens.\n * @param client - The SDK client\n * @param params - The configuration of the requested tokens\n * @param options - Request options\n * @returns The tokens that are available on the requested chains\n */\nexport async function getTokens(\n client: SDKClient,\n params?: TokensRequest & { extended?: false | undefined },\n options?: RequestOptions\n): Promise<TokensResponse>\nexport async function getTokens(\n client: SDKClient,\n params: TokensRequest & { extended: true },\n options?: RequestOptions\n): Promise<TokensExtendedResponse>\nexport async function getTokens(\n client: SDKClient,\n params?: TokensRequest,\n options?: RequestOptions\n): Promise<TokensResponse> {\n if (params) {\n for (const key of Object.keys(params)) {\n const value = params[key as keyof TokensRequest]\n if (value === undefined || value === null) {\n delete params[key as keyof TokensRequest]\n }\n }\n }\n const urlSearchParams = new URLSearchParams(\n params as Record<string, string>\n ).toString()\n const _isExtended = params?.extended === true\n const response = await withDedupe(\n () =>\n request<\n typeof _isExtended extends true\n ? TokensExtendedResponse\n : TokensResponse\n >(client.config, `${client.config.apiUrl}/tokens?${urlSearchParams}`, {\n signal: options?.signal,\n }),\n { id: `${getTokens.name}.${urlSearchParams}` }\n )\n return response\n}\n"],"mappings":";;;AA2BA,eAAsB,UACpB,QACA,QACA,SACyB;CACzB,IAAI,QACF,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAAG;EACrC,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,KAAa,UAAU,MACnC,OAAO,OAAO;CAElB;CAEF,MAAM,kBAAkB,IAAI,gBAC1B,MACF,CAAC,CAAC,SAAS;CACS,QAAQ;CAY5B,OAAO,MAXgB,iBAEnB,QAIE,OAAO,QAAQ,GAAG,OAAO,OAAO,OAAO,UAAU,mBAAmB,EACpE,QAAQ,SAAS,OACnB,CAAC,GACH,EAAE,IAAI,GAAG,UAAU,KAAK,GAAG,kBAAkB,CAC/C;AAEF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getWalletBalances.js","names":[],"sources":["../../../src/actions/getWalletBalances.ts"],"sourcesContent":["import type {\n GetWalletBalanceExtendedResponse,\n RequestOptions,\n WalletTokenExtended,\n} from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\n\n/**\n * Returns the balances of tokens a wallet holds across EVM chains.\n * @param client - The SDK client.\n * @param walletAddress - A wallet address.\n * @param options - Optional request options.\n * @returns An object containing the tokens and the amounts organized by chain ids.\n * @throws {ValidationError} Throws a ValidationError if parameters are invalid.\n */\nexport const getWalletBalances = async (\n client: SDKClient,\n walletAddress: string,\n options?: RequestOptions\n): Promise<Record<number, WalletTokenExtended[]>> => {\n if (!walletAddress) {\n throw new ValidationError('Missing walletAddress.')\n }\n\n const response = await request<GetWalletBalanceExtendedResponse>(\n client.config,\n `${client.config.apiUrl}/wallets/${walletAddress}/balances?extended=true`,\n {\n signal: options?.signal,\n }\n )\n\n return (response?.balances || {}) as Record<number, WalletTokenExtended[]>\n}\n"],"mappings":";;;;;;;;;;;AAiBA,MAAa,oBAAoB,OAC/B,QACA,eACA,YACmD;CACnD,IAAI,CAAC,eACH,MAAM,IAAI,gBAAgB,wBAAwB;CAWpD,QAAQ,MARe,QACrB,OAAO,QACP,GAAG,OAAO,OAAO,OAAO,WAAW,cAAc,0BACjD,EACE,QAAQ,SAAS,OACnB,CACF,
|
|
1
|
+
{"version":3,"file":"getWalletBalances.js","names":[],"sources":["../../../src/actions/getWalletBalances.ts"],"sourcesContent":["import type {\n GetWalletBalanceExtendedResponse,\n RequestOptions,\n WalletTokenExtended,\n} from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\n\n/**\n * Returns the balances of tokens a wallet holds across EVM chains.\n * @param client - The SDK client.\n * @param walletAddress - A wallet address.\n * @param options - Optional request options.\n * @returns An object containing the tokens and the amounts organized by chain ids.\n * @throws {ValidationError} Throws a ValidationError if parameters are invalid.\n */\nexport const getWalletBalances = async (\n client: SDKClient,\n walletAddress: string,\n options?: RequestOptions\n): Promise<Record<number, WalletTokenExtended[]>> => {\n if (!walletAddress) {\n throw new ValidationError('Missing walletAddress.')\n }\n\n const response = await request<GetWalletBalanceExtendedResponse>(\n client.config,\n `${client.config.apiUrl}/wallets/${walletAddress}/balances?extended=true`,\n {\n signal: options?.signal,\n }\n )\n\n return (response?.balances || {}) as Record<number, WalletTokenExtended[]>\n}\n"],"mappings":";;;;;;;;;;;AAiBA,MAAa,oBAAoB,OAC/B,QACA,eACA,YACmD;CACnD,IAAI,CAAC,eACH,MAAM,IAAI,gBAAgB,wBAAwB;CAWpD,QAAQ,MARe,QACrB,OAAO,QACP,GAAG,OAAO,OAAO,OAAO,WAAW,cAAc,0BACjD,EACE,QAAQ,SAAS,OACnB,CACF,EAAA,EAEkB,YAAY,CAAC;AACjC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createClient.js","names":[],"sources":["../../../src/client/createClient.ts"],"sourcesContent":["import type { ChainId, ChainType, ExtendedChain } from '@lifi/types'\nimport type {\n SDKBaseConfig,\n SDKClient,\n SDKConfig,\n SDKProvider,\n} from '../types/core.js'\nimport { checkPackageUpdates } from '../utils/checkPackageUpdates.js'\nimport { name, version } from '../version.js'\nimport { getClientStorage } from './getClientStorage.js'\n\nexport function createClient(options: SDKConfig): SDKClient {\n if (!options.integrator) {\n throw new Error(\n 'Integrator not found. Please see documentation https://docs.li.fi/integrate-li.fi-js-sdk/set-up-the-sdk'\n )\n }\n\n if (!options.disableVersionCheck && process.env.NODE_ENV === 'development') {\n checkPackageUpdates(name, version)\n }\n\n const { providers, ...configOptions } = options\n\n const _config: SDKBaseConfig = {\n ...configOptions,\n apiUrl: configOptions?.apiUrl ?? 'https://li.quest/v1',\n rpcUrls: configOptions?.rpcUrls ?? {},\n debug: configOptions?.debug ?? false,\n preloadChains: configOptions?.preloadChains ?? true,\n integrator: configOptions?.integrator ?? 'lifi-sdk',\n }\n\n let _providers: SDKProvider[] = providers ?? []\n const _storage = getClientStorage(_config)\n\n const client: SDKClient = {\n get config() {\n return _config\n },\n get providers() {\n return _providers\n },\n getProvider(type: ChainType) {\n return this.providers.find((provider) => provider.type === type)\n },\n setProviders(newProviders: SDKProvider[]) {\n const providerMap = new Map(\n this.providers.map((provider) => [provider.type, provider])\n )\n for (const provider of newProviders) {\n providerMap.set(provider.type, provider)\n }\n _providers = Array.from(providerMap.values())\n },\n setChains(chains: ExtendedChain[]) {\n _storage.setChains(chains)\n },\n async getChains() {\n return await _storage.getChains()\n },\n async getChainById(chainId: ChainId) {\n const chains = await this.getChains()\n const chain = chains?.find((chain) => chain.id === chainId)\n if (!chain) {\n throw new Error(`ChainId ${chainId} not found`)\n }\n return chain\n },\n async getRpcUrls() {\n return await _storage.getRpcUrls()\n },\n async getRpcUrlsByChainId(chainId: ChainId) {\n const rpcUrls = await this.getRpcUrls()\n const chainRpcUrls = rpcUrls[chainId]\n if (!chainRpcUrls?.length) {\n throw new Error(`RPC URL not found for chainId: ${chainId}`)\n }\n return chainRpcUrls\n },\n }\n\n function extend<TClient extends SDKClient>(\n base: TClient\n ): <TExtensions extends Record<string, any>>(\n extendFn: (client: TClient) => TExtensions\n ) => TClient & TExtensions {\n return (extendFn) => {\n const extensions = extendFn(base)\n const extended = { ...base, ...extensions } as TClient & typeof extensions\n\n // Preserve the extend function for further extensions\n return Object.assign(extended, {\n extend: extend(extended),\n })\n }\n }\n\n return Object.assign(client, { extend: extend(client) })\n}\n"],"mappings":";;;;AAWA,SAAgB,aAAa,SAA+B;CAC1D,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,yGACF;CAGF,IAAI,CAAC,QAAQ,uBAAuB,QAAQ,IAAI,aAAa,eAC3D,oBAAoB,MAAM,OAAO;CAGnC,MAAM,EAAE,WAAW,GAAG,kBAAkB;CAExC,MAAM,UAAyB;EAC7B,GAAG;EACH,QAAQ,eAAe,UAAU;EACjC,SAAS,eAAe,WAAW,CAAC;EACpC,OAAO,eAAe,SAAS;EAC/B,eAAe,eAAe,iBAAiB;EAC/C,YAAY,eAAe,cAAc;CAC3C;CAEA,IAAI,aAA4B,aAAa,CAAC;CAC9C,MAAM,WAAW,iBAAiB,OAAO;CAEzC,MAAM,SAAoB;EACxB,IAAI,SAAS;GACX,OAAO;EACT;EACA,IAAI,YAAY;GACd,OAAO;EACT;EACA,YAAY,MAAiB;GAC3B,OAAO,KAAK,UAAU,MAAM,aAAa,SAAS,SAAS,IAAI;EACjE;EACA,aAAa,cAA6B;GACxC,MAAM,cAAc,IAAI,IACtB,KAAK,UAAU,KAAK,aAAa,CAAC,SAAS,MAAM,QAAQ,CAAC,CAC5D;GACA,KAAK,MAAM,YAAY,cACrB,YAAY,IAAI,SAAS,MAAM,QAAQ;GAEzC,aAAa,MAAM,KAAK,YAAY,OAAO,CAAC;EAC9C;EACA,UAAU,QAAyB;GACjC,SAAS,UAAU,MAAM;EAC3B;EACA,MAAM,YAAY;GAChB,OAAO,MAAM,SAAS,UAAU;EAClC;EACA,MAAM,aAAa,SAAkB;GAEnC,MAAM,SAAQ,MADO,KAAK,UAAU,
|
|
1
|
+
{"version":3,"file":"createClient.js","names":[],"sources":["../../../src/client/createClient.ts"],"sourcesContent":["import type { ChainId, ChainType, ExtendedChain } from '@lifi/types'\nimport type {\n SDKBaseConfig,\n SDKClient,\n SDKConfig,\n SDKProvider,\n} from '../types/core.js'\nimport { checkPackageUpdates } from '../utils/checkPackageUpdates.js'\nimport { name, version } from '../version.js'\nimport { getClientStorage } from './getClientStorage.js'\n\nexport function createClient(options: SDKConfig): SDKClient {\n if (!options.integrator) {\n throw new Error(\n 'Integrator not found. Please see documentation https://docs.li.fi/integrate-li.fi-js-sdk/set-up-the-sdk'\n )\n }\n\n if (!options.disableVersionCheck && process.env.NODE_ENV === 'development') {\n checkPackageUpdates(name, version)\n }\n\n const { providers, ...configOptions } = options\n\n const _config: SDKBaseConfig = {\n ...configOptions,\n apiUrl: configOptions?.apiUrl ?? 'https://li.quest/v1',\n rpcUrls: configOptions?.rpcUrls ?? {},\n debug: configOptions?.debug ?? false,\n preloadChains: configOptions?.preloadChains ?? true,\n integrator: configOptions?.integrator ?? 'lifi-sdk',\n }\n\n let _providers: SDKProvider[] = providers ?? []\n const _storage = getClientStorage(_config)\n\n const client: SDKClient = {\n get config() {\n return _config\n },\n get providers() {\n return _providers\n },\n getProvider(type: ChainType) {\n return this.providers.find((provider) => provider.type === type)\n },\n setProviders(newProviders: SDKProvider[]) {\n const providerMap = new Map(\n this.providers.map((provider) => [provider.type, provider])\n )\n for (const provider of newProviders) {\n providerMap.set(provider.type, provider)\n }\n _providers = Array.from(providerMap.values())\n },\n setChains(chains: ExtendedChain[]) {\n _storage.setChains(chains)\n },\n async getChains() {\n return await _storage.getChains()\n },\n async getChainById(chainId: ChainId) {\n const chains = await this.getChains()\n const chain = chains?.find((chain) => chain.id === chainId)\n if (!chain) {\n throw new Error(`ChainId ${chainId} not found`)\n }\n return chain\n },\n async getRpcUrls() {\n return await _storage.getRpcUrls()\n },\n async getRpcUrlsByChainId(chainId: ChainId) {\n const rpcUrls = await this.getRpcUrls()\n const chainRpcUrls = rpcUrls[chainId]\n if (!chainRpcUrls?.length) {\n throw new Error(`RPC URL not found for chainId: ${chainId}`)\n }\n return chainRpcUrls\n },\n }\n\n function extend<TClient extends SDKClient>(\n base: TClient\n ): <TExtensions extends Record<string, any>>(\n extendFn: (client: TClient) => TExtensions\n ) => TClient & TExtensions {\n return (extendFn) => {\n const extensions = extendFn(base)\n const extended = { ...base, ...extensions } as TClient & typeof extensions\n\n // Preserve the extend function for further extensions\n return Object.assign(extended, {\n extend: extend(extended),\n })\n }\n }\n\n return Object.assign(client, { extend: extend(client) })\n}\n"],"mappings":";;;;AAWA,SAAgB,aAAa,SAA+B;CAC1D,IAAI,CAAC,QAAQ,YACX,MAAM,IAAI,MACR,yGACF;CAGF,IAAI,CAAC,QAAQ,uBAAuB,QAAQ,IAAI,aAAa,eAC3D,oBAAoB,MAAM,OAAO;CAGnC,MAAM,EAAE,WAAW,GAAG,kBAAkB;CAExC,MAAM,UAAyB;EAC7B,GAAG;EACH,QAAQ,eAAe,UAAU;EACjC,SAAS,eAAe,WAAW,CAAC;EACpC,OAAO,eAAe,SAAS;EAC/B,eAAe,eAAe,iBAAiB;EAC/C,YAAY,eAAe,cAAc;CAC3C;CAEA,IAAI,aAA4B,aAAa,CAAC;CAC9C,MAAM,WAAW,iBAAiB,OAAO;CAEzC,MAAM,SAAoB;EACxB,IAAI,SAAS;GACX,OAAO;EACT;EACA,IAAI,YAAY;GACd,OAAO;EACT;EACA,YAAY,MAAiB;GAC3B,OAAO,KAAK,UAAU,MAAM,aAAa,SAAS,SAAS,IAAI;EACjE;EACA,aAAa,cAA6B;GACxC,MAAM,cAAc,IAAI,IACtB,KAAK,UAAU,KAAK,aAAa,CAAC,SAAS,MAAM,QAAQ,CAAC,CAC5D;GACA,KAAK,MAAM,YAAY,cACrB,YAAY,IAAI,SAAS,MAAM,QAAQ;GAEzC,aAAa,MAAM,KAAK,YAAY,OAAO,CAAC;EAC9C;EACA,UAAU,QAAyB;GACjC,SAAS,UAAU,MAAM;EAC3B;EACA,MAAM,YAAY;GAChB,OAAO,MAAM,SAAS,UAAU;EAClC;EACA,MAAM,aAAa,SAAkB;GAEnC,MAAM,SAAQ,MADO,KAAK,UAAU,EAAA,EACd,MAAM,UAAU,MAAM,OAAO,OAAO;GAC1D,IAAI,CAAC,OACH,MAAM,IAAI,MAAM,WAAW,QAAQ,WAAW;GAEhD,OAAO;EACT;EACA,MAAM,aAAa;GACjB,OAAO,MAAM,SAAS,WAAW;EACnC;EACA,MAAM,oBAAoB,SAAkB;GAE1C,MAAM,gBAAe,MADC,KAAK,WAAW,EAAA,CACT;GAC7B,IAAI,CAAC,cAAc,QACjB,MAAM,IAAI,MAAM,kCAAkC,SAAS;GAE7D,OAAO;EACT;CACF;CAEA,SAAS,OACP,MAGyB;EACzB,QAAQ,aAAa;GACnB,MAAM,aAAa,SAAS,IAAI;GAChC,MAAM,WAAW;IAAE,GAAG;IAAM,GAAG;GAAW;GAG1C,OAAO,OAAO,OAAO,UAAU,EAC7B,QAAQ,OAAO,QAAQ,EACzB,CAAC;EACH;CACF;CAEA,OAAO,OAAO,OAAO,QAAQ,EAAE,QAAQ,OAAO,MAAM,EAAE,CAAC;AACzD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseStepExecutor.js","names":[],"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,IAAI,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,
|
|
1
|
+
{"version":3,"file":"BaseStepExecutor.js","names":[],"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,IAAI,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,kBAAkB,wBACtB,IAAI,QACF,KAAK,cAAc,aAAa,MAAM,OAAO,MAAM,UAAU,EAC3D,OAAO;IACL,SAAS,OAAO,OAAO;IACvB,MAAM,OAAO;GACf,EACF,CAAC;QAED,KAAK,cAAc,gBAAgB,MAAM;IACvC,QAAQ;IACR,OAAO;KACL,SAAS,OAAO,OAAO;KACvB,MAAM,OAAO;IACf;GACF,CAAC;GAGL,MAAM;EACR;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actionMessages.js","names":[],"sources":["../../../src/core/actionMessages.ts"],"sourcesContent":["import type { StatusMessage, Substatus } from '@lifi/types'\nimport type {\n ExecutionActionStatus,\n ExecutionActionType,\n} from '../types/core.js'\n\nconst actionMessages: Record<\n ExecutionActionType,\n Partial<Record<ExecutionActionStatus, string>>\n> = {\n CHECK_ALLOWANCE: {\n STARTED: 'Checking token allowance',\n PENDING: 'Waiting for token allowance check',\n DONE: 'Token allowance checked',\n },\n RESET_ALLOWANCE: {\n STARTED: 'Resetting token allowance',\n RESET_REQUIRED: 'Resetting token allowance',\n PENDING: 'Waiting for token allowance reset',\n DONE: 'Token allowance reset',\n },\n SET_ALLOWANCE: {\n STARTED: 'Setting token allowance',\n ACTION_REQUIRED: 'Set token allowance',\n PENDING: 'Waiting for token allowance',\n DONE: 'Token allowance set',\n },\n SWAP: {\n STARTED: 'Preparing swap transaction',\n ACTION_REQUIRED: 'Sign swap transaction',\n MESSAGE_REQUIRED: 'Sign swap message',\n PENDING: 'Waiting for swap transaction',\n DONE: 'Swap completed',\n },\n CROSS_CHAIN: {\n STARTED: 'Preparing bridge transaction',\n ACTION_REQUIRED: 'Sign bridge transaction',\n MESSAGE_REQUIRED: 'Sign bridge message',\n PENDING: 'Waiting for bridge transaction',\n DONE: 'Bridge transaction confirmed',\n },\n RECEIVING_CHAIN: {\n STARTED: 'Waiting for destination chain',\n PENDING: 'Waiting for destination chain',\n DONE: 'Bridge completed',\n },\n PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n NATIVE_PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n}\n\nconst substatusMessages: Record<\n StatusMessage,\n Partial<Record<Substatus, string>>\n> = {\n PENDING: {\n BRIDGE_NOT_AVAILABLE: 'Bridge communication is temporarily unavailable.',\n CHAIN_NOT_AVAILABLE: 'RPC communication is temporarily unavailable.',\n UNKNOWN_ERROR:\n 'An unexpected error occurred. Please seek assistance in the LI.FI discord server.',\n WAIT_SOURCE_CONFIRMATIONS:\n 'The bridge deposit has been received. The bridge is waiting for more confirmations to start the off-chain logic.',\n WAIT_DESTINATION_TRANSACTION:\n 'The bridge off-chain logic is being executed. Wait for the transaction to appear on the destination chain.',\n },\n DONE: {\n PARTIAL:\n 'Some of the received tokens are not the requested destination tokens.',\n REFUNDED: 'The tokens were refunded to the sender address.',\n COMPLETED: 'The transfer is complete.',\n },\n FAILED: {},\n INVALID: {},\n NOT_FOUND: {},\n}\n\nexport function getActionMessage(\n type: ExecutionActionType,\n status: ExecutionActionStatus\n): string | undefined {\n const actionMessage = actionMessages[type][status]\n return actionMessage\n}\n\nexport function getSubstatusMessage(\n status: StatusMessage,\n substatus?: Substatus\n): string | undefined {\n if (!substatus) {\n return\n }\n const message = substatusMessages[status][substatus]\n return message\n}\n"],"mappings":";AAMA,MAAM,iBAGF;CACF,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;CACR;CACA,iBAAiB;EACf,SAAS;EACT,gBAAgB;EAChB,SAAS;EACT,MAAM;CACR;CACA,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;CACA,MAAM;EACJ,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;CACR;CACA,aAAa;EACX,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;CACR;CACA,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;CACR;CACA,QAAQ;EACN,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;CACA,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;AACF;AAEA,MAAM,oBAGF;CACF,SAAS;EACP,sBAAsB;EACtB,qBAAqB;EACrB,eACE;EACF,2BACE;EACF,8BACE;CACJ;CACA,MAAM;EACJ,SACE;EACF,UAAU;EACV,WAAW;CACb;CACA,QAAQ,CAAC;CACT,SAAS,CAAC;CACV,WAAW,CAAC;AACd;AAEA,SAAgB,iBACd,MACA,QACoB;CAEpB,OADsB,eAAe,
|
|
1
|
+
{"version":3,"file":"actionMessages.js","names":[],"sources":["../../../src/core/actionMessages.ts"],"sourcesContent":["import type { StatusMessage, Substatus } from '@lifi/types'\nimport type {\n ExecutionActionStatus,\n ExecutionActionType,\n} from '../types/core.js'\n\nconst actionMessages: Record<\n ExecutionActionType,\n Partial<Record<ExecutionActionStatus, string>>\n> = {\n CHECK_ALLOWANCE: {\n STARTED: 'Checking token allowance',\n PENDING: 'Waiting for token allowance check',\n DONE: 'Token allowance checked',\n },\n RESET_ALLOWANCE: {\n STARTED: 'Resetting token allowance',\n RESET_REQUIRED: 'Resetting token allowance',\n PENDING: 'Waiting for token allowance reset',\n DONE: 'Token allowance reset',\n },\n SET_ALLOWANCE: {\n STARTED: 'Setting token allowance',\n ACTION_REQUIRED: 'Set token allowance',\n PENDING: 'Waiting for token allowance',\n DONE: 'Token allowance set',\n },\n SWAP: {\n STARTED: 'Preparing swap transaction',\n ACTION_REQUIRED: 'Sign swap transaction',\n MESSAGE_REQUIRED: 'Sign swap message',\n PENDING: 'Waiting for swap transaction',\n DONE: 'Swap completed',\n },\n CROSS_CHAIN: {\n STARTED: 'Preparing bridge transaction',\n ACTION_REQUIRED: 'Sign bridge transaction',\n MESSAGE_REQUIRED: 'Sign bridge message',\n PENDING: 'Waiting for bridge transaction',\n DONE: 'Bridge transaction confirmed',\n },\n RECEIVING_CHAIN: {\n STARTED: 'Waiting for destination chain',\n PENDING: 'Waiting for destination chain',\n DONE: 'Bridge completed',\n },\n PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n NATIVE_PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n}\n\nconst substatusMessages: Record<\n StatusMessage,\n Partial<Record<Substatus, string>>\n> = {\n PENDING: {\n BRIDGE_NOT_AVAILABLE: 'Bridge communication is temporarily unavailable.',\n CHAIN_NOT_AVAILABLE: 'RPC communication is temporarily unavailable.',\n UNKNOWN_ERROR:\n 'An unexpected error occurred. Please seek assistance in the LI.FI discord server.',\n WAIT_SOURCE_CONFIRMATIONS:\n 'The bridge deposit has been received. The bridge is waiting for more confirmations to start the off-chain logic.',\n WAIT_DESTINATION_TRANSACTION:\n 'The bridge off-chain logic is being executed. Wait for the transaction to appear on the destination chain.',\n },\n DONE: {\n PARTIAL:\n 'Some of the received tokens are not the requested destination tokens.',\n REFUNDED: 'The tokens were refunded to the sender address.',\n COMPLETED: 'The transfer is complete.',\n },\n FAILED: {},\n INVALID: {},\n NOT_FOUND: {},\n}\n\nexport function getActionMessage(\n type: ExecutionActionType,\n status: ExecutionActionStatus\n): string | undefined {\n const actionMessage = actionMessages[type][status]\n return actionMessage\n}\n\nexport function getSubstatusMessage(\n status: StatusMessage,\n substatus?: Substatus\n): string | undefined {\n if (!substatus) {\n return\n }\n const message = substatusMessages[status][substatus]\n return message\n}\n"],"mappings":";AAMA,MAAM,iBAGF;CACF,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;CACR;CACA,iBAAiB;EACf,SAAS;EACT,gBAAgB;EAChB,SAAS;EACT,MAAM;CACR;CACA,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;CACA,MAAM;EACJ,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;CACR;CACA,aAAa;EACX,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;CACR;CACA,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;CACR;CACA,QAAQ;EACN,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;CACA,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;CACR;AACF;AAEA,MAAM,oBAGF;CACF,SAAS;EACP,sBAAsB;EACtB,qBAAqB;EACrB,eACE;EACF,2BACE;EACF,8BACE;CACJ;CACA,MAAM;EACJ,SACE;EACF,UAAU;EACV,WAAW;CACb;CACA,QAAQ,CAAC;CACT,SAAS,CAAC;CACV,WAAW,CAAC;AACd;AAEA,SAAgB,iBACd,MACA,QACoB;CAEpB,OADsB,eAAe,KAAK,CAAC;AAE7C;AAEA,SAAgB,oBACd,QACA,WACoB;CACpB,IAAI,CAAC,WACH;CAGF,OADgB,kBAAkB,OAAO,CAAC;AAE5C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.js","names":[],"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,mBAAmB,eAAe,IAAI,YAAY,EAAE,
|
|
1
|
+
{"version":3,"file":"execution.js","names":[],"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,mBAAmB,eAAe,IAAI,YAAY,EAAE,CAAC,EAAE;CAE3D,IAAI,kBACF,OAAO;CAGT,eAAe,OAAO;EAAE,OAAO;EAAa;CAAiB,CAAC;CAC9D,mBAAmB,aAAa,QAAQ,WAAW;CACnD,eAAe,OAAO;EACpB,OAAO;EACP,SAAS;CACX,CAAC;CAED,OAAO;AACT;;;;;;;;;AAUA,MAAa,cAAc,OACzB,QACA,OACA,qBAC2B;CAC3B,MAAM,YAAY,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,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,YAAY,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,EAAE,CAAC,OAAO,aAC3B,aAAa,UAAU;EAE7B;EAEA,IAAI;GACF,MAAM,cAAc,KAAK,OAAO;GAChC,IAAI,CAAC,aACH,MAAM,IAAI,MAAM,sCAAsC;GAGxD,MAAM,WAAW,OAAO,UAAU,MAAM,aACtC,SAAS,UAAU,WAAW,CAChC;GAEA,IAAI,CAAC,UACH,MAAM,IAAI,cAAA,MAER,mCACF;GAGF,MAAM,eAAe,MAAM,SAAS,gBAAgB;IAClD,SAAS,MAAM;IACf,kBAAkB,UAAU;GAC9B,CAAC;GACD,UAAU,UAAU,KAAK,YAAY;GAGrC,IAAI,UAAU,kBACZ,qBAAqB,OAAO,UAAU,gBAAgB;GAGxD,IAAI;GACJ,IAAI;IACF,eAAe,MAAM,aAAa,YAAY,QAAQ,IAAI;GAC5D,SAAS,GAAG;IACV,IAAI,aAAa,uBAAuB;KACtC,KAAK,YAAY,KAAA;KACjB,eAAe,MAAM,aAAa,YAChC,QACA,MACA,EAAE,WACJ;IACF,OACE,MAAM;GAEV;GAGA,IAAI,aAAa,WAAW,WAAW,QACrC,mBAAmB,KAAK;GAI1B,IAAI,CAAC,aAAa,gBAChB,OAAO;EAEX,SAAS,GAAG;GACV,mBAAmB,KAAK;GACxB,MAAM;EACR;CACF;CAGA,eAAe,OAAO,MAAM,EAAE;CAC9B,OAAO;AACT;;;;;;AAOA,MAAa,wBACX,OACA,YACS;CACT,MAAM,YAAY,eAAe,IAAI,MAAM,EAAE;CAC7C,IAAI,CAAC,WACH;CAGF,IAAI,yBAAyB,SAC3B,KAAK,MAAM,YAAY,UAAU,WAC/B,SAAS,eAAe;EACtB,kBAAkB,CAAC,SAAS;EAC5B,cAAc;CAChB,CAAC;CAIL,UAAU,mBAAmB;EAC3B,GAAG,UAAU;EACb,GAAG;CACL;AACF;;;;;;AAOA,MAAa,sBAAsB,UAAwB;CACzD,MAAM,YAAY,eAAe,IAAI,MAAM,EAAE;CAC7C,IAAI,CAAC,WACH,OAAO;CAGT,KAAK,MAAM,YAAY,UAAU,WAC/B,SAAS,eAAe;EACtB,kBAAkB;EAClB,cAAc;EACd,gBAAgB;CAClB,CAAC;CAEH,eAAe,OAAO,MAAM,EAAE;CAC9B,OAAO,UAAU;AACnB;;;;;AAMA,MAAa,wBAAyC;CACpD,OAAO,OAAO,OAAO,eAAe,KAAK,CAAC,CACvC,KAAK,SAAS,MAAM,KAAK,CAAC,CAC1B,OAAO,OAAO;AACnB;;;;;;AAOA,MAAa,kBAAkB,YAA+C;CAC5E,OAAO,eAAe,IAAI,OAAO,CAAC,EAAE;AACtC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executionState.js","names":[],"sources":["../../../src/core/executionState.ts"],"sourcesContent":["import type {\n ExecutionOptions,\n RouteExtended,\n StepExecutor,\n} from '../types/core.js'\n\ninterface ExecutionData {\n route: RouteExtended\n executors: StepExecutor[]\n executionOptions?: ExecutionOptions\n promise?: Promise<RouteExtended>\n}\n\ntype ExecutionStateParams = Omit<ExecutionData, 'executors'>\n\ninterface ExecutionState {\n state: Partial<Record<string, ExecutionData>>\n get(routeId: string): ExecutionData | undefined\n create(params: ExecutionStateParams): ExecutionData\n update(params: ExecutionStateParams): void\n delete(routeId: string): void\n}\n\nexport const executionState: ExecutionState = {\n state: {},\n get(routeId: string) {\n return this.state[routeId]\n },\n create(params) {\n this.state[params.route.id] = {\n ...this.state[params.route.id],\n ...params,\n executors: this.state[params.route.id]?.executors ?? [],\n }\n return this.state[params.route.id]!\n },\n update(state) {\n if (this.state[state.route.id]) {\n this.state[state.route.id] = {\n ...this.state[state.route.id]!,\n ...state,\n }\n }\n },\n delete(routeId) {\n delete this.state[routeId]\n },\n}\n"],"mappings":";AAuBA,MAAa,iBAAiC;CAC5C,OAAO,CAAC;CACR,IAAI,SAAiB;EACnB,OAAO,KAAK,MAAM;CACpB;CACA,OAAO,QAAQ;EACb,KAAK,MAAM,OAAO,MAAM,MAAM;GAC5B,GAAG,KAAK,MAAM,OAAO,MAAM;GAC3B,GAAG;GACH,WAAW,KAAK,MAAM,OAAO,MAAM,
|
|
1
|
+
{"version":3,"file":"executionState.js","names":[],"sources":["../../../src/core/executionState.ts"],"sourcesContent":["import type {\n ExecutionOptions,\n RouteExtended,\n StepExecutor,\n} from '../types/core.js'\n\ninterface ExecutionData {\n route: RouteExtended\n executors: StepExecutor[]\n executionOptions?: ExecutionOptions\n promise?: Promise<RouteExtended>\n}\n\ntype ExecutionStateParams = Omit<ExecutionData, 'executors'>\n\ninterface ExecutionState {\n state: Partial<Record<string, ExecutionData>>\n get(routeId: string): ExecutionData | undefined\n create(params: ExecutionStateParams): ExecutionData\n update(params: ExecutionStateParams): void\n delete(routeId: string): void\n}\n\nexport const executionState: ExecutionState = {\n state: {},\n get(routeId: string) {\n return this.state[routeId]\n },\n create(params) {\n this.state[params.route.id] = {\n ...this.state[params.route.id],\n ...params,\n executors: this.state[params.route.id]?.executors ?? [],\n }\n return this.state[params.route.id]!\n },\n update(state) {\n if (this.state[state.route.id]) {\n this.state[state.route.id] = {\n ...this.state[state.route.id]!,\n ...state,\n }\n }\n },\n delete(routeId) {\n delete this.state[routeId]\n },\n}\n"],"mappings":";AAuBA,MAAa,iBAAiC;CAC5C,OAAO,CAAC;CACR,IAAI,SAAiB;EACnB,OAAO,KAAK,MAAM;CACpB;CACA,OAAO,QAAQ;EACb,KAAK,MAAM,OAAO,MAAM,MAAM;GAC5B,GAAG,KAAK,MAAM,OAAO,MAAM;GAC3B,GAAG;GACH,WAAW,KAAK,MAAM,OAAO,MAAM,GAAG,EAAE,aAAa,CAAC;EACxD;EACA,OAAO,KAAK,MAAM,OAAO,MAAM;CACjC;CACA,OAAO,OAAO;EACZ,IAAI,KAAK,MAAM,MAAM,MAAM,KACzB,KAAK,MAAM,MAAM,MAAM,MAAM;GAC3B,GAAG,KAAK,MAAM,MAAM,MAAM;GAC1B,GAAG;EACL;CAEJ;CACA,OAAO,SAAS;EACd,OAAO,KAAK,MAAM;CACpB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepareRestart.js","names":[],"sources":["../../../src/core/prepareRestart.ts"],"sourcesContent":["import type { RouteExtended } from '../types/core.js'\n\nexport const prepareRestart = (route: RouteExtended): void => {\n for (let index = 0; index < route.steps.length; index++) {\n const step = route.steps[index]\n if (step.execution) {\n // Find the index of the last action that has tx hash, taskId, or signed messages\n const lastValidIndex = step.execution.actions.findLastIndex(\n (action) =>\n ['SWAP', 'CROSS_CHAIN', 'RECEIVING_CHAIN'].includes(action.type) &&\n (!!action.txHash || !!action.taskId) &&\n action.status !== 'FAILED'\n )\n\n // Keep all actions up to the one with tx hash\n if (lastValidIndex >= 0) {\n step.execution.actions = step.execution.actions.slice(\n 0,\n lastValidIndex + 1\n )\n } else {\n // If no tx hash exists, reset the actions array\n step.execution.actions = []\n }\n }\n step.transactionRequest = undefined\n }\n}\n"],"mappings":";AAEA,MAAa,kBAAkB,UAA+B;CAC5D,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,MAAM,QAAQ,SAAS;EACvD,MAAM,OAAO,MAAM,MAAM;EACzB,IAAI,KAAK,WAAW;GAElB,MAAM,iBAAiB,KAAK,UAAU,QAAQ,eAC3C,WACC;IAAC;IAAQ;IAAe;GAAiB,
|
|
1
|
+
{"version":3,"file":"prepareRestart.js","names":[],"sources":["../../../src/core/prepareRestart.ts"],"sourcesContent":["import type { RouteExtended } from '../types/core.js'\n\nexport const prepareRestart = (route: RouteExtended): void => {\n for (let index = 0; index < route.steps.length; index++) {\n const step = route.steps[index]\n if (step.execution) {\n // Find the index of the last action that has tx hash, taskId, or signed messages\n const lastValidIndex = step.execution.actions.findLastIndex(\n (action) =>\n ['SWAP', 'CROSS_CHAIN', 'RECEIVING_CHAIN'].includes(action.type) &&\n (!!action.txHash || !!action.taskId) &&\n action.status !== 'FAILED'\n )\n\n // Keep all actions up to the one with tx hash\n if (lastValidIndex >= 0) {\n step.execution.actions = step.execution.actions.slice(\n 0,\n lastValidIndex + 1\n )\n } else {\n // If no tx hash exists, reset the actions array\n step.execution.actions = []\n }\n }\n step.transactionRequest = undefined\n }\n}\n"],"mappings":";AAEA,MAAa,kBAAkB,UAA+B;CAC5D,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,MAAM,QAAQ,SAAS;EACvD,MAAM,OAAO,MAAM,MAAM;EACzB,IAAI,KAAK,WAAW;GAElB,MAAM,iBAAiB,KAAK,UAAU,QAAQ,eAC3C,WACC;IAAC;IAAQ;IAAe;GAAiB,CAAC,CAAC,SAAS,OAAO,IAAI,MAC9D,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,WAC7B,OAAO,WAAW,QACtB;GAGA,IAAI,kBAAkB,GACpB,KAAK,UAAU,UAAU,KAAK,UAAU,QAAQ,MAC9C,GACA,iBAAiB,CACnB;QAGA,KAAK,UAAU,UAAU,CAAC;EAE9B;EACA,KAAK,qBAAqB,KAAA;CAC5B;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkBalance.js","names":[],"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":"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"}
|
|
1
|
+
{"version":3,"file":"checkBalance.js","names":[],"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,MAAM,aAAa,IAAI,GAAG,KAAK;GACnC;GACA,YAAY;GACZ,SAAS;GACT,SAAS;EACX;EACA,IAAI,WAAW,UACb,IAAI,cAAc;OACb,IAAI,WAAW,OACpB,IAAI,WAAW;OAEf,IAAI,WAAW;EAEjB,aAAa,IAAI,KAAK,GAAG;CAC3B;CACA,IAAI,KAAK,OAAO,WAAW,OAAO,KAAK,OAAO,UAAU,GAAG,QAAQ;CACnE,KAAK,MAAM,OAAO,KAAK,UAAU,YAAY,CAAC,GAC5C,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,GAAG,KAAK;CAE1C,KAAK,MAAM,OAAO,KAAK,UAAU,YAAY,CAAC,GAE5C,IAAI,CAAC,IAAI,UACP,IAAI,IAAI,OAAO,OAAO,IAAI,MAAM,GAAG,KAAK;CAI5C,MAAM,oBAAoB,MACxB,EAAE,WAAW,gBAAgB,EAAE,UAAU;CAC3C,MAAM,QAAQ,MAA2B,EAAE,aAAa,iBAAiB,CAAC;CAI1E,KAAK,MAAM,CAAC,KAAK,QAAQ,cACvB,IAAI,KAAK,GAAG,MAAM,IAChB,aAAa,OAAO,GAAG;CAI3B,IAAI,aAAa,SAAS,GACxB;CAKF,MAAM,WAAW,OAAO,UAAU,MAAM,MAAM,EAAE,UAAU,aAAa,CAAC;CACxE,IAAI,CAAC,UACH,MAAM,IAAI,MAAM,0BAA0B,cAAc,eAAe;CAGzE,MAAM,OAAO,MAAM,KAAK,aAAa,OAAO,CAAC;CAC7C,MAAM,SAAS,KAAK,KAAK,MAAM,EAAE,KAAK;CACtC,MAAM,WAAW,KAAK,OAAO,YAAY;CACzC,MAAM,iBAAiB,OACrB,KAAK,OAAO,IAAI,YAAY,OAAO,kBAAkB,CAAC,CACxD;CAEA,MAAM,YACJ,YAAY;EACV,KAAK,IAAI,UAAU,GAAG,UAAU,cAAc,WAAW;GACvD,MAAM,UAAU,YAAY,eAAe;GAE3C,IAAI;GACJ,IAAI;IACF,WAAW,MAAM,SAAS,WAAW,QAAQ,eAAe,MAAM;GACpE,SAAS,OAAO;IACd,IAAI,SACF,MAAM,IAAI,aACR,kCACA,KACF;IAEF,MAAM,MAAM,kBAAkB,KAAK,OAAO;IAC1C;GACF;GAEA,MAAM,mBAAmB,IAAI,IAC3B,SAAS,KAAK,MAAM,CAAC,EAAE,QAAQ,YAAY,GAAG,EAAE,MAAM,CAAU,CAClE;GAEA,MAAM,UAAmB,CAAC;GAC1B,MAAM,eAAqD,CAAC;GAC5D,KAAK,MAAM,OAAO,MAAM;IACtB,MAAM,OAAO,iBAAiB,IAAI,IAAI,MAAM,QAAQ,YAAY,CAAC;IACjE,IAAI,SAAS,KAAA,GACX,QAAQ,KAAK,IAAI,KAAK;SACjB,IAAI,OAAO,KAAK,GAAG,GACxB,aAAa,KAAK;KAAE;KAAK;IAAK,CAAC;GAEnC;GAEA,IAAI,QAAQ,WAAW,KAAK,aAAa,WAAW,GAClD;GAMF,IACE,WACA,QAAQ,WAAW,KACnB,aAAa,WAAW,KACxB,aAAa,EAAE,CAAC,IAAI,aAAa,IACjC;IACA,MAAM,EAAE,KAAK,SAAS,aAAa;IACnC,MAAM,WAAW,iBAAiB,GAAG;IAGrC,IAAI,QADD,IAAI,aAAa,iBAAkB,qBAAqB,UAChC;KACzB,MAAM,iBAAiB,OAAO,SAAA,CAAU,SAAS;KACjD,KAAK,OAAO,aAAa;KACzB,IAAI,KAAK,eAAe,QACtB,KAAK,cAAc,EAAE,CAAC,OAAO,aAAa;KAE5C;IACF;GACF;GAEA,IAAI,SAAS;IACX,IAAI,QAAQ,SAAS,GACnB,MAAM,IAAI,aACR,kDACA,IAAI,MACF,+BAA+B,QAC5B,KAAK,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,CACjC,KAAK,IAAI,EAAE,EAChB,CACF;IAEF,MAAM,QAAQ,aAAa,KAAK,EAAE,KAAK,WAAW;KAChD,MAAM,SAAS,YAAY,KAAK,GAAG,GAAG,IAAI,MAAM,QAAQ;KACxD,MAAM,UAAU,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,IAAI,aACR,2CACA,IAAI,MAAM,GAAG,MAAM,KAAK,GAAG,EAAE,0BAA0B,CACzD;GACF;GAEA,MAAM,MAAM,kBAAkB,KAAK,OAAO;EAC5C;CACF,GACA;EACE,SAAS;EACT,eAAe,IAAI,aAAa,gCAAgC;CAClE,CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"waitForTransactionStatus.js","names":[],"sources":["../../../../../src/core/tasks/helpers/waitForTransactionStatus.ts"],"sourcesContent":["import type { FullStatusData, LiFiStep, StatusResponse } from '@lifi/types'\nimport { getStatus } from '../../../actions/getStatus.js'\nimport { ServerError } from '../../../errors/errors.js'\nimport type { ExecutionActionType, SDKClient } from '../../../types/core.js'\nimport { waitForResult } from '../../../utils/waitForResult.js'\nimport { getSubstatusMessage } from '../../actionMessages.js'\nimport type { StatusManager } from '../../StatusManager.js'\n\nconst TRANSACTION_HASH_OBSERVERS: Record<string, Promise<StatusResponse>> = {}\n\nexport async function waitForTransactionStatus(\n client: SDKClient,\n statusManager: StatusManager,\n txHash: string,\n step: LiFiStep,\n actionType: ExecutionActionType,\n interval = 5_000\n): Promise<StatusResponse> {\n const _getStatus = (): Promise<StatusResponse | undefined> => {\n return getStatus(client, {\n fromChain: step.action.fromChainId,\n fromAddress: step.action.fromAddress,\n toChain: step.action.toChainId,\n txHash,\n ...(step.tool !== 'custom' && { bridge: step.tool }),\n ...(step.transactionId && { transactionId: step.transactionId }),\n })\n .then((statusResponse) => {\n switch (statusResponse.status) {\n case 'DONE':\n return statusResponse\n case 'PENDING':\n statusManager?.updateAction(step, actionType, 'PENDING', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(\n statusResponse.status,\n statusResponse.substatus\n ),\n txLink: (statusResponse as FullStatusData).bridgeExplorerLink,\n })\n return undefined\n case 'NOT_FOUND':\n return undefined\n default:\n return Promise.reject()\n }\n })\n .catch((e) => {\n if (process.env.NODE_ENV === 'development') {\n console.debug('Fetching status from backend failed.', e)\n }\n return undefined\n })\n }\n\n let status = TRANSACTION_HASH_OBSERVERS[txHash]\n\n if (!status) {\n status = waitForResult(_getStatus, interval).finally(() => {\n delete TRANSACTION_HASH_OBSERVERS[txHash]\n })\n TRANSACTION_HASH_OBSERVERS[txHash] = status\n }\n\n const resolvedStatus = await status\n\n if (!('receiving' in resolvedStatus)) {\n throw new ServerError(\n \"Status doesn't contain destination chain information.\"\n )\n }\n\n return resolvedStatus\n}\n"],"mappings":";;;;;AAQA,MAAM,6BAAsE,CAAC;AAE7E,eAAsB,yBACpB,QACA,eACA,QACA,MACA,YACA,WAAW,KACc;CACzB,MAAM,mBAAwD;EAC5D,OAAO,UAAU,QAAQ;GACvB,WAAW,KAAK,OAAO;GACvB,aAAa,KAAK,OAAO;GACzB,SAAS,KAAK,OAAO;GACrB;GACA,GAAI,KAAK,SAAS,YAAY,EAAE,QAAQ,KAAK,KAAK;GAClD,GAAI,KAAK,iBAAiB,EAAE,eAAe,KAAK,cAAc;EAChE,CAAC,
|
|
1
|
+
{"version":3,"file":"waitForTransactionStatus.js","names":[],"sources":["../../../../../src/core/tasks/helpers/waitForTransactionStatus.ts"],"sourcesContent":["import type { FullStatusData, LiFiStep, StatusResponse } from '@lifi/types'\nimport { getStatus } from '../../../actions/getStatus.js'\nimport { ServerError } from '../../../errors/errors.js'\nimport type { ExecutionActionType, SDKClient } from '../../../types/core.js'\nimport { waitForResult } from '../../../utils/waitForResult.js'\nimport { getSubstatusMessage } from '../../actionMessages.js'\nimport type { StatusManager } from '../../StatusManager.js'\n\nconst TRANSACTION_HASH_OBSERVERS: Record<string, Promise<StatusResponse>> = {}\n\nexport async function waitForTransactionStatus(\n client: SDKClient,\n statusManager: StatusManager,\n txHash: string,\n step: LiFiStep,\n actionType: ExecutionActionType,\n interval = 5_000\n): Promise<StatusResponse> {\n const _getStatus = (): Promise<StatusResponse | undefined> => {\n return getStatus(client, {\n fromChain: step.action.fromChainId,\n fromAddress: step.action.fromAddress,\n toChain: step.action.toChainId,\n txHash,\n ...(step.tool !== 'custom' && { bridge: step.tool }),\n ...(step.transactionId && { transactionId: step.transactionId }),\n })\n .then((statusResponse) => {\n switch (statusResponse.status) {\n case 'DONE':\n return statusResponse\n case 'PENDING':\n statusManager?.updateAction(step, actionType, 'PENDING', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(\n statusResponse.status,\n statusResponse.substatus\n ),\n txLink: (statusResponse as FullStatusData).bridgeExplorerLink,\n })\n return undefined\n case 'NOT_FOUND':\n return undefined\n default:\n return Promise.reject()\n }\n })\n .catch((e) => {\n if (process.env.NODE_ENV === 'development') {\n console.debug('Fetching status from backend failed.', e)\n }\n return undefined\n })\n }\n\n let status = TRANSACTION_HASH_OBSERVERS[txHash]\n\n if (!status) {\n status = waitForResult(_getStatus, interval).finally(() => {\n delete TRANSACTION_HASH_OBSERVERS[txHash]\n })\n TRANSACTION_HASH_OBSERVERS[txHash] = status\n }\n\n const resolvedStatus = await status\n\n if (!('receiving' in resolvedStatus)) {\n throw new ServerError(\n \"Status doesn't contain destination chain information.\"\n )\n }\n\n return resolvedStatus\n}\n"],"mappings":";;;;;AAQA,MAAM,6BAAsE,CAAC;AAE7E,eAAsB,yBACpB,QACA,eACA,QACA,MACA,YACA,WAAW,KACc;CACzB,MAAM,mBAAwD;EAC5D,OAAO,UAAU,QAAQ;GACvB,WAAW,KAAK,OAAO;GACvB,aAAa,KAAK,OAAO;GACzB,SAAS,KAAK,OAAO;GACrB;GACA,GAAI,KAAK,SAAS,YAAY,EAAE,QAAQ,KAAK,KAAK;GAClD,GAAI,KAAK,iBAAiB,EAAE,eAAe,KAAK,cAAc;EAChE,CAAC,CAAC,CACC,MAAM,mBAAmB;GACxB,QAAQ,eAAe,QAAvB;IACE,KAAK,QACH,OAAO;IACT,KAAK;KACH,eAAe,aAAa,MAAM,YAAY,WAAW;MACvD,WAAW,eAAe;MAC1B,kBACE,eAAe,oBACf,oBACE,eAAe,QACf,eAAe,SACjB;MACF,QAAS,eAAkC;KAC7C,CAAC;KACD;IACF,KAAK,aACH;IACF,SACE,OAAO,QAAQ,OAAO;GAC1B;EACF,CAAC,CAAC,CACD,OAAO,MAAM;GACZ,IAAI,QAAQ,IAAI,aAAa,eAC3B,QAAQ,MAAM,wCAAwC,CAAC;EAG3D,CAAC;CACL;CAEA,IAAI,SAAS,2BAA2B;CAExC,IAAI,CAAC,QAAQ;EACX,SAAS,cAAc,YAAY,QAAQ,CAAC,CAAC,cAAc;GACzD,OAAO,2BAA2B;EACpC,CAAC;EACD,2BAA2B,UAAU;CACvC;CAEA,MAAM,iBAAiB,MAAM;CAE7B,IAAI,EAAE,eAAe,iBACnB,MAAM,IAAI,YACR,uDACF;CAGF,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","names":[],"sources":["../../../src/core/utils.ts"],"sourcesContent":["import type { ChainId, ExtendedChain, LiFiStep } from '@lifi/types'\nimport type { RPCUrls } from '../types/core.js'\n\n// Standard threshold for destination amount difference (0.5%)\nconst standardThreshold = 0.005\n\n/**\n * Used to check if changed exchange rate is in the range of slippage threshold.\n * We use a slippage value as a threshold to trigger the rate change hook.\n * This can result in almost doubled slippage for the user and need to be revisited.\n * @param oldStep - old step\n * @param newStep - new step\n * @returns Boolean\n */\nexport function checkStepSlippageThreshold(\n oldStep: LiFiStep,\n newStep: LiFiStep\n): boolean {\n const setSlippage = oldStep.action.slippage || standardThreshold\n const oldEstimatedToAmount = BigInt(oldStep.estimate.toAmountMin)\n const newEstimatedToAmount = BigInt(newStep.estimate.toAmountMin)\n const amountDifference = oldEstimatedToAmount - newEstimatedToAmount\n // oldEstimatedToAmount can be 0 when we use contract calls\n let actualSlippage = 0\n if (oldEstimatedToAmount > 0) {\n actualSlippage =\n Number((amountDifference * 1_000_000_000n) / oldEstimatedToAmount) /\n 1_000_000_000\n }\n return actualSlippage <= setSlippage\n}\n\nexport function getRpcUrlsFromChains(\n existingRpcUrls: RPCUrls,\n chains: ExtendedChain[],\n skipChains?: ChainId[]\n): RPCUrls {\n const rpcUrlsFromChains = chains.reduce((rpcUrls, chain) => {\n if (chain.metamask?.rpcUrls?.length) {\n rpcUrls[chain.id as ChainId] = chain.metamask.rpcUrls\n }\n return rpcUrls\n }, {} as RPCUrls)\n const result = { ...existingRpcUrls }\n for (const rpcUrlsKey in rpcUrlsFromChains) {\n const chainId = Number(rpcUrlsKey) as ChainId\n const urls = rpcUrlsFromChains[chainId]\n if (!urls?.length) {\n continue\n }\n if (!result[chainId]?.length) {\n result[chainId] = Array.from(urls)\n } else if (!skipChains?.includes(chainId)) {\n const filteredUrls = urls.filter((url) => !result[chainId]?.includes(url))\n result[chainId].push(...filteredUrls)\n }\n }\n return result\n}\n"],"mappings":";AAIA,MAAM,oBAAoB;;;;;;;;;AAU1B,SAAgB,2BACd,SACA,SACS;CACT,MAAM,cAAc,QAAQ,OAAO,YAAY;CAC/C,MAAM,uBAAuB,OAAO,QAAQ,SAAS,WAAW;CAEhE,MAAM,mBAAmB,uBADI,OAAO,QAAQ,SAAS,WACc;CAEnE,IAAI,iBAAiB;CACrB,IAAI,uBAAuB,GACzB,iBACE,OAAQ,mBAAmB,cAAkB,oBAAoB,IACjE;CAEJ,OAAO,kBAAkB;AAC3B;AAEA,SAAgB,qBACd,iBACA,QACA,YACS;CACT,MAAM,oBAAoB,OAAO,QAAQ,SAAS,UAAU;EAC1D,IAAI,MAAM,UAAU,SAAS,QAC3B,QAAQ,MAAM,MAAiB,MAAM,SAAS;EAEhD,OAAO;CACT,GAAG,CAAC,CAAY;CAChB,MAAM,SAAS,EAAE,GAAG,gBAAgB;CACpC,KAAK,MAAM,cAAc,mBAAmB;EAC1C,MAAM,UAAU,OAAO,UAAU;EACjC,MAAM,OAAO,kBAAkB;EAC/B,IAAI,CAAC,MAAM,QACT;EAEF,IAAI,CAAC,OAAO,
|
|
1
|
+
{"version":3,"file":"utils.js","names":[],"sources":["../../../src/core/utils.ts"],"sourcesContent":["import type { ChainId, ExtendedChain, LiFiStep } from '@lifi/types'\nimport type { RPCUrls } from '../types/core.js'\n\n// Standard threshold for destination amount difference (0.5%)\nconst standardThreshold = 0.005\n\n/**\n * Used to check if changed exchange rate is in the range of slippage threshold.\n * We use a slippage value as a threshold to trigger the rate change hook.\n * This can result in almost doubled slippage for the user and need to be revisited.\n * @param oldStep - old step\n * @param newStep - new step\n * @returns Boolean\n */\nexport function checkStepSlippageThreshold(\n oldStep: LiFiStep,\n newStep: LiFiStep\n): boolean {\n const setSlippage = oldStep.action.slippage || standardThreshold\n const oldEstimatedToAmount = BigInt(oldStep.estimate.toAmountMin)\n const newEstimatedToAmount = BigInt(newStep.estimate.toAmountMin)\n const amountDifference = oldEstimatedToAmount - newEstimatedToAmount\n // oldEstimatedToAmount can be 0 when we use contract calls\n let actualSlippage = 0\n if (oldEstimatedToAmount > 0) {\n actualSlippage =\n Number((amountDifference * 1_000_000_000n) / oldEstimatedToAmount) /\n 1_000_000_000\n }\n return actualSlippage <= setSlippage\n}\n\nexport function getRpcUrlsFromChains(\n existingRpcUrls: RPCUrls,\n chains: ExtendedChain[],\n skipChains?: ChainId[]\n): RPCUrls {\n const rpcUrlsFromChains = chains.reduce((rpcUrls, chain) => {\n if (chain.metamask?.rpcUrls?.length) {\n rpcUrls[chain.id as ChainId] = chain.metamask.rpcUrls\n }\n return rpcUrls\n }, {} as RPCUrls)\n const result = { ...existingRpcUrls }\n for (const rpcUrlsKey in rpcUrlsFromChains) {\n const chainId = Number(rpcUrlsKey) as ChainId\n const urls = rpcUrlsFromChains[chainId]\n if (!urls?.length) {\n continue\n }\n if (!result[chainId]?.length) {\n result[chainId] = Array.from(urls)\n } else if (!skipChains?.includes(chainId)) {\n const filteredUrls = urls.filter((url) => !result[chainId]?.includes(url))\n result[chainId].push(...filteredUrls)\n }\n }\n return result\n}\n"],"mappings":";AAIA,MAAM,oBAAoB;;;;;;;;;AAU1B,SAAgB,2BACd,SACA,SACS;CACT,MAAM,cAAc,QAAQ,OAAO,YAAY;CAC/C,MAAM,uBAAuB,OAAO,QAAQ,SAAS,WAAW;CAEhE,MAAM,mBAAmB,uBADI,OAAO,QAAQ,SAAS,WACc;CAEnE,IAAI,iBAAiB;CACrB,IAAI,uBAAuB,GACzB,iBACE,OAAQ,mBAAmB,cAAkB,oBAAoB,IACjE;CAEJ,OAAO,kBAAkB;AAC3B;AAEA,SAAgB,qBACd,iBACA,QACA,YACS;CACT,MAAM,oBAAoB,OAAO,QAAQ,SAAS,UAAU;EAC1D,IAAI,MAAM,UAAU,SAAS,QAC3B,QAAQ,MAAM,MAAiB,MAAM,SAAS;EAEhD,OAAO;CACT,GAAG,CAAC,CAAY;CAChB,MAAM,SAAS,EAAE,GAAG,gBAAgB;CACpC,KAAK,MAAM,cAAc,mBAAmB;EAC1C,MAAM,UAAU,OAAO,UAAU;EACjC,MAAM,OAAO,kBAAkB;EAC/B,IAAI,CAAC,MAAM,QACT;EAEF,IAAI,CAAC,OAAO,QAAQ,EAAE,QACpB,OAAO,WAAW,MAAM,KAAK,IAAI;OAC5B,IAAI,CAAC,YAAY,SAAS,OAAO,GAAG;GACzC,MAAM,eAAe,KAAK,QAAQ,QAAQ,CAAC,OAAO,QAAQ,EAAE,SAAS,GAAG,CAAC;GACzE,OAAO,QAAQ,CAAC,KAAK,GAAG,YAAY;EACtC;CACF;CACA,OAAO;AACT"}
|
|
@@ -4,7 +4,7 @@ const checkPackageUpdates = async (packageName, packageVersion) => {
|
|
|
4
4
|
try {
|
|
5
5
|
const pkgName = packageName ?? "@lifi/sdk";
|
|
6
6
|
const latestVersion = (await (await fetch(`https://registry.npmjs.org/${pkgName}/latest`)).json()).version;
|
|
7
|
-
const currentVersion = packageVersion ?? "4.0.
|
|
7
|
+
const currentVersion = packageVersion ?? "4.0.1";
|
|
8
8
|
if (latestVersion > currentVersion) console.warn(`${pkgName}: new package version is available. Please update as soon as possible to enjoy the newest features. Current version: ${currentVersion}. Latest version: ${latestVersion}.`);
|
|
9
9
|
} catch (_error) {}
|
|
10
10
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkPackageUpdates.js","names":[],"sources":["../../../src/utils/checkPackageUpdates.ts"],"sourcesContent":["import { name, version } from '../version.js'\n\nexport const checkPackageUpdates = async (\n packageName?: string,\n packageVersion?: string\n): Promise<void> => {\n try {\n const pkgName = packageName ?? name\n const response = await fetch(`https://registry.npmjs.org/${pkgName}/latest`)\n const reponseBody = await response.json()\n const latestVersion = reponseBody.version\n const currentVersion = packageVersion ?? version\n\n if (latestVersion > currentVersion) {\n console.warn(\n `${pkgName}: new package version is available. Please update as soon as possible to enjoy the newest features. Current version: ${currentVersion}. Latest version: ${latestVersion}.`\n )\n }\n } catch (_error) {\n // Cannot verify version, might be network error etc. We don't bother showing anything in that case\n }\n}\n"],"mappings":";;AAEA,MAAa,sBAAsB,OACjC,aACA,mBACkB;CAClB,IAAI;EACF,MAAM,UAAU,eAAA;EAGhB,MAAM,iBAAgB,OADI,MADH,MAAM,8BAA8B,QAAQ,QAAQ,
|
|
1
|
+
{"version":3,"file":"checkPackageUpdates.js","names":[],"sources":["../../../src/utils/checkPackageUpdates.ts"],"sourcesContent":["import { name, version } from '../version.js'\n\nexport const checkPackageUpdates = async (\n packageName?: string,\n packageVersion?: string\n): Promise<void> => {\n try {\n const pkgName = packageName ?? name\n const response = await fetch(`https://registry.npmjs.org/${pkgName}/latest`)\n const reponseBody = await response.json()\n const latestVersion = reponseBody.version\n const currentVersion = packageVersion ?? version\n\n if (latestVersion > currentVersion) {\n console.warn(\n `${pkgName}: new package version is available. Please update as soon as possible to enjoy the newest features. Current version: ${currentVersion}. Latest version: ${latestVersion}.`\n )\n }\n } catch (_error) {\n // Cannot verify version, might be network error etc. We don't bother showing anything in that case\n }\n}\n"],"mappings":";;AAEA,MAAa,sBAAsB,OACjC,aACA,mBACkB;CAClB,IAAI;EACF,MAAM,UAAU,eAAA;EAGhB,MAAM,iBAAgB,OADI,MADH,MAAM,8BAA8B,QAAQ,QAAQ,EAAA,CACxC,KAAK,EAAA,CACN;EAClC,MAAM,iBAAiB,kBAAA;EAEvB,IAAI,gBAAgB,gBAClB,QAAQ,KACN,GAAG,QAAQ,uHAAuH,eAAe,oBAAoB,cAAc,EACrL;CAEJ,SAAS,QAAQ,CAEjB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"convertQuoteToRoute.js","names":[],"sources":["../../../src/utils/convertQuoteToRoute.ts"],"sourcesContent":["import type { LiFiStep, Route, Step } from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport { formatUnits } from './formatUnits.js'\n\ninterface ConvertQuoteToRouteOptions {\n /**\n * When true, if the quote has zero output values (toAmount, toAmountMin, toAmountUSD),\n * use the values from the previous included step that has non-zero output.\n */\n adjustZeroOutputFromPreviousStep?: boolean\n}\n\nconst parseBigInt = (value: string | undefined): bigint => {\n if (!value) {\n return 0n\n }\n try {\n return BigInt(value)\n } catch {\n return 0n\n }\n}\n\nconst parseNumber = (value: string | undefined): number => {\n if (!value) {\n return 0\n }\n const parsed = Number(value)\n return Number.isNaN(parsed) ? 0 : parsed\n}\n\nconst isZeroOutput = (\n toAmount: string,\n toAmountMin: string,\n toAmountUSD?: string\n): boolean => {\n return (\n !parseBigInt(toAmount) &&\n !parseBigInt(toAmountMin) &&\n !parseNumber(toAmountUSD)\n )\n}\n\nconst hasNonZeroOutput = (step: Step): boolean => {\n return (\n !!parseBigInt(step.estimate.toAmount) ||\n !!parseBigInt(step.estimate.toAmountMin)\n )\n}\n\nconst findPreviousNonZeroStep = (steps: Step[]): Step | undefined => {\n // Find the last step that has non-zero output (the step before the zero output step)\n for (let i = steps.length - 1; i >= 0; i--) {\n const step = steps[i]\n if (hasNonZeroOutput(step)) {\n return step\n }\n }\n return undefined\n}\n\nexport function formatTokenPrice(\n amount?: string | bigint,\n price?: string,\n decimals?: number\n): number {\n if (!amount || !price) {\n return 0\n }\n\n const formattedAmount =\n typeof amount === 'bigint' && decimals !== undefined\n ? formatUnits(amount, decimals)\n : amount.toString()\n\n if (Number.isNaN(Number(formattedAmount)) || Number.isNaN(Number(price))) {\n return 0\n }\n return Number.parseFloat(formattedAmount) * Number.parseFloat(price)\n}\n\n/**\n * Converts a quote to Route\n * @param quote - Step returned from the quote endpoint.\n * @param options - Optional configuration for handling edge cases.\n * @returns - The route to be executed.\n * @throws {BaseError} Throws a ValidationError if the step has missing values.\n */\nexport const convertQuoteToRoute = (\n quote: LiFiStep,\n options?: ConvertQuoteToRouteOptions\n): Route => {\n let toAmount = quote.estimate.toAmount\n let toAmountMin = quote.estimate.toAmountMin\n let toAmountUSD = quote.estimate.toAmountUSD\n\n // Handle zero output values by looking at previous included step\n if (\n options?.adjustZeroOutputFromPreviousStep &&\n quote.includedSteps?.length &&\n isZeroOutput(toAmount, toAmountMin, toAmountUSD)\n ) {\n const previousStep = findPreviousNonZeroStep(quote.includedSteps)\n if (previousStep) {\n toAmount = previousStep.estimate.toAmount\n toAmountMin = previousStep.estimate.toAmountMin\n toAmountUSD = formatTokenPrice(\n parseBigInt(toAmount),\n previousStep.action.toToken.priceUSD,\n previousStep.action.toToken.decimals\n ).toFixed(2)\n\n // Update the last included step's estimate with the adjusted values\n const lastStep = quote.includedSteps[quote.includedSteps.length - 1]\n if (lastStep && !hasNonZeroOutput(lastStep)) {\n lastStep.estimate.toAmount = toAmount\n lastStep.estimate.toAmountMin = toAmountMin\n }\n }\n }\n\n if (!quote.estimate.fromAmountUSD) {\n throw new SDKError(\n new ValidationError(\"Missing 'fromAmountUSD' in step estimate.\")\n )\n }\n\n if (!toAmountUSD) {\n throw new SDKError(\n new ValidationError(\"Missing 'toAmountUSD' in step estimate.\")\n )\n }\n\n const route: Route = {\n id: quote.id,\n fromChainId: quote.action.fromToken.chainId,\n fromToken: quote.action.fromToken,\n fromAmount: quote.action.fromAmount,\n fromAmountUSD: quote.estimate.fromAmountUSD,\n fromAddress: quote.action.fromAddress,\n toChainId: quote.action.toToken.chainId,\n toToken: quote.action.toToken,\n toAmount,\n toAmountMin,\n toAmountUSD,\n toAddress: quote.action.toAddress || quote.action.fromAddress,\n gasCostUSD: quote.estimate.gasCosts?.[0]?.amountUSD || '0',\n steps: [quote],\n insurance: { state: 'NOT_INSURABLE', feeAmountUsd: '0' },\n }\n\n return route\n}\n"],"mappings":";;;;AAaA,MAAM,eAAe,UAAsC;CACzD,IAAI,CAAC,OACH,OAAO;CAET,IAAI;EACF,OAAO,OAAO,KAAK;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,eAAe,UAAsC;CACzD,IAAI,CAAC,OACH,OAAO;CAET,MAAM,SAAS,OAAO,KAAK;CAC3B,OAAO,OAAO,MAAM,MAAM,IAAI,IAAI;AACpC;AAEA,MAAM,gBACJ,UACA,aACA,gBACY;CACZ,OACE,CAAC,YAAY,QAAQ,KACrB,CAAC,YAAY,WAAW,KACxB,CAAC,YAAY,WAAW;AAE5B;AAEA,MAAM,oBAAoB,SAAwB;CAChD,OACE,CAAC,CAAC,YAAY,KAAK,SAAS,QAAQ,KACpC,CAAC,CAAC,YAAY,KAAK,SAAS,WAAW;AAE3C;AAEA,MAAM,2BAA2B,UAAoC;CAEnE,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;EAC1C,MAAM,OAAO,MAAM;EACnB,IAAI,iBAAiB,IAAI,GACvB,OAAO;CAEX;AAEF;AAEA,SAAgB,iBACd,QACA,OACA,UACQ;CACR,IAAI,CAAC,UAAU,CAAC,OACd,OAAO;CAGT,MAAM,kBACJ,OAAO,WAAW,YAAY,aAAa,KAAA,IACvC,YAAY,QAAQ,QAAQ,IAC5B,OAAO,SAAS;CAEtB,IAAI,OAAO,MAAM,OAAO,eAAe,CAAC,KAAK,OAAO,MAAM,OAAO,KAAK,CAAC,GACrE,OAAO;CAET,OAAO,OAAO,WAAW,eAAe,IAAI,OAAO,WAAW,KAAK;AACrE;;;;;;;;AASA,MAAa,uBACX,OACA,YACU;CACV,IAAI,WAAW,MAAM,SAAS;CAC9B,IAAI,cAAc,MAAM,SAAS;CACjC,IAAI,cAAc,MAAM,SAAS;CAGjC,IACE,SAAS,oCACT,MAAM,eAAe,UACrB,aAAa,UAAU,aAAa,WAAW,GAC/C;EACA,MAAM,eAAe,wBAAwB,MAAM,aAAa;EAChE,IAAI,cAAc;GAChB,WAAW,aAAa,SAAS;GACjC,cAAc,aAAa,SAAS;GACpC,cAAc,iBACZ,YAAY,QAAQ,GACpB,aAAa,OAAO,QAAQ,UAC5B,aAAa,OAAO,QAAQ,QAC9B,
|
|
1
|
+
{"version":3,"file":"convertQuoteToRoute.js","names":[],"sources":["../../../src/utils/convertQuoteToRoute.ts"],"sourcesContent":["import type { LiFiStep, Route, Step } from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport { SDKError } from '../errors/SDKError.js'\nimport { formatUnits } from './formatUnits.js'\n\ninterface ConvertQuoteToRouteOptions {\n /**\n * When true, if the quote has zero output values (toAmount, toAmountMin, toAmountUSD),\n * use the values from the previous included step that has non-zero output.\n */\n adjustZeroOutputFromPreviousStep?: boolean\n}\n\nconst parseBigInt = (value: string | undefined): bigint => {\n if (!value) {\n return 0n\n }\n try {\n return BigInt(value)\n } catch {\n return 0n\n }\n}\n\nconst parseNumber = (value: string | undefined): number => {\n if (!value) {\n return 0\n }\n const parsed = Number(value)\n return Number.isNaN(parsed) ? 0 : parsed\n}\n\nconst isZeroOutput = (\n toAmount: string,\n toAmountMin: string,\n toAmountUSD?: string\n): boolean => {\n return (\n !parseBigInt(toAmount) &&\n !parseBigInt(toAmountMin) &&\n !parseNumber(toAmountUSD)\n )\n}\n\nconst hasNonZeroOutput = (step: Step): boolean => {\n return (\n !!parseBigInt(step.estimate.toAmount) ||\n !!parseBigInt(step.estimate.toAmountMin)\n )\n}\n\nconst findPreviousNonZeroStep = (steps: Step[]): Step | undefined => {\n // Find the last step that has non-zero output (the step before the zero output step)\n for (let i = steps.length - 1; i >= 0; i--) {\n const step = steps[i]\n if (hasNonZeroOutput(step)) {\n return step\n }\n }\n return undefined\n}\n\nexport function formatTokenPrice(\n amount?: string | bigint,\n price?: string,\n decimals?: number\n): number {\n if (!amount || !price) {\n return 0\n }\n\n const formattedAmount =\n typeof amount === 'bigint' && decimals !== undefined\n ? formatUnits(amount, decimals)\n : amount.toString()\n\n if (Number.isNaN(Number(formattedAmount)) || Number.isNaN(Number(price))) {\n return 0\n }\n return Number.parseFloat(formattedAmount) * Number.parseFloat(price)\n}\n\n/**\n * Converts a quote to Route\n * @param quote - Step returned from the quote endpoint.\n * @param options - Optional configuration for handling edge cases.\n * @returns - The route to be executed.\n * @throws {BaseError} Throws a ValidationError if the step has missing values.\n */\nexport const convertQuoteToRoute = (\n quote: LiFiStep,\n options?: ConvertQuoteToRouteOptions\n): Route => {\n let toAmount = quote.estimate.toAmount\n let toAmountMin = quote.estimate.toAmountMin\n let toAmountUSD = quote.estimate.toAmountUSD\n\n // Handle zero output values by looking at previous included step\n if (\n options?.adjustZeroOutputFromPreviousStep &&\n quote.includedSteps?.length &&\n isZeroOutput(toAmount, toAmountMin, toAmountUSD)\n ) {\n const previousStep = findPreviousNonZeroStep(quote.includedSteps)\n if (previousStep) {\n toAmount = previousStep.estimate.toAmount\n toAmountMin = previousStep.estimate.toAmountMin\n toAmountUSD = formatTokenPrice(\n parseBigInt(toAmount),\n previousStep.action.toToken.priceUSD,\n previousStep.action.toToken.decimals\n ).toFixed(2)\n\n // Update the last included step's estimate with the adjusted values\n const lastStep = quote.includedSteps[quote.includedSteps.length - 1]\n if (lastStep && !hasNonZeroOutput(lastStep)) {\n lastStep.estimate.toAmount = toAmount\n lastStep.estimate.toAmountMin = toAmountMin\n }\n }\n }\n\n if (!quote.estimate.fromAmountUSD) {\n throw new SDKError(\n new ValidationError(\"Missing 'fromAmountUSD' in step estimate.\")\n )\n }\n\n if (!toAmountUSD) {\n throw new SDKError(\n new ValidationError(\"Missing 'toAmountUSD' in step estimate.\")\n )\n }\n\n const route: Route = {\n id: quote.id,\n fromChainId: quote.action.fromToken.chainId,\n fromToken: quote.action.fromToken,\n fromAmount: quote.action.fromAmount,\n fromAmountUSD: quote.estimate.fromAmountUSD,\n fromAddress: quote.action.fromAddress,\n toChainId: quote.action.toToken.chainId,\n toToken: quote.action.toToken,\n toAmount,\n toAmountMin,\n toAmountUSD,\n toAddress: quote.action.toAddress || quote.action.fromAddress,\n gasCostUSD: quote.estimate.gasCosts?.[0]?.amountUSD || '0',\n steps: [quote],\n insurance: { state: 'NOT_INSURABLE', feeAmountUsd: '0' },\n }\n\n return route\n}\n"],"mappings":";;;;AAaA,MAAM,eAAe,UAAsC;CACzD,IAAI,CAAC,OACH,OAAO;CAET,IAAI;EACF,OAAO,OAAO,KAAK;CACrB,QAAQ;EACN,OAAO;CACT;AACF;AAEA,MAAM,eAAe,UAAsC;CACzD,IAAI,CAAC,OACH,OAAO;CAET,MAAM,SAAS,OAAO,KAAK;CAC3B,OAAO,OAAO,MAAM,MAAM,IAAI,IAAI;AACpC;AAEA,MAAM,gBACJ,UACA,aACA,gBACY;CACZ,OACE,CAAC,YAAY,QAAQ,KACrB,CAAC,YAAY,WAAW,KACxB,CAAC,YAAY,WAAW;AAE5B;AAEA,MAAM,oBAAoB,SAAwB;CAChD,OACE,CAAC,CAAC,YAAY,KAAK,SAAS,QAAQ,KACpC,CAAC,CAAC,YAAY,KAAK,SAAS,WAAW;AAE3C;AAEA,MAAM,2BAA2B,UAAoC;CAEnE,KAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;EAC1C,MAAM,OAAO,MAAM;EACnB,IAAI,iBAAiB,IAAI,GACvB,OAAO;CAEX;AAEF;AAEA,SAAgB,iBACd,QACA,OACA,UACQ;CACR,IAAI,CAAC,UAAU,CAAC,OACd,OAAO;CAGT,MAAM,kBACJ,OAAO,WAAW,YAAY,aAAa,KAAA,IACvC,YAAY,QAAQ,QAAQ,IAC5B,OAAO,SAAS;CAEtB,IAAI,OAAO,MAAM,OAAO,eAAe,CAAC,KAAK,OAAO,MAAM,OAAO,KAAK,CAAC,GACrE,OAAO;CAET,OAAO,OAAO,WAAW,eAAe,IAAI,OAAO,WAAW,KAAK;AACrE;;;;;;;;AASA,MAAa,uBACX,OACA,YACU;CACV,IAAI,WAAW,MAAM,SAAS;CAC9B,IAAI,cAAc,MAAM,SAAS;CACjC,IAAI,cAAc,MAAM,SAAS;CAGjC,IACE,SAAS,oCACT,MAAM,eAAe,UACrB,aAAa,UAAU,aAAa,WAAW,GAC/C;EACA,MAAM,eAAe,wBAAwB,MAAM,aAAa;EAChE,IAAI,cAAc;GAChB,WAAW,aAAa,SAAS;GACjC,cAAc,aAAa,SAAS;GACpC,cAAc,iBACZ,YAAY,QAAQ,GACpB,aAAa,OAAO,QAAQ,UAC5B,aAAa,OAAO,QAAQ,QAC9B,CAAC,CAAC,QAAQ,CAAC;GAGX,MAAM,WAAW,MAAM,cAAc,MAAM,cAAc,SAAS;GAClE,IAAI,YAAY,CAAC,iBAAiB,QAAQ,GAAG;IAC3C,SAAS,SAAS,WAAW;IAC7B,SAAS,SAAS,cAAc;GAClC;EACF;CACF;CAEA,IAAI,CAAC,MAAM,SAAS,eAClB,MAAM,IAAI,SACR,IAAI,gBAAgB,2CAA2C,CACjE;CAGF,IAAI,CAAC,aACH,MAAM,IAAI,SACR,IAAI,gBAAgB,yCAAyC,CAC/D;CAqBF,OAAO;EAjBL,IAAI,MAAM;EACV,aAAa,MAAM,OAAO,UAAU;EACpC,WAAW,MAAM,OAAO;EACxB,YAAY,MAAM,OAAO;EACzB,eAAe,MAAM,SAAS;EAC9B,aAAa,MAAM,OAAO;EAC1B,WAAW,MAAM,OAAO,QAAQ;EAChC,SAAS,MAAM,OAAO;EACtB;EACA;EACA;EACA,WAAW,MAAM,OAAO,aAAa,MAAM,OAAO;EAClD,YAAY,MAAM,SAAS,WAAW,EAAE,EAAE,aAAa;EACvD,OAAO,CAAC,KAAK;EACb,WAAW;GAAE,OAAO;GAAiB,cAAc;EAAI;CAG9C;AACb"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"decode.js","names":[],"sources":["../../../src/utils/decode.ts"],"sourcesContent":["export const decodeTaskId = (taskId: string): string[] => {\n const decoded = new TextDecoder()\n .decode(\n new Uint8Array(\n taskId\n .slice(2)\n .match(/.{1,2}/g)\n ?.map((byte) => Number.parseInt(byte, 16)) ?? []\n )\n )\n .split('|')\n return decoded\n}\n"],"mappings":";AAAA,MAAa,gBAAgB,WAA6B;CAWxD,OAVgB,IAAI,YAAY,
|
|
1
|
+
{"version":3,"file":"decode.js","names":[],"sources":["../../../src/utils/decode.ts"],"sourcesContent":["export const decodeTaskId = (taskId: string): string[] => {\n const decoded = new TextDecoder()\n .decode(\n new Uint8Array(\n taskId\n .slice(2)\n .match(/.{1,2}/g)\n ?.map((byte) => Number.parseInt(byte, 16)) ?? []\n )\n )\n .split('|')\n return decoded\n}\n"],"mappings":";AAAA,MAAa,gBAAgB,WAA6B;CAWxD,OAVgB,IAAI,YAAY,CAAC,CAC9B,OACC,IAAI,WACF,OACG,MAAM,CAAC,CAAC,CACR,MAAM,SAAS,CAAC,EACf,KAAK,SAAS,OAAO,SAAS,MAAM,EAAE,CAAC,KAAK,CAAC,CACnD,CACF,CAAC,CACA,MAAM,GACI;AACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fetchTxErrorDetails.js","names":[],"sources":["../../../src/utils/fetchTxErrorDetails.ts"],"sourcesContent":["export const fetchTxErrorDetails = async (\n txHash: string,\n chainId: number\n): Promise<unknown> => {\n try {\n const response = await fetch(\n `https://api.tenderly.co/api/v1/public-contract/${chainId}/tx/${txHash}`\n )\n const reponseBody = await response.json()\n\n return reponseBody\n } catch (_) {\n return undefined\n }\n}\n"],"mappings":";AAAA,MAAa,sBAAsB,OACjC,QACA,YACqB;CACrB,IAAI;EAMF,OAAO,OAFmB,MAHH,MACrB,kDAAkD,QAAQ,MAAM,QAClE,
|
|
1
|
+
{"version":3,"file":"fetchTxErrorDetails.js","names":[],"sources":["../../../src/utils/fetchTxErrorDetails.ts"],"sourcesContent":["export const fetchTxErrorDetails = async (\n txHash: string,\n chainId: number\n): Promise<unknown> => {\n try {\n const response = await fetch(\n `https://api.tenderly.co/api/v1/public-contract/${chainId}/tx/${txHash}`\n )\n const reponseBody = await response.json()\n\n return reponseBody\n } catch (_) {\n return undefined\n }\n}\n"],"mappings":";AAAA,MAAa,sBAAsB,OACjC,QACA,YACqB;CACrB,IAAI;EAMF,OAAO,OAFmB,MAHH,MACrB,kDAAkD,QAAQ,MAAM,QAClE,EAAA,CACmC,KAAK;CAG1C,SAAS,GAAG;EACV;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTransactionMessage.js","names":[],"sources":["../../../src/utils/getTransactionMessage.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport type { SDKClient } from '../types/core.js'\n\nexport const getTransactionFailedMessage = async (\n client: SDKClient,\n step: LiFiStep,\n txLink?: string\n): Promise<string> => {\n const chain = await client.getChainById(step.action.toChainId)\n\n const baseString = `It appears that your transaction may not have been successful.\n However, to confirm this, please check your ${chain.name} wallet for ${step.action.toToken.symbol}.`\n return txLink\n ? `${baseString}\n You can also check the <a href=\"${txLink}\" target=\"_blank\" rel=\"nofollow noreferrer\">block explorer</a> for more information.`\n : baseString\n}\n"],"mappings":";AAGA,MAAa,8BAA8B,OACzC,QACA,MACA,WACoB;CAGpB,MAAM,aAAa;iDAC2B,MAH1B,OAAO,aAAa,KAAK,OAAO,SAAS,
|
|
1
|
+
{"version":3,"file":"getTransactionMessage.js","names":[],"sources":["../../../src/utils/getTransactionMessage.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport type { SDKClient } from '../types/core.js'\n\nexport const getTransactionFailedMessage = async (\n client: SDKClient,\n step: LiFiStep,\n txLink?: string\n): Promise<string> => {\n const chain = await client.getChainById(step.action.toChainId)\n\n const baseString = `It appears that your transaction may not have been successful.\n However, to confirm this, please check your ${chain.name} wallet for ${step.action.toToken.symbol}.`\n return txLink\n ? `${baseString}\n You can also check the <a href=\"${txLink}\" target=\"_blank\" rel=\"nofollow noreferrer\">block explorer</a> for more information.`\n : baseString\n}\n"],"mappings":";AAGA,MAAa,8BAA8B,OACzC,QACA,MACA,WACoB;CAGpB,MAAM,aAAa;iDAC2B,MAH1B,OAAO,aAAa,KAAK,OAAO,SAAS,EAAA,CAGT,KAAK,cAAc,KAAK,OAAO,QAAQ,OAAO;CAClG,OAAO,SACH,GAAG,WAAW;2CACuB,OAAO,wFAC5C;AACN"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"isStep.js","names":[],"sources":["../../../src/utils/isStep.ts"],"sourcesContent":["import type { Action, Estimate, LiFiStep } from '@lifi/types'\nimport { isToken } from './isToken.js'\n\nconst isAction = (action: Action): action is Action => {\n const { fromChainId, fromAmount, fromToken, toChainId, toToken } = action\n\n return (\n typeof fromChainId === 'number' &&\n typeof fromAmount === 'string' &&\n fromAmount !== '' &&\n isToken(fromToken) &&\n typeof toChainId === 'number' &&\n isToken(toToken)\n )\n}\n\nconst isEstimate = (estimate: Estimate): estimate is Estimate => {\n const { fromAmount, toAmount, toAmountMin, approvalAddress } = estimate\n\n return (\n typeof fromAmount === 'string' &&\n fromAmount !== '' &&\n typeof toAmount === 'string' &&\n toAmount !== '' &&\n typeof toAmountMin === 'string' &&\n toAmountMin !== '' &&\n (typeof approvalAddress === 'string' || approvalAddress === null)\n )\n}\n\nexport const isStep = (step: LiFiStep): step is LiFiStep => {\n const { id, type, tool, action, estimate } = step\n\n return (\n typeof id === 'string' &&\n ['swap', 'cross', 'lifi'].includes(type) &&\n typeof tool === 'string' &&\n isAction(action) &&\n isEstimate(estimate)\n )\n}\n"],"mappings":";;AAGA,MAAM,YAAY,WAAqC;CACrD,MAAM,EAAE,aAAa,YAAY,WAAW,WAAW,YAAY;CAEnE,OACE,OAAO,gBAAgB,YACvB,OAAO,eAAe,YACtB,eAAe,MACf,QAAQ,SAAS,KACjB,OAAO,cAAc,YACrB,QAAQ,OAAO;AAEnB;AAEA,MAAM,cAAc,aAA6C;CAC/D,MAAM,EAAE,YAAY,UAAU,aAAa,oBAAoB;CAE/D,OACE,OAAO,eAAe,YACtB,eAAe,MACf,OAAO,aAAa,YACpB,aAAa,MACb,OAAO,gBAAgB,YACvB,gBAAgB,OACf,OAAO,oBAAoB,YAAY,oBAAoB;AAEhE;AAEA,MAAa,UAAU,SAAqC;CAC1D,MAAM,EAAE,IAAI,MAAM,MAAM,QAAQ,aAAa;CAE7C,OACE,OAAO,OAAO,YACd;EAAC;EAAQ;EAAS;CAAM,
|
|
1
|
+
{"version":3,"file":"isStep.js","names":[],"sources":["../../../src/utils/isStep.ts"],"sourcesContent":["import type { Action, Estimate, LiFiStep } from '@lifi/types'\nimport { isToken } from './isToken.js'\n\nconst isAction = (action: Action): action is Action => {\n const { fromChainId, fromAmount, fromToken, toChainId, toToken } = action\n\n return (\n typeof fromChainId === 'number' &&\n typeof fromAmount === 'string' &&\n fromAmount !== '' &&\n isToken(fromToken) &&\n typeof toChainId === 'number' &&\n isToken(toToken)\n )\n}\n\nconst isEstimate = (estimate: Estimate): estimate is Estimate => {\n const { fromAmount, toAmount, toAmountMin, approvalAddress } = estimate\n\n return (\n typeof fromAmount === 'string' &&\n fromAmount !== '' &&\n typeof toAmount === 'string' &&\n toAmount !== '' &&\n typeof toAmountMin === 'string' &&\n toAmountMin !== '' &&\n (typeof approvalAddress === 'string' || approvalAddress === null)\n )\n}\n\nexport const isStep = (step: LiFiStep): step is LiFiStep => {\n const { id, type, tool, action, estimate } = step\n\n return (\n typeof id === 'string' &&\n ['swap', 'cross', 'lifi'].includes(type) &&\n typeof tool === 'string' &&\n isAction(action) &&\n isEstimate(estimate)\n )\n}\n"],"mappings":";;AAGA,MAAM,YAAY,WAAqC;CACrD,MAAM,EAAE,aAAa,YAAY,WAAW,WAAW,YAAY;CAEnE,OACE,OAAO,gBAAgB,YACvB,OAAO,eAAe,YACtB,eAAe,MACf,QAAQ,SAAS,KACjB,OAAO,cAAc,YACrB,QAAQ,OAAO;AAEnB;AAEA,MAAM,cAAc,aAA6C;CAC/D,MAAM,EAAE,YAAY,UAAU,aAAa,oBAAoB;CAE/D,OACE,OAAO,eAAe,YACtB,eAAe,MACf,OAAO,aAAa,YACpB,aAAa,MACb,OAAO,gBAAgB,YACvB,gBAAgB,OACf,OAAO,oBAAoB,YAAY,oBAAoB;AAEhE;AAEA,MAAa,UAAU,SAAqC;CAC1D,MAAM,EAAE,IAAI,MAAM,MAAM,QAAQ,aAAa;CAE7C,OACE,OAAO,OAAO,YACd;EAAC;EAAQ;EAAS;CAAM,CAAC,CAAC,SAAS,IAAI,KACvC,OAAO,SAAS,YAChB,SAAS,MAAM,KACf,WAAW,QAAQ;AAEvB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withDedupe.js","names":[],"sources":["../../../src/utils/withDedupe.ts"],"sourcesContent":["/**\n * Map with a LRU (Least recently used) policy.\n *\n * https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap<value = unknown> extends Map<string, value> {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override set(key: string, value: value): this {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n this.delete(this.keys().next().value!)\n }\n return this\n }\n}\n\n/** @internal */\nconst promiseCache = /*#__PURE__*/ new LruMap<Promise<any>>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe<T>(\n fn: () => Promise<T>,\n { enabled = true, id }: WithDedupeOptions\n): Promise<T> {\n if (!enabled || !id) {\n return fn()\n }\n if (promiseCache.get(id)) {\n return promiseCache.get(id)!\n }\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n"],"mappings":";;;;;;AAKA,IAAa,SAAb,cAA6C,IAAmB;CAC9D;CAEA,YAAY,MAAc;EACxB,MAAM;EACN,KAAK,UAAU;CACjB;CAEA,IAAa,KAAa,OAAoB;EAC5C,MAAM,IAAI,KAAK,KAAK;EACpB,IAAI,KAAK,WAAW,KAAK,OAAO,KAAK,SACnC,KAAK,OAAO,KAAK,KAAK,
|
|
1
|
+
{"version":3,"file":"withDedupe.js","names":[],"sources":["../../../src/utils/withDedupe.ts"],"sourcesContent":["/**\n * Map with a LRU (Least recently used) policy.\n *\n * https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap<value = unknown> extends Map<string, value> {\n maxSize: number\n\n constructor(size: number) {\n super()\n this.maxSize = size\n }\n\n override set(key: string, value: value): this {\n super.set(key, value)\n if (this.maxSize && this.size > this.maxSize) {\n this.delete(this.keys().next().value!)\n }\n return this\n }\n}\n\n/** @internal */\nconst promiseCache = /*#__PURE__*/ new LruMap<Promise<any>>(8192)\n\ntype WithDedupeOptions = {\n enabled?: boolean | undefined\n id?: string | undefined\n}\n\n/** Deduplicates in-flight promises. */\nexport function withDedupe<T>(\n fn: () => Promise<T>,\n { enabled = true, id }: WithDedupeOptions\n): Promise<T> {\n if (!enabled || !id) {\n return fn()\n }\n if (promiseCache.get(id)) {\n return promiseCache.get(id)!\n }\n const promise = fn().finally(() => promiseCache.delete(id))\n promiseCache.set(id, promise)\n return promise\n}\n"],"mappings":";;;;;;AAKA,IAAa,SAAb,cAA6C,IAAmB;CAC9D;CAEA,YAAY,MAAc;EACxB,MAAM;EACN,KAAK,UAAU;CACjB;CAEA,IAAa,KAAa,OAAoB;EAC5C,MAAM,IAAI,KAAK,KAAK;EACpB,IAAI,KAAK,WAAW,KAAK,OAAO,KAAK,SACnC,KAAK,OAAO,KAAK,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,KAAM;EAEvC,OAAO;CACT;AACF;;AAGA,MAAM,6BAA6B,IAAI,OAAqB,IAAI;;AAQhE,SAAgB,WACd,IACA,EAAE,UAAU,MAAM,MACN;CACZ,IAAI,CAAC,WAAW,CAAC,IACf,OAAO,GAAG;CAEZ,IAAI,aAAa,IAAI,EAAE,GACrB,OAAO,aAAa,IAAI,EAAE;CAE5B,MAAM,UAAU,GAAG,CAAC,CAAC,cAAc,aAAa,OAAO,EAAE,CAAC;CAC1D,aAAa,IAAI,IAAI,OAAO;CAC5B,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"withTimeout.js","names":[],"sources":["../../../src/utils/withTimeout.ts"],"sourcesContent":["/**\n * Wraps a function in a timeout.\n * Based on viem's withTimeout implementation.\n * @param fn - The function to wrap.\n * @param timeout - The timeout in milliseconds.\n * @param errorInstance - The error instance to throw when the timeout is reached.\n * @param signal - Whether or not the timeout should use an abort signal.\n * @returns The result of the function.\n */\nexport function withTimeout<T>(\n fn: ({ signal }: { signal: AbortController['signal'] | null }) => Promise<T>,\n {\n errorInstance = new Error('Timed out after waiting for too long.'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n }\n): Promise<T> {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') {\n reject(errorInstance)\n }\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,YACd,IACA,EACE,gCAAgB,IAAI,MAAM,uCAAuC,GACjE,SACA,UASU;CACZ,OAAO,IAAI,SAAS,SAAS,WAAW;EACrC,CAAC,YAAY;GACZ,IAAI;GACJ,IAAI;IACF,MAAM,aAAa,IAAI,gBAAgB;IACvC,IAAI,UAAU,GACZ,YAAY,iBAAiB;KAC3B,IAAI,QACF,WAAW,MAAM;UAEjB,OAAO,aAAa;IAExB,GAAG,OAAO;IAEZ,QAAQ,MAAM,GAAG,EAAE,QAAQ,YAAY,UAAU,KAAK,CAAC,CAAC;GAC1D,SAAS,KAAK;IACZ,IAAK,KAAe,SAAS,cAC3B,OAAO,aAAa;IAEtB,OAAO,GAAG;GACZ,UAAU;IACR,aAAa,SAAS;GACxB;EACF,
|
|
1
|
+
{"version":3,"file":"withTimeout.js","names":[],"sources":["../../../src/utils/withTimeout.ts"],"sourcesContent":["/**\n * Wraps a function in a timeout.\n * Based on viem's withTimeout implementation.\n * @param fn - The function to wrap.\n * @param timeout - The timeout in milliseconds.\n * @param errorInstance - The error instance to throw when the timeout is reached.\n * @param signal - Whether or not the timeout should use an abort signal.\n * @returns The result of the function.\n */\nexport function withTimeout<T>(\n fn: ({ signal }: { signal: AbortController['signal'] | null }) => Promise<T>,\n {\n errorInstance = new Error('Timed out after waiting for too long.'),\n timeout,\n signal,\n }: {\n // The error instance to throw when the timeout is reached.\n errorInstance?: Error | undefined\n // The timeout (in ms).\n timeout: number\n // Whether or not the timeout should use an abort signal.\n signal?: boolean | undefined\n }\n): Promise<T> {\n return new Promise((resolve, reject) => {\n ;(async () => {\n let timeoutId!: NodeJS.Timeout\n try {\n const controller = new AbortController()\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort()\n } else {\n reject(errorInstance)\n }\n }, timeout) as NodeJS.Timeout // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }))\n } catch (err) {\n if ((err as Error)?.name === 'AbortError') {\n reject(errorInstance)\n }\n reject(err)\n } finally {\n clearTimeout(timeoutId)\n }\n })()\n })\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,YACd,IACA,EACE,gCAAgB,IAAI,MAAM,uCAAuC,GACjE,SACA,UASU;CACZ,OAAO,IAAI,SAAS,SAAS,WAAW;EACrC,CAAC,YAAY;GACZ,IAAI;GACJ,IAAI;IACF,MAAM,aAAa,IAAI,gBAAgB;IACvC,IAAI,UAAU,GACZ,YAAY,iBAAiB;KAC3B,IAAI,QACF,WAAW,MAAM;UAEjB,OAAO,aAAa;IAExB,GAAG,OAAO;IAEZ,QAAQ,MAAM,GAAG,EAAE,QAAQ,YAAY,UAAU,KAAK,CAAC,CAAC;GAC1D,SAAS,KAAK;IACZ,IAAK,KAAe,SAAS,cAC3B,OAAO,aAAa;IAEtB,OAAO,GAAG;GACZ,UAAU;IACR,aAAa,SAAS;GACxB;EACF,EAAA,CAAG;CACL,CAAC;AACH"}
|
package/dist/esm/version.d.ts
CHANGED
package/dist/esm/version.js
CHANGED
package/dist/esm/version.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk'\nexport const version = '4.0.
|
|
1
|
+
{"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk'\nexport const version = '4.0.1'\n"],"mappings":";AAAA,MAAa,OAAO;AACpB,MAAa,UAAU"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lifi/sdk",
|
|
3
|
-
"version": "4.0.
|
|
3
|
+
"version": "4.0.1",
|
|
4
4
|
"description": "LI.FI SDK for Any-to-Any Cross-Chain-Swap",
|
|
5
5
|
"homepage": "https://github.com/lifinance/sdk",
|
|
6
6
|
"bugs": {
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
"./package.json": "./package.json"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@lifi/types": "17.
|
|
31
|
+
"@lifi/types": "17.85.0"
|
|
32
32
|
},
|
|
33
33
|
"publishConfig": {
|
|
34
34
|
"access": "public"
|
package/src/version.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export const name = '@lifi/sdk'
|
|
2
|
-
export const version = '4.0.
|
|
2
|
+
export const version = '4.0.1'
|