@lifi/sdk 4.0.0-beta.6 → 4.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/cjs/actions/getChains.js.map +1 -1
  2. package/dist/cjs/actions/getConnections.js.map +1 -1
  3. package/dist/cjs/actions/getContractCallsQuote.js.map +1 -1
  4. package/dist/cjs/actions/getNameServiceAddress.js.map +1 -1
  5. package/dist/cjs/actions/getQuote.js.map +1 -1
  6. package/dist/cjs/actions/getRelayedTransactionStatus.js +2 -2
  7. package/dist/cjs/actions/getRelayedTransactionStatus.js.map +1 -1
  8. package/dist/cjs/actions/getRelayerQuote.js +2 -2
  9. package/dist/cjs/actions/getRelayerQuote.js.map +1 -1
  10. package/dist/cjs/actions/getTokenBalances.js.map +1 -1
  11. package/dist/cjs/actions/getTokenBalancesByChain.js.map +1 -1
  12. package/dist/cjs/actions/getTokens.js.map +1 -1
  13. package/dist/cjs/actions/getWalletBalances.js.map +1 -1
  14. package/dist/cjs/actions/relayTransaction.js +2 -2
  15. package/dist/cjs/actions/relayTransaction.js.map +1 -1
  16. package/dist/cjs/client/createClient.js.map +1 -1
  17. package/dist/cjs/core/BaseStepExecutor.js.map +1 -1
  18. package/dist/cjs/core/StatusManager.js.map +1 -1
  19. package/dist/cjs/core/TaskPipeline.js.map +1 -1
  20. package/dist/cjs/core/execution.js +2 -2
  21. package/dist/cjs/core/execution.js.map +1 -1
  22. package/dist/cjs/core/tasks/CheckBalanceTask.d.ts +9 -0
  23. package/dist/cjs/core/tasks/CheckBalanceTask.js +13 -3
  24. package/dist/cjs/core/tasks/CheckBalanceTask.js.map +1 -1
  25. package/dist/cjs/core/tasks/PrepareTransactionTask.js +3 -3
  26. package/dist/cjs/core/tasks/PrepareTransactionTask.js.map +1 -1
  27. package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js +2 -2
  28. package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  29. package/dist/cjs/core/tasks/helpers/checkBalance.d.ts +12 -2
  30. package/dist/cjs/core/tasks/helpers/checkBalance.js +19 -12
  31. package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
  32. package/dist/cjs/core/tasks/helpers/getTransactionRequestData.js +3 -3
  33. package/dist/cjs/core/tasks/helpers/getTransactionRequestData.js.map +1 -1
  34. package/dist/cjs/core/tasks/helpers/stepComparison.js +2 -2
  35. package/dist/cjs/core/tasks/helpers/stepComparison.js.map +1 -1
  36. package/dist/cjs/core/utils.js.map +1 -1
  37. package/dist/cjs/errors/errors.js +9 -9
  38. package/dist/cjs/errors/errors.js.map +1 -1
  39. package/dist/cjs/errors/httpError.js +17 -17
  40. package/dist/cjs/errors/httpError.js.map +1 -1
  41. package/dist/cjs/index.d.ts +2 -2
  42. package/dist/cjs/types/core.d.ts +0 -4
  43. package/dist/cjs/utils/checkPackageUpdates.js +1 -1
  44. package/dist/cjs/utils/checkPackageUpdates.js.map +1 -1
  45. package/dist/cjs/utils/convertQuoteToRoute.js.map +1 -1
  46. package/dist/cjs/utils/decode.js.map +1 -1
  47. package/dist/cjs/utils/fetchTxErrorDetails.js.map +1 -1
  48. package/dist/cjs/utils/getTransactionMessage.js.map +1 -1
  49. package/dist/cjs/version.d.ts +1 -1
  50. package/dist/cjs/version.js +1 -1
  51. package/dist/cjs/version.js.map +1 -1
  52. package/dist/esm/actions/getChains.js.map +1 -1
  53. package/dist/esm/actions/getConnections.js.map +1 -1
  54. package/dist/esm/actions/getContractCallsQuote.js.map +1 -1
  55. package/dist/esm/actions/getNameServiceAddress.js.map +1 -1
  56. package/dist/esm/actions/getQuote.js.map +1 -1
  57. package/dist/esm/actions/getRelayedTransactionStatus.js +2 -2
  58. package/dist/esm/actions/getRelayedTransactionStatus.js.map +1 -1
  59. package/dist/esm/actions/getRelayerQuote.js +2 -2
  60. package/dist/esm/actions/getRelayerQuote.js.map +1 -1
  61. package/dist/esm/actions/getTokenBalances.js.map +1 -1
  62. package/dist/esm/actions/getTokenBalancesByChain.js.map +1 -1
  63. package/dist/esm/actions/getTokens.js.map +1 -1
  64. package/dist/esm/actions/getWalletBalances.js.map +1 -1
  65. package/dist/esm/actions/relayTransaction.js +2 -2
  66. package/dist/esm/actions/relayTransaction.js.map +1 -1
  67. package/dist/esm/client/createClient.js.map +1 -1
  68. package/dist/esm/core/BaseStepExecutor.js.map +1 -1
  69. package/dist/esm/core/StatusManager.js.map +1 -1
  70. package/dist/esm/core/TaskPipeline.js.map +1 -1
  71. package/dist/esm/core/execution.js +2 -2
  72. package/dist/esm/core/execution.js.map +1 -1
  73. package/dist/esm/core/tasks/CheckBalanceTask.d.ts +9 -0
  74. package/dist/esm/core/tasks/CheckBalanceTask.d.ts.map +1 -1
  75. package/dist/esm/core/tasks/CheckBalanceTask.js +13 -3
  76. package/dist/esm/core/tasks/CheckBalanceTask.js.map +1 -1
  77. package/dist/esm/core/tasks/PrepareTransactionTask.js +3 -3
  78. package/dist/esm/core/tasks/PrepareTransactionTask.js.map +1 -1
  79. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js +2 -3
  80. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  81. package/dist/esm/core/tasks/helpers/checkBalance.d.ts +12 -2
  82. package/dist/esm/core/tasks/helpers/checkBalance.d.ts.map +1 -1
  83. package/dist/esm/core/tasks/helpers/checkBalance.js +19 -12
  84. package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
  85. package/dist/esm/core/tasks/helpers/getTransactionRequestData.js +3 -3
  86. package/dist/esm/core/tasks/helpers/getTransactionRequestData.js.map +1 -1
  87. package/dist/esm/core/tasks/helpers/stepComparison.js +2 -2
  88. package/dist/esm/core/tasks/helpers/stepComparison.js.map +1 -1
  89. package/dist/esm/core/utils.js.map +1 -1
  90. package/dist/esm/errors/errors.js +9 -9
  91. package/dist/esm/errors/errors.js.map +1 -1
  92. package/dist/esm/errors/httpError.js +17 -17
  93. package/dist/esm/errors/httpError.js.map +1 -1
  94. package/dist/esm/index.d.ts +2 -2
  95. package/dist/esm/types/core.d.ts +0 -4
  96. package/dist/esm/types/core.d.ts.map +1 -1
  97. package/dist/esm/utils/checkPackageUpdates.js +1 -1
  98. package/dist/esm/utils/checkPackageUpdates.js.map +1 -1
  99. package/dist/esm/utils/convertQuoteToRoute.js.map +1 -1
  100. package/dist/esm/utils/decode.js.map +1 -1
  101. package/dist/esm/utils/fetchTxErrorDetails.js.map +1 -1
  102. package/dist/esm/utils/getTransactionMessage.js.map +1 -1
  103. package/dist/esm/version.d.ts +1 -1
  104. package/dist/esm/version.js +1 -1
  105. package/dist/esm/version.js.map +1 -1
  106. package/package.json +2 -2
  107. package/src/core/tasks/CheckBalanceTask.ts +19 -2
  108. package/src/core/tasks/helpers/checkBalance.ts +53 -21
  109. package/src/index.ts +4 -1
  110. package/src/types/core.ts +0 -4
  111. package/src/version.ts +1 -1
@@ -2,6 +2,16 @@ import { SDKClient } from "../../../types/core.js";
2
2
  import { LiFiStep } from "@lifi/types";
3
3
 
4
4
  //#region src/core/tasks/helpers/checkBalance.d.ts
5
+ type CheckBalanceOptions = {
6
+ /**
7
+ * Set to `false` when outer-tx gas is paid by something other than
8
+ * `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):
9
+ * `gasPart` is excluded from the sufficiency check and slippage rescue.
10
+ * Source amount and non-included fees (e.g. LZ `msg.value`) are still
11
+ * verified. Defaults to `true` (strict, today's behavior).
12
+ */
13
+ walletPaysGas?: boolean;
14
+ };
5
15
  /**
6
16
  * Verifies that the wallet holds enough of every token required to execute
7
17
  * the step on its source chain — the source-token amount, any gas costs, and
@@ -14,7 +24,7 @@ import { LiFiStep } from "@lifi/types";
14
24
  * BalanceError("Could not read wallet balance.") if the balance can't be read
15
25
  * after retries.
16
26
  */
