@lifi/sdk 4.8.2 → 4.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/dist/cjs/actions/getChains.js +7 -1
- package/dist/cjs/actions/getChains.js.map +1 -1
- package/dist/cjs/actions/getContractCallsQuote.js +1 -1
- package/dist/cjs/actions/getGasRecommendation.js +1 -1
- package/dist/cjs/actions/getQuote.js +1 -1
- package/dist/cjs/actions/getRelayedTransactionStatus.js +1 -1
- package/dist/cjs/actions/getRelayerQuote.js +1 -1
- package/dist/cjs/actions/getRoutes.js +1 -1
- package/dist/cjs/actions/getStatus.js +1 -1
- package/dist/cjs/actions/getToken.js +1 -1
- package/dist/cjs/actions/getTokens.js +7 -1
- package/dist/cjs/actions/getTokens.js.map +1 -1
- package/dist/cjs/actions/relayTransaction.js +1 -1
- package/dist/cjs/client/createClient.js +23 -2
- package/dist/cjs/client/createClient.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/checkBalance.js +6 -3
- package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/cjs/index.d.ts +4 -3
- package/dist/cjs/index.js +4 -3
- package/dist/cjs/types/core.d.ts +56 -1
- package/dist/cjs/utils/abort.d.ts +6 -0
- package/dist/cjs/utils/abort.js +10 -0
- package/dist/cjs/utils/abort.js.map +1 -0
- package/dist/cjs/utils/checkPackageUpdates.js +1 -1
- package/dist/cjs/utils/convertQuoteToRoute.js +1 -1
- package/dist/cjs/utils/formatUnits.js +1 -0
- package/dist/cjs/utils/formatUnits.js.map +1 -1
- package/dist/cjs/utils/lru.d.ts +14 -0
- package/dist/cjs/utils/lru.js +35 -0
- package/dist/cjs/utils/lru.js.map +1 -0
- package/dist/cjs/utils/parseUnits.js +30 -16
- package/dist/cjs/utils/parseUnits.js.map +1 -1
- package/dist/cjs/utils/request.js +2 -2
- package/dist/cjs/utils/sleep.d.ts +7 -1
- package/dist/cjs/utils/sleep.js +22 -3
- package/dist/cjs/utils/sleep.js.map +1 -1
- package/dist/cjs/utils/waitForResult.d.ts +4 -4
- package/dist/cjs/utils/waitForResult.js +4 -4
- package/dist/cjs/utils/waitForResult.js.map +1 -1
- package/dist/cjs/utils/withDedupe.d.ts +15 -12
- package/dist/cjs/utils/withDedupe.js +69 -25
- package/dist/cjs/utils/withDedupe.js.map +1 -1
- package/dist/cjs/utils/withTimeout.js +6 -2
- 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.d.ts.map +1 -1
- package/dist/esm/actions/getChains.js +7 -1
- package/dist/esm/actions/getChains.js.map +1 -1
- package/dist/esm/actions/getContractCallsQuote.js +1 -1
- package/dist/esm/actions/getGasRecommendation.js +1 -1
- package/dist/esm/actions/getQuote.js +1 -1
- package/dist/esm/actions/getRelayedTransactionStatus.js +1 -1
- package/dist/esm/actions/getRelayerQuote.js +1 -1
- package/dist/esm/actions/getRoutes.js +1 -1
- package/dist/esm/actions/getStatus.js +1 -1
- package/dist/esm/actions/getToken.js +1 -1
- package/dist/esm/actions/getTokens.d.ts.map +1 -1
- package/dist/esm/actions/getTokens.js +7 -1
- package/dist/esm/actions/getTokens.js.map +1 -1
- package/dist/esm/actions/relayTransaction.js +1 -1
- package/dist/esm/client/createClient.d.ts.map +1 -1
- package/dist/esm/client/createClient.js +23 -2
- package/dist/esm/client/createClient.js.map +1 -1
- package/dist/esm/core/tasks/helpers/checkBalance.js +6 -3
- package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/esm/index.d.ts +4 -3
- package/dist/esm/index.js +4 -3
- package/dist/esm/types/core.d.ts +56 -1
- package/dist/esm/types/core.d.ts.map +1 -1
- package/dist/esm/utils/abort.d.ts +6 -0
- package/dist/esm/utils/abort.d.ts.map +1 -0
- package/dist/esm/utils/abort.js +8 -0
- package/dist/esm/utils/abort.js.map +1 -0
- package/dist/esm/utils/checkPackageUpdates.js +1 -1
- package/dist/esm/utils/convertQuoteToRoute.js +1 -1
- package/dist/esm/utils/formatUnits.js +1 -0
- package/dist/esm/utils/formatUnits.js.map +1 -1
- package/dist/esm/utils/lru.d.ts +14 -0
- package/dist/esm/utils/lru.d.ts.map +1 -0
- package/dist/esm/utils/lru.js +34 -0
- package/dist/esm/utils/lru.js.map +1 -0
- package/dist/esm/utils/parseUnits.js +30 -16
- package/dist/esm/utils/parseUnits.js.map +1 -1
- package/dist/esm/utils/request.js +2 -2
- package/dist/esm/utils/sleep.d.ts +7 -1
- package/dist/esm/utils/sleep.d.ts.map +1 -1
- package/dist/esm/utils/sleep.js +22 -3
- package/dist/esm/utils/sleep.js.map +1 -1
- package/dist/esm/utils/waitForResult.d.ts +4 -4
- package/dist/esm/utils/waitForResult.js +4 -4
- package/dist/esm/utils/waitForResult.js.map +1 -1
- package/dist/esm/utils/withDedupe.d.ts +15 -12
- package/dist/esm/utils/withDedupe.d.ts.map +1 -1
- package/dist/esm/utils/withDedupe.js +71 -25
- package/dist/esm/utils/withDedupe.js.map +1 -1
- package/dist/esm/utils/withTimeout.d.ts.map +1 -1
- package/dist/esm/utils/withTimeout.js +6 -2
- 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/actions/getChains.ts +12 -4
- package/src/actions/getTokens.ts +12 -4
- package/src/client/createClient.ts +35 -2
- package/src/core/tasks/helpers/checkBalance.ts +11 -3
- package/src/index.ts +4 -1
- package/src/types/core.ts +59 -1
- package/src/utils/abort.ts +10 -0
- package/src/utils/formatUnits.ts +6 -0
- package/src/utils/lru.ts +38 -0
- package/src/utils/parseUnits.ts +53 -20
- package/src/utils/sleep.ts +27 -3
- package/src/utils/waitForResult.ts +4 -4
- package/src/utils/withDedupe.ts +121 -27
- package/src/utils/withTimeout.ts +7 -2
- package/src/version.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,38 @@
|
|
|
1
1
|
# @lifi/sdk
|
|
2
2
|
|
|
3
|
+
## 4.10.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#499](https://github.com/lifinance/sdk/pull/499) [`2d60ab4`](https://github.com/lifinance/sdk/commit/2d60ab43af2ecd1c17a3bbb126de408952a46d80) Thanks [@chybisov](https://github.com/chybisov)! - `sleep` takes an optional `{ signal }`. It rejects with the abort reason as soon as the signal aborts.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- [#496](https://github.com/lifinance/sdk/pull/496) [`dcbbdcc`](https://github.com/lifinance/sdk/commit/dcbbdccc2684c4549cbfe06444698f11347206af) Thanks [@chybisov](https://github.com/chybisov)! - Bump the `@lifi/types` pin to `^18.12.1`, which adds `slippageScope` and the route-wide
|
|
12
|
+
slippage commitment types.
|
|
13
|
+
|
|
14
|
+
- [#499](https://github.com/lifinance/sdk/pull/499) [`2d60ab4`](https://github.com/lifinance/sdk/commit/2d60ab43af2ecd1c17a3bbb126de408952a46d80) Thanks [@chybisov](https://github.com/chybisov)! - Stop the balance check's retry loop once its 10 s timeout rejects, so a late balance read can no longer change `step.action.fromAmount`.
|
|
15
|
+
|
|
16
|
+
- [#499](https://github.com/lifinance/sdk/pull/499) [`2d60ab4`](https://github.com/lifinance/sdk/commit/2d60ab43af2ecd1c17a3bbb126de408952a46d80) Thanks [@chybisov](https://github.com/chybisov)! - `LruMap` now evicts the least recently used entry instead of the oldest one, and no longer grows past its size on iOS 18.
|
|
17
|
+
|
|
18
|
+
- [#499](https://github.com/lifinance/sdk/pull/499) [`2d60ab4`](https://github.com/lifinance/sdk/commit/2d60ab43af2ecd1c17a3bbb126de408952a46d80) Thanks [@chybisov](https://github.com/chybisov)! - `parseUnits` rounds long fractions exactly, and `parseUnits` and `formatUnits` throw on a negative or fractional `decimals` instead of giving a wrong amount. An input with no digit, such as `''`, still parses as `0n`.
|
|
19
|
+
|
|
20
|
+
- [#499](https://github.com/lifinance/sdk/pull/499) [`2d60ab4`](https://github.com/lifinance/sdk/commit/2d60ab43af2ecd1c17a3bbb126de408952a46d80) Thanks [@chybisov](https://github.com/chybisov)! - `withTimeout` now rejects with its timeout error only when its own timeout fires. Any other `AbortError` from the wrapped function passes through, so a wallet `AbortError` in the Bitcoin and Solana signing steps is no longer reported as `TransactionExpired`.
|
|
21
|
+
|
|
22
|
+
## 4.9.0
|
|
23
|
+
|
|
24
|
+
### Minor Changes
|
|
25
|
+
|
|
26
|
+
- [#493](https://github.com/lifinance/sdk/pull/493) [`145f2b4`](https://github.com/lifinance/sdk/commit/145f2b49dbbc55776e0b0fe34b0b890f3e5be199) Thanks [@chybisov](https://github.com/chybisov)! - The `rpcUrls` option of `createClient` can split a chain's RPCs by role: `{ read?: string[]; write?: string[]; bundle?: string[] }` next to the existing plain list. Reads use `read` (unset: the chain's own RPCs). `write` and `bundle` are dedicated send and bundle-submission RPCs; only `@lifi/sdk-provider-solana` uses them today, and other providers ignore them. `client.config.rpcUrls`, `getRpcUrls` and `getRpcUrlsByChainId` keep holding plain read lists; the new optional `client.getWriteRpcUrlsByChainId` and `client.getBundleRpcUrlsByChainId` return a chain's write and bundle lists, empty when it has none.
|
|
27
|
+
|
|
28
|
+
Plain lists work as before. At the type level, `SDKConfig['rpcUrls']` is now `RPCUrlsConfig`, so code that reads it back from a config object must narrow each entry with `Array.isArray`.
|
|
29
|
+
|
|
30
|
+
### Patch Changes
|
|
31
|
+
|
|
32
|
+
- [#491](https://github.com/lifinance/sdk/pull/491) [`a65b003`](https://github.com/lifinance/sdk/commit/a65b00391698c3e8c2a1cd826bb0969c6977ecb6) Thanks [@chybisov](https://github.com/chybisov)! - A caller that aborts a deduplicated request no longer fails the other callers of that request. `getTokens` and `getChains` share an in-flight request between callers that ask the same query, and the shared request carried the first caller's signal, so when that caller aborted, every other caller got its `AbortError`. Now a caller that aborts leaves the shared request at once, and the request is aborted only when every caller has aborted. `withDedupe` takes an optional `signal` and passes its callback the signal to hand on to the request.
|
|
33
|
+
|
|
34
|
+
- [#495](https://github.com/lifinance/sdk/pull/495) [`9e815bd`](https://github.com/lifinance/sdk/commit/9e815bdd0d818b7e0866c78bdf48065185b64210) Thanks [@chybisov](https://github.com/chybisov)! - `withDedupe` adds its own handler to a shared request only once a caller with a signal joins. A request shared only by callers without a signal is still reported as an unhandled rejection when it fails and no caller handles it, as it was before `signal` support.
|
|
35
|
+
|
|
3
36
|
## 4.8.2
|
|
4
37
|
|
|
5
38
|
### Patch Changes
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
2
3
|
const require_utils_request = require("../utils/request.js");
|
|
3
4
|
const require_utils_withDedupe = require("../utils/withDedupe.js");
|
|
4
5
|
//#region src/actions/getChains.ts
|
|
@@ -19,7 +20,12 @@ const _getChains = async (config, params, options) => {
|
|
|
19
20
|
if (value === void 0 || value === null) delete params[key];
|
|
20
21
|
}
|
|
21
22
|
const urlSearchParams = new URLSearchParams(params).toString();
|
|
22
|
-
return (await require_utils_withDedupe.withDedupe(() => require_utils_request.request(config, `${config.apiUrl}/chains?${urlSearchParams}`, { signal
|
|
23
|
+
return (await require_utils_withDedupe.withDedupe((signal) => require_utils_request.request(config, `${config.apiUrl}/chains?${urlSearchParams}`, { signal }), {
|
|
24
|
+
id: `${getChains.name}.${config.apiUrl}.${urlSearchParams}`,
|
|
25
|
+
signal: options?.signal
|
|
26
|
+
}).catch((error) => {
|
|
27
|
+
throw error instanceof require_errors_SDKError.SDKError ? error : new require_errors_SDKError.SDKError(error);
|
|
28
|
+
})).chains;
|
|
23
29
|
};
|
|
24
30
|
//#endregion
|
|
25
31
|
exports._getChains = _getChains;
|
|
@@ -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
|
|
1
|
+
{"version":3,"file":"getChains.js","names":["withDedupe","request","SDKError"],"sources":["../../../src/actions/getChains.ts"],"sourcesContent":["import type {\n ChainsRequest,\n ChainsResponse,\n ExtendedChain,\n RequestOptions,\n} from '@lifi/types'\nimport { SDKError } from '../errors/SDKError.js'\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 (signal) =>\n request<ChainsResponse>(\n config,\n `${config.apiUrl}/chains?${urlSearchParams}`,\n {\n signal,\n }\n ),\n {\n id: `${getChains.name}.${config.apiUrl}.${urlSearchParams}`,\n signal: options?.signal,\n }\n ).catch((error) => {\n // A caller that aborts leaves before the request settles; keep its error\n // shaped like one from `request`.\n throw error instanceof SDKError ? error : new SDKError(error)\n })\n return response.chains\n}\n"],"mappings":";;;;;;;;;;;;;AAmBA,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;CAmBX,QAAO,MAlBgBA,yBAAAA,YACpB,WACCC,sBAAAA,QACE,QACA,GAAG,OAAO,OAAO,UAAU,mBAC3B,EACE,OACF,CACF,GACF;EACE,IAAI,GAAG,UAAU,KAAK,GAAG,OAAO,OAAO,GAAG;EAC1C,QAAQ,SAAS;CACnB,CACF,CAAC,CAAC,OAAO,UAAU;EAGjB,MAAM,iBAAiBC,wBAAAA,WAAW,QAAQ,IAAIA,wBAAAA,SAAS,KAAK;CAC9D,CAAC,EAAA,CACe;AAClB"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_errors_errors = require("../errors/errors.js");
|
|
3
2
|
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
3
|
+
const require_errors_errors = require("../errors/errors.js");
|
|
4
4
|
const require_utils_request = require("../utils/request.js");
|
|
5
5
|
let _lifi_types = require("@lifi/types");
|
|
6
6
|
//#region src/actions/getContractCallsQuote.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_errors_errors = require("../errors/errors.js");
|
|
3
2
|
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
3
|
+
const require_errors_errors = require("../errors/errors.js");
|
|
4
4
|
const require_utils_request = require("../utils/request.js");
|
|
5
5
|
//#region src/actions/getGasRecommendation.ts
|
|
6
6
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_errors_errors = require("../errors/errors.js");
|
|
3
2
|
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
3
|
+
const require_errors_errors = require("../errors/errors.js");
|
|
4
4
|
const require_utils_request = require("../utils/request.js");
|
|
5
5
|
const require_utils_toQueryString = require("../utils/toQueryString.js");
|
|
6
6
|
//#region src/actions/getQuote.ts
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
2
3
|
const require_errors_baseError = require("../errors/baseError.js");
|
|
3
4
|
require("../errors/constants.js");
|
|
4
5
|
const require_errors_errors = require("../errors/errors.js");
|
|
5
|
-
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
6
6
|
const require_utils_request = require("../utils/request.js");
|
|
7
7
|
const require_utils_decode = require("../utils/decode.js");
|
|
8
8
|
const require_actions_getStatus = require("./getStatus.js");
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
2
3
|
const require_errors_baseError = require("../errors/baseError.js");
|
|
3
4
|
require("../errors/constants.js");
|
|
4
5
|
const require_errors_errors = require("../errors/errors.js");
|
|
5
|
-
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
6
6
|
const require_utils_request = require("../utils/request.js");
|
|
7
7
|
//#region src/actions/getRelayerQuote.ts
|
|
8
8
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_errors_errors = require("../errors/errors.js");
|
|
3
2
|
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
3
|
+
const require_errors_errors = require("../errors/errors.js");
|
|
4
4
|
const require_utils_request = require("../utils/request.js");
|
|
5
5
|
const require_utils_isRoutesRequest = require("../utils/isRoutesRequest.js");
|
|
6
6
|
//#region src/actions/getRoutes.ts
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_errors_errors = require("../errors/errors.js");
|
|
3
2
|
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
3
|
+
const require_errors_errors = require("../errors/errors.js");
|
|
4
4
|
const require_utils_request = require("../utils/request.js");
|
|
5
5
|
//#region src/actions/getStatus.ts
|
|
6
6
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_errors_errors = require("../errors/errors.js");
|
|
3
2
|
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
3
|
+
const require_errors_errors = require("../errors/errors.js");
|
|
4
4
|
const require_utils_request = require("../utils/request.js");
|
|
5
5
|
//#region src/actions/getToken.ts
|
|
6
6
|
/**
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
2
3
|
const require_utils_request = require("../utils/request.js");
|
|
3
4
|
const require_utils_withDedupe = require("../utils/withDedupe.js");
|
|
4
5
|
//#region src/actions/getTokens.ts
|
|
@@ -9,7 +10,12 @@ async function getTokens(client, params, options) {
|
|
|
9
10
|
}
|
|
10
11
|
const urlSearchParams = new URLSearchParams(params).toString();
|
|
11
12
|
params?.extended;
|
|
12
|
-
return await require_utils_withDedupe.withDedupe(() => require_utils_request.request(client.config, `${client.config.apiUrl}/tokens?${urlSearchParams}`, { signal
|
|
13
|
+
return await require_utils_withDedupe.withDedupe((signal) => require_utils_request.request(client.config, `${client.config.apiUrl}/tokens?${urlSearchParams}`, { signal }), {
|
|
14
|
+
id: `${getTokens.name}.${client.config.apiUrl}.${urlSearchParams}`,
|
|
15
|
+
signal: options?.signal
|
|
16
|
+
}).catch((error) => {
|
|
17
|
+
throw error instanceof require_errors_SDKError.SDKError ? error : new require_errors_SDKError.SDKError(error);
|
|
18
|
+
});
|
|
13
19
|
}
|
|
14
20
|
//#endregion
|
|
15
21
|
exports.getTokens = getTokens;
|
|
@@ -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
|
|
1
|
+
{"version":3,"file":"getTokens.js","names":["withDedupe","request","SDKError"],"sources":["../../../src/actions/getTokens.ts"],"sourcesContent":["import type {\n RequestOptions,\n TokensExtendedResponse,\n TokensRequest,\n TokensResponse,\n} from '@lifi/types'\nimport { SDKError } from '../errors/SDKError.js'\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 (signal) =>\n request<\n typeof _isExtended extends true\n ? TokensExtendedResponse\n : TokensResponse\n >(client.config, `${client.config.apiUrl}/tokens?${urlSearchParams}`, {\n signal,\n }),\n {\n id: `${getTokens.name}.${client.config.apiUrl}.${urlSearchParams}`,\n signal: options?.signal,\n }\n ).catch((error) => {\n // A caller that aborts leaves before the request settles; keep its error\n // shaped like one from `request`.\n throw error instanceof SDKError ? error : new SDKError(error)\n })\n return response\n}\n"],"mappings":";;;;;AA4BA,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;CAmB5B,OAAO,MAlBgBA,yBAAAA,YACpB,WACCC,sBAAAA,QAIE,OAAO,QAAQ,GAAG,OAAO,OAAO,OAAO,UAAU,mBAAmB,EACpE,OACF,CAAC,GACH;EACE,IAAI,GAAG,UAAU,KAAK,GAAG,OAAO,OAAO,OAAO,GAAG;EACjD,QAAQ,SAAS;CACnB,CACF,CAAC,CAAC,OAAO,UAAU;EAGjB,MAAM,iBAAiBC,wBAAAA,WAAW,QAAQ,IAAIA,wBAAAA,SAAS,KAAK;CAC9D,CAAC;AAEH"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
2
3
|
const require_errors_baseError = require("../errors/baseError.js");
|
|
3
4
|
require("../errors/constants.js");
|
|
4
5
|
const require_errors_errors = require("../errors/errors.js");
|
|
5
|
-
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
6
6
|
const require_utils_request = require("../utils/request.js");
|
|
7
7
|
//#region src/actions/relayTransaction.ts
|
|
8
8
|
/**
|
|
@@ -6,11 +6,26 @@ const require_client_getClientStorage = require("./getClientStorage.js");
|
|
|
6
6
|
function createClient(options) {
|
|
7
7
|
if (!options.integrator) throw new Error("Integrator not found. Please see documentation https://docs.li.fi/integrate-li.fi-js-sdk/set-up-the-sdk");
|
|
8
8
|
if (!options.disableVersionCheck && process.env.NODE_ENV === "development") require_utils_checkPackageUpdates.checkPackageUpdates(require_version.name, require_version.version);
|
|
9
|
-
const { providers, ...configOptions } = options;
|
|
9
|
+
const { providers, rpcUrls, ...configOptions } = options;
|
|
10
|
+
const readRpcUrls = {};
|
|
11
|
+
const writeRpcUrls = {};
|
|
12
|
+
const bundleRpcUrls = {};
|
|
13
|
+
let hasRoles = false;
|
|
14
|
+
for (const key in rpcUrls) {
|
|
15
|
+
const chainId = Number(key);
|
|
16
|
+
const entry = rpcUrls[chainId];
|
|
17
|
+
if (Array.isArray(entry)) readRpcUrls[chainId] = entry;
|
|
18
|
+
else if (entry) {
|
|
19
|
+
hasRoles = true;
|
|
20
|
+
if (entry.read) readRpcUrls[chainId] = entry.read;
|
|
21
|
+
if (entry.write?.length) writeRpcUrls[chainId] = entry.write;
|
|
22
|
+
if (entry.bundle?.length) bundleRpcUrls[chainId] = entry.bundle;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
10
25
|
const _config = {
|
|
11
26
|
...configOptions,
|
|
12
27
|
apiUrl: configOptions?.apiUrl ?? "https://li.quest/v1",
|
|
13
|
-
rpcUrls:
|
|
28
|
+
rpcUrls: hasRoles ? readRpcUrls : rpcUrls ?? {},
|
|
14
29
|
debug: configOptions?.debug ?? false,
|
|
15
30
|
preloadChains: configOptions?.preloadChains ?? true,
|
|
16
31
|
integrator: configOptions?.integrator ?? "lifi-sdk"
|
|
@@ -50,6 +65,12 @@ function createClient(options) {
|
|
|
50
65
|
const chainRpcUrls = (await this.getRpcUrls())[chainId];
|
|
51
66
|
if (!chainRpcUrls?.length) throw new Error(`RPC URL not found for chainId: ${chainId}`);
|
|
52
67
|
return chainRpcUrls;
|
|
68
|
+
},
|
|
69
|
+
async getWriteRpcUrlsByChainId(chainId) {
|
|
70
|
+
return writeRpcUrls[chainId] ?? [];
|
|
71
|
+
},
|
|
72
|
+
async getBundleRpcUrlsByChainId(chainId) {
|
|
73
|
+
return bundleRpcUrls[chainId] ?? [];
|
|
53
74
|
}
|
|
54
75
|
};
|
|
55
76
|
function extend(base) {
|
|
@@ -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:
|
|
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 RPCUrls,\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, rpcUrls, ...configOptions } = options\n\n // Role entries split once, here: the config keeps plain read lists, so\n // everything that reads `config.rpcUrls` sees `string[]` as before.\n const readRpcUrls: RPCUrls = {}\n const writeRpcUrls: RPCUrls = {}\n const bundleRpcUrls: RPCUrls = {}\n let hasRoles = false\n for (const key in rpcUrls) {\n const chainId = Number(key) as ChainId\n const entry = rpcUrls[chainId]\n if (Array.isArray(entry)) {\n readRpcUrls[chainId] = entry\n } else if (entry) {\n hasRoles = true\n if (entry.read) {\n readRpcUrls[chainId] = entry.read\n }\n if (entry.write?.length) {\n writeRpcUrls[chainId] = entry.write\n }\n if (entry.bundle?.length) {\n bundleRpcUrls[chainId] = entry.bundle\n }\n }\n }\n\n const _config: SDKBaseConfig = {\n ...configOptions,\n apiUrl: configOptions?.apiUrl ?? 'https://li.quest/v1',\n // Plain lists only: the caller's own object, exactly as before.\n rpcUrls: hasRoles ? readRpcUrls : ((rpcUrls ?? {}) as 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 async getWriteRpcUrlsByChainId(chainId: ChainId) {\n return writeRpcUrls[chainId] ?? []\n },\n async getBundleRpcUrlsByChainId(chainId: ChainId) {\n return bundleRpcUrls[chainId] ?? []\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 // Copy descriptors rather than spreading. `config` and `providers` are\n // accessors over closure variables, and `setProviders` reassigns\n // `_providers` — so a spread would freeze the extension on the values\n // those getters happened to return at extend time, leaving it with a\n // provider list that never updates.\n const extended = Object.defineProperties(\n {},\n {\n ...Object.getOwnPropertyDescriptors(base),\n ...Object.getOwnPropertyDescriptors(extensions),\n }\n ) 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":";;;;;AAYA,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,SAAS,GAAG,kBAAkB;CAIjD,MAAM,cAAuB,CAAC;CAC9B,MAAM,eAAwB,CAAC;CAC/B,MAAM,gBAAyB,CAAC;CAChC,IAAI,WAAW;CACf,KAAK,MAAM,OAAO,SAAS;EACzB,MAAM,UAAU,OAAO,GAAG;EAC1B,MAAM,QAAQ,QAAQ;EACtB,IAAI,MAAM,QAAQ,KAAK,GACrB,YAAY,WAAW;OAClB,IAAI,OAAO;GAChB,WAAW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jB,MAAM,IAAI,MAAM,kCAAkC,SAAS;GAE7D,OAAO;EACT;EACA,MAAM,yBAAyB,SAAkB;GAC/C,OAAO,aAAa,YAAY,CAAC;EACnC;EACA,MAAM,0BAA0B,SAAkB;GAChD,OAAO,cAAc,YAAY,CAAC;EACpC;CACF;CAEA,SAAS,OACP,MAGyB;EACzB,QAAQ,aAAa;GACnB,MAAM,aAAa,SAAS,IAAI;GAMhC,MAAM,WAAW,OAAO,iBACtB,CAAC,GACD;IACE,GAAG,OAAO,0BAA0B,IAAI;IACxC,GAAG,OAAO,0BAA0B,UAAU;GAChD,CACF;GAGA,OAAO,OAAO,OAAO,UAAU,EAC7B,QAAQ,OAAO,QAAQ,EACzB,CAAC;EACH;CACF;CAEA,OAAO,OAAO,OAAO,QAAQ,EAAE,QAAQ,OAAO,MAAM,EAAE,CAAC;AACzD"}
|
|
@@ -52,6 +52,8 @@ const checkBalance = async (client, walletAddress, step, options = {}) => {
|
|
|
52
52
|
const tokens = reqs.map((r) => r.token);
|
|
53
53
|
const slippage = step.action.slippage ?? 0;
|
|
54
54
|
const slippageScaled = BigInt(Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION)));
|
|
55
|
+
const controller = new AbortController();
|
|
56
|
+
const { signal } = controller;
|
|
55
57
|
await require_utils_withTimeout.withTimeout(async () => {
|
|
56
58
|
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
|
|
57
59
|
const isFinal = attempt === 5;
|
|
@@ -60,9 +62,10 @@ const checkBalance = async (client, walletAddress, step, options = {}) => {
|
|
|
60
62
|
balances = await provider.getBalance(client, walletAddress, tokens);
|
|
61
63
|
} catch (error) {
|
|
62
64
|
if (isFinal) throw new require_errors_errors.BalanceError("Could not read wallet balance.", error);
|
|
63
|
-
await require_utils_sleep.sleep(BACKOFF_BASE_MS * 2 ** attempt);
|
|
65
|
+
await require_utils_sleep.sleep(BACKOFF_BASE_MS * 2 ** attempt, { signal });
|
|
64
66
|
continue;
|
|
65
67
|
}
|
|
68
|
+
if (signal.aborted) return;
|
|
66
69
|
const balanceByAddress = new Map(balances.map((b) => [b.address.toLowerCase(), b.amount]));
|
|
67
70
|
const unknown = [];
|
|
68
71
|
const insufficient = [];
|
|
@@ -95,12 +98,12 @@ const checkBalance = async (client, walletAddress, step, options = {}) => {
|
|
|
95
98
|
});
|
|
96
99
|
throw new require_errors_errors.BalanceError("The balance is too low.", /* @__PURE__ */ new Error(`${lines.join(" ")} No funds have been sent.`));
|
|
97
100
|
}
|
|
98
|
-
await require_utils_sleep.sleep(BACKOFF_BASE_MS * 2 ** attempt);
|
|
101
|
+
await require_utils_sleep.sleep(BACKOFF_BASE_MS * 2 ** attempt, { signal });
|
|
99
102
|
}
|
|
100
103
|
}, {
|
|
101
104
|
timeout: OVERALL_TIMEOUT_MS,
|
|
102
105
|
errorInstance: new require_errors_errors.BalanceError("Could not read wallet balance.")
|
|
103
|
-
});
|
|
106
|
+
}).finally(() => controller.abort());
|
|
104
107
|
};
|
|
105
108
|
//#endregion
|
|
106
109
|
exports.checkBalance = checkBalance;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkBalance.js","names":["withTimeout","BalanceError","sleep","formatUnits"],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"sourcesContent":["import type { LiFiStep, Token, TokenAmount } from '@lifi/types'\nimport { BalanceError } from '../../../errors/errors.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { formatUnits } from '../../../utils/formatUnits.js'\nimport { sleep } from '../../../utils/sleep.js'\nimport { withTimeout } from '../../../utils/withTimeout.js'\n\nconst MAX_ATTEMPTS = 6\n// Exponential backoff: 150, 300, 600, 1200, 2400 → ≈4.65s of sleep total.\nconst BACKOFF_BASE_MS = 150\nconst OVERALL_TIMEOUT_MS = 10_000\nconst SLIPPAGE_PRECISION = 1_000_000_000n\n\ntype Bucket = 'source' | 'gas' | 'fee'\n\ntype Requirement = {\n token: Token\n sourcePart: bigint // step.action.fromAmount\n gasPart: bigint // step.estimate.gasCosts in this token\n feePart: bigint // non-included step.estimate.feeCosts in this token\n}\n\nexport type CheckBalanceOptions = {\n /**\n * Set to `false` when outer-tx gas is paid by something other than\n * `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):\n * `gasPart` is excluded from the sufficiency check and slippage rescue.\n * Source amount and non-included fees (e.g. LZ `msg.value`) are still\n * verified. Defaults to `true` (strict, today's behavior).\n */\n walletPaysGas?: boolean\n}\n\n/**\n * Verifies that the wallet holds enough of every token required to execute\n * the step on its source chain — the source-token amount, any gas costs, and\n * any non-included fee costs. Reads all balances in one batched provider\n * call, retries within a bounded budget to absorb transient RPC failures and\n * post-confirmation propagation lag, and applies slippage to the source-token\n * portion only as a last resort (overhead is never trimmed).\n *\n * Throws BalanceError(\"The balance is too low.\") on a genuine shortfall, or\n * BalanceError(\"Could not read wallet balance.\") if the balance can't be read\n * after retries.\n */\nexport const checkBalance = async (\n client: SDKClient,\n walletAddress: string,\n step: LiFiStep,\n options: CheckBalanceOptions = {}\n): Promise<void> => {\n const fromChainId = step.action.fromChainId\n // Chains with non-standard native decimals (e.g. Tempo, Stable) report\n // gas costs in units that don't align with wallet balances — drop the\n // gas portion of the check on those chains.\n const fromChain = await client.getChainById(fromChainId)\n const walletPaysGas =\n (options.walletPaysGas ?? true) && !fromChain.nonStandardNativeDecimals\n const requirements = new Map<string, Requirement>()\n const add = (token: Token, amount: bigint, bucket: Bucket): void => {\n if (token.chainId !== fromChainId || amount === 0n) {\n return\n }\n const key = token.address.toLowerCase()\n const req = requirements.get(key) ?? {\n token,\n sourcePart: 0n,\n gasPart: 0n,\n feePart: 0n,\n }\n if (bucket === 'source') {\n req.sourcePart += amount\n } else if (bucket === 'gas') {\n req.gasPart += amount\n } else {\n req.feePart += amount\n }\n requirements.set(key, req)\n }\n add(step.action.fromToken, BigInt(step.action.fromAmount), 'source')\n for (const gas of step.estimate?.gasCosts ?? []) {\n add(gas.token, BigInt(gas.amount), 'gas')\n }\n for (const fee of step.estimate?.feeCosts ?? []) {\n // Included fees are already part of fromAmount — don't count twice.\n if (!fee.included) {\n add(fee.token, BigInt(fee.amount), 'fee')\n }\n }\n\n const reservedOverhead = (r: Requirement): bigint =>\n r.feePart + (walletPaysGas ? r.gasPart : 0n)\n const need = (r: Requirement): bigint => r.sourcePart + reservedOverhead(r)\n\n // Drop pure-gas entries when `walletPaysGas` is false (e.g. native ETH\n // on Safe Apps with only `gasPart`) — saves one balance read each.\n for (const [key, req] of requirements) {\n if (need(req) === 0n) {\n requirements.delete(key)\n }\n }\n\n if (requirements.size === 0) {\n return\n }\n\n // Provider is dispatched by wallet address; all requirements share the\n // source chain, which matches this provider by virtue of the address.\n const provider = client.providers.find((p) => p.isAddress(walletAddress))\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const reqs = Array.from(requirements.values())\n const tokens = reqs.map((r) => r.token)\n const slippage = step.action.slippage ?? 0\n const slippageScaled = BigInt(\n Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))\n )\n\n await withTimeout(\n async () => {\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n const isFinal = attempt === MAX_ATTEMPTS - 1\n\n let balances: TokenAmount[]\n try {\n balances = await provider.getBalance(client, walletAddress, tokens)\n } catch (error) {\n if (isFinal) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n error as Error\n )\n }\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n continue\n }\n\n const balanceByAddress = new Map(\n balances.map((b) => [b.address.toLowerCase(), b.amount] as const)\n )\n\n const unknown: Token[] = []\n const insufficient: { req: Requirement; have: bigint }[] = []\n for (const req of reqs) {\n const have = balanceByAddress.get(req.token.address.toLowerCase())\n if (have === undefined) {\n unknown.push(req.token)\n } else if (have < need(req)) {\n insufficient.push({ req, have })\n }\n }\n\n if (unknown.length === 0 && insufficient.length === 0) {\n return\n }\n\n // Final-attempt slippage rescue: only when the sole shortfall is\n // the source-token portion. Trim source to (balance − reserved\n // overhead) so the overhead reserve is preserved.\n if (\n isFinal &&\n unknown.length === 0 &&\n insufficient.length === 1 &&\n insufficient[0].req.sourcePart > 0n\n ) {\n const { req, have } = insufficient[0]\n const reserved = reservedOverhead(req)\n const minAcceptable =\n (req.sourcePart * slippageScaled) / SLIPPAGE_PRECISION + reserved\n if (have >= minAcceptable) {\n const newFromAmount = (have - reserved).toString()\n step.action.fromAmount = newFromAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount = newFromAmount\n }\n return\n }\n }\n\n if (isFinal) {\n if (unknown.length > 0) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n new Error(\n `Could not read balance for: ${unknown\n .map((t) => t.symbol || t.address)\n .join(', ')}.`\n )\n )\n }\n const lines = insufficient.map(({ req, have }) => {\n const needed = formatUnits(need(req), req.token.decimals)\n const current = formatUnits(have, req.token.decimals)\n const symbol = req.token.symbol\n // The \"fees\" branch covers pure-overhead tokens; with\n // walletPaysGas=false, gas is excluded from `need(req)` so it\n // only fires for genuine fee shortfalls.\n return req.sourcePart > 0n\n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.`\n : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`\n })\n throw new BalanceError(\n 'The balance is too low.',\n new Error(`${lines.join(' ')} No funds have been sent.`)\n )\n }\n\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n }\n },\n {\n timeout: OVERALL_TIMEOUT_MS,\n errorInstance: new BalanceError('Could not read wallet balance.'),\n }\n )\n}\n"],"mappings":";;;;;;AAOA,MAAM,eAAe;AAErB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;;;;;;;;;;;;;AAkC3B,MAAa,eAAe,OAC1B,QACA,eACA,MACA,UAA+B,CAAC,MACd;CAClB,MAAM,cAAc,KAAK,OAAO;CAIhC,MAAM,YAAY,MAAM,OAAO,aAAa,WAAW;CACvD,MAAM,i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AAI,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,SAASE,0BAAAA,YAAY,KAAK,GAAG,GAAG,IAAI,MAAM,QAAQ;KACxD,MAAM,UAAUA,0BAAAA,YAAY,MAAM,IAAI,MAAM,QAAQ;KACpD,MAAM,SAAS,IAAI,MAAM;KAIzB,OAAO,IAAI,aAAa,KACpB,QAAQ,OAAO,2CAA2C,OAAO,GAAG,OAAO,+BAA+B,QAAQ,GAAG,OAAO,KAC5H,gBAAgB,OAAO,kBAAkB,OAAO,GAAG,OAAO,SAAS,QAAQ,GAAG,OAAO;IAC3F,CAAC;IACD,MAAM,IAAIF,sBAAAA,aACR,2CACA,IAAI,MAAM,GAAG,MAAM,KAAK,GAAG,EAAE,0BAA0B,CACzD;GACF;GAEA,MAAMC,oBAAAA,MAAM,kBAAkB,KAAK,OAAO;EAC5C;CACF,GACA;EACE,SAAS;EACT,eAAe,IAAID,sBAAAA,aAAa,gCAAgC;CAClE,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"checkBalance.js","names":["withTimeout","BalanceError","sleep","formatUnits"],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"sourcesContent":["import type { LiFiStep, Token, TokenAmount } from '@lifi/types'\nimport { BalanceError } from '../../../errors/errors.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { formatUnits } from '../../../utils/formatUnits.js'\nimport { sleep } from '../../../utils/sleep.js'\nimport { withTimeout } from '../../../utils/withTimeout.js'\n\nconst MAX_ATTEMPTS = 6\n// Exponential backoff: 150, 300, 600, 1200, 2400 → ≈4.65s of sleep total.\nconst BACKOFF_BASE_MS = 150\nconst OVERALL_TIMEOUT_MS = 10_000\nconst SLIPPAGE_PRECISION = 1_000_000_000n\n\ntype Bucket = 'source' | 'gas' | 'fee'\n\ntype Requirement = {\n token: Token\n sourcePart: bigint // step.action.fromAmount\n gasPart: bigint // step.estimate.gasCosts in this token\n feePart: bigint // non-included step.estimate.feeCosts in this token\n}\n\nexport type CheckBalanceOptions = {\n /**\n * Set to `false` when outer-tx gas is paid by something other than\n * `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):\n * `gasPart` is excluded from the sufficiency check and slippage rescue.\n * Source amount and non-included fees (e.g. LZ `msg.value`) are still\n * verified. Defaults to `true` (strict, today's behavior).\n */\n walletPaysGas?: boolean\n}\n\n/**\n * Verifies that the wallet holds enough of every token required to execute\n * the step on its source chain — the source-token amount, any gas costs, and\n * any non-included fee costs. Reads all balances in one batched provider\n * call, retries within a bounded budget to absorb transient RPC failures and\n * post-confirmation propagation lag, and applies slippage to the source-token\n * portion only as a last resort (overhead is never trimmed).\n *\n * Throws BalanceError(\"The balance is too low.\") on a genuine shortfall, or\n * BalanceError(\"Could not read wallet balance.\") if the balance can't be read\n * after retries.\n */\nexport const checkBalance = async (\n client: SDKClient,\n walletAddress: string,\n step: LiFiStep,\n options: CheckBalanceOptions = {}\n): Promise<void> => {\n const fromChainId = step.action.fromChainId\n // Chains with non-standard native decimals (e.g. Tempo, Stable) report\n // gas costs in units that don't align with wallet balances — drop the\n // gas portion of the check on those chains.\n const fromChain = await client.getChainById(fromChainId)\n const walletPaysGas =\n (options.walletPaysGas ?? true) && !fromChain.nonStandardNativeDecimals\n const requirements = new Map<string, Requirement>()\n const add = (token: Token, amount: bigint, bucket: Bucket): void => {\n if (token.chainId !== fromChainId || amount === 0n) {\n return\n }\n const key = token.address.toLowerCase()\n const req = requirements.get(key) ?? {\n token,\n sourcePart: 0n,\n gasPart: 0n,\n feePart: 0n,\n }\n if (bucket === 'source') {\n req.sourcePart += amount\n } else if (bucket === 'gas') {\n req.gasPart += amount\n } else {\n req.feePart += amount\n }\n requirements.set(key, req)\n }\n add(step.action.fromToken, BigInt(step.action.fromAmount), 'source')\n for (const gas of step.estimate?.gasCosts ?? []) {\n add(gas.token, BigInt(gas.amount), 'gas')\n }\n for (const fee of step.estimate?.feeCosts ?? []) {\n // Included fees are already part of fromAmount — don't count twice.\n if (!fee.included) {\n add(fee.token, BigInt(fee.amount), 'fee')\n }\n }\n\n const reservedOverhead = (r: Requirement): bigint =>\n r.feePart + (walletPaysGas ? r.gasPart : 0n)\n const need = (r: Requirement): bigint => r.sourcePart + reservedOverhead(r)\n\n // Drop pure-gas entries when `walletPaysGas` is false (e.g. native ETH\n // on Safe Apps with only `gasPart`) — saves one balance read each.\n for (const [key, req] of requirements) {\n if (need(req) === 0n) {\n requirements.delete(key)\n }\n }\n\n if (requirements.size === 0) {\n return\n }\n\n // Provider is dispatched by wallet address; all requirements share the\n // source chain, which matches this provider by virtue of the address.\n const provider = client.providers.find((p) => p.isAddress(walletAddress))\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const reqs = Array.from(requirements.values())\n const tokens = reqs.map((r) => r.token)\n const slippage = step.action.slippage ?? 0\n const slippageScaled = BigInt(\n Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))\n )\n\n // Aborted once `withTimeout` settles. A timeout rejects at once, but the\n // loop keeps running; the signal stops it before it can change `step`.\n const controller = new AbortController()\n const { signal } = controller\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, { signal })\n continue\n }\n if (signal.aborted) {\n return\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, { signal })\n }\n },\n {\n timeout: OVERALL_TIMEOUT_MS,\n errorInstance: new BalanceError('Could not read wallet balance.'),\n }\n ).finally(() => controller.abort())\n}\n"],"mappings":";;;;;;AAOA,MAAM,eAAe;AAErB,MAAM,kBAAkB;AACxB,MAAM,qBA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AGrC,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,IAAID,sBAAAA,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,SAASE,0BAAAA,YAAY,KAAK,GAAG,GAAG,IAAI,MAAM,QAAQ;KACxD,MAAM,UAAUA,0BAAAA,YAAY,MAAM,IAAI,MAAM,QAAQ;KACpD,MAAM,SAAS,IAAI,MAAM;KAIzB,OAAO,IAAI,aAAa,KACpB,QAAQ,OAAO,2CAA2C,OAAO,GAAG,OAAO,+BAA+B,QAAQ,GAAG,OAAO,KAC5H,gBAAgB,OAAO,kBAAkB,OAAO,GAAG,OAAO,SAAS,QAAQ,GAAG,OAAO;IAC3F,CAAC;IACD,MAAM,IAAIF,sBAAAA,aACR,2CACA,IAAI,MAAM,GAAG,MAAM,KAAK,GAAG,EAAE,0BAA0B,CACzD;GACF;GAEA,MAAMC,oBAAAA,MAAM,kBAAkB,KAAK,SAAS,EAAE,OAAO,CAAC;EACxD;CACF,GACA;EACE,SAAS;EACT,eAAe,IAAID,sBAAAA,aAAa,gCAAgC;CAClE,CACF,CAAC,CAAC,cAAc,WAAW,MAAM,CAAC;AACpC"}
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { InMemoryStorage, LocalStorageAdapter, SDKStorage, createDefaultStorage } from "./core/storage.js";
|
|
2
|
-
import { AcceptExchangeRateUpdateHook, AcceptSlippageUpdateHook, AcceptSlippageUpdateHookParams, ContractCallParams, ContractTool, ExchangeRateUpdateParams, ExecuteStepRetryParams, Execution, ExecutionAction, ExecutionActionStatus, ExecutionActionType, ExecutionOptions, ExecutionStatus, GetContractCallsHook, GetContractCallsResult, InteractionSettings, LiFiStepExtended, RPCUrls, RequestInterceptor, RouteExecutionData, RouteExecutionDataDictionary, RouteExecutionDictionary, RouteExtended, SDKBaseConfig, SDKClient, SDKConfig, SDKProvider, StepExecutor, StepExecutorOptions, StepExtended, TransactionMethodType, TransactionParameters, TransactionRequestParameters, TransactionRequestUpdateHook, UpdateRouteHook } from "./types/core.js";
|
|
2
|
+
import { AcceptExchangeRateUpdateHook, AcceptSlippageUpdateHook, AcceptSlippageUpdateHookParams, ContractCallParams, ContractTool, ExchangeRateUpdateParams, ExecuteStepRetryParams, Execution, ExecutionAction, ExecutionActionStatus, ExecutionActionType, ExecutionOptions, ExecutionStatus, GetContractCallsHook, GetContractCallsResult, InteractionSettings, LiFiStepExtended, RPCUrls, RPCUrlsByRole, RPCUrlsConfig, RequestInterceptor, RouteExecutionData, RouteExecutionDataDictionary, RouteExecutionDictionary, RouteExtended, SDKBaseConfig, SDKClient, SDKConfig, SDKProvider, StepExecutor, StepExecutorOptions, StepExtended, TransactionMethodType, TransactionParameters, TransactionRequestParameters, TransactionRequestUpdateHook, UpdateRouteHook } from "./types/core.js";
|
|
3
3
|
import { getChains } from "./actions/getChains.js";
|
|
4
4
|
import { getConnections } from "./actions/getConnections.js";
|
|
5
5
|
import { getContractCallsQuote } from "./actions/getContractCallsQuote.js";
|
|
@@ -46,11 +46,12 @@ import { convertQuoteToRoute } from "./utils/convertQuoteToRoute.js";
|
|
|
46
46
|
import { fetchTxErrorDetails } from "./utils/fetchTxErrorDetails.js";
|
|
47
47
|
import { formatUnits } from "./utils/formatUnits.js";
|
|
48
48
|
import { isHex } from "./utils/isHex.js";
|
|
49
|
+
import { LruMap } from "./utils/lru.js";
|
|
49
50
|
import { parseUnits } from "./utils/parseUnits.js";
|
|
50
51
|
import { sleep } from "./utils/sleep.js";
|
|
51
52
|
import { waitForResult } from "./utils/waitForResult.js";
|
|
52
|
-
import {
|
|
53
|
+
import { withDedupe } from "./utils/withDedupe.js";
|
|
53
54
|
import { withTimeout } from "./utils/withTimeout.js";
|
|
54
55
|
import { name, version } from "./version.js";
|
|
55
56
|
export * from "@lifi/types";
|
|
56
|
-
export { type AcceptExchangeRateUpdateHook, type AcceptSlippageUpdateHook, type AcceptSlippageUpdateHookParams, BalanceError, BaseError, BaseStepExecutionTask, BaseStepExecutor, type CheckBalanceOptions, CheckBalanceTask, type ContractCallParams, type ContractTool, type ErrorCode, ErrorMessage, ErrorName, type ExchangeRateUpdateParams, ExecuteStepRetryError, type ExecuteStepRetryParams, type Execution, type ExecutionAction, type ExecutionActionStatus, type ExecutionActionType, type ExecutionOptions, type ExecutionStatus, type GetContractCallsHook, type GetContractCallsResult, type GetStatusRequestExtended, HTTPError, InMemoryStorage, type InteractionSettings, LiFiErrorCode, type LiFiStepExtended, type LiFiStepRequest, LocalStorageAdapter, LruMap, PrepareTransactionTask, ProviderError, type QuoteRequest, type QuoteRequestFromAmount, type QuoteRequestToAmount, RPCError, type RPCUrls, type RequestInterceptor, type RouteExecutionData, type RouteExecutionDataDictionary, type RouteExecutionDictionary, type RouteExtended, type SDKBaseConfig, type SDKClient, type SDKConfig, SDKError, type SDKProvider, type SDKStorage, ServerError, StatusManager, type StepExecutor, type StepExecutorBaseContext, type StepExecutorContext, type StepExecutorOptions, type StepExtended, TaskPipeline, type TaskResult, type TaskStatus, TransactionError, type TransactionMethodType, type TransactionParameters, type TransactionRequestParameters, type TransactionRequestUpdateHook, UnknownError, type UpdateRouteHook, ValidationError, WaitForTransactionStatusTask, actions, checkBalance, checkPackageUpdates, convertQuoteToRoute, createClient, createDefaultStorage, executeRoute, fetchTxErrorDetails, formatUnits, getActionMessage, getActiveRoute, getActiveRoutes, getChains, getConnections, getContractCallsQuote, getGasRecommendation, getNameServiceAddress, getQuote, getRelayedTransactionStatus, getRelayerQuote, getRoutes, getStatus, getStepTransaction, getSubstatusMessage, getToken, getTokenBalance, getTokenBalances, getTokenBalancesByChain, getTokens, getTools, getTransactionHistory, getTransactionRequestData, isHex, name, parseUnits, patchContractCalls, relayTransaction, resumeRoute, sleep, stepComparison, stopRouteExecution, updateRouteExecution, version, waitForResult, withDedupe, withTimeout };
|
|
57
|
+
export { type AcceptExchangeRateUpdateHook, type AcceptSlippageUpdateHook, type AcceptSlippageUpdateHookParams, BalanceError, BaseError, BaseStepExecutionTask, BaseStepExecutor, type CheckBalanceOptions, CheckBalanceTask, type ContractCallParams, type ContractTool, type ErrorCode, ErrorMessage, ErrorName, type ExchangeRateUpdateParams, ExecuteStepRetryError, type ExecuteStepRetryParams, type Execution, type ExecutionAction, type ExecutionActionStatus, type ExecutionActionType, type ExecutionOptions, type ExecutionStatus, type GetContractCallsHook, type GetContractCallsResult, type GetStatusRequestExtended, HTTPError, InMemoryStorage, type InteractionSettings, LiFiErrorCode, type LiFiStepExtended, type LiFiStepRequest, LocalStorageAdapter, LruMap, PrepareTransactionTask, ProviderError, type QuoteRequest, type QuoteRequestFromAmount, type QuoteRequestToAmount, RPCError, type RPCUrls, type RPCUrlsByRole, type RPCUrlsConfig, type RequestInterceptor, type RouteExecutionData, type RouteExecutionDataDictionary, type RouteExecutionDictionary, type RouteExtended, type SDKBaseConfig, type SDKClient, type SDKConfig, SDKError, type SDKProvider, type SDKStorage, ServerError, StatusManager, type StepExecutor, type StepExecutorBaseContext, type StepExecutorContext, type StepExecutorOptions, type StepExtended, TaskPipeline, type TaskResult, type TaskStatus, TransactionError, type TransactionMethodType, type TransactionParameters, type TransactionRequestParameters, type TransactionRequestUpdateHook, UnknownError, type UpdateRouteHook, ValidationError, WaitForTransactionStatusTask, actions, checkBalance, checkPackageUpdates, convertQuoteToRoute, createClient, createDefaultStorage, executeRoute, fetchTxErrorDetails, formatUnits, getActionMessage, getActiveRoute, getActiveRoutes, getChains, getConnections, getContractCallsQuote, getGasRecommendation, getNameServiceAddress, getQuote, getRelayedTransactionStatus, getRelayerQuote, getRoutes, getStatus, getStepTransaction, getSubstatusMessage, getToken, getTokenBalance, getTokenBalances, getTokenBalancesByChain, getTokens, getTools, getTransactionHistory, getTransactionRequestData, isHex, name, parseUnits, patchContractCalls, relayTransaction, resumeRoute, sleep, stepComparison, stopRouteExecution, updateRouteExecution, version, waitForResult, withDedupe, withTimeout };
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
const require_version = require("./version.js");
|
|
3
|
+
const require_errors_SDKError = require("./errors/SDKError.js");
|
|
2
4
|
const require_errors_baseError = require("./errors/baseError.js");
|
|
3
5
|
const require_errors_constants = require("./errors/constants.js");
|
|
4
6
|
const require_errors_errors = require("./errors/errors.js");
|
|
5
7
|
const require_errors_httpError = require("./errors/httpError.js");
|
|
6
|
-
const require_version = require("./version.js");
|
|
7
|
-
const require_errors_SDKError = require("./errors/SDKError.js");
|
|
8
8
|
const require_utils_sleep = require("./utils/sleep.js");
|
|
9
|
+
const require_utils_lru = require("./utils/lru.js");
|
|
9
10
|
const require_utils_withDedupe = require("./utils/withDedupe.js");
|
|
10
11
|
const require_actions_getChains = require("./actions/getChains.js");
|
|
11
12
|
const require_actions_getConnections = require("./actions/getConnections.js");
|
|
@@ -62,7 +63,7 @@ exports.HTTPError = require_errors_httpError.HTTPError;
|
|
|
62
63
|
exports.InMemoryStorage = require_core_storage.InMemoryStorage;
|
|
63
64
|
exports.LiFiErrorCode = require_errors_constants.LiFiErrorCode;
|
|
64
65
|
exports.LocalStorageAdapter = require_core_storage.LocalStorageAdapter;
|
|
65
|
-
exports.LruMap =
|
|
66
|
+
exports.LruMap = require_utils_lru.LruMap;
|
|
66
67
|
exports.PrepareTransactionTask = require_core_tasks_PrepareTransactionTask.PrepareTransactionTask;
|
|
67
68
|
exports.ProviderError = require_errors_errors.ProviderError;
|
|
68
69
|
exports.RPCError = require_errors_errors.RPCError;
|
package/dist/cjs/types/core.d.ts
CHANGED
|
@@ -19,10 +19,51 @@ export interface SDKBaseConfig {
|
|
|
19
19
|
requestInterceptor?: RequestInterceptor;
|
|
20
20
|
storage?: SDKStorage;
|
|
21
21
|
}
|
|
22
|
-
export interface SDKConfig extends Partial<Omit<SDKBaseConfig, "integrator">> {
|
|
22
|
+
export interface SDKConfig extends Partial<Omit<SDKBaseConfig, "integrator" | "rpcUrls">> {
|
|
23
23
|
integrator: string;
|
|
24
|
+
/**
|
|
25
|
+
* Per chain, one list for reads and sends, or lists by role. The client
|
|
26
|
+
* keeps the read lists in `config.rpcUrls` and serves the write and bundle
|
|
27
|
+
* lists through `getWriteRpcUrlsByChainId` and `getBundleRpcUrlsByChainId`.
|
|
28
|
+
*/
|
|
29
|
+
rpcUrls?: RPCUrlsConfig;
|
|
24
30
|
providers?: SDKProvider[];
|
|
25
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* RPC URLs for one chain, split by what they are used for.
|
|
34
|
+
*/
|
|
35
|
+
export interface RPCUrlsByRole {
|
|
36
|
+
/**
|
|
37
|
+
* Reads: balances, simulation and confirmation. Unset, the chain's own RPC
|
|
38
|
+
* URLs serve reads, as for a chain with no `rpcUrls` entry.
|
|
39
|
+
*/
|
|
40
|
+
read?: string[];
|
|
41
|
+
/**
|
|
42
|
+
* Sends. Unset or empty, the read URLs send as well. While `write` is set,
|
|
43
|
+
* nothing is sent through the read URLs: when `bundle` is unset, the write
|
|
44
|
+
* URLs that support bundles also submit bundles, and with none of them, a
|
|
45
|
+
* route that needs a bundle fails.
|
|
46
|
+
*
|
|
47
|
+
* Only `@lifi/sdk-provider-solana` uses this today; other providers ignore
|
|
48
|
+
* it.
|
|
49
|
+
*/
|
|
50
|
+
write?: string[];
|
|
51
|
+
/**
|
|
52
|
+
* Bundle submissions (Jito `sendBundle`). Unset, empty, or with no URL that
|
|
53
|
+
* supports bundles, the write URLs that do submit them. While `bundle` or
|
|
54
|
+
* `write` is set, bundles never go to the read URLs.
|
|
55
|
+
*
|
|
56
|
+
* Only `@lifi/sdk-provider-solana` uses this today; other providers ignore
|
|
57
|
+
* it.
|
|
58
|
+
*/
|
|
59
|
+
bundle?: string[];
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The `rpcUrls` option of `createClient`: per chain, either one list for reads
|
|
63
|
+
* and sends, or lists by role.
|
|
64
|
+
*/
|
|
65
|
+
export type RPCUrlsConfig = Partial<Record<ChainId, string[] | RPCUrlsByRole>>;
|
|
66
|
+
/** RPC URL lists per chain. `client.config.rpcUrls` holds the read lists. */
|
|
26
67
|
export type RPCUrls = Partial<Record<ChainId, string[]>>;
|
|
27
68
|
export interface SDKProvider {
|
|
28
69
|
readonly type: ChainType;
|
|
@@ -47,6 +88,20 @@ export interface SDKClient {
|
|
|
47
88
|
getChainById(chainId: ChainId): Promise<ExtendedChain>;
|
|
48
89
|
getRpcUrls(): Promise<RPCUrls>;
|
|
49
90
|
getRpcUrlsByChainId(chainId: ChainId): Promise<string[]>;
|
|
91
|
+
/**
|
|
92
|
+
* The chain's dedicated write RPC URLs (`rpcUrls[chainId].write`). Empty
|
|
93
|
+
* when the chain has none.
|
|
94
|
+
*
|
|
95
|
+
* Optional so clients from other SDK versions, and hand-written ones, still
|
|
96
|
+
* satisfy `SDKClient`. Providers treat a missing method as no write list.
|
|
97
|
+
*/
|
|
98
|
+
getWriteRpcUrlsByChainId?(chainId: ChainId): Promise<string[]>;
|
|
99
|
+
/**
|
|
100
|
+
* The chain's dedicated bundle RPC URLs (`rpcUrls[chainId].bundle`). Empty
|
|
101
|
+
* when the chain has none. Optional for the same reason as
|
|
102
|
+
* `getWriteRpcUrlsByChainId`.
|
|
103
|
+
*/
|
|
104
|
+
getBundleRpcUrlsByChainId?(chainId: ChainId): Promise<string[]>;
|
|
50
105
|
}
|
|
51
106
|
export interface StepExecutorOptions {
|
|
52
107
|
routeId: string;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
//#region src/utils/abort.d.ts
|
|
2
|
+
/** Older runtimes and polyfills can abort a signal without a `reason`. */
|
|
3
|
+
export declare const getAbortError: (signal: AbortSignal) => unknown;
|
|
4
|
+
export declare const isAbortError: (error: unknown) => boolean;
|
|
5
|
+
//#endregion
|
|
6
|
+
//# sourceMappingURL=abort.d.ts.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
+
//#region src/utils/abort.ts
|
|
3
|
+
/** Older runtimes and polyfills can abort a signal without a `reason`. */
|
|
4
|
+
const getAbortError = (signal) => signal.reason ?? Object.assign(/* @__PURE__ */ new Error("This operation was aborted"), { name: "AbortError" });
|
|
5
|
+
const isAbortError = (error) => typeof error === "object" && error !== null && "name" in error && error.name === "AbortError";
|
|
6
|
+
//#endregion
|
|
7
|
+
exports.getAbortError = getAbortError;
|
|
8
|
+
exports.isAbortError = isAbortError;
|
|
9
|
+
|
|
10
|
+
//# sourceMappingURL=abort.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"abort.js","names":[],"sources":["../../../src/utils/abort.ts"],"sourcesContent":["/** Older runtimes and polyfills can abort a signal without a `reason`. */\nexport const getAbortError = (signal: AbortSignal): unknown =>\n signal.reason ??\n Object.assign(new Error('This operation was aborted'), { name: 'AbortError' })\n\nexport const isAbortError = (error: unknown): boolean =>\n typeof error === 'object' &&\n error !== null &&\n 'name' in error &&\n error.name === 'AbortError'\n"],"mappings":";;;AACA,MAAa,iBAAiB,WAC5B,OAAO,UACP,OAAO,uBAAO,IAAI,MAAM,4BAA4B,GAAG,EAAE,MAAM,aAAa,CAAC;AAE/E,MAAa,gBAAgB,UAC3B,OAAO,UAAU,YACjB,UAAU,QACV,UAAU,SACV,MAAM,SAAS"}
|
|
@@ -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.
|
|
8
|
+
const currentVersion = packageVersion ?? "4.10.0";
|
|
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,6 +1,6 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_errors_errors = require("../errors/errors.js");
|
|
3
2
|
const require_errors_SDKError = require("../errors/SDKError.js");
|
|
3
|
+
const require_errors_errors = require("../errors/errors.js");
|
|
4
4
|
const require_utils_formatUnits = require("./formatUnits.js");
|
|
5
5
|
//#region src/utils/convertQuoteToRoute.ts
|
|
6
6
|
const parseBigInt = (value) => {
|
|
@@ -4,6 +4,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
4
4
|
* Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number.
|
|
5
5
|
*/
|
|
6
6
|
function formatUnits(value, decimals) {
|
|
7
|
+
if (!Number.isInteger(decimals) || decimals < 0) throw new Error(`\`decimals\` must be a non-negative integer. Got \`${decimals}\`.`);
|
|
7
8
|
let display = value.toString();
|
|
8
9
|
const negative = display.startsWith("-");
|
|
9
10
|
if (negative) display = display.slice(1);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"formatUnits.js","names":[],"sources":["../../../src/utils/formatUnits.ts"],"sourcesContent":["/**\n * Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number.\n */\nexport function formatUnits(value: bigint, decimals: number): string {\n let display = value.toString()\n\n const negative = display.startsWith('-')\n if (negative) {\n display = display.slice(1)\n }\n\n display = display.padStart(decimals, '0')\n\n let [integer, fraction] = [\n display.slice(0, display.length - decimals),\n display.slice(display.length - decimals),\n ]\n fraction = fraction.replace(/(0+)$/, '')\n return `${negative ? '-' : ''}${integer || '0'}${\n fraction ? `.${fraction}` : ''\n }`\n}\n"],"mappings":";;;;;AAGA,SAAgB,YAAY,OAAe,UAA0B;CACnE,IAAI,UAAU,MAAM,SAAS;CAE7B,MAAM,WAAW,QAAQ,WAAW,GAAG;CACvC,IAAI,UACF,UAAU,QAAQ,MAAM,CAAC;CAG3B,UAAU,QAAQ,SAAS,UAAU,GAAG;CAExC,IAAI,CAAC,SAAS,YAAY,CACxB,QAAQ,MAAM,GAAG,QAAQ,SAAS,QAAQ,GAC1C,QAAQ,MAAM,QAAQ,SAAS,QAAQ,CACzC;CACA,WAAW,SAAS,QAAQ,SAAS,EAAE;CACvC,OAAO,GAAG,WAAW,MAAM,KAAK,WAAW,MACzC,WAAW,IAAI,aAAa;AAEhC"}
|
|
1
|
+
{"version":3,"file":"formatUnits.js","names":[],"sources":["../../../src/utils/formatUnits.ts"],"sourcesContent":["/**\n * Divides a number by a given exponent of base 10 (10exponent), and formats it into a string representation of the number.\n */\nexport function formatUnits(value: bigint, decimals: number): string {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new Error(\n `\\`decimals\\` must be a non-negative integer. Got \\`${decimals}\\`.`\n )\n }\n\n let display = value.toString()\n\n const negative = display.startsWith('-')\n if (negative) {\n display = display.slice(1)\n }\n\n display = display.padStart(decimals, '0')\n\n let [integer, fraction] = [\n display.slice(0, display.length - decimals),\n display.slice(display.length - decimals),\n ]\n fraction = fraction.replace(/(0+)$/, '')\n return `${negative ? '-' : ''}${integer || '0'}${\n fraction ? `.${fraction}` : ''\n }`\n}\n"],"mappings":";;;;;AAGA,SAAgB,YAAY,OAAe,UAA0B;CACnE,IAAI,CAAC,OAAO,UAAU,QAAQ,KAAK,WAAW,GAC5C,MAAM,IAAI,MACR,sDAAsD,SAAS,IACjE;CAGF,IAAI,UAAU,MAAM,SAAS;CAE7B,MAAM,WAAW,QAAQ,WAAW,GAAG;CACvC,IAAI,UACF,UAAU,QAAQ,MAAM,CAAC;CAG3B,UAAU,QAAQ,SAAS,UAAU,GAAG;CAExC,IAAI,CAAC,SAAS,YAAY,CACxB,QAAQ,MAAM,GAAG,QAAQ,SAAS,QAAQ,GAC1C,QAAQ,MAAM,QAAQ,SAAS,QAAQ,CACzC;CACA,WAAW,SAAS,QAAQ,SAAS,EAAE;CACvC,OAAO,GAAG,WAAW,MAAM,KAAK,WAAW,MACzC,WAAW,IAAI,aAAa;AAEhC"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/utils/lru.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Map with a LRU (Least recently used) policy.
|
|
4
|
+
*
|
|
5
|
+
* https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU
|
|
6
|
+
*/
|
|
7
|
+
export declare class LruMap<value = unknown> extends Map<string, value> {
|
|
8
|
+
maxSize: number;
|
|
9
|
+
constructor(size: number);
|
|
10
|
+
override get(key: string): value | undefined;
|
|
11
|
+
override set(key: string, value: value): this;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//# sourceMappingURL=lru.d.ts.map
|