@lifi/sdk 4.2.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/cjs/actions/getContractCallsQuote.js.map +1 -1
  3. package/dist/cjs/actions/getTokenBalances.js +3 -2
  4. package/dist/cjs/actions/getTokenBalances.js.map +1 -1
  5. package/dist/cjs/actions/getTokenBalancesByChain.js.map +1 -1
  6. package/dist/cjs/actions/index.d.ts +1 -8
  7. package/dist/cjs/actions/index.js +0 -2
  8. package/dist/cjs/actions/index.js.map +1 -1
  9. package/dist/cjs/client/getClientStorage.js +3 -2
  10. package/dist/cjs/client/getClientStorage.js.map +1 -1
  11. package/dist/cjs/core/BaseStepExecutor.js +11 -9
  12. package/dist/cjs/core/BaseStepExecutor.js.map +1 -1
  13. package/dist/cjs/core/StatusManager.js +1 -4
  14. package/dist/cjs/core/StatusManager.js.map +1 -1
  15. package/dist/cjs/core/execution.js.map +1 -1
  16. package/dist/cjs/core/tasks/CheckBalanceTask.js +2 -1
  17. package/dist/cjs/core/tasks/CheckBalanceTask.js.map +1 -1
  18. package/dist/cjs/core/tasks/PrepareTransactionTask.d.ts +7 -0
  19. package/dist/cjs/core/tasks/PrepareTransactionTask.js +12 -2
  20. package/dist/cjs/core/tasks/PrepareTransactionTask.js.map +1 -1
  21. package/dist/cjs/core/tasks/helpers/checkBalance.js +1 -1
  22. package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
  23. package/dist/cjs/index.d.ts +1 -2
  24. package/dist/cjs/index.js +0 -2
  25. package/dist/cjs/utils/checkPackageUpdates.js +1 -1
  26. package/dist/cjs/version.d.ts +1 -1
  27. package/dist/cjs/version.js +1 -1
  28. package/dist/cjs/version.js.map +1 -1
  29. package/dist/esm/actions/getTokenBalances.js +3 -2
  30. package/dist/esm/actions/getTokenBalances.js.map +1 -1
  31. package/dist/esm/actions/getTokenBalancesByChain.d.ts.map +1 -1
  32. package/dist/esm/actions/getTokenBalancesByChain.js.map +1 -1
  33. package/dist/esm/actions/index.d.ts +1 -8
  34. package/dist/esm/actions/index.d.ts.map +1 -1
  35. package/dist/esm/actions/index.js +0 -2
  36. package/dist/esm/actions/index.js.map +1 -1
  37. package/dist/esm/client/getClientStorage.js +3 -2
  38. package/dist/esm/client/getClientStorage.js.map +1 -1
  39. package/dist/esm/core/BaseStepExecutor.js +11 -9
  40. package/dist/esm/core/BaseStepExecutor.js.map +1 -1
  41. package/dist/esm/core/StatusManager.js +1 -4
  42. package/dist/esm/core/StatusManager.js.map +1 -1
  43. package/dist/esm/core/execution.js.map +1 -1
  44. package/dist/esm/core/tasks/CheckBalanceTask.js +2 -1
  45. package/dist/esm/core/tasks/CheckBalanceTask.js.map +1 -1
  46. package/dist/esm/core/tasks/PrepareTransactionTask.d.ts +7 -0
  47. package/dist/esm/core/tasks/PrepareTransactionTask.d.ts.map +1 -1
  48. package/dist/esm/core/tasks/PrepareTransactionTask.js +12 -2
  49. package/dist/esm/core/tasks/PrepareTransactionTask.js.map +1 -1
  50. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js +2 -1
  51. package/dist/esm/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
  52. package/dist/esm/core/tasks/helpers/checkBalance.js +1 -1
  53. package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
  54. package/dist/esm/index.d.ts +1 -2
  55. package/dist/esm/index.js +1 -2
  56. package/dist/esm/utils/checkPackageUpdates.js +1 -1
  57. package/dist/esm/version.d.ts +1 -1
  58. package/dist/esm/version.js +1 -1
  59. package/dist/esm/version.js.map +1 -1
  60. package/package.json +2 -2
  61. package/src/actions/index.ts +0 -15
  62. package/src/client/getClientStorage.ts +1 -0
  63. package/src/core/tasks/PrepareTransactionTask.ts +11 -1
  64. package/src/index.ts +0 -1
  65. package/src/version.ts +1 -1
  66. package/dist/cjs/actions/getWalletBalances.d.ts +0 -15
  67. package/dist/cjs/actions/getWalletBalances.js +0 -20
  68. package/dist/cjs/actions/getWalletBalances.js.map +0 -1
  69. package/dist/esm/actions/getWalletBalances.d.ts +0 -15
  70. package/dist/esm/actions/getWalletBalances.d.ts.map +0 -1
  71. package/dist/esm/actions/getWalletBalances.js +0 -19
  72. package/dist/esm/actions/getWalletBalances.js.map +0 -1
  73. package/src/actions/getWalletBalances.ts +0 -36