17
- declare const checkBalance: (client: SDKClient, walletAddress: string, step: LiFiStep) => Promise<void>;
27
+ declare const checkBalance: (client: SDKClient, walletAddress: string, step: LiFiStep, options?: CheckBalanceOptions) => Promise<void>;
18
28
  //#endregion
19
- export { checkBalance };
29
+ export { CheckBalanceOptions, checkBalance };
20
30
  //# sourceMappingURL=checkBalance.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"checkBalance.d.ts","names":[],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"mappings":";;;;;;AA+BA;;;;;;;;;;cAAa,YAAA,GACX,MAAA,EAAQ,SAAA,EACR,aAAA,UACA,IAAA,EAAM,QAAA,KACL,OAAA"}
1
+ {"version":3,"file":"checkBalance.d.ts","names":[],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"mappings":";;;;KAsBY,mBAAA;;AAAZ;;;;;AAuBA;EAfE,aAAA;AAAA;;;;;;;;;;;;;cAeW,YAAA,GACX,MAAA,EAAQ,SAAA,EACR,aAAA,UACA,IAAA,EAAM,QAAA,EACN,OAAA,GAAS,mBAAA,KACR,OAAA"}
@@ -19,24 +19,30 @@ const SLIPPAGE_PRECISION = 1000000000n;
19
19
  * BalanceError("Could not read wallet balance.") if the balance can't be read
20
20
  * after retries.
21
21
  */