@@ -53,7 +53,7 @@ const checkBalance = async (client, walletAddress, step, options = {}) => {
53
53
  const slippageScaled = BigInt(Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION)));
54
54
  await withTimeout(async () => {
55
55
  for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
56
- const isFinal = attempt === MAX_ATTEMPTS - 1;
56
+ const isFinal = attempt === 5;
57
57
  let balances;
58
58
  try {
59
59
  balances = await provider.getBalance(client, walletAddress, tokens);
@@ -1 +1 @@
1
- {"version":3,"file":"checkBalance.js","names":[],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"sourcesContent":["import type { LiFiStep, Token, TokenAmount } from '@lifi/types'\nimport { BalanceError } from '../../../errors/errors.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { formatUnits } from '../../../utils/formatUnits.js'\nimport { sleep } from '../../../utils/sleep.js'\nimport { withTimeout } from '../../../utils/withTimeout.js'\n\nconst MAX_ATTEMPTS = 6\n// Exponential backoff: 150, 300, 600, 1200, 2400 → ≈4.65s of sleep total.\nconst BACKOFF_BASE_MS = 150\nconst OVERALL_TIMEOUT_MS = 10_000\nconst SLIPPAGE_PRECISION = 1_000_000_000n\n\ntype Bucket = 'source' | 'gas' | 'fee'\n\ntype Requirement = {\n token: Token\n sourcePart: bigint // step.action.fromAmount\n gasPart: bigint // step.estimate.gasCosts in this token\n feePart: bigint // non-included step.estimate.feeCosts in this token\n}\n\nexport type CheckBalanceOptions = {\n /**\n * Set to `false` when outer-tx gas is paid by something other than\n * `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):\n * `gasPart` is excluded from the sufficiency check and slippage rescue.\n * Source amount and non-included fees (e.g. LZ `msg.value`) are still\n * verified. Defaults to `true` (strict, today's behavior).\n */\n walletPaysGas?: boolean\n}\n\n/**\n * Verifies that the wallet holds enough of every token required to execute\n * the step on its source chain — the source-token amount, any gas costs, and\n * any non-included fee costs. Reads all balances in one batched provider\n * call, retries within a bounded budget to absorb transient RPC failures and\n * post-confirmation propagation lag, and applies slippage to the source-token\n * portion only as a last resort (overhead is never trimmed).\n *\n * Throws BalanceError(\"The balance is too low.\") on a genuine shortfall, or\n * BalanceError(\"Could not read wallet balance.\") if the balance can't be read\n * after retries.\n */\nexport const checkBalance = async (\n client: SDKClient,\n walletAddress: string,\n step: LiFiStep,\n options: CheckBalanceOptions = {}\n): Promise<void> => {\n const fromChainId = step.action.fromChainId\n // Chains with non-standard native decimals (e.g. Tempo, Stable) report\n // gas costs in units that don't align with wallet balances — drop the\n // gas portion of the check on those chains.\n const fromChain = await client.getChainById(fromChainId)\n const walletPaysGas =\n (options.walletPaysGas ?? true) && !fromChain.nonStandardNativeDecimals\n const requirements = new Map<string, Requirement>()\n const add = (token: Token, amount: bigint, bucket: Bucket): void => {\n if (token.chainId !== fromChainId || amount === 0n) {\n return\n }\n const key = token.address.toLowerCase()\n const req = requirements.get(key) ?? {\n token,\n sourcePart: 0n,\n gasPart: 0n,\n feePart: 0n,\n }\n if (bucket === 'source') {\n req.sourcePart += amount\n } else if (bucket === 'gas') {\n req.gasPart += amount\n } else {\n req.feePart += amount\n }\n requirements.set(key, req)\n }\n add(step.action.fromToken, BigInt(step.action.fromAmount), 'source')\n for (const gas of step.estimate?.gasCosts ?? []) {\n add(gas.token, BigInt(gas.amount), 'gas')\n }\n for (const fee of step.estimate?.feeCosts ?? []) {\n // Included fees are already part of fromAmount — don't count twice.\n if (!fee.included) {\n add(fee.token, BigInt(fee.amount), 'fee')\n }\n }\n\n const reservedOverhead = (r: Requirement): bigint =>\n r.feePart + (walletPaysGas ? r.gasPart : 0n)\n const need = (r: Requirement): bigint => r.sourcePart + reservedOverhead(r)\n\n // Drop pure-gas entries when `walletPaysGas` is false (e.g. native ETH\n // on Safe Apps with only `gasPart`) — saves one balance read each.\n for (const [key, req] of requirements) {\n if (need(req) === 0n) {\n requirements.delete(key)\n }\n }\n\n if (requirements.size === 0) {\n return\n }\n\n // Provider is dispatched by wallet address; all requirements share the\n // source chain, which matches this provider by virtue of the address.\n const provider = client.providers.find((p) => p.isAddress(walletAddress))\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const reqs = Array.from(requirements.values())\n const tokens = reqs.map((r) => r.token)\n const slippage = step.action.slippage ?? 0\n const slippageScaled = BigInt(\n Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))\n )\n\n await withTimeout(\n async () => {\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n const isFinal = attempt === MAX_ATTEMPTS - 1\n\n let balances: TokenAmount[]\n try {\n balances = await provider.getBalance(client, walletAddress, tokens)\n } catch (error) {\n if (isFinal) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n error as Error\n )\n }\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n continue\n }\n\n const balanceByAddress = new Map(\n balances.map((b) => [b.address.toLowerCase(), b.amount] as const)\n )\n\n const unknown: Token[] = []\n const insufficient: { req: Requirement; have: bigint }[] = []\n for (const req of reqs) {\n const have = balanceByAddress.get(req.token.address.toLowerCase())\n if (have === undefined) {\n unknown.push(req.token)\n } else if (have < need(req)) {\n insufficient.push({ req, have })\n }\n }\n\n if (unknown.length === 0 && insufficient.length === 0) {\n return\n }\n\n // Final-attempt slippage rescue: only when the sole shortfall is\n // the source-token portion. Trim source to (balance − reserved\n // overhead) so the overhead reserve is preserved.\n if (\n isFinal &&\n unknown.length === 0 &&\n insufficient.length === 1 &&\n insufficient[0].req.sourcePart > 0n\n ) {\n const { req, have } = insufficient[0]\n const reserved = reservedOverhead(req)\n const minAcceptable =\n (req.sourcePart * slippageScaled) / SLIPPAGE_PRECISION + reserved\n if (have >= minAcceptable) {\n const newFromAmount = (have - reserved).toString()\n step.action.fromAmount = newFromAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount = newFromAmount\n }\n return\n }\n }\n\n if (isFinal) {\n if (unknown.length > 0) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n new Error(\n `Could not read balance for: ${unknown\n .map((t) => t.symbol || t.address)\n .join(', ')}.`\n )\n )\n }\n const lines = insufficient.map(({ req, have }) => {\n const needed = formatUnits(need(req), req.token.decimals)\n const current = formatUnits(have, req.token.decimals)\n const symbol = req.token.symbol\n // The \"fees\" branch covers pure-overhead tokens; with\n // walletPaysGas=false, gas is excluded from `need(req)` so it\n // only fires for genuine fee shortfalls.\n return req.sourcePart > 0n\n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.`\n : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`\n })\n throw new BalanceError(\n 'The balance is too low.',\n new Error(`${lines.join(' ')} No funds have been sent.`)\n )\n }\n\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n }\n },\n {\n timeout: OVERALL_TIMEOUT_MS,\n errorInstance: new BalanceError('Could not read wallet balance.'),\n }\n )\n}\n"],"mappings":";;;;;AAOA,MAAM,eAAe;AAErB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;;;;;;;;;;;;;AAkC3B,MAAa,eAAe,OAC1B,QACA,eACA,MACA,UAA+B,CAAC,MACd;CAClB,MAAM,cAAc,KAAK,OAAO;CAIhC,MAAM,YAAY,MAAM,OAAO,aAAa,WAAW;CACvD,MAAM,iBACH,QAAQ,iBAAiB,SAAS,CAAC,UAAU;CAChD,MAAM,+BAAe,IAAI,IAAyB;CAClD,MAAM,OAAO,OAAc,QAAgB,WAAyB;EAClE,IAAI,MAAM,YAAY,eAAe,WAAW,IAC9C;EAEF,MAAM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AAI,MAAM,QAAQ;KACxD,MAAM,UAAU,YAAY,MAAM,IAAI,MAAM,QAAQ;KACpD,MAAM,SAAS,IAAI,MAAM;KAIzB,OAAO,IAAI,aAAa,KACpB,QAAQ,OAAO,2CAA2C,OAAO,GAAG,OAAO,+BAA+B,QAAQ,GAAG,OAAO,KAC5H,gBAAgB,OAAO,kBAAkB,OAAO,GAAG,OAAO,SAAS,QAAQ,GAAG,OAAO;IAC3F,CAAC;IACD,MAAM,IAAI,aACR,2CACA,IAAI,MAAM,GAAG,MAAM,KAAK,GAAG,EAAE,0BAA0B,CACzD;GACF;GAEA,MAAM,MAAM,kBAAkB,KAAK,OAAO;EAC5C;CACF,GACA;EACE,SAAS;EACT,eAAe,IAAI,aAAa,gCAAgC;CAClE,CACF;AACF"}
1
+ {"version":3,"file":"checkBalance.js","names":[],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"sourcesContent":["import type { LiFiStep, Token, TokenAmount } from '@lifi/types'\nimport { BalanceError } from '../../../errors/errors.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { formatUnits } from '../../../utils/formatUnits.js'\nimport { sleep } from '../../../utils/sleep.js'\nimport { withTimeout } from '../../../utils/withTimeout.js'\n\nconst MAX_ATTEMPTS = 6\n// Exponential backoff: 150, 300, 600, 1200, 2400 → ≈4.65s of sleep total.\nconst BACKOFF_BASE_MS = 150\nconst OVERALL_TIMEOUT_MS = 10_000\nconst SLIPPAGE_PRECISION = 1_000_000_000n\n\ntype Bucket = 'source' | 'gas' | 'fee'\n\ntype Requirement = {\n token: Token\n sourcePart: bigint // step.action.fromAmount\n gasPart: bigint // step.estimate.gasCosts in this token\n feePart: bigint // non-included step.estimate.feeCosts in this token\n}\n\nexport type CheckBalanceOptions = {\n /**\n * Set to `false` when outer-tx gas is paid by something other than\n * `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):\n * `gasPart` is excluded from the sufficiency check and slippage rescue.\n * Source amount and non-included fees (e.g. LZ `msg.value`) are still\n * verified. Defaults to `true` (strict, today's behavior).\n */\n walletPaysGas?: boolean\n}\n\n/**\n * Verifies that the wallet holds enough of every token required to execute\n * the step on its source chain — the source-token amount, any gas costs, and\n * any non-included fee costs. Reads all balances in one batched provider\n * call, retries within a bounded budget to absorb transient RPC failures and\n * post-confirmation propagation lag, and applies slippage to the source-token\n * portion only as a last resort (overhead is never trimmed).\n *\n * Throws BalanceError(\"The balance is too low.\") on a genuine shortfall, or\n * BalanceError(\"Could not read wallet balance.\") if the balance can't be read\n * after retries.\n */\nexport const checkBalance = async (\n client: SDKClient,\n walletAddress: string,\n step: LiFiStep,\n options: CheckBalanceOptions = {}\n): Promise<void> => {\n const fromChainId = step.action.fromChainId\n // Chains with non-standard native decimals (e.g. Tempo, Stable) report\n // gas costs in units that don't align with wallet balances — drop the\n // gas portion of the check on those chains.\n const fromChain = await client.getChainById(fromChainId)\n const walletPaysGas =\n (options.walletPaysGas ?? true) && !fromChain.nonStandardNativeDecimals\n const requirements = new Map<string, Requirement>()\n const add = (token: Token, amount: bigint, bucket: Bucket): void => {\n if (token.chainId !== fromChainId || amount === 0n) {\n return\n }\n const key = token.address.toLowerCase()\n const req = requirements.get(key) ?? {\n token,\n sourcePart: 0n,\n gasPart: 0n,\n feePart: 0n,\n }\n if (bucket === 'source') {\n req.sourcePart += amount\n } else if (bucket === 'gas') {\n req.gasPart += amount\n } else {\n req.feePart += amount\n }\n requirements.set(key, req)\n }\n add(step.action.fromToken, BigInt(step.action.fromAmount), 'source')\n for (const gas of step.estimate?.gasCosts ?? []) {\n add(gas.token, BigInt(gas.amount), 'gas')\n }\n for (const fee of step.estimate?.feeCosts ?? []) {\n // Included fees are already part of fromAmount — don't count twice.\n if (!fee.included) {\n add(fee.token, BigInt(fee.amount), 'fee')\n }\n }\n\n const reservedOverhead = (r: Requirement): bigint =>\n r.feePart + (walletPaysGas ? r.gasPart : 0n)\n const need = (r: Requirement): bigint => r.sourcePart + reservedOverhead(r)\n\n // Drop pure-gas entries when `walletPaysGas` is false (e.g. native ETH\n // on Safe Apps with only `gasPart`) — saves one balance read each.\n for (const [key, req] of requirements) {\n if (need(req) === 0n) {\n requirements.delete(key)\n }\n }\n\n if (requirements.size === 0) {\n return\n }\n\n // Provider is dispatched by wallet address; all requirements share the\n // source chain, which matches this provider by virtue of the address.\n const provider = client.providers.find((p) => p.isAddress(walletAddress))\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const reqs = Array.from(requirements.values())\n const tokens = reqs.map((r) => r.token)\n const slippage = step.action.slippage ?? 0\n const slippageScaled = BigInt(\n Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))\n )\n\n await withTimeout(\n async () => {\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n const isFinal = attempt === MAX_ATTEMPTS - 1\n\n let balances: TokenAmount[]\n try {\n balances = await provider.getBalance(client, walletAddress, tokens)\n } catch (error) {\n if (isFinal) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n error as Error\n )\n }\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n continue\n }\n\n const balanceByAddress = new Map(\n balances.map((b) => [b.address.toLowerCase(), b.amount] as const)\n )\n\n const unknown: Token[] = []\n const insufficient: { req: Requirement; have: bigint }[] = []\n for (const req of reqs) {\n const have = balanceByAddress.get(req.token.address.toLowerCase())\n if (have === undefined) {\n unknown.push(req.token)\n } else if (have < need(req)) {\n insufficient.push({ req, have })\n }\n }\n\n if (unknown.length === 0 && insufficient.length === 0) {\n return\n }\n\n // Final-attempt slippage rescue: only when the sole shortfall is\n // the source-token portion. Trim source to (balance − reserved\n // overhead) so the overhead reserve is preserved.\n if (\n isFinal &&\n unknown.length === 0 &&\n insufficient.length === 1 &&\n insufficient[0].req.sourcePart > 0n\n ) {\n const { req, have } = insufficient[0]\n const reserved = reservedOverhead(req)\n const minAcceptable =\n (req.sourcePart * slippageScaled) / SLIPPAGE_PRECISION + reserved\n if (have >= minAcceptable) {\n const newFromAmount = (have - reserved).toString()\n step.action.fromAmount = newFromAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount = newFromAmount\n }\n return\n }\n }\n\n if (isFinal) {\n if (unknown.length > 0) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n new Error(\n `Could not read balance for: ${unknown\n .map((t) => t.symbol || t.address)\n .join(', ')}.`\n )\n )\n }\n const lines = insufficient.map(({ req, have }) => {\n const needed = formatUnits(need(req), req.token.decimals)\n const current = formatUnits(have, req.token.decimals)\n const symbol = req.token.symbol\n // The \"fees\" branch covers pure-overhead tokens; with\n // walletPaysGas=false, gas is excluded from `need(req)` so it\n // only fires for genuine fee shortfalls.\n return req.sourcePart > 0n\n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.`\n : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`\n })\n throw new BalanceError(\n 'The balance is too low.',\n new Error(`${lines.join(' ')} No funds have been sent.`)\n )\n }\n\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n }\n },\n {\n timeout: OVERALL_TIMEOUT_MS,\n errorInstance: new BalanceError('Could not read wallet balance.'),\n }\n )\n}\n"],"mappings":";;;;;AAOA,MAAM,eAAe;AAErB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;;;;;;;;;;;;;AAkC3B,MAAa,eAAe,OAC1B,QACA,eACA,MACA,UAA+B,CAAC,MACd;CAClB,MAAM,cAAc,KAAK,OAAO;CAIhC,MAAM,YAAY,MAAM,OAAO,aAAa,WAAW;CACvD,MAAM,iBACH,QAAQ,iBAAiB,SAAS,CAAC,UAAU;CAChD,MAAM,+BAAe,IAAI,IAAyB;CAClD,MAAM,OAAO,OAAc,QAAgB,WAAyB;EAClE,IAAI,MAAM,YAAY,eAAe,WAAW,IAC9C;EAEF,MAAM,MAAM,MAAM,QAAQ,YAAY;EACtC,MAAM,MAAM,aAAa,IAAI,GAAG,K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pD,MAAM,SAAS,IAAI,MAAM;KAIzB,OAAO,IAAI,aAAa,KACpB,QAAQ,OAAO,2CAA2C,OAAO,GAAG,OAAO,+BAA+B,QAAQ,GAAG,OAAO,KAC5H,gBAAgB,OAAO,kBAAkB,OAAO,GAAG,OAAO,SAAS,QAAQ,GAAG,OAAO;IAC3F,CAAC;IACD,MAAM,IAAI,aACR,2CACA,IAAI,MAAM,GAAG,MAAM,KAAK,GAAG,EAAE,0BAA0B,CACzD;GACF;GAEA,MAAM,MAAM,kBAAkB,KAAK,OAAO;EAC5C;CACF,GACA;EACE,SAAS;EACT,eAAe,IAAI,aAAa,gCAAgC;CAClE,CACF;AACF"}
@@ -19,7 +19,6 @@ import { getTokenBalancesByChain } from "./actions/getTokenBalancesByChain.js";
19
19
  import { getTokens } from "./actions/getTokens.js";
20
20
  import { getTools } from "./actions/getTools.js";
21
21
  import { getTransactionHistory } from "./actions/getTransactionHistory.js";
22
- import { getWalletBalances } from "./actions/getWalletBalances.js";
23
22
  import { patchContractCalls } from "./actions/patchContractCalls.js";
24
23
  import { actions } from "./actions/index.js";
25
24
  import { relayTransaction } from "./actions/relayTransaction.js";
@@ -53,4 +52,4 @@ import { waitForResult } from "./utils/waitForResult.js";
53
52
  import { LruMap, withDedupe } from "./utils/withDedupe.js";
54
53
  import { withTimeout } from "./utils/withTimeout.js";
55
54
  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, 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, 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, parseUnits, patchContractCalls, relayTransaction, resumeRoute, sleep, stepComparison, stopRouteExecution, updateRouteExecution, waitForResult, withDedupe, withTimeout };
package/dist/esm/index.js CHANGED
@@ -23,7 +23,6 @@ import { getTokenBalance } from "./actions/getTokenBalance.js";
23
23
  import { getTokens } from "./actions/getTokens.js";
24
24
  import { getTools } from "./actions/getTools.js";
25
25
  import { getTransactionHistory } from "./actions/getTransactionHistory.js";
26
- import { getWalletBalances } from "./actions/getWalletBalances.js";
27
26
  import { patchContractCalls } from "./actions/patchContractCalls.js";
28
27
  import { relayTransaction } from "./actions/relayTransaction.js";
29
28
  import { actions } from "./actions/index.js";
@@ -50,4 +49,4 @@ import { fetchTxErrorDetails } from "./utils/fetchTxErrorDetails.js";
50
49
  import { isHex } from "./utils/isHex.js";
51
50
  import { parseUnits } from "./utils/parseUnits.js";
52
51
  export * from "@lifi/types";
53
- export { BalanceError, BaseError, BaseStepExecutionTask, BaseStepExecutor, CheckBalanceTask, ErrorMessage, ErrorName, ExecuteStepRetryError, HTTPError, InMemoryStorage, LiFiErrorCode, LocalStorageAdapter, LruMap, PrepareTransactionTask, ProviderError, RPCError, SDKError, ServerError, StatusManager, TaskPipeline, TransactionError, UnknownError, 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 };
52
+ export { BalanceError, BaseError, BaseStepExecutionTask, BaseStepExecutor, CheckBalanceTask, ErrorMessage, ErrorName, ExecuteStepRetryError, HTTPError, InMemoryStorage, LiFiErrorCode, LocalStorageAdapter, LruMap, PrepareTransactionTask, ProviderError, RPCError, SDKError, ServerError, StatusManager, TaskPipeline, TransactionError, UnknownError, 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, parseUnits, patchContractCalls, relayTransaction, resumeRoute, sleep, stepComparison, stopRouteExecution, updateRouteExecution, waitForResult, withDedupe, withTimeout };
@@ -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.2.0";
7
+ const currentVersion = packageVersion ?? "4.4.0";
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,6 +1,6 @@
1
1
  //#region src/version.d.ts
2
2
  declare const name = "@lifi/sdk";
3
- declare const version = "4.2.0";
3
+ declare const version = "4.4.0";
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.2.0";
3
+ const version = "4.4.0";
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.2.0'\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.4.0'\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.2.0",
3
+ "version": "4.4.0",
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.85.0"
31
+ "@lifi/types": "18.2.0"
32
32
  },
33
33
  "publishConfig": {
34
34
  "access": "public"
@@ -28,7 +28,6 @@ import type {
28
28
  ToolsResponse,
29
29
  TransactionAnalyticsRequest,
30
30
  TransactionAnalyticsResponse,
31
- WalletTokenExtended,
32
31
  } from '@lifi/types'
33
32
  import type {
34
33
  GetStatusRequestExtended,
@@ -55,7 +54,6 @@ import { getTokenBalancesByChain } from './getTokenBalancesByChain.js'
55
54
  import { getTokens } from './getTokens.js'
56
55
  import { getTools } from './getTools.js'
57
56
  import { getTransactionHistory } from './getTransactionHistory.js'
58
- import { getWalletBalances } from './getWalletBalances.js'
59
57
  import {
60
58
  type PatchContractCallsResponse,
61
59
  patchContractCalls,
@@ -274,17 +272,6 @@ export type Actions = {
274
272
  options?: RequestOptions
275
273
  ) => Promise<TransactionAnalyticsResponse>
276
274
 
277
- /**
278
- * Get wallet balances
279
- * @param params - The configuration of the requested wallet balances
280
- * @param options - Request options
281
- * @returns Wallet balances
282
- */
283
- getWalletBalances: (
284
- walletAddress: string,
285
- options?: RequestOptions
286
- ) => Promise<Record<number, WalletTokenExtended[]>>
287
-
288
275
  /**
289
276
  * Relay a transaction through the relayer service
290
277
  * @param params - The configuration for the relay request
@@ -340,8 +327,6 @@ export function actions(client: SDKClient): Actions {
340
327
  getTokenBalancesByChain(client, walletAddress, tokensByChain),
341
328
  getTransactionHistory: (params, options) =>
342
329
  getTransactionHistory(client, params, options),
343
- getWalletBalances: (walletAddress, options) =>
344
- getWalletBalances(client, walletAddress, options),
345
330
  relayTransaction: (params, options) =>
346
331
  relayTransaction(client, params, options),
347
332
  patchContractCalls: (params, options) =>
@@ -50,6 +50,7 @@ export const getClientStorage = (config: SDKBaseConfig): ClientStorage => {
50
50
  ChainType.UTXO,
51
51
  ChainType.MVM,
52
52
  ChainType.TVM,
53
+ ChainType.STL,
53
54
  ],
54
55
  })
55
56
  _chainsUpdatedAt = Date.now()
@@ -6,6 +6,16 @@ import { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'
6
6
  import { stepComparison } from './helpers/stepComparison.js'
7
7
 
8
8
  export class PrepareTransactionTask extends BaseStepExecutionTask {
9
+ /**
10
+ * Whether `run()` has to fetch a fresh transaction request. The default asks
11
+ * only when the step carries none, which keeps every existing provider
12
+ * unchanged. Chains whose payload cannot be reused override it — see
13
+ * `StellarPrepareTransactionTask`.
14
+ */
15
+ protected shouldRefetchTransaction(context: StepExecutorContext): boolean {
16
+ return !context.step.transactionRequest
17
+ }
18
+
9
19
  async run(context: StepExecutorContext): Promise<TaskResult> {
10
20
  const {
11
21
  client,
@@ -28,7 +38,7 @@ export class PrepareTransactionTask extends BaseStepExecutionTask {
28
38
  )
29
39
  }
30
40
 
31
- if (!step.transactionRequest) {
41
+ if (this.shouldRefetchTransaction(context)) {
32
42
  const { execution, ...stepBase } = step
33
43
  const updatedStep = await getStepTransaction(client, stepBase)
34
44
  const comparedStep = await stepComparison(
package/src/index.ts CHANGED
@@ -19,7 +19,6 @@ export { getTokenBalancesByChain } from './actions/getTokenBalancesByChain.js'
19
19
  export { getTokens } from './actions/getTokens.js'
20
20
  export { getTools } from './actions/getTools.js'
21
21
  export { getTransactionHistory } from './actions/getTransactionHistory.js'
22
- export { getWalletBalances } from './actions/getWalletBalances.js'
23
22
  export { actions } from './actions/index.js'
24
23
  export { patchContractCalls } from './actions/patchContractCalls.js'
25
24
  export { relayTransaction } from './actions/relayTransaction.js'
package/src/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  export const name = '@lifi/sdk'
2
- export const version = '4.2.0'
2
+ export const version = '4.4.0'
@@ -1,15 +0,0 @@
1
- import { SDKClient } from "../types/core.js";
2
- import { RequestOptions, WalletTokenExtended } from "@lifi/types";
3
- //#region src/actions/getWalletBalances.d.ts
4
- /**
5
- * Returns the balances of tokens a wallet holds across EVM chains.
6
- * @param client - The SDK client.
7
- * @param walletAddress - A wallet address.
8
- * @param options - Optional request options.
9
- * @returns An object containing the tokens and the amounts organized by chain ids.
10
- * @throws {ValidationError} Throws a ValidationError if parameters are invalid.
11
- */
12
- declare const getWalletBalances: (client: SDKClient, walletAddress: string, options?: RequestOptions) => Promise<Record<number, WalletTokenExtended[]>>;
13
- //#endregion
14
- export { getWalletBalances };
15
- //# sourceMappingURL=getWalletBalances.d.ts.map
@@ -1,20 +0,0 @@
1
- Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_errors_errors = require("../errors/errors.js");
3
- const require_utils_request = require("../utils/request.js");
4
- //#region src/actions/getWalletBalances.ts
5
- /**
6
- * Returns the balances of tokens a wallet holds across EVM chains.
7
- * @param client - The SDK client.
8
- * @param walletAddress - A wallet address.
9
- * @param options - Optional request options.
10
- * @returns An object containing the tokens and the amounts organized by chain ids.
11
- * @throws {ValidationError} Throws a ValidationError if parameters are invalid.
12
- */
13
- const getWalletBalances = async (client, walletAddress, options) => {
14
- if (!walletAddress) throw new require_errors_errors.ValidationError("Missing walletAddress.");
15
- return (await require_utils_request.request(client.config, `${client.config.apiUrl}/wallets/${walletAddress}/balances?extended=true`, { signal: options?.signal }))?.balances || {};
16
- };
17
- //#endregion
18
- exports.getWalletBalances = getWalletBalances;
19
-
20
- //# sourceMappingURL=getWalletBalances.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"getWalletBalances.js","names":["ValidationError","request"],"sources":["../../../src/actions/getWalletBalances.ts"],"sourcesContent":["import type {\n GetWalletBalanceExtendedResponse,\n RequestOptions,\n WalletTokenExtended,\n} from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\n\n/**\n * Returns the balances of tokens a wallet holds across EVM chains.\n * @param client - The SDK client.\n * @param walletAddress - A wallet address.\n * @param options - Optional request options.\n * @returns An object containing the tokens and the amounts organized by chain ids.\n * @throws {ValidationError} Throws a ValidationError if parameters are invalid.\n */\nexport const getWalletBalances = async (\n client: SDKClient,\n walletAddress: string,\n options?: RequestOptions\n): Promise<Record<number, WalletTokenExtended[]>> => {\n if (!walletAddress) {\n throw new ValidationError('Missing walletAddress.')\n }\n\n const response = await request<GetWalletBalanceExtendedResponse>(\n client.config,\n `${client.config.apiUrl}/wallets/${walletAddress}/balances?extended=true`,\n {\n signal: options?.signal,\n }\n )\n\n return (response?.balances || {}) as Record<number, WalletTokenExtended[]>\n}\n"],"mappings":";;;;;;;;;;;;AAiBA,MAAa,oBAAoB,OAC/B,QACA,eACA,YACmD;CACnD,IAAI,CAAC,eACH,MAAM,IAAIA,sBAAAA,gBAAgB,wBAAwB;CAWpD,QAAQ,MAReC,sBAAAA,QACrB,OAAO,QACP,GAAG,OAAO,OAAO,OAAO,WAAW,cAAc,0BACjD,EACE,QAAQ,SAAS,OACnB,CACF,EAAA,EAEkB,YAAY,CAAC;AACjC"}
@@ -1,15 +0,0 @@
1
- import { SDKClient } from "../types/core.js";
2
- import { RequestOptions, WalletTokenExtended } from "@lifi/types";
3
- //#region src/actions/getWalletBalances.d.ts
4
- /**
5
- * Returns the balances of tokens a wallet holds across EVM chains.
6
- * @param client - The SDK client.
7
- * @param walletAddress - A wallet address.
8
- * @param options - Optional request options.
9
- * @returns An object containing the tokens and the amounts organized by chain ids.
10
- * @throws {ValidationError} Throws a ValidationError if parameters are invalid.
11
- */
12
- declare const getWalletBalances: (client: SDKClient, walletAddress: string, options?: RequestOptions) => Promise<Record<number, WalletTokenExtended[]>>;
13
- //#endregion
14
- export { getWalletBalances };
15
- //# sourceMappingURL=getWalletBalances.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"getWalletBalances.d.ts","names":[],"sources":["../../../src/actions/getWalletBalances.ts"],"mappings":";;;;;;;;;;;cAiBa,oBACX,QAAQ,WACR,uBACA,UAAU,mBACT,QAAQ,eAAe"}
@@ -1,19 +0,0 @@
1
- import { ValidationError } from "../errors/errors.js";
2
- import { request } from "../utils/request.js";
3
- //#region src/actions/getWalletBalances.ts
4
- /**
5
- * Returns the balances of tokens a wallet holds across EVM chains.
6
- * @param client - The SDK client.
7
- * @param walletAddress - A wallet address.
8
- * @param options - Optional request options.
9
- * @returns An object containing the tokens and the amounts organized by chain ids.
10
- * @throws {ValidationError} Throws a ValidationError if parameters are invalid.
11
- */
12
- const getWalletBalances = async (client, walletAddress, options) => {
13
- if (!walletAddress) throw new ValidationError("Missing walletAddress.");
14
- return (await request(client.config, `${client.config.apiUrl}/wallets/${walletAddress}/balances?extended=true`, { signal: options?.signal }))?.balances || {};
15
- };
16
- //#endregion
17
- export { getWalletBalances };
18
-
19
- //# sourceMappingURL=getWalletBalances.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"getWalletBalances.js","names":[],"sources":["../../../src/actions/getWalletBalances.ts"],"sourcesContent":["import type {\n GetWalletBalanceExtendedResponse,\n RequestOptions,\n WalletTokenExtended,\n} from '@lifi/types'\nimport { ValidationError } from '../errors/errors.js'\nimport type { SDKClient } from '../types/core.js'\nimport { request } from '../utils/request.js'\n\n/**\n * Returns the balances of tokens a wallet holds across EVM chains.\n * @param client - The SDK client.\n * @param walletAddress - A wallet address.\n * @param options - Optional request options.\n * @returns An object containing the tokens and the amounts organized by chain ids.\n * @throws {ValidationError} Throws a ValidationError if parameters are invalid.\n */\nexport const getWalletBalances = async (\n client: SDKClient,\n walletAddress: string,\n options?: RequestOptions\n): Promise<Record<number, WalletTokenExtended[]>> => {\n if (!walletAddress) {\n throw new ValidationError('Missing walletAddress.')\n }\n\n const response = await request<GetWalletBalanceExtendedResponse>(\n client.config,\n `${client.config.apiUrl}/wallets/${walletAddress}/balances?extended=true`,\n {\n signal: options?.signal,\n }\n )\n\n return (response?.balances || {}) as Record<number, WalletTokenExtended[]>\n}\n"],"mappings":";;;;;;;;;;;AAiBA,MAAa,oBAAoB,OAC/B,QACA,eACA,YACmD;CACnD,IAAI,CAAC,eACH,MAAM,IAAI,gBAAgB,wBAAwB;CAWpD,QAAQ,MARe,QACrB,OAAO,QACP,GAAG,OAAO,OAAO,OAAO,WAAW,cAAc,0BACjD,EACE,QAAQ,SAAS,OACnB,CACF,EAAA,EAEkB,YAAY,CAAC;AACjC"}
@@ -1,36 +0,0 @@
1
- import type {
2
- GetWalletBalanceExtendedResponse,
3
- RequestOptions,
4
- WalletTokenExtended,
5
- } from '@lifi/types'
6
- import { ValidationError } from '../errors/errors.js'
7
- import type { SDKClient } from '../types/core.js'
8
- import { request } from '../utils/request.js'
9
-
10
- /**
11
- * Returns the balances of tokens a wallet holds across EVM chains.
12
- * @param client - The SDK client.
13
- * @param walletAddress - A wallet address.
14
- * @param options - Optional request options.
15
- * @returns An object containing the tokens and the amounts organized by chain ids.
16
- * @throws {ValidationError} Throws a ValidationError if parameters are invalid.
17
- */
18
- export const getWalletBalances = async (
19
- client: SDKClient,
20
- walletAddress: string,
21
- options?: RequestOptions
22
- ): Promise<Record<number, WalletTokenExtended[]>> => {
23
- if (!walletAddress) {
24
- throw new ValidationError('Missing walletAddress.')
25
- }
26
-
27
- const response = await request<GetWalletBalanceExtendedResponse>(
28
- client.config,
29
- `${client.config.apiUrl}/wallets/${walletAddress}/balances?extended=true`,
30
- {
31
- signal: options?.signal,
32
- }
33
- )
34
-
35
- return (response?.balances || {}) as Record<number, WalletTokenExtended[]>
36
- }