22
- const checkBalance = async (client, walletAddress, step) => {
22
+ const checkBalance = async (client, walletAddress, step, options = {}) => {
23
+ const walletPaysGas = options.walletPaysGas ?? true;
23
24
  const fromChainId = step.action.fromChainId;
24
25
  const requirements = /* @__PURE__ */ new Map();
25
- const add = (token, amount, source) => {
26
+ const add = (token, amount, bucket) => {
26
27
  if (token.chainId !== fromChainId || amount === 0n) return;
27
28
  const key = token.address.toLowerCase();
28
29
  const req = requirements.get(key) ?? {
29
30
  token,
30
31
  sourcePart: 0n,
31
- overheadPart: 0n
32
+ gasPart: 0n,
33
+ feePart: 0n
32
34
  };
33
- if (source) req.sourcePart += amount;
34
- else req.overheadPart += amount;
35
+ if (bucket === "source") req.sourcePart += amount;
36
+ else if (bucket === "gas") req.gasPart += amount;
37
+ else req.feePart += amount;
35
38
  requirements.set(key, req);
36
39
  };
37
- add(step.action.fromToken, BigInt(step.action.fromAmount), true);
38
- for (const gas of step.estimate?.gasCosts ?? []) add(gas.token, BigInt(gas.amount), false);
39
- for (const fee of step.estimate?.feeCosts ?? []) if (!fee.included) add(fee.token, BigInt(fee.amount), false);
40
+ add(step.action.fromToken, BigInt(step.action.fromAmount), "source");
41
+ for (const gas of step.estimate?.gasCosts ?? []) add(gas.token, BigInt(gas.amount), "gas");
42
+ for (const fee of step.estimate?.feeCosts ?? []) if (!fee.included) add(fee.token, BigInt(fee.amount), "fee");
43
+ const reservedOverhead = (r) => r.feePart + (walletPaysGas ? r.gasPart : 0n);
44
+ const need = (r) => r.sourcePart + reservedOverhead(r);
45
+ for (const [key, req] of requirements) if (need(req) === 0n) requirements.delete(key);
40
46
  if (requirements.size === 0) return;
41
47
  const provider = client.providers.find((p) => p.isAddress(walletAddress));
42
48
  if (!provider) throw new Error(`SDK Token Provider for ${walletAddress} is not found.`);
@@ -61,7 +67,7 @@ const checkBalance = async (client, walletAddress, step) => {
61
67
  for (const req of reqs) {
62
68
  const have = balanceByAddress.get(req.token.address.toLowerCase());
63
69
  if (have === void 0) unknown.push(req.token);
64
- else if (have < req.sourcePart + req.overheadPart) insufficient.push({
70
+ else if (have < need(req)) insufficient.push({
65
71
  req,
66
72
  have
67
73
  });
@@ -69,15 +75,16 @@ const checkBalance = async (client, walletAddress, step) => {
69
75
  if (unknown.length === 0 && insufficient.length === 0) return;
70
76
  if (isFinal && unknown.length === 0 && insufficient.length === 1 && insufficient[0].req.sourcePart > 0n) {
71
77
  const { req, have } = insufficient[0];
72
- if (have >= req.sourcePart * slippageScaled / SLIPPAGE_PRECISION + req.overheadPart) {
73
- step.action.fromAmount = (have - req.overheadPart).toString();
78
+ const reserved = reservedOverhead(req);
79
+ if (have >= req.sourcePart * slippageScaled / SLIPPAGE_PRECISION + reserved) {
80
+ step.action.fromAmount = (have - reserved).toString();
74
81
  return;
75
82
  }
76
83
  }
77
84
  if (isFinal) {
78
85
  if (unknown.length > 0) throw new BalanceError("Could not read wallet balance.", /* @__PURE__ */ new Error(`Could not read balance for: ${unknown.map((t) => t.symbol || t.address).join(", ")}.`));
79
86
  const lines = insufficient.map(({ req, have }) => {
80
- const needed = formatUnits(req.sourcePart + req.overheadPart, req.token.decimals);
87
+ const needed = formatUnits(need(req), req.token.decimals);
81
88
  const current = formatUnits(have, req.token.decimals);
82
89
  const symbol = req.token.symbol;
83
90
  return req.sourcePart > 0n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.` : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`;
@@ -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 Requirement = {\n token: Token\n sourcePart: bigint // 0n for pure overhead tokens\n overheadPart: bigint // gas + non-included fees in this token\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): Promise<void> => {\n const fromChainId = step.action.fromChainId\n const requirements = new Map<string, Requirement>()\n const add = (token: Token, amount: bigint, source: boolean): 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 overheadPart: 0n,\n }\n if (source) {\n req.sourcePart += amount\n } else {\n req.overheadPart += amount\n }\n requirements.set(key, req)\n }\n add(step.action.fromToken, BigInt(step.action.fromAmount), true)\n for (const gas of step.estimate?.gasCosts ?? []) {\n add(gas.token, BigInt(gas.amount), false)\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), false)\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 < req.sourcePart + req.overheadPart) {\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 the\n // source-token portion. Trim source down to (balance − overhead) so\n // 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 minAcceptable =\n (req.sourcePart * slippageScaled) / SLIPPAGE_PRECISION +\n req.overheadPart\n if (have >= minAcceptable) {\n step.action.fromAmount = (have - req.overheadPart).toString()\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(\n req.sourcePart + req.overheadPart,\n req.token.decimals\n )\n const current = formatUnits(have, req.token.decimals)\n const symbol = req.token.symbol\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;;;;;;;;;;;;;AAoB3B,MAAa,eAAe,OAC1B,QACA,eACA,SACkB;CAClB,MAAM,cAAc,KAAK,OAAO;CAChC,MAAM,+BAAe,IAAI,KAA0B;CACnD,MAAM,OAAO,OAAc,QAAgB,WAA0B;AACnE,MAAI,MAAM,YAA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AAM,kBAAkB,KAAK,QAAQ;;IAG/C;EACE,SAAS;EACT,eAAe,IAAI,aAAa,iCAAiC;EAClE,CACF"}
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 walletPaysGas = options.walletPaysGas ?? true\n const fromChainId = step.action.fromChainId\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 step.action.fromAmount = (have - reserved).toString()\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,EAAE,KACf;CAClB,MAAM,gBAAgB,QAAQ,iBAAiB;CAC/C,MAAM,cAAc,KAAK,OAAO;CAChC,MAAM,+BAAe,IAAI,KAA0B;CACnD,MAAM,OAAO,OAAc,QAAgB,WAAyB;AAClE,MAAI,MAAM,YAAY,eAAe,WAAW,GAC9C;EAEF,MAAM,MAAM,MAAM,QAAQ,aAAa;EACvC,MAAM,MAAM,aAAa,IAAI,IAAI,IAAI;GACnC;GACA,YAAY;GACZ,SAAS;GACT,SAAS;GACV;AACD,MAAI,WAAW,SACb,KAAI,cAAc;WACT,WAAW,MACpB,KAAI,WAAW;MAEf,KAAI,WAAW;AAEjB,eAAa,IAAI,KAAK,IAAI;;AAE5B,KAAI,KAAK,OAAO,WAAW,OAAO,KAAK,OAAO,WAAW,EAAE,SAAS;AACpE,MAAK,MAAM,OAAO,KAAK,UAAU,YAAY,EAAE,CAC7C,KAAI,IAAI,OAAO,OAAO,IAAI,OAAO,EAAE,MAAM;AAE3C,MAAK,MAAM,OAAO,KAAK,UAAU,YAAY,EAAE,CAE7C,KAAI,CAAC,IAAI,SACP,KAAI,IAAI,OAAO,OAAO,IAAI,OAAO,EAAE,MAAM;CAI7C,MAAM,oBAAoB,MACxB,EAAE,WAAW,gBAAgB,EAAE,UAAU;CAC3C,MAAM,QAAQ,MAA2B,EAAE,aAAa,iBAAiB,EAAE;AAI3E,MAAK,MAAM,CAAC,KAAK,QAAQ,aACvB,KAAI,KAAK,IAAI,KAAK,GAChB,cAAa,OAAO,IA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GtC,QAAI,QADD,IAAI,aAAa,iBAAkB,qBAAqB,UAChC;AACzB,UAAK,OAAO,cAAc,OAAO,UAAU,UAAU;AACrD;;;AAIJ,OAAI,SAAS;AACX,QAAI,QAAQ,SAAS,EACnB,OAAM,IAAI,aACR,kDACA,IAAI,MACF,+BAA+B,QAC5B,KAAK,MAAM,EAAE,UAAU,EAAE,QAAQ,CACjC,KAAK,KAAK,CAAC,GACf,CACF;IAEH,MAAM,QAAQ,aAAa,KAAK,EAAE,KAAK,WAAW;KAChD,MAAM,SAAS,YAAY,KAAK,IAAI,EAAE,IAAI,MAAM,SAAS;KACzD,MAAM,UAAU,YAAY,MAAM,IAAI,MAAM,SAAS;KACrD,MAAM,SAAS,IAAI,MAAM;AAIzB,YAAO,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;MACzF;AACF,UAAM,IAAI,aACR,2CACA,IAAI,MAAM,GAAG,MAAM,KAAK,IAAI,CAAC,2BAA2B,CACzD;;AAGH,SAAM,MAAM,kBAAkB,KAAK,QAAQ;;IAG/C;EACE,SAAS;EACT,eAAe,IAAI,aAAa,iCAAiC;EAClE,CACF"}
@@ -1,8 +1,8 @@
1
- import { LiFiErrorCode } from "../../../errors/constants.js";
1
+ import "../../../errors/constants.js";
2
2
  import { TransactionError } from "../../../errors/errors.js";
3
3
  //#region src/core/tasks/helpers/getTransactionRequestData.ts
4
4
  const getTransactionRequestData = async (step, executionOptions) => {
5
- if (!step.transactionRequest?.data) throw new TransactionError(LiFiErrorCode.TransactionUnprepared, "Unable to prepare transaction. Transaction request data is not found.");
5
+ if (!step.transactionRequest?.data) throw new TransactionError(1008, "Unable to prepare transaction. Transaction request data is not found.");
6
6
  let transactionRequest = { data: step.transactionRequest.data };
7
7
  if (executionOptions?.updateTransactionRequestHook) {
8
8
  const customizedTransactionRequest = await executionOptions.updateTransactionRequestHook({
@@ -15,7 +15,7 @@ const getTransactionRequestData = async (step, executionOptions) => {
15
15
  };
16
16
  }
17
17
  const transactionRequestData = transactionRequest.data;
18
- if (!transactionRequestData) throw new TransactionError(LiFiErrorCode.TransactionUnprepared, "Unable to prepare transaction. Transaction request data is not found.");
18
+ if (!transactionRequestData) throw new TransactionError(1008, "Unable to prepare transaction. Transaction request data is not found.");
19
19
  return transactionRequestData;
20
20
  };
21
21
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"getTransactionRequestData.js","names":[],"sources":["../../../../../src/core/tasks/helpers/getTransactionRequestData.ts"],"sourcesContent":["import { LiFiErrorCode } from '../../../errors/constants.js'\nimport { TransactionError } from '../../../errors/errors.js'\nimport type {\n ExecutionOptions,\n LiFiStepExtended,\n TransactionParameters,\n} from '../../../types/core.js'\n\nexport const getTransactionRequestData = async (\n step: LiFiStepExtended,\n executionOptions?: ExecutionOptions\n): Promise<string> => {\n if (!step.transactionRequest?.data) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Transaction request data is not found.'\n )\n }\n\n let transactionRequest: TransactionParameters = {\n data: step.transactionRequest.data,\n }\n\n if (executionOptions?.updateTransactionRequestHook) {\n const customizedTransactionRequest: TransactionParameters =\n await executionOptions.updateTransactionRequestHook({\n requestType: 'transaction',\n ...transactionRequest,\n })\n\n transactionRequest = {\n ...transactionRequest,\n ...customizedTransactionRequest,\n }\n }\n\n const transactionRequestData = transactionRequest.data\n\n if (!transactionRequestData) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Transaction request data is not found.'\n )\n }\n\n return transactionRequestData\n}\n"],"mappings":";;;AAQA,MAAa,4BAA4B,OACvC,MACA,qBACoB;AACpB,KAAI,CAAC,KAAK,oBAAoB,KAC5B,OAAM,IAAI,iBACR,cAAc,uBACd,wEACD;CAGH,IAAI,qBAA4C,EAC9C,MAAM,KAAK,mBAAmB,MAC/B;AAED,KAAI,kBAAkB,8BAA8B;EAClD,MAAM,+BACJ,MAAM,iBAAiB,6BAA6B;GAClD,aAAa;GACb,GAAG;GACJ,CAAC;AAEJ,uBAAqB;GACnB,GAAG;GACH,GAAG;GACJ;;CAGH,MAAM,yBAAyB,mBAAmB;AAElD,KAAI,CAAC,uBACH,OAAM,IAAI,iBACR,cAAc,uBACd,wEACD;AAGH,QAAO"}
1
+ {"version":3,"file":"getTransactionRequestData.js","names":[],"sources":["../../../../../src/core/tasks/helpers/getTransactionRequestData.ts"],"sourcesContent":["import { LiFiErrorCode } from '../../../errors/constants.js'\nimport { TransactionError } from '../../../errors/errors.js'\nimport type {\n ExecutionOptions,\n LiFiStepExtended,\n TransactionParameters,\n} from '../../../types/core.js'\n\nexport const getTransactionRequestData = async (\n step: LiFiStepExtended,\n executionOptions?: ExecutionOptions\n): Promise<string> => {\n if (!step.transactionRequest?.data) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Transaction request data is not found.'\n )\n }\n\n let transactionRequest: TransactionParameters = {\n data: step.transactionRequest.data,\n }\n\n if (executionOptions?.updateTransactionRequestHook) {\n const customizedTransactionRequest: TransactionParameters =\n await executionOptions.updateTransactionRequestHook({\n requestType: 'transaction',\n ...transactionRequest,\n })\n\n transactionRequest = {\n ...transactionRequest,\n ...customizedTransactionRequest,\n }\n }\n\n const transactionRequestData = transactionRequest.data\n\n if (!transactionRequestData) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Transaction request data is not found.'\n )\n }\n\n return transactionRequestData\n}\n"],"mappings":";;;AAQA,MAAa,4BAA4B,OACvC,MACA,qBACoB;AACpB,KAAI,CAAC,KAAK,oBAAoB,KAC5B,OAAM,IAAI,iBAAA,MAER,wEACD;CAGH,IAAI,qBAA4C,EAC9C,MAAM,KAAK,mBAAmB,MAC/B;AAED,KAAI,kBAAkB,8BAA8B;EAClD,MAAM,+BACJ,MAAM,iBAAiB,6BAA6B;GAClD,aAAa;GACb,GAAG;GACJ,CAAC;AAEJ,uBAAqB;GACnB,GAAG;GACH,GAAG;GACJ;;CAGH,MAAM,yBAAyB,mBAAmB;AAElD,KAAI,CAAC,uBACH,OAAM,IAAI,iBAAA,MAER,wEACD;AAGH,QAAO"}
@@ -1,4 +1,4 @@
1
- import { LiFiErrorCode } from "../../../errors/constants.js";
1
+ import "../../../errors/constants.js";
2
2
  import { TransactionError } from "../../../errors/errors.js";
3
3
  import { checkStepSlippageThreshold } from "../../utils.js";
4
4
  //#region src/core/tasks/helpers/stepComparison.ts
@@ -22,7 +22,7 @@ const stepComparison = async (statusManager, oldStep, newStep, allowUserInteract
22
22
  newToAmount: newStep.estimate.toAmount,
23
23
  toToken: newStep.action.toToken
24
24
  });
25
- if (!allowStepUpdate) throw new TransactionError(LiFiErrorCode.ExchangeRateUpdateCanceled, "Exchange rate has changed!\nTransaction was not sent, your funds are still in your wallet.\nThe exchange rate has changed and the previous estimation can not be fulfilled due to value loss.");
25
+ if (!allowStepUpdate) throw new TransactionError(1016, "Exchange rate has changed!\nTransaction was not sent, your funds are still in your wallet.\nThe exchange rate has changed and the previous estimation can not be fulfilled due to value loss.");
26
26
  return statusManager.updateStepInRoute(newStep);
27
27
  };
28
28
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"stepComparison.js","names":[],"sources":["../../../../../src/core/tasks/helpers/stepComparison.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport type { StatusManager } from '../../../core/StatusManager.js'\nimport { checkStepSlippageThreshold } from '../../../core/utils.js'\nimport { LiFiErrorCode } from '../../../errors/constants.js'\nimport { TransactionError } from '../../../errors/errors.js'\nimport type { ExecutionOptions } from '../../../types/core.js'\n\n/**\n * This method checks whether the new and updated Step meets the required exchange rate conditions.\n * If yes it returns the updated Step.\n * If no and if user interaction is allowed it triggers the acceptExchangeRateUpdateHook. If no user interaction is allowed it aborts.\n * @param statusManager\n * @param oldStep\n * @param newStep\n * @param settings\n * @param allowUserInteraction\n * @param executionOptions\n * @returns Return LiFiStep\n */\nexport const stepComparison = async (\n statusManager: StatusManager,\n oldStep: LiFiStep,\n newStep: LiFiStep,\n allowUserInteraction: boolean,\n executionOptions?: ExecutionOptions\n): Promise<LiFiStep> => {\n // Check if changed exchange rate is in the range of slippage threshold\n if (checkStepSlippageThreshold(oldStep, newStep)) {\n return statusManager.updateStepInRoute(newStep)\n }\n\n let allowStepUpdate: boolean | undefined\n if (allowUserInteraction) {\n allowStepUpdate = await executionOptions?.acceptExchangeRateUpdateHook?.({\n oldToAmount: oldStep.estimate.toAmount,\n newToAmount: newStep.estimate.toAmount,\n toToken: newStep.action.toToken,\n })\n }\n\n if (!allowStepUpdate) {\n // The user declined the new exchange rate, so we are not going to proceed\n throw new TransactionError(\n LiFiErrorCode.ExchangeRateUpdateCanceled,\n 'Exchange rate has changed!\\nTransaction was not sent, your funds are still in your wallet.\\nThe exchange rate has changed and the previous estimation can not be fulfilled due to value loss.'\n )\n }\n\n return statusManager.updateStepInRoute(newStep)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,MAAa,iBAAiB,OAC5B,eACA,SACA,SACA,sBACA,qBACsB;AAEtB,KAAI,2BAA2B,SAAS,QAAQ,CAC9C,QAAO,cAAc,kBAAkB,QAAQ;CAGjD,IAAI;AACJ,KAAI,qBACF,mBAAkB,MAAM,kBAAkB,+BAA+B;EACvE,aAAa,QAAQ,SAAS;EAC9B,aAAa,QAAQ,SAAS;EAC9B,SAAS,QAAQ,OAAO;EACzB,CAAC;AAGJ,KAAI,CAAC,gBAEH,OAAM,IAAI,iBACR,cAAc,4BACd,gMACD;AAGH,QAAO,cAAc,kBAAkB,QAAQ"}
1
+ {"version":3,"file":"stepComparison.js","names":[],"sources":["../../../../../src/core/tasks/helpers/stepComparison.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport type { StatusManager } from '../../../core/StatusManager.js'\nimport { checkStepSlippageThreshold } from '../../../core/utils.js'\nimport { LiFiErrorCode } from '../../../errors/constants.js'\nimport { TransactionError } from '../../../errors/errors.js'\nimport type { ExecutionOptions } from '../../../types/core.js'\n\n/**\n * This method checks whether the new and updated Step meets the required exchange rate conditions.\n * If yes it returns the updated Step.\n * If no and if user interaction is allowed it triggers the acceptExchangeRateUpdateHook. If no user interaction is allowed it aborts.\n * @param statusManager\n * @param oldStep\n * @param newStep\n * @param settings\n * @param allowUserInteraction\n * @param executionOptions\n * @returns Return LiFiStep\n */\nexport const stepComparison = async (\n statusManager: StatusManager,\n oldStep: LiFiStep,\n newStep: LiFiStep,\n allowUserInteraction: boolean,\n executionOptions?: ExecutionOptions\n): Promise<LiFiStep> => {\n // Check if changed exchange rate is in the range of slippage threshold\n if (checkStepSlippageThreshold(oldStep, newStep)) {\n return statusManager.updateStepInRoute(newStep)\n }\n\n let allowStepUpdate: boolean | undefined\n if (allowUserInteraction) {\n allowStepUpdate = await executionOptions?.acceptExchangeRateUpdateHook?.({\n oldToAmount: oldStep.estimate.toAmount,\n newToAmount: newStep.estimate.toAmount,\n toToken: newStep.action.toToken,\n })\n }\n\n if (!allowStepUpdate) {\n // The user declined the new exchange rate, so we are not going to proceed\n throw new TransactionError(\n LiFiErrorCode.ExchangeRateUpdateCanceled,\n 'Exchange rate has changed!\\nTransaction was not sent, your funds are still in your wallet.\\nThe exchange rate has changed and the previous estimation can not be fulfilled due to value loss.'\n )\n }\n\n return statusManager.updateStepInRoute(newStep)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,MAAa,iBAAiB,OAC5B,eACA,SACA,SACA,sBACA,qBACsB;AAEtB,KAAI,2BAA2B,SAAS,QAAQ,CAC9C,QAAO,cAAc,kBAAkB,QAAQ;CAGjD,IAAI;AACJ,KAAI,qBACF,mBAAkB,MAAM,kBAAkB,+BAA+B;EACvE,aAAa,QAAQ,SAAS;EAC9B,aAAa,QAAQ,SAAS;EAC9B,SAAS,QAAQ,OAAO;EACzB,CAAC;AAGJ,KAAI,CAAC,gBAEH,OAAM,IAAI,iBAAA,MAER,gMACD;AAGH,QAAO,cAAc,kBAAkB,QAAQ"}
@@ -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,YAAY;CAEjE,MAAM,mBAAmB,uBADI,OAAO,QAAQ,SAAS,YAAY;CAGjE,IAAI,iBAAiB;AACrB,KAAI,uBAAuB,EACzB,kBACE,OAAQ,mBAAmB,cAAkB,qBAAqB,GAClE;AAEJ,QAAO,kBAAkB;;AAG3B,SAAgB,qBACd,iBACA,QACA,YACS;CACT,MAAM,oBAAoB,OAAO,QAAQ,SAAS,UAAU;AAC1D,MAAI,MAAM,UAAU,SAAS,OAC3B,SAAQ,MAAM,MAAiB,MAAM,SAAS;AAEhD,SAAO;IACN,EAAE,CAAY;CACjB,MAAM,SAAS,EAAE,GAAG,iBAAiB;AACrC,MAAK,MAAM,cAAc,mBAAmB;EAC1C,MAAM,UAAU,OAAO,WAAW;EAClC,MAAM,OAAO,kBAAkB;AAC/B,MAAI,CAAC,MAAM,OACT;AAEF,MAAI,CAAC,OAAO,UAAU,OACpB,QAAO,WAAW,MAAM,KAAK,KAAK;WACzB,CAAC,YAAY,SAAS,QAAQ,EAAE;GACzC,MAAM,eAAe,KAAK,QAAQ,QAAQ,CAAC,OAAO,UAAU,SAAS,IAAI,CAAC;AAC1E,UAAO,SAAS,KAAK,GAAG,aAAa;;;AAGzC,QAAO"}
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,YAAY;CAEjE,MAAM,mBAAmB,uBADI,OAAO,QAAQ,SAAS,YACe;CAEpE,IAAI,iBAAiB;AACrB,KAAI,uBAAuB,EACzB,kBACE,OAAQ,mBAAmB,cAAkB,qBAAqB,GAClE;AAEJ,QAAO,kBAAkB;;AAG3B,SAAgB,qBACd,iBACA,QACA,YACS;CACT,MAAM,oBAAoB,OAAO,QAAQ,SAAS,UAAU;AAC1D,MAAI,MAAM,UAAU,SAAS,OAC3B,SAAQ,MAAM,MAAiB,MAAM,SAAS;AAEhD,SAAO;IACN,EAAE,CAAY;CACjB,MAAM,SAAS,EAAE,GAAG,iBAAiB;AACrC,MAAK,MAAM,cAAc,mBAAmB;EAC1C,MAAM,UAAU,OAAO,WAAW;EAClC,MAAM,OAAO,kBAAkB;AAC/B,MAAI,CAAC,MAAM,OACT;AAEF,MAAI,CAAC,OAAO,UAAU,OACpB,QAAO,WAAW,MAAM,KAAK,KAAK;WACzB,CAAC,YAAY,SAAS,QAAQ,EAAE;GACzC,MAAM,eAAe,KAAK,QAAQ,QAAQ,CAAC,OAAO,UAAU,SAAS,IAAI,CAAC;AAC1E,UAAO,SAAS,KAAK,GAAG,aAAa;;;AAGzC,QAAO"}
@@ -1,39 +1,39 @@
1
1
  import { BaseError } from "./baseError.js";
2
- import { ErrorName, LiFiErrorCode } from "./constants.js";
2
+ import "./constants.js";
3
3
  //#region src/errors/errors.ts
4
4
  var RPCError = class extends BaseError {
5
5
  constructor(code, message, cause) {
6
- super(ErrorName.RPCError, code, message, cause);
6
+ super("RPCError", code, message, cause);
7
7
  }
8
8
  };
9
9
  var ProviderError = class extends BaseError {
10
10
  constructor(code, message, cause) {
11
- super(ErrorName.ProviderError, code, message, cause);
11
+ super("ProviderError", code, message, cause);
12
12
  }
13
13
  };
14
14
  var TransactionError = class extends BaseError {
15
15
  constructor(code, message, cause) {
16
- super(ErrorName.TransactionError, code, message, cause);
16
+ super("TransactionError", code, message, cause);
17
17
  }
18
18
  };
19
19
  var UnknownError = class extends BaseError {
20
20
  constructor(message, cause) {
21
- super(ErrorName.UnknownError, LiFiErrorCode.InternalError, message, cause);
21
+ super("UnknownError", 1e3, message, cause);
22
22
  }
23
23
  };
24
24
  var BalanceError = class extends BaseError {
25
25
  constructor(message, cause) {
26
- super(ErrorName.BalanceError, LiFiErrorCode.BalanceError, message, cause);
26
+ super("BalanceError", 1013, message, cause);
27
27
  }
28
28
  };
29
29
  var ServerError = class extends BaseError {
30
30
  constructor(message) {
31
- super(ErrorName.ServerError, LiFiErrorCode.InternalError, message);
31
+ super("ServerError", 1e3, message);
32
32
  }
33
33
  };
34
34
  var ValidationError = class extends BaseError {
35
35
  constructor(message) {
36
- super(ErrorName.ValidationError, LiFiErrorCode.ValidationError, message);
36
+ super("ValidationError", 1001, message);
37
37
  }
38
38
  };
39
39
  /**
@@ -44,7 +44,7 @@ var ValidationError = class extends BaseError {
44
44
  var ExecuteStepRetryError = class extends BaseError {
45
45
  retryParams;
46
46
  constructor(message, retryParams, cause) {
47
- super(ErrorName.ExecuteStepRetryError, LiFiErrorCode.InternalError, message, cause);
47
+ super("ExecuteStepRetryError", 1e3, message, cause);
48
48
  this.retryParams = retryParams;
49
49
  }
50
50
  };
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":[],"sources":["../../../src/errors/errors.ts"],"sourcesContent":["import type { ExecuteStepRetryParams } from '../types/core.js'\nimport { BaseError } from './baseError.js'\nimport { ErrorName, LiFiErrorCode } from './constants.js'\n\nexport class RPCError extends BaseError {\n constructor(code: LiFiErrorCode, message: string, cause?: Error) {\n super(ErrorName.RPCError, code, message, cause)\n }\n}\n\nexport class ProviderError extends BaseError {\n constructor(code: LiFiErrorCode, message: string, cause?: Error) {\n super(ErrorName.ProviderError, code, message, cause)\n }\n}\n\nexport class TransactionError extends BaseError {\n constructor(code: LiFiErrorCode, message: string, cause?: Error) {\n super(ErrorName.TransactionError, code, message, cause)\n }\n}\n\nexport class UnknownError extends BaseError {\n constructor(message: string, cause?: Error) {\n super(ErrorName.UnknownError, LiFiErrorCode.InternalError, message, cause)\n }\n}\n\nexport class BalanceError extends BaseError {\n constructor(message: string, cause?: Error) {\n super(ErrorName.BalanceError, LiFiErrorCode.BalanceError, message, cause)\n }\n}\n\nexport class ServerError extends BaseError {\n constructor(message: string) {\n super(ErrorName.ServerError, LiFiErrorCode.InternalError, message)\n }\n}\n\nexport class ValidationError extends BaseError {\n constructor(message: string) {\n super(ErrorName.ValidationError, LiFiErrorCode.ValidationError, message)\n }\n}\n\n/**\n * Thrown by a step executor when executeStep should be retried with the given params\n * (e.g. wallet rejected 7702 upgrade → retry with atomicityNotReady).\n * The execution layer catches this and retries executeStep(client, step, retryParams).\n */\nexport class ExecuteStepRetryError extends BaseError {\n readonly retryParams: ExecuteStepRetryParams\n\n constructor(\n message: string,\n retryParams: ExecuteStepRetryParams,\n cause?: Error\n ) {\n super(\n ErrorName.ExecuteStepRetryError,\n LiFiErrorCode.InternalError,\n message,\n cause\n )\n this.retryParams = retryParams\n }\n}\n"],"mappings":";;;AAIA,IAAa,WAAb,cAA8B,UAAU;CACtC,YAAY,MAAqB,SAAiB,OAAe;AAC/D,QAAM,UAAU,UAAU,MAAM,SAAS,MAAM;;;AAInD,IAAa,gBAAb,cAAmC,UAAU;CAC3C,YAAY,MAAqB,SAAiB,OAAe;AAC/D,QAAM,UAAU,eAAe,MAAM,SAAS,MAAM;;;AAIxD,IAAa,mBAAb,cAAsC,UAAU;CAC9C,YAAY,MAAqB,SAAiB,OAAe;AAC/D,QAAM,UAAU,kBAAkB,MAAM,SAAS,MAAM;;;AAI3D,IAAa,eAAb,cAAkC,UAAU;CAC1C,YAAY,SAAiB,OAAe;AAC1C,QAAM,UAAU,cAAc,cAAc,eAAe,SAAS,MAAM;;;AAI9E,IAAa,eAAb,cAAkC,UAAU;CAC1C,YAAY,SAAiB,OAAe;AAC1C,QAAM,UAAU,cAAc,cAAc,cAAc,SAAS,MAAM;;;AAI7E,IAAa,cAAb,cAAiC,UAAU;CACzC,YAAY,SAAiB;AAC3B,QAAM,UAAU,aAAa,cAAc,eAAe,QAAQ;;;AAItE,IAAa,kBAAb,cAAqC,UAAU;CAC7C,YAAY,SAAiB;AAC3B,QAAM,UAAU,iBAAiB,cAAc,iBAAiB,QAAQ;;;;;;;;AAS5E,IAAa,wBAAb,cAA2C,UAAU;CACnD;CAEA,YACE,SACA,aACA,OACA;AACA,QACE,UAAU,uBACV,cAAc,eACd,SACA,MACD;AACD,OAAK,cAAc"}
1
+ {"version":3,"file":"errors.js","names":[],"sources":["../../../src/errors/errors.ts"],"sourcesContent":["import type { ExecuteStepRetryParams } from '../types/core.js'\nimport { BaseError } from './baseError.js'\nimport { ErrorName, LiFiErrorCode } from './constants.js'\n\nexport class RPCError extends BaseError {\n constructor(code: LiFiErrorCode, message: string, cause?: Error) {\n super(ErrorName.RPCError, code, message, cause)\n }\n}\n\nexport class ProviderError extends BaseError {\n constructor(code: LiFiErrorCode, message: string, cause?: Error) {\n super(ErrorName.ProviderError, code, message, cause)\n }\n}\n\nexport class TransactionError extends BaseError {\n constructor(code: LiFiErrorCode, message: string, cause?: Error) {\n super(ErrorName.TransactionError, code, message, cause)\n }\n}\n\nexport class UnknownError extends BaseError {\n constructor(message: string, cause?: Error) {\n super(ErrorName.UnknownError, LiFiErrorCode.InternalError, message, cause)\n }\n}\n\nexport class BalanceError extends BaseError {\n constructor(message: string, cause?: Error) {\n super(ErrorName.BalanceError, LiFiErrorCode.BalanceError, message, cause)\n }\n}\n\nexport class ServerError extends BaseError {\n constructor(message: string) {\n super(ErrorName.ServerError, LiFiErrorCode.InternalError, message)\n }\n}\n\nexport class ValidationError extends BaseError {\n constructor(message: string) {\n super(ErrorName.ValidationError, LiFiErrorCode.ValidationError, message)\n }\n}\n\n/**\n * Thrown by a step executor when executeStep should be retried with the given params\n * (e.g. wallet rejected 7702 upgrade → retry with atomicityNotReady).\n * The execution layer catches this and retries executeStep(client, step, retryParams).\n */\nexport class ExecuteStepRetryError extends BaseError {\n readonly retryParams: ExecuteStepRetryParams\n\n constructor(\n message: string,\n retryParams: ExecuteStepRetryParams,\n cause?: Error\n ) {\n super(\n ErrorName.ExecuteStepRetryError,\n LiFiErrorCode.InternalError,\n message,\n cause\n )\n this.retryParams = retryParams\n }\n}\n"],"mappings":";;;AAIA,IAAa,WAAb,cAA8B,UAAU;CACtC,YAAY,MAAqB,SAAiB,OAAe;AAC/D,QAAA,YAA0B,MAAM,SAAS,MAAM;;;AAInD,IAAa,gBAAb,cAAmC,UAAU;CAC3C,YAAY,MAAqB,SAAiB,OAAe;AAC/D,QAAA,iBAA+B,MAAM,SAAS,MAAM;;;AAIxD,IAAa,mBAAb,cAAsC,UAAU;CAC9C,YAAY,MAAqB,SAAiB,OAAe;AAC/D,QAAA,oBAAkC,MAAM,SAAS,MAAM;;;AAI3D,IAAa,eAAb,cAAkC,UAAU;CAC1C,YAAY,SAAiB,OAAe;AAC1C,QAAA,gBAAA,KAA2D,SAAS,MAAM;;;AAI9E,IAAa,eAAb,cAAkC,UAAU;CAC1C,YAAY,SAAiB,OAAe;AAC1C,QAAA,gBAAA,MAA0D,SAAS,MAAM;;;AAI7E,IAAa,cAAb,cAAiC,UAAU;CACzC,YAAY,SAAiB;AAC3B,QAAA,eAAA,KAA0D,QAAQ;;;AAItE,IAAa,kBAAb,cAAqC,UAAU;CAC7C,YAAY,SAAiB;AAC3B,QAAA,mBAAA,MAAgE,QAAQ;;;;;;;;AAS5E,IAAa,wBAAb,cAA2C,UAAU;CACnD;CAEA,YACE,SACA,aACA,OACA;AACA,QAAA,yBAAA,KAGE,SACA,MACD;AACD,OAAK,cAAc"}
@@ -1,36 +1,36 @@
1
1
  import { BaseError } from "./baseError.js";
2
- import { ErrorMessage, ErrorName, LiFiErrorCode } from "./constants.js";
2
+ import "./constants.js";
3
3
  //#region src/errors/httpError.ts
4
4
  const statusCodeToErrorClassificationMap = new Map([
5
5
  [400, {
6
- type: ErrorName.ValidationError,
7
- code: LiFiErrorCode.ValidationError
6
+ type: "ValidationError",
7
+ code: 1001
8
8
  }],
9
9
  [404, {
10
- type: ErrorName.NotFoundError,
11
- code: LiFiErrorCode.NotFound
10
+ type: "NotFoundError",
11
+ code: 1006
12
12
  }],
13
13
  [409, {
14
- type: ErrorName.SlippageError,
15
- code: LiFiErrorCode.SlippageError,
16
- message: ErrorMessage.SlippageError
14
+ type: "SlippageError",
15
+ code: 1011,
16
+ message: "The slippage is larger than the defined threshold. Please request a new route to get a fresh quote."
17
17
  }],
18
18
  [424, {
19
- type: ErrorName.ServerError,
20
- code: LiFiErrorCode.ThirdPartyError
19
+ type: "ServerError",
20
+ code: 1024
21
21
  }],
22
22
  [429, {
23
- type: ErrorName.ServerError,
24
- code: LiFiErrorCode.RateLimitExceeded
23
+ type: "ServerError",
24
+ code: 1023
25
25
  }],
26
26
  [500, {
27
- type: ErrorName.ServerError,
28
- code: LiFiErrorCode.InternalError
27
+ type: "ServerError",
28
+ code: 1e3
29
29
  }]
30
30
  ]);
31
31
  const getErrorClassificationFromStatusCode = (code) => statusCodeToErrorClassificationMap.get(code) ?? {
32
- type: ErrorName.ServerError,
33
- code: LiFiErrorCode.InternalError
32
+ type: "ServerError",
33
+ code: 1e3
34
34
  };
35
35
  const createInitialMessage = (response) => {
36
36
  const status = `${response.status || response.status === 0 ? response.status : ""} ${response.statusText || ""}`.trim();
@@ -47,7 +47,7 @@ var HTTPError = class extends BaseError {
47
47
  const errorClassification = getErrorClassificationFromStatusCode(response.status);
48
48
  const additionalMessage = errorClassification?.message ? `\n${errorClassification.message}` : "";
49
49
  const message = createInitialMessage(response) + additionalMessage;
50
- super(ErrorName.HTTPError, errorClassification.code, message);
50
+ super("HTTPError", errorClassification.code, message);
51
51
  this.type = errorClassification.type;
52
52
  this.response = response;
53
53
  this.status = response.status;
@@ -1 +1 @@
1
- {"version":3,"file":"httpError.js","names":[],"sources":["../../../src/errors/httpError.ts"],"sourcesContent":["import type { UnavailableRoutes } from '@lifi/types'\nimport type { ExtendedRequestInit } from '../types/request.js'\nimport { BaseError } from './baseError.js'\nimport { ErrorMessage, ErrorName, LiFiErrorCode } from './constants.js'\n\ninterface ServerErrorResponseBody {\n code: number\n message: string\n errors?: UnavailableRoutes\n}\n\nconst statusCodeToErrorClassificationMap = new Map([\n [\n 400,\n { type: ErrorName.ValidationError, code: LiFiErrorCode.ValidationError },\n ],\n [404, { type: ErrorName.NotFoundError, code: LiFiErrorCode.NotFound }],\n [\n 409,\n {\n type: ErrorName.SlippageError,\n code: LiFiErrorCode.SlippageError,\n message: ErrorMessage.SlippageError,\n },\n ],\n [424, { type: ErrorName.ServerError, code: LiFiErrorCode.ThirdPartyError }],\n [429, { type: ErrorName.ServerError, code: LiFiErrorCode.RateLimitExceeded }],\n [500, { type: ErrorName.ServerError, code: LiFiErrorCode.InternalError }],\n])\n\nconst getErrorClassificationFromStatusCode = (code: number) =>\n statusCodeToErrorClassificationMap.get(code) ?? {\n type: ErrorName.ServerError,\n code: LiFiErrorCode.InternalError,\n }\n\nconst createInitialMessage = (response: Response) => {\n const statusCode =\n response.status || response.status === 0 ? response.status : ''\n const title = response.statusText || ''\n const status = `${statusCode} ${title}`.trim()\n const reason = status ? `status code ${status}` : 'an unknown error'\n return `Request failed with ${reason}`\n}\n\nexport class HTTPError extends BaseError {\n public response: Response\n public status: number\n public url: RequestInfo | URL\n public fetchOptions: ExtendedRequestInit\n public type?: ErrorName\n public responseBody?: ServerErrorResponseBody\n\n constructor(\n response: Response,\n url: RequestInfo | URL,\n options: ExtendedRequestInit\n ) {\n const errorClassification = getErrorClassificationFromStatusCode(\n response.status\n )\n const additionalMessage = errorClassification?.message\n ? `\\n${errorClassification.message}`\n : ''\n const message = createInitialMessage(response) + additionalMessage\n\n super(ErrorName.HTTPError, errorClassification.code, message)\n\n this.type = errorClassification.type\n this.response = response\n this.status = response.status\n this.message = message\n this.url = url\n this.fetchOptions = options\n }\n\n async buildAdditionalDetails(): Promise<void> {\n if (this.type) {\n this.message = `[${this.type}] ${this.message}`\n }\n\n try {\n this.responseBody = await this.response.json()\n\n if (this.responseBody?.message) {\n this.message += this.message.endsWith('.')\n ? ` ${this.responseBody.message.toString()}`\n : `. ${this.responseBody.message.toString()}`\n }\n } catch {}\n }\n}\n"],"m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eAAe,MAAM,KAAK,SAAS,MAAM;AAE9C,OAAI,KAAK,cAAc,QACrB,MAAK,WAAW,KAAK,QAAQ,SAAS,IAAI,GACtC,IAAI,KAAK,aAAa,QAAQ,UAAU,KACxC,KAAK,KAAK,aAAa,QAAQ,UAAU;UAEzC"}
1
+ {"version":3,"file":"httpError.js","names":[],"sources":["../../../src/errors/httpError.ts"],"sourcesContent":["import type { UnavailableRoutes } from '@lifi/types'\nimport type { ExtendedRequestInit } from '../types/request.js'\nimport { BaseError } from './baseError.js'\nimport { ErrorMessage, ErrorName, LiFiErrorCode } from './constants.js'\n\ninterface ServerErrorResponseBody {\n code: number\n message: string\n errors?: UnavailableRoutes\n}\n\nconst statusCodeToErrorClassificationMap = new Map([\n [\n 400,\n { type: ErrorName.ValidationError, code: LiFiErrorCode.ValidationError },\n ],\n [404, { type: ErrorName.NotFoundError, code: LiFiErrorCode.NotFound }],\n [\n 409,\n {\n type: ErrorName.SlippageError,\n code: LiFiErrorCode.SlippageError,\n message: ErrorMessage.SlippageError,\n },\n ],\n [424, { type: ErrorName.ServerError, code: LiFiErrorCode.ThirdPartyError }],\n [429, { type: ErrorName.ServerError, code: LiFiErrorCode.RateLimitExceeded }],\n [500, { type: ErrorName.ServerError, code: LiFiErrorCode.InternalError }],\n])\n\nconst getErrorClassificationFromStatusCode = (code: number) =>\n statusCodeToErrorClassificationMap.get(code) ?? {\n type: ErrorName.ServerError,\n code: LiFiErrorCode.InternalError,\n }\n\nconst createInitialMessage = (response: Response) => {\n const statusCode =\n response.status || response.status === 0 ? response.status : ''\n const title = response.statusText || ''\n const status = `${statusCode} ${title}`.trim()\n const reason = status ? `status code ${status}` : 'an unknown error'\n return `Request failed with ${reason}`\n}\n\nexport class HTTPError extends BaseError {\n public response: Response\n public status: number\n public url: RequestInfo | URL\n public fetchOptions: ExtendedRequestInit\n public type?: ErrorName\n public responseBody?: ServerErrorResponseBody\n\n constructor(\n response: Response,\n url: RequestInfo | URL,\n options: ExtendedRequestInit\n ) {\n const errorClassification = getErrorClassificationFromStatusCode(\n response.status\n )\n const additionalMessage = errorClassification?.message\n ? `\\n${errorClassification.message}`\n : ''\n const message = createInitialMessage(response) + additionalMessage\n\n super(ErrorName.HTTPError, errorClassification.code, message)\n\n this.type = errorClassification.type\n this.response = response\n this.status = response.status\n this.message = message\n this.url = url\n this.fetchOptions = options\n }\n\n async buildAdditionalDetails(): Promise<void> {\n if (this.type) {\n this.message = `[${this.type}] ${this.message}`\n }\n\n try {\n this.responseBody = await this.response.json()\n\n if (this.responseBody?.message) {\n this.message += this.message.endsWith('.')\n ? ` ${this.responseBody.message.toString()}`\n : `. ${this.responseBody.message.toString()}`\n }\n } catch {}\n }\n}\n"],"mappings":";;;AAWA,MAAM,qCAAqC,IAAI,IAAI;CACjD,CACE,KACA;EAAE,MAAA;EAAiC,MAAA;EAAqC,CACzE;CACD,CAAC,KAAK;EAAE,MAAA;EAA+B,MAAA;EAA8B,CAAC;CACtE,CACE,KACA;EACE,MAAA;EACA,MAAA;EACA,SAAA;EACD,CACF;CACD,CAAC,KAAK;EAAE,MAAA;EAA6B,MAAA;EAAqC,CAAC;CAC3E,CAAC,KAAK;EAAE,MAAA;EAA6B,MAAA;EAAuC,CAAC;CAC7E,CAAC,KAAK;EAAE,MAAA;EAA6B,MAAA;EAAmC,CAAC;CAC1E,CAAC;AAEF,MAAM,wCAAwC,SAC5C,mCAAmC,IAAI,KAAK,IAAI;CAC9C,MAAA;CACA,MAAA;CACD;AAEH,MAAM,wBAAwB,aAAuB;CAInD,MAAM,SAAS,GAFb,SAAS,UAAU,SAAS,WAAW,IAAI,SAAS,SAAS,GAElC,GADf,SAAS,cAAc,KACG,MAAM;AAE9C,QAAO,uBADQ,SAAS,eAAe,WAAW;;AAIpD,IAAa,YAAb,cAA+B,UAAU;CACvC;CACA;CACA;CACA;CACA;CACA;CAEA,YACE,UACA,KACA,SACA;EACA,MAAM,sBAAsB,qCAC1B,SAAS,OACV;EACD,MAAM,oBAAoB,qBAAqB,UAC3C,KAAK,oBAAoB,YACzB;EACJ,MAAM,UAAU,qBAAqB,SAAS,GAAG;AAEjD,QAAA,aAA2B,oBAAoB,MAAM,QAAQ;AAE7D,OAAK,OAAO,oBAAoB;AAChC,OAAK,WAAW;AAChB,OAAK,SAAS,SAAS;AACvB,OAAK,UAAU;AACf,OAAK,MAAM;AACX,OAAK,eAAe;;CAGtB,MAAM,yBAAwC;AAC5C,MAAI,KAAK,KACP,MAAK,UAAU,IAAI,KAAK,KAAK,IAAI,KAAK;AAGxC,MAAI;AACF,QAAK,eAAe,MAAM,KAAK,SAAS,MAAM;AAE9C,OAAI,KAAK,cAAc,QACrB,MAAK,WAAW,KAAK,QAAQ,SAAS,IAAI,GACtC,IAAI,KAAK,aAAa,QAAQ,UAAU,KACxC,KAAK,KAAK,aAAa,QAAQ,UAAU;UAEzC"}
@@ -34,10 +34,10 @@ import { TaskPipeline } from "./core/TaskPipeline.js";
34
34
  import { BaseStepExecutor } from "./core/BaseStepExecutor.js";
35
35
  import { getActionMessage, getSubstatusMessage } from "./core/actionMessages.js";
36
36
  import { executeRoute, getActiveRoute, getActiveRoutes, resumeRoute, stopRouteExecution, updateRouteExecution } from "./core/execution.js";
37
+ import { CheckBalanceOptions, checkBalance } from "./core/tasks/helpers/checkBalance.js";
37
38
  import { CheckBalanceTask } from "./core/tasks/CheckBalanceTask.js";
38
39
  import { PrepareTransactionTask } from "./core/tasks/PrepareTransactionTask.js";
39
40
  import { WaitForTransactionStatusTask } from "./core/tasks/WaitForTransactionStatusTask.js";
40
- import { checkBalance } from "./core/tasks/helpers/checkBalance.js";
41
41
  import { getTransactionRequestData } from "./core/tasks/helpers/getTransactionRequestData.js";
42
42
  import { stepComparison } from "./core/tasks/helpers/stepComparison.js";
43
43
  import { HTTPError } from "./errors/httpError.js";
@@ -52,4 +52,4 @@ import { waitForResult } from "./utils/waitForResult.js";
52
52
  import { LruMap, withDedupe } from "./utils/withDedupe.js";
53
53
  import { withTimeout } from "./utils/withTimeout.js";
54
54
  export * from "@lifi/types";
55
- export { type AcceptExchangeRateUpdateHook, type AcceptSlippageUpdateHook, type AcceptSlippageUpdateHookParams, BalanceError, BaseError, BaseStepExecutionTask, BaseStepExecutor, 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, HTTPError, InMemoryStorage, type InteractionSettings, LiFiErrorCode, type LiFiStepExtended, LocalStorageAdapter, LruMap, PrepareTransactionTask, ProviderError, 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, getWalletBalances, isHex, parseUnits, patchContractCalls, relayTransaction, resumeRoute, sleep, stepComparison, stopRouteExecution, updateRouteExecution, waitForResult, withDedupe, withTimeout };
55
+ 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, HTTPError, InMemoryStorage, type InteractionSettings, LiFiErrorCode, type LiFiStepExtended, LocalStorageAdapter, LruMap, PrepareTransactionTask, ProviderError, 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, getWalletBalances, isHex, parseUnits, patchContractCalls, relayTransaction, resumeRoute, sleep, stepComparison, stopRouteExecution, updateRouteExecution, waitForResult, withDedupe, withTimeout };
@@ -138,10 +138,6 @@ interface ExecutionOptions {
138
138
  getContractCalls?: GetContractCallsHook;
139
139
  adjustZeroOutputFromPreviousStep?: boolean;
140
140
  executeInBackground?: boolean;
141
- /**
142
- * @deprecated
143
- */
144
- infiniteApproval?: boolean;
145
141
  }
146
142
  type ExecutionStatus = "ACTION_REQUIRED" | "PENDING" | "FAILED" | "DONE";
147
143
  type ExecutionActionStatus = "STARTED" | "ACTION_REQUIRED" | "MESSAGE_REQUIRED" | "RESET_REQUIRED" | "PENDING" | "FAILED" | "DONE" | "CANCELLED";
@@ -1 +1 @@
1
- {"version":3,"file":"core.d.ts","names":[],"sources":["../../../src/types/core.ts"],"mappings":";;;;;KAmBY,kBAAA,IACV,OAAA,EAAS,mBAAA,KACN,mBAAA,GAAsB,OAAA,CAAQ,mBAAA;AAAA,UAElB,aAAA;EACf,MAAA;EACA,MAAA;EACA,UAAA;EACA,MAAA;EACA,YAAA,GAAe,YAAA;EACf,gBAAA,GAAmB,gBAAA;EACnB,OAAA,EAAS,OAAA;EACT,mBAAA;EACA,aAAA;EACA,KAAA;EACA,aAAA;EACA,qBAAA;EACA,kBAAA,GAAqB,kBAAA;EACrB,OAAA,GAAU,UAAA;AAAA;AAAA,UAGK,SAAA,SAAkB,OAAA,CAAQ,IAAA,CAAK,aAAA;EAC9C,UAAA;EACA,SAAA,GAAY,WAAA;AAAA;AAAA,KAGF,OAAA,GAAU,OAAA,CAAQ,MAAA,CAAO,OAAA;AAAA,UAEpB,WAAA;EAAA,SACN,IAAA,EAAM,SAAA;EACf,SAAA,CAAU,OAAA;EACV,cAAA,CACE,IAAA,UACA,MAAA,EAAQ,SAAA,EACR,OAAA,GAAU,OAAA,EACV,KAAA,GAAQ,OAAA,GACP,OAAA;EACH,eAAA,CAAgB,OAAA,EAAS,mBAAA,GAAsB,OAAA,CAAQ,YAAA;EACvD,UAAA,CACE,MAAA,EAAQ,SAAA,EACR,aAAA,UACA,MAAA,EAAQ,KAAA,KACP,OAAA,CAAQ,WAAA;AAAA;AAAA,UAGI,SAAA;EACf,MAAA,EAAQ,aAAA;EACR,SAAA,EAAW,WAAA;EACX,WAAA,CAAY,IAAA,EAAM,SAAA,GAAY,WAAA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AAA,UAGnC,SAAA;EACf,SAAA;EACA,QAAA;EACA,MAAA,EAAQ,eAAA;EACR,OAAA,EAAS,KAAA,CAAM,eAAA;EACf,UAAA;EACA,QAAA;EACA,OAAA,GAAU,KAAA;EACV,QAAA,GAAW,OAAA;EACX,QAAA,GAAW,OAAA;EACX,cAAA;EACA,cAAA;EAEA,KAAA;IAAU,IAAA;IAAuB,OAAA;IAAiB,WAAA;EAAA;AAAA;AAAA,KAGxC,qBAAA"}
@@ -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.0-beta.6";
7
+ const currentVersion = packageVersion ?? "4.0.0-beta.8";
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;AAClB,KAAI;EACF,MAAM,UAAU,eAAA;EAGhB,MAAM,iBADc,OADH,MAAM,MAAM,8BAA8B,QAAQ,SAAS,EACzC,MAAM,EACP;EAClC,MAAM,iBAAiB,kBAAA;AAEvB,MAAI,gBAAgB,eAClB,SAAQ,KACN,GAAG,QAAQ,uHAAuH,eAAe,oBAAoB,cAAc,GACpL;UAEI,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;AAClB,KAAI;EACF,MAAM,UAAU,eAAA;EAGhB,MAAM,iBAAgB,OADI,MADH,MAAM,8BAA8B,QAAQ,SAAS,EACzC,MAAM,EACP;EAClC,MAAM,iBAAiB,kBAAA;AAEvB,MAAI,gBAAgB,eAClB,SAAQ,KACN,GAAG,QAAQ,uHAAuH,eAAe,oBAAoB,cAAc,GACpL;UAEI,QAAQ"}
@@ -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;AACzD,KAAI,CAAC,MACH,QAAO;AAET,KAAI;AACF,SAAO,OAAO,MAAM;SACd;AACN,SAAO;;;AAIX,MAAM,eAAe,UAAsC;AACzD,KAAI,CAAC,MACH,QAAO;CAET,MAAM,SAAS,OAAO,MAAM;AAC5B,QAAO,OAAO,MAAM,OAAO,GAAG,IAAI;;AAGpC,MAAM,gBACJ,UACA,aACA,gBACY;AACZ,QACE,CAAC,YAAY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,MAAM,SAAS,cAClB,OAAM,IAAI,SACR,IAAI,gBAAgB,4CAA4C,CACjE;AAGH,KAAI,CAAC,YACH,OAAM,IAAI,SACR,IAAI,gBAAgB,0CAA0C,CAC/D;AAqBH,QAlBqB;EACnB,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,IAAI,aAAa;EACvD,OAAO,CAAC,MAAM;EACd,WAAW;GAAE,OAAO;GAAiB,cAAc;GAAK;EACzD"}
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;AACzD,KAAI,CAAC,MACH,QAAO;AAET,KAAI;AACF,SAAO,OAAO,MAAM;SACd;AACN,SAAO;;;AAIX,MAAM,eAAe,UAAsC;AACzD,KAAI,CAAC,MACH,QAAO;CAET,MAAM,SAAS,OAAO,MAAM;AAC5B,QAAO,OAAO,MAAM,OAAO,GAAG,IAAI;;AAGpC,MAAM,gBACJ,UACA,aACA,gBACY;AACZ,QACE,CAAC,YAAY,SAAS,IACtB,CAAC,YAAY,YAAY,IACzB,CAAC,YAAY,YAAY;;AAI7B,MAAM,oBAAoB,SAAwB;AAChD,QACE,CAAC,CAAC,YAAY,KAAK,SAAS,SAAS,IACrC,CAAC,CAAC,YAAY,KAAK,SAAS,YAAY;;AAI5C,MAAM,2BAA2B,UAAoC;AAEnE,MAAK,IAAI,IAAI,MAAM,SAAS,GAAG,KAAK,GAAG,KAAK;EAC1C,MAAM,OAAO,MAAM;AACnB,MAAI,iBAAiB,KAAK,CACxB,QAAO;;;AAMb,SAAgB,iBACd,QACA,OACA,UACQ;AACR,KAAI,CAAC,UAAU,CAAC,MACd,QAA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O;EAClD,YAAY,MAAM,SAAS,WAAW,IAAI,aAAa;EACvD,OAAO,CAAC,MAAM;EACd,WAAW;GAAE,OAAO;GAAiB,cAAc;GAAK;EAG9C"}
@@ -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;AAWxD,QAVgB,IAAI,aAAa,CAC9B,OACC,IAAI,WACF,OACG,MAAM,EAAE,CACR,MAAM,UAAU,EACf,KAAK,SAAS,OAAO,SAAS,MAAM,GAAG,CAAC,IAAI,EAAE,CACnD,CACF,CACA,MAAM,IAAI"}
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;AAWxD,QAVgB,IAAI,aAAa,CAC9B,OACC,IAAI,WACF,OACG,MAAM,EAAE,CACR,MAAM,UAAU,EACf,KAAK,SAAS,OAAO,SAAS,MAAM,GAAG,CAAC,IAAI,EAAE,CACnD,CACF,CACA,MAAM,IACK"}
@@ -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;AACrB,KAAI;AAMF,SAFoB,OAHH,MAAM,MACrB,kDAAkD,QAAQ,MAAM,SACjE,EACkC,MAAM;UAGlC,GAAG;AACV"}
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;AACrB,KAAI;AAMF,SAAO,OAFmB,MAHH,MACrB,kDAAkD,QAAQ,MAAM,SACjE,EACkC,MAAM;UAGlC,GAAG;AACV"}
@@ -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&nbsp;<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;iDAFL,MAAM,OAAO,aAAa,KAAK,OAAO,UAAU,EAGV,KAAK,cAAc,KAAK,OAAO,QAAQ,OAAO;AAClG,QAAO,SACH,GAAG,WAAW;2CACuB,OAAO,wFAC5C"}
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&nbsp;<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,UAAU,EAGV,KAAK,cAAc,KAAK,OAAO,QAAQ,OAAO;AAClG,QAAO,SACH,GAAG,WAAW;2CACuB,OAAO,wFAC5C"}
@@ -1,6 +1,6 @@
1
1
  //#region src/version.d.ts
2
2
  declare const name = "@lifi/sdk";
3
- declare const version = "4.0.0-beta.6";
3
+ declare const version = "4.0.0-beta.8";
4
4
  //#endregion
5
5
  export { name, version };
6
6
  //# sourceMappingURL=version.d.ts.map
@@ -1,6 +1,6 @@
1
1
  //#region src/version.ts
2
2
  const name = "@lifi/sdk";
3
- const version = "4.0.0-beta.6";
3
+ const version = "4.0.0-beta.8";
4
4
  //#endregion
5
5
  export { name, version };
6
6
 
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk'\nexport const version = '4.0.0-beta.6'\n"],"mappings":";AAAA,MAAa,OAAO;AACpB,MAAa,UAAU"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/version.ts"],"sourcesContent":["export const name = '@lifi/sdk'\nexport const version = '4.0.0-beta.8'\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.0-beta.6",
3
+ "version": "4.0.0-beta.8",
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.75.1"
31
+ "@lifi/types": "17.78.0"
32
32
  },
33
33
  "publishConfig": {
34
34
  "access": "public"