@lifi/sdk 4.0.0-beta.8 → 4.0.0-beta.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/actions/getChains.js.map +1 -1
- package/dist/cjs/actions/getConnections.js.map +1 -1
- package/dist/cjs/actions/getContractCallsQuote.js.map +1 -1
- package/dist/cjs/actions/getGasRecommendation.js.map +1 -1
- package/dist/cjs/actions/getNameServiceAddress.js.map +1 -1
- package/dist/cjs/actions/getQuote.js.map +1 -1
- package/dist/cjs/actions/getRelayedTransactionStatus.js.map +1 -1
- package/dist/cjs/actions/getRelayerQuote.js.map +1 -1
- package/dist/cjs/actions/getRoutes.js.map +1 -1
- package/dist/cjs/actions/getStatus.js.map +1 -1
- package/dist/cjs/actions/getStepTransaction.js.map +1 -1
- package/dist/cjs/actions/getToken.js.map +1 -1
- package/dist/cjs/actions/getTokenBalance.js.map +1 -1
- package/dist/cjs/actions/getTokenBalances.js.map +1 -1
- package/dist/cjs/actions/getTokenBalancesByChain.js.map +1 -1
- package/dist/cjs/actions/getTokens.js.map +1 -1
- package/dist/cjs/actions/getTools.js.map +1 -1
- package/dist/cjs/actions/getTransactionHistory.js.map +1 -1
- package/dist/cjs/actions/getWalletBalances.js.map +1 -1
- package/dist/cjs/actions/index.js.map +1 -1
- package/dist/cjs/actions/patchContractCalls.js.map +1 -1
- package/dist/cjs/actions/relayTransaction.js.map +1 -1
- package/dist/cjs/client/createClient.js.map +1 -1
- package/dist/cjs/client/getClientStorage.js.map +1 -1
- package/dist/cjs/core/BaseStepExecutionTask.js.map +1 -1
- package/dist/cjs/core/BaseStepExecutor.js.map +1 -1
- package/dist/cjs/core/StatusManager.js.map +1 -1
- package/dist/cjs/core/TaskPipeline.js.map +1 -1
- package/dist/cjs/core/actionMessages.js.map +1 -1
- package/dist/cjs/core/execution.js.map +1 -1
- package/dist/cjs/core/executionState.js.map +1 -1
- package/dist/cjs/core/prepareRestart.js.map +1 -1
- package/dist/cjs/core/storage.js.map +1 -1
- package/dist/cjs/core/tasks/CheckBalanceTask.js.map +1 -1
- package/dist/cjs/core/tasks/PrepareTransactionTask.js.map +1 -1
- package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/checkBalance.js +3 -1
- package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/getTransactionRequestData.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/stepComparison.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
- package/dist/cjs/core/utils.js.map +1 -1
- package/dist/cjs/errors/SDKError.js.map +1 -1
- package/dist/cjs/errors/baseError.js.map +1 -1
- package/dist/cjs/errors/constants.js.map +1 -1
- package/dist/cjs/errors/errors.js.map +1 -1
- package/dist/cjs/errors/httpError.js.map +1 -1
- package/dist/cjs/errors/utils/baseErrorRootCause.js.map +1 -1
- package/dist/cjs/errors/utils/rootCause.js.map +1 -1
- package/dist/cjs/utils/checkPackageUpdates.js +1 -1
- package/dist/cjs/utils/checkPackageUpdates.js.map +1 -1
- package/dist/cjs/utils/convertQuoteToRoute.js.map +1 -1
- package/dist/cjs/utils/decode.js.map +1 -1
- package/dist/cjs/utils/fetchTxErrorDetails.js.map +1 -1
- package/dist/cjs/utils/formatUnits.js.map +1 -1
- package/dist/cjs/utils/getTransactionMessage.js.map +1 -1
- package/dist/cjs/utils/isHex.js.map +1 -1
- package/dist/cjs/utils/isRoutesRequest.js.map +1 -1
- package/dist/cjs/utils/isStep.js.map +1 -1
- package/dist/cjs/utils/isToken.js.map +1 -1
- package/dist/cjs/utils/parseUnits.js.map +1 -1
- package/dist/cjs/utils/request.js.map +1 -1
- package/dist/cjs/utils/sleep.js.map +1 -1
- package/dist/cjs/utils/waitForResult.js.map +1 -1
- package/dist/cjs/utils/withDedupe.js.map +1 -1
- package/dist/cjs/utils/withTimeout.js.map +1 -1
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/version.js.map +1 -1
- package/dist/esm/actions/getChains.js.map +1 -1
- package/dist/esm/actions/getConnections.js.map +1 -1
- package/dist/esm/actions/getContractCallsQuote.js.map +1 -1
- package/dist/esm/actions/getGasRecommendation.js.map +1 -1
- package/dist/esm/actions/getNameServiceAddress.js.map +1 -1
- package/dist/esm/actions/getQuote.js.map +1 -1
- package/dist/esm/actions/getRelayedTransactionStatus.js.map +1 -1
- package/dist/esm/actions/getRelayerQuote.js.map +1 -1
- package/dist/esm/actions/getRoutes.js.map +1 -1
- package/dist/esm/actions/getStatus.js.map +1 -1
- package/dist/esm/actions/getStepTransaction.js.map +1 -1
- package/dist/esm/actions/getToken.js.map +1 -1
- package/dist/esm/actions/getTokenBalance.js.map +1 -1
- package/dist/esm/actions/getTokenBalances.js.map +1 -1
- package/dist/esm/actions/getTokenBalancesByChain.js.map +1 -1
- package/dist/esm/actions/getTokens.js.map +1 -1
- package/dist/esm/actions/getTools.js.map +1 -1
- package/dist/esm/actions/getTransactionHistory.js.map +1 -1
- package/dist/esm/actions/getWalletBalances.js.map +1 -1
- package/dist/esm/actions/index.js.map +1 -1
- package/dist/esm/actions/patchContractCalls.js.map +1 -1
- package/dist/esm/actions/relayTransaction.js.map +1 -1
- package/dist/esm/client/createClient.js.map +1 -1
- package/dist/esm/client/getClientStorage.js.map +1 -1
- package/dist/esm/core/BaseStepExecutionTask.js.map +1 -1
- package/dist/esm/core/BaseStepExecutor.js.map +1 -1
- package/dist/esm/core/StatusManager.js.map +1 -1
- package/dist/esm/core/TaskPipeline.js.map +1 -1
- package/dist/esm/core/actionMessages.js.map +1 -1
- package/dist/esm/core/execution.js.map +1 -1
- package/dist/esm/core/executionState.js.map +1 -1
- package/dist/esm/core/prepareRestart.js.map +1 -1
- package/dist/esm/core/storage.js.map +1 -1
- package/dist/esm/core/tasks/CheckBalanceTask.js.map +1 -1
- package/dist/esm/core/tasks/PrepareTransactionTask.js.map +1 -1
- package/dist/esm/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
- package/dist/esm/core/tasks/helpers/checkBalance.js +3 -1
- package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/esm/core/tasks/helpers/getTransactionRequestData.js.map +1 -1
- package/dist/esm/core/tasks/helpers/stepComparison.js.map +1 -1
- package/dist/esm/core/tasks/helpers/waitForTransactionStatus.js.map +1 -1
- package/dist/esm/core/utils.js.map +1 -1
- package/dist/esm/errors/SDKError.js.map +1 -1
- package/dist/esm/errors/baseError.js.map +1 -1
- package/dist/esm/errors/constants.js.map +1 -1
- package/dist/esm/errors/errors.js.map +1 -1
- package/dist/esm/errors/httpError.js.map +1 -1
- package/dist/esm/errors/utils/baseErrorRootCause.js.map +1 -1
- package/dist/esm/errors/utils/rootCause.js.map +1 -1
- package/dist/esm/utils/checkPackageUpdates.js +1 -1
- package/dist/esm/utils/checkPackageUpdates.js.map +1 -1
- package/dist/esm/utils/convertQuoteToRoute.js.map +1 -1
- package/dist/esm/utils/decode.js.map +1 -1
- package/dist/esm/utils/fetchTxErrorDetails.js.map +1 -1
- package/dist/esm/utils/formatUnits.js.map +1 -1
- package/dist/esm/utils/getTransactionMessage.js.map +1 -1
- package/dist/esm/utils/isHex.js.map +1 -1
- package/dist/esm/utils/isRoutesRequest.js.map +1 -1
- package/dist/esm/utils/isStep.js.map +1 -1
- package/dist/esm/utils/isToken.js.map +1 -1
- package/dist/esm/utils/parseUnits.js.map +1 -1
- package/dist/esm/utils/request.js.map +1 -1
- package/dist/esm/utils/sleep.js.map +1 -1
- package/dist/esm/utils/waitForResult.js.map +1 -1
- package/dist/esm/utils/withDedupe.js.map +1 -1
- package/dist/esm/utils/withTimeout.js.map +1 -1
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/version.js.map +1 -1
- package/package.json +2 -2
- package/src/core/tasks/helpers/checkBalance.ts +5 -1
- package/src/version.ts +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseStepExecutionTask.js","names":[],"sources":["../../../src/core/BaseStepExecutionTask.ts"],"sourcesContent":["import type { StepExecutorContext, TaskResult } from '../types/execution.js'\n\nexport abstract class BaseStepExecutionTask {\n shouldRun(_context: StepExecutorContext): Promise<boolean> {\n return Promise.resolve(true)\n }\n\n abstract run(context: StepExecutorContext): Promise<TaskResult>\n}\n"],"mappings":";AAEA,IAAsB,wBAAtB,MAA4C;CAC1C,UAAU,UAAiD;
|
|
1
|
+
{"version":3,"file":"BaseStepExecutionTask.js","names":[],"sources":["../../../src/core/BaseStepExecutionTask.ts"],"sourcesContent":["import type { StepExecutorContext, TaskResult } from '../types/execution.js'\n\nexport abstract class BaseStepExecutionTask {\n shouldRun(_context: StepExecutorContext): Promise<boolean> {\n return Promise.resolve(true)\n }\n\n abstract run(context: StepExecutorContext): Promise<TaskResult>\n}\n"],"mappings":";AAEA,IAAsB,wBAAtB,MAA4C;CAC1C,UAAU,UAAiD;EACzD,OAAO,QAAQ,QAAQ,KAAK"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BaseStepExecutor.js","names":[],"sources":["../../../src/core/BaseStepExecutor.ts"],"sourcesContent":["import { ExecuteStepRetryError } from '../errors/errors.js'\nimport type { SDKError } from '../errors/SDKError.js'\nimport type {\n ExecuteStepRetryParams,\n ExecutionAction,\n ExecutionOptions,\n InteractionSettings,\n LiFiStepExtended,\n SDKClient,\n StepExecutor,\n StepExecutorOptions,\n} from '../types/core.js'\nimport type {\n StepExecutorBaseContext,\n StepExecutorContext,\n} from '../types/execution.js'\nimport { StatusManager } from './StatusManager.js'\nimport type { TaskPipeline } from './TaskPipeline.js'\n\n// Please be careful when changing the defaults as it may break the behavior (e.g., background execution)\nconst defaultInteractionSettings = {\n allowInteraction: true,\n allowUpdates: true,\n allowExecution: true,\n}\n\nexport abstract class BaseStepExecutor implements StepExecutor {\n protected executionOptions?: ExecutionOptions\n protected statusManager: StatusManager\n\n public allowUserInteraction = true\n public allowExecution = true\n\n constructor(options: StepExecutorOptions) {\n this.statusManager = new StatusManager(options.routeId)\n this.executionOptions = options.executionOptions\n }\n\n setInteraction = (settings?: InteractionSettings): void => {\n const interactionSettings = {\n ...defaultInteractionSettings,\n ...settings,\n }\n this.allowUserInteraction = interactionSettings.allowInteraction\n this.statusManager.allowUpdates(interactionSettings.allowUpdates)\n this.allowExecution = interactionSettings.allowExecution\n }\n\n private createBaseContext = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams\n ): Promise<StepExecutorBaseContext> => {\n const fromChain = await client.getChainById(step.action.fromChainId)\n const toChain = await client.getChainById(step.action.toChainId)\n\n const isBridgeExecution = fromChain.id !== toChain.id\n\n return {\n client,\n step,\n fromChain,\n toChain,\n isBridgeExecution,\n retryParams,\n statusManager: this.statusManager,\n executionOptions: this.executionOptions,\n allowUserInteraction: this.allowUserInteraction,\n }\n }\n\n abstract createContext(\n baseContext: StepExecutorBaseContext\n ): Promise<StepExecutorContext>\n\n abstract createPipeline(context: StepExecutorContext): TaskPipeline\n\n abstract parseErrors(\n error: Error,\n step?: LiFiStepExtended,\n action?: ExecutionAction,\n retryParams?: ExecuteStepRetryParams\n ): Promise<SDKError | ExecuteStepRetryError>\n\n executeStep = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams\n ): Promise<LiFiStepExtended> => {\n try {\n step.execution = this.statusManager.initializeExecution(step)\n\n const baseContext = await this.createBaseContext(\n client,\n step,\n retryParams\n )\n const context = await this.createContext(baseContext)\n const pipeline = this.createPipeline(context)\n\n await pipeline.run(context)\n\n return step\n } catch (error: any) {\n // Derive failing action from last in execution.actions\n const action = step.execution?.actions?.at(-1)\n const parsed = await this.parseErrors(error, step, action, retryParams)\n if (!(parsed instanceof ExecuteStepRetryError)) {\n if (action) {\n this.statusManager.updateAction(step, action.type, 'FAILED', {\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n } else {\n this.statusManager.updateExecution(step, {\n status: 'FAILED',\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n }\n }\n throw parsed\n }\n }\n}\n"],"mappings":";;;AAoBA,MAAM,6BAA6B;CACjC,kBAAkB;CAClB,cAAc;CACd,gBAAgB;CACjB;AAED,IAAsB,mBAAtB,MAA+D;CAC7D;CACA;CAEA,uBAA8B;CAC9B,iBAAwB;CAExB,YAAY,SAA8B;
|
|
1
|
+
{"version":3,"file":"BaseStepExecutor.js","names":[],"sources":["../../../src/core/BaseStepExecutor.ts"],"sourcesContent":["import { ExecuteStepRetryError } from '../errors/errors.js'\nimport type { SDKError } from '../errors/SDKError.js'\nimport type {\n ExecuteStepRetryParams,\n ExecutionAction,\n ExecutionOptions,\n InteractionSettings,\n LiFiStepExtended,\n SDKClient,\n StepExecutor,\n StepExecutorOptions,\n} from '../types/core.js'\nimport type {\n StepExecutorBaseContext,\n StepExecutorContext,\n} from '../types/execution.js'\nimport { StatusManager } from './StatusManager.js'\nimport type { TaskPipeline } from './TaskPipeline.js'\n\n// Please be careful when changing the defaults as it may break the behavior (e.g., background execution)\nconst defaultInteractionSettings = {\n allowInteraction: true,\n allowUpdates: true,\n allowExecution: true,\n}\n\nexport abstract class BaseStepExecutor implements StepExecutor {\n protected executionOptions?: ExecutionOptions\n protected statusManager: StatusManager\n\n public allowUserInteraction = true\n public allowExecution = true\n\n constructor(options: StepExecutorOptions) {\n this.statusManager = new StatusManager(options.routeId)\n this.executionOptions = options.executionOptions\n }\n\n setInteraction = (settings?: InteractionSettings): void => {\n const interactionSettings = {\n ...defaultInteractionSettings,\n ...settings,\n }\n this.allowUserInteraction = interactionSettings.allowInteraction\n this.statusManager.allowUpdates(interactionSettings.allowUpdates)\n this.allowExecution = interactionSettings.allowExecution\n }\n\n private createBaseContext = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams\n ): Promise<StepExecutorBaseContext> => {\n const fromChain = await client.getChainById(step.action.fromChainId)\n const toChain = await client.getChainById(step.action.toChainId)\n\n const isBridgeExecution = fromChain.id !== toChain.id\n\n return {\n client,\n step,\n fromChain,\n toChain,\n isBridgeExecution,\n retryParams,\n statusManager: this.statusManager,\n executionOptions: this.executionOptions,\n allowUserInteraction: this.allowUserInteraction,\n }\n }\n\n abstract createContext(\n baseContext: StepExecutorBaseContext\n ): Promise<StepExecutorContext>\n\n abstract createPipeline(context: StepExecutorContext): TaskPipeline\n\n abstract parseErrors(\n error: Error,\n step?: LiFiStepExtended,\n action?: ExecutionAction,\n retryParams?: ExecuteStepRetryParams\n ): Promise<SDKError | ExecuteStepRetryError>\n\n executeStep = async (\n client: SDKClient,\n step: LiFiStepExtended,\n retryParams?: ExecuteStepRetryParams\n ): Promise<LiFiStepExtended> => {\n try {\n step.execution = this.statusManager.initializeExecution(step)\n\n const baseContext = await this.createBaseContext(\n client,\n step,\n retryParams\n )\n const context = await this.createContext(baseContext)\n const pipeline = this.createPipeline(context)\n\n await pipeline.run(context)\n\n return step\n } catch (error: any) {\n // Derive failing action from last in execution.actions\n const action = step.execution?.actions?.at(-1)\n const parsed = await this.parseErrors(error, step, action, retryParams)\n if (!(parsed instanceof ExecuteStepRetryError)) {\n if (action) {\n this.statusManager.updateAction(step, action.type, 'FAILED', {\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n } else {\n this.statusManager.updateExecution(step, {\n status: 'FAILED',\n error: {\n message: parsed.cause?.message,\n code: parsed.code,\n },\n })\n }\n }\n throw parsed\n }\n }\n}\n"],"mappings":";;;AAoBA,MAAM,6BAA6B;CACjC,kBAAkB;CAClB,cAAc;CACd,gBAAgB;CACjB;AAED,IAAsB,mBAAtB,MAA+D;CAC7D;CACA;CAEA,uBAA8B;CAC9B,iBAAwB;CAExB,YAAY,SAA8B;EACxC,KAAK,gBAAgB,IAAI,cAAc,QAAQ,QAAQ;EACvD,KAAK,mBAAmB,QAAQ;;CAGlC,kBAAkB,aAAyC;EACzD,MAAM,sBAAsB;GAC1B,GAAG;GACH,GAAG;GACJ;EACD,KAAK,uBAAuB,oBAAoB;EAChD,KAAK,cAAc,aAAa,oBAAoB,aAAa;EACjE,KAAK,iBAAiB,oBAAoB;;CAG5C,oBAA4B,OAC1B,QACA,MACA,gBACqC;EACrC,MAAM,YAAY,MAAM,OAAO,aAAa,KAAK,OAAO,YAAY;EACpE,MAAM,UAAU,MAAM,OAAO,aAAa,KAAK,OAAO,UAAU;EAIhE,OAAO;GACL;GACA;GACA;GACA;GACA,mBAPwB,UAAU,OAAO,QAAQ;GAQjD;GACA,eAAe,KAAK;GACpB,kBAAkB,KAAK;GACvB,sBAAsB,KAAK;GAC5B;;CAgBH,cAAc,OACZ,QACA,MACA,gBAC8B;EAC9B,IAAI;GACF,KAAK,YAAY,KAAK,cAAc,oBAAoB,KAAK;GAE7D,MAAM,cAAc,MAAM,KAAK,kBAC7B,QACA,MACA,YACD;GACD,MAAM,UAAU,MAAM,KAAK,cAAc,YAAY;GAGrD,MAFiB,KAAK,eAAe,QAEvB,CAAC,IAAI,QAAQ;GAE3B,OAAO;WACA,OAAY;GAEnB,MAAM,SAAS,KAAK,WAAW,SAAS,GAAG,GAAG;GAC9C,MAAM,SAAS,MAAM,KAAK,YAAY,OAAO,MAAM,QAAQ,YAAY;GACvE,IAAI,EAAE,kBAAkB,wBACtB,IAAI,QACF,KAAK,cAAc,aAAa,MAAM,OAAO,MAAM,UAAU,EAC3D,OAAO;IACL,SAAS,OAAO,OAAO;IACvB,MAAM,OAAO;IACd,EACF,CAAC;QAEF,KAAK,cAAc,gBAAgB,MAAM;IACvC,QAAQ;IACR,OAAO;KACL,SAAS,OAAO,OAAO;KACvB,MAAM,OAAO;KACd;IACF,CAAC;GAGN,MAAM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"StatusManager.js","names":[],"sources":["../../../src/core/StatusManager.ts"],"sourcesContent":["import type { ChainId, LiFiStep } from '@lifi/types'\nimport type {\n Execution,\n ExecutionAction,\n ExecutionActionStatus,\n ExecutionActionType,\n LiFiStepExtended,\n} from '../types/core.js'\nimport { getActionMessage } from './actionMessages.js'\nimport { executionState } from './executionState.js'\n\ntype ActionProps = {\n step: LiFiStepExtended\n type: ExecutionActionType\n chainId: ChainId\n status: ExecutionActionStatus\n}\n\n/**\n * Manages status updates of a route and provides various functions for tracking actions.\n */\nexport class StatusManager {\n private readonly routeId: string\n private shouldUpdate = true\n\n constructor(routeId: string) {\n this.routeId = routeId\n }\n\n /**\n * Initializes the execution object of a Step.\n * @param step The current step in execution\n * @returns The initialized execution object for this step\n */\n initializeExecution = (step: LiFiStepExtended): Execution => {\n if (!step.execution) {\n step.execution = {\n startedAt: Date.now(),\n status: 'PENDING',\n actions: [],\n }\n this.updateStepInRoute(step)\n }\n\n // Change status to PENDING after resuming from FAILED\n if (step.execution.status === 'FAILED') {\n step.execution.startedAt = Date.now()\n step.execution.status = 'PENDING'\n step.execution.signedAt = undefined\n step.execution.error = undefined\n this.updateStepInRoute(step)\n }\n\n return step.execution\n }\n\n /**\n * Updates the execution object of a Step.\n * @param step The current step in execution\n * @param execution Partial execution data to merge\n * @returns The step with the updated execution object\n */\n updateExecution(\n step: LiFiStepExtended,\n execution: Partial<Execution>\n ): LiFiStep {\n if (!step.execution) {\n throw Error(\"Can't update empty execution.\")\n }\n step.execution = {\n ...step.execution,\n ...execution,\n }\n this.updateStepInRoute(step)\n return step\n }\n\n /**\n * Finds an action of the specified type in the step's execution\n * @param step The step to search in\n * @param type The action type to find\n * @returns The found action or undefined if not found\n */\n findAction(\n step: LiFiStepExtended,\n type: ExecutionActionType\n ): ExecutionAction | undefined {\n if (!step.execution?.actions) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const action = step.execution.actions.find((p) => p.type === type)\n\n return action\n }\n\n /**\n * Create and push a new action into the execution.\n * Caller is responsible for ensuring an action of this type does not already exist.\n * @param step The step that should contain the new action.\n * @param type Type of the action.\n * @param chainId Chain Id of the action.\n * @param status The initial status for the new action.\n * @returns The created action.\n */\n createAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const newAction: ExecutionAction = {\n type,\n message: getActionMessage(type, status),\n status,\n chainId,\n }\n\n step.execution.actions.push(newAction)\n this.updateStepInRoute(step)\n return newAction\n }\n\n /**\n * Find an existing action by type and update it, or create a new one if none exists.\n * @param step The step that should contain the action.\n * @param type Type of the action. Used to identify already existing actions.\n * @param chainId Chain Id of the action (used when creating).\n * @param status The status to set on the found or newly created action.\n * @returns The updated or newly created action.\n */\n initializeAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n const action = this.findAction(step, type)\n\n if (action) {\n return this.updateAction(step, type, status, {\n error: undefined,\n })\n }\n\n return this.createAction({ step, type, chainId, status })\n }\n\n /**\n * Update an action object.\n * @param step The step where the action should be updated\n * @param type The action type to update\n * @param status The status the action gets.\n * @param [params] Additional parameters to append to the action.\n * @returns The updated action\n */\n updateAction = (\n step: LiFiStepExtended,\n type: ExecutionActionType,\n status: ExecutionActionStatus,\n params?: Partial<ExecutionAction & { signedAt?: number }>\n ): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Can't update an empty step execution.\")\n }\n const currentAction = this.findAction(step, type)\n\n if (!currentAction) {\n throw new Error(\"Can't find an action for the given type.\")\n }\n\n switch (status) {\n case 'CANCELLED':\n break\n case 'FAILED':\n step.execution.status = 'FAILED'\n if (params?.error) {\n step.execution.error = params.error\n }\n break\n case 'DONE':\n break\n case 'PENDING':\n step.execution.status = 'PENDING'\n if (params?.signedAt) {\n step.execution.signedAt = params.signedAt\n }\n break\n case 'RESET_REQUIRED':\n case 'MESSAGE_REQUIRED':\n case 'ACTION_REQUIRED':\n step.execution.status = 'ACTION_REQUIRED'\n break\n default:\n break\n }\n\n currentAction.status = status\n currentAction.message = getActionMessage(type, status)\n // set extra parameters or overwrite the standard params set in the switch statement\n if (params) {\n const { signedAt: _signedAt, ...rest } = params\n Object.assign(currentAction, rest)\n }\n // Sort actions, the ones with DONE status go first\n step.execution.actions = [\n ...step.execution.actions.filter((action) => action.status === 'DONE'),\n ...step.execution.actions.filter((action) => action.status !== 'DONE'),\n ]\n this.updateStepInRoute(step) // updates the step in the route\n return currentAction\n }\n\n updateStepInRoute = (step: LiFiStep): LiFiStep => {\n if (!this.shouldUpdate) {\n return step\n }\n const data = executionState.get(this.routeId)\n\n if (!data) {\n throw new Error('Execution data not found.')\n }\n\n const stepIndex = data.route.steps.findIndex(\n (routeStep) => routeStep.id === step.id\n )\n\n if (stepIndex === -1) {\n throw new Error(\"Couldn't find a step to update.\")\n }\n\n data.route.steps[stepIndex] = { ...data.route.steps[stepIndex], ...step }\n\n data.executionOptions?.updateRouteHook?.(data.route)\n return data.route.steps[stepIndex]\n }\n\n allowUpdates(value: boolean): void {\n this.shouldUpdate = value\n }\n}\n"],"mappings":";;;;;;AAqBA,IAAa,gBAAb,MAA2B;CACzB;CACA,eAAuB;CAEvB,YAAY,SAAiB;
|
|
1
|
+
{"version":3,"file":"StatusManager.js","names":[],"sources":["../../../src/core/StatusManager.ts"],"sourcesContent":["import type { ChainId, LiFiStep } from '@lifi/types'\nimport type {\n Execution,\n ExecutionAction,\n ExecutionActionStatus,\n ExecutionActionType,\n LiFiStepExtended,\n} from '../types/core.js'\nimport { getActionMessage } from './actionMessages.js'\nimport { executionState } from './executionState.js'\n\ntype ActionProps = {\n step: LiFiStepExtended\n type: ExecutionActionType\n chainId: ChainId\n status: ExecutionActionStatus\n}\n\n/**\n * Manages status updates of a route and provides various functions for tracking actions.\n */\nexport class StatusManager {\n private readonly routeId: string\n private shouldUpdate = true\n\n constructor(routeId: string) {\n this.routeId = routeId\n }\n\n /**\n * Initializes the execution object of a Step.\n * @param step The current step in execution\n * @returns The initialized execution object for this step\n */\n initializeExecution = (step: LiFiStepExtended): Execution => {\n if (!step.execution) {\n step.execution = {\n startedAt: Date.now(),\n status: 'PENDING',\n actions: [],\n }\n this.updateStepInRoute(step)\n }\n\n // Change status to PENDING after resuming from FAILED\n if (step.execution.status === 'FAILED') {\n step.execution.startedAt = Date.now()\n step.execution.status = 'PENDING'\n step.execution.signedAt = undefined\n step.execution.error = undefined\n this.updateStepInRoute(step)\n }\n\n return step.execution\n }\n\n /**\n * Updates the execution object of a Step.\n * @param step The current step in execution\n * @param execution Partial execution data to merge\n * @returns The step with the updated execution object\n */\n updateExecution(\n step: LiFiStepExtended,\n execution: Partial<Execution>\n ): LiFiStep {\n if (!step.execution) {\n throw Error(\"Can't update empty execution.\")\n }\n step.execution = {\n ...step.execution,\n ...execution,\n }\n this.updateStepInRoute(step)\n return step\n }\n\n /**\n * Finds an action of the specified type in the step's execution\n * @param step The step to search in\n * @param type The action type to find\n * @returns The found action or undefined if not found\n */\n findAction(\n step: LiFiStepExtended,\n type: ExecutionActionType\n ): ExecutionAction | undefined {\n if (!step.execution?.actions) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const action = step.execution.actions.find((p) => p.type === type)\n\n return action\n }\n\n /**\n * Create and push a new action into the execution.\n * Caller is responsible for ensuring an action of this type does not already exist.\n * @param step The step that should contain the new action.\n * @param type Type of the action.\n * @param chainId Chain Id of the action.\n * @param status The initial status for the new action.\n * @returns The created action.\n */\n createAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Execution hasn't been initialized.\")\n }\n\n const newAction: ExecutionAction = {\n type,\n message: getActionMessage(type, status),\n status,\n chainId,\n }\n\n step.execution.actions.push(newAction)\n this.updateStepInRoute(step)\n return newAction\n }\n\n /**\n * Find an existing action by type and update it, or create a new one if none exists.\n * @param step The step that should contain the action.\n * @param type Type of the action. Used to identify already existing actions.\n * @param chainId Chain Id of the action (used when creating).\n * @param status The status to set on the found or newly created action.\n * @returns The updated or newly created action.\n */\n initializeAction = ({\n step,\n type,\n chainId,\n status,\n }: ActionProps): ExecutionAction => {\n const action = this.findAction(step, type)\n\n if (action) {\n return this.updateAction(step, type, status, {\n error: undefined,\n })\n }\n\n return this.createAction({ step, type, chainId, status })\n }\n\n /**\n * Update an action object.\n * @param step The step where the action should be updated\n * @param type The action type to update\n * @param status The status the action gets.\n * @param [params] Additional parameters to append to the action.\n * @returns The updated action\n */\n updateAction = (\n step: LiFiStepExtended,\n type: ExecutionActionType,\n status: ExecutionActionStatus,\n params?: Partial<ExecutionAction & { signedAt?: number }>\n ): ExecutionAction => {\n if (!step.execution) {\n throw new Error(\"Can't update an empty step execution.\")\n }\n const currentAction = this.findAction(step, type)\n\n if (!currentAction) {\n throw new Error(\"Can't find an action for the given type.\")\n }\n\n switch (status) {\n case 'CANCELLED':\n break\n case 'FAILED':\n step.execution.status = 'FAILED'\n if (params?.error) {\n step.execution.error = params.error\n }\n break\n case 'DONE':\n break\n case 'PENDING':\n step.execution.status = 'PENDING'\n if (params?.signedAt) {\n step.execution.signedAt = params.signedAt\n }\n break\n case 'RESET_REQUIRED':\n case 'MESSAGE_REQUIRED':\n case 'ACTION_REQUIRED':\n step.execution.status = 'ACTION_REQUIRED'\n break\n default:\n break\n }\n\n currentAction.status = status\n currentAction.message = getActionMessage(type, status)\n // set extra parameters or overwrite the standard params set in the switch statement\n if (params) {\n const { signedAt: _signedAt, ...rest } = params\n Object.assign(currentAction, rest)\n }\n // Sort actions, the ones with DONE status go first\n step.execution.actions = [\n ...step.execution.actions.filter((action) => action.status === 'DONE'),\n ...step.execution.actions.filter((action) => action.status !== 'DONE'),\n ]\n this.updateStepInRoute(step) // updates the step in the route\n return currentAction\n }\n\n updateStepInRoute = (step: LiFiStep): LiFiStep => {\n if (!this.shouldUpdate) {\n return step\n }\n const data = executionState.get(this.routeId)\n\n if (!data) {\n throw new Error('Execution data not found.')\n }\n\n const stepIndex = data.route.steps.findIndex(\n (routeStep) => routeStep.id === step.id\n )\n\n if (stepIndex === -1) {\n throw new Error(\"Couldn't find a step to update.\")\n }\n\n data.route.steps[stepIndex] = { ...data.route.steps[stepIndex], ...step }\n\n data.executionOptions?.updateRouteHook?.(data.route)\n return data.route.steps[stepIndex]\n }\n\n allowUpdates(value: boolean): void {\n this.shouldUpdate = value\n }\n}\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TaskPipeline.js","names":[],"sources":["../../../src/core/TaskPipeline.ts"],"sourcesContent":["import type { StepExecutorContext, TaskResult } from '../types/execution.js'\nimport type { BaseStepExecutionTask } from './BaseStepExecutionTask.js'\n\nexport class TaskPipeline {\n private readonly tasks: BaseStepExecutionTask[]\n\n constructor(tasks: BaseStepExecutionTask[]) {\n this.tasks = tasks\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n for (const task of this.tasks) {\n const shouldRun = await task.shouldRun(context)\n if (!shouldRun) {\n continue\n }\n const result = await task.run(context)\n if (result.status === 'PAUSED') {\n return { status: 'PAUSED' }\n }\n if (result.context && typeof result.context === 'object') {\n Object.assign(context, result.context)\n }\n }\n\n return { status: 'COMPLETED' }\n }\n}\n"],"mappings":";AAGA,IAAa,eAAb,MAA0B;CACxB;CAEA,YAAY,OAAgC;
|
|
1
|
+
{"version":3,"file":"TaskPipeline.js","names":[],"sources":["../../../src/core/TaskPipeline.ts"],"sourcesContent":["import type { StepExecutorContext, TaskResult } from '../types/execution.js'\nimport type { BaseStepExecutionTask } from './BaseStepExecutionTask.js'\n\nexport class TaskPipeline {\n private readonly tasks: BaseStepExecutionTask[]\n\n constructor(tasks: BaseStepExecutionTask[]) {\n this.tasks = tasks\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n for (const task of this.tasks) {\n const shouldRun = await task.shouldRun(context)\n if (!shouldRun) {\n continue\n }\n const result = await task.run(context)\n if (result.status === 'PAUSED') {\n return { status: 'PAUSED' }\n }\n if (result.context && typeof result.context === 'object') {\n Object.assign(context, result.context)\n }\n }\n\n return { status: 'COMPLETED' }\n }\n}\n"],"mappings":";AAGA,IAAa,eAAb,MAA0B;CACxB;CAEA,YAAY,OAAgC;EAC1C,KAAK,QAAQ;;CAGf,MAAM,IAAI,SAAmD;EAC3D,KAAK,MAAM,QAAQ,KAAK,OAAO;GAE7B,IAAI,CAAC,MADmB,KAAK,UAAU,QAAQ,EAE7C;GAEF,MAAM,SAAS,MAAM,KAAK,IAAI,QAAQ;GACtC,IAAI,OAAO,WAAW,UACpB,OAAO,EAAE,QAAQ,UAAU;GAE7B,IAAI,OAAO,WAAW,OAAO,OAAO,YAAY,UAC9C,OAAO,OAAO,SAAS,OAAO,QAAQ;;EAI1C,OAAO,EAAE,QAAQ,aAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"actionMessages.js","names":[],"sources":["../../../src/core/actionMessages.ts"],"sourcesContent":["import type { StatusMessage, Substatus } from '@lifi/types'\nimport type {\n ExecutionActionStatus,\n ExecutionActionType,\n} from '../types/core.js'\n\nconst actionMessages: Record<\n ExecutionActionType,\n Partial<Record<ExecutionActionStatus, string>>\n> = {\n CHECK_ALLOWANCE: {\n STARTED: 'Checking token allowance',\n PENDING: 'Waiting for token allowance check',\n DONE: 'Token allowance checked',\n },\n RESET_ALLOWANCE: {\n STARTED: 'Resetting token allowance',\n RESET_REQUIRED: 'Resetting token allowance',\n PENDING: 'Waiting for token allowance reset',\n DONE: 'Token allowance reset',\n },\n SET_ALLOWANCE: {\n STARTED: 'Setting token allowance',\n ACTION_REQUIRED: 'Set token allowance',\n PENDING: 'Waiting for token allowance',\n DONE: 'Token allowance set',\n },\n SWAP: {\n STARTED: 'Preparing swap transaction',\n ACTION_REQUIRED: 'Sign swap transaction',\n MESSAGE_REQUIRED: 'Sign swap message',\n PENDING: 'Waiting for swap transaction',\n DONE: 'Swap completed',\n },\n CROSS_CHAIN: {\n STARTED: 'Preparing bridge transaction',\n ACTION_REQUIRED: 'Sign bridge transaction',\n MESSAGE_REQUIRED: 'Sign bridge message',\n PENDING: 'Waiting for bridge transaction',\n DONE: 'Bridge transaction confirmed',\n },\n RECEIVING_CHAIN: {\n STARTED: 'Waiting for destination chain',\n PENDING: 'Waiting for destination chain',\n DONE: 'Bridge completed',\n },\n PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n NATIVE_PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n}\n\nconst substatusMessages: Record<\n StatusMessage,\n Partial<Record<Substatus, string>>\n> = {\n PENDING: {\n BRIDGE_NOT_AVAILABLE: 'Bridge communication is temporarily unavailable.',\n CHAIN_NOT_AVAILABLE: 'RPC communication is temporarily unavailable.',\n UNKNOWN_ERROR:\n 'An unexpected error occurred. Please seek assistance in the LI.FI discord server.',\n WAIT_SOURCE_CONFIRMATIONS:\n 'The bridge deposit has been received. The bridge is waiting for more confirmations to start the off-chain logic.',\n WAIT_DESTINATION_TRANSACTION:\n 'The bridge off-chain logic is being executed. Wait for the transaction to appear on the destination chain.',\n },\n DONE: {\n PARTIAL:\n 'Some of the received tokens are not the requested destination tokens.',\n REFUNDED: 'The tokens were refunded to the sender address.',\n COMPLETED: 'The transfer is complete.',\n },\n FAILED: {},\n INVALID: {},\n NOT_FOUND: {},\n}\n\nexport function getActionMessage(\n type: ExecutionActionType,\n status: ExecutionActionStatus\n): string | undefined {\n const actionMessage = actionMessages[type][status]\n return actionMessage\n}\n\nexport function getSubstatusMessage(\n status: StatusMessage,\n substatus?: Substatus\n): string | undefined {\n if (!substatus) {\n return\n }\n const message = substatusMessages[status][substatus]\n return message\n}\n"],"mappings":";AAMA,MAAM,iBAGF;CACF,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;EACP;CACD,iBAAiB;EACf,SAAS;EACT,gBAAgB;EAChB,SAAS;EACT,MAAM;EACP;CACD,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;EACP;CACD,MAAM;EACJ,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;EACP;CACD,aAAa;EACX,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;EACP;CACD,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;EACP;CACD,QAAQ;EACN,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;EACP;CACD,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;EACP;CACF;AAED,MAAM,oBAGF;CACF,SAAS;EACP,sBAAsB;EACtB,qBAAqB;EACrB,eACE;EACF,2BACE;EACF,8BACE;EACH;CACD,MAAM;EACJ,SACE;EACF,UAAU;EACV,WAAW;EACZ;CACD,QAAQ,EAAE;CACV,SAAS,EAAE;CACX,WAAW,EAAE;CACd;AAED,SAAgB,iBACd,MACA,QACoB;
|
|
1
|
+
{"version":3,"file":"actionMessages.js","names":[],"sources":["../../../src/core/actionMessages.ts"],"sourcesContent":["import type { StatusMessage, Substatus } from '@lifi/types'\nimport type {\n ExecutionActionStatus,\n ExecutionActionType,\n} from '../types/core.js'\n\nconst actionMessages: Record<\n ExecutionActionType,\n Partial<Record<ExecutionActionStatus, string>>\n> = {\n CHECK_ALLOWANCE: {\n STARTED: 'Checking token allowance',\n PENDING: 'Waiting for token allowance check',\n DONE: 'Token allowance checked',\n },\n RESET_ALLOWANCE: {\n STARTED: 'Resetting token allowance',\n RESET_REQUIRED: 'Resetting token allowance',\n PENDING: 'Waiting for token allowance reset',\n DONE: 'Token allowance reset',\n },\n SET_ALLOWANCE: {\n STARTED: 'Setting token allowance',\n ACTION_REQUIRED: 'Set token allowance',\n PENDING: 'Waiting for token allowance',\n DONE: 'Token allowance set',\n },\n SWAP: {\n STARTED: 'Preparing swap transaction',\n ACTION_REQUIRED: 'Sign swap transaction',\n MESSAGE_REQUIRED: 'Sign swap message',\n PENDING: 'Waiting for swap transaction',\n DONE: 'Swap completed',\n },\n CROSS_CHAIN: {\n STARTED: 'Preparing bridge transaction',\n ACTION_REQUIRED: 'Sign bridge transaction',\n MESSAGE_REQUIRED: 'Sign bridge message',\n PENDING: 'Waiting for bridge transaction',\n DONE: 'Bridge transaction confirmed',\n },\n RECEIVING_CHAIN: {\n STARTED: 'Waiting for destination chain',\n PENDING: 'Waiting for destination chain',\n DONE: 'Bridge completed',\n },\n PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n NATIVE_PERMIT: {\n STARTED: 'Preparing transaction',\n ACTION_REQUIRED: 'Sign permit message',\n PENDING: 'Waiting for permit message',\n DONE: 'Permit message signed',\n },\n}\n\nconst substatusMessages: Record<\n StatusMessage,\n Partial<Record<Substatus, string>>\n> = {\n PENDING: {\n BRIDGE_NOT_AVAILABLE: 'Bridge communication is temporarily unavailable.',\n CHAIN_NOT_AVAILABLE: 'RPC communication is temporarily unavailable.',\n UNKNOWN_ERROR:\n 'An unexpected error occurred. Please seek assistance in the LI.FI discord server.',\n WAIT_SOURCE_CONFIRMATIONS:\n 'The bridge deposit has been received. The bridge is waiting for more confirmations to start the off-chain logic.',\n WAIT_DESTINATION_TRANSACTION:\n 'The bridge off-chain logic is being executed. Wait for the transaction to appear on the destination chain.',\n },\n DONE: {\n PARTIAL:\n 'Some of the received tokens are not the requested destination tokens.',\n REFUNDED: 'The tokens were refunded to the sender address.',\n COMPLETED: 'The transfer is complete.',\n },\n FAILED: {},\n INVALID: {},\n NOT_FOUND: {},\n}\n\nexport function getActionMessage(\n type: ExecutionActionType,\n status: ExecutionActionStatus\n): string | undefined {\n const actionMessage = actionMessages[type][status]\n return actionMessage\n}\n\nexport function getSubstatusMessage(\n status: StatusMessage,\n substatus?: Substatus\n): string | undefined {\n if (!substatus) {\n return\n }\n const message = substatusMessages[status][substatus]\n return message\n}\n"],"mappings":";AAMA,MAAM,iBAGF;CACF,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;EACP;CACD,iBAAiB;EACf,SAAS;EACT,gBAAgB;EAChB,SAAS;EACT,MAAM;EACP;CACD,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;EACP;CACD,MAAM;EACJ,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;EACP;CACD,aAAa;EACX,SAAS;EACT,iBAAiB;EACjB,kBAAkB;EAClB,SAAS;EACT,MAAM;EACP;CACD,iBAAiB;EACf,SAAS;EACT,SAAS;EACT,MAAM;EACP;CACD,QAAQ;EACN,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;EACP;CACD,eAAe;EACb,SAAS;EACT,iBAAiB;EACjB,SAAS;EACT,MAAM;EACP;CACF;AAED,MAAM,oBAGF;CACF,SAAS;EACP,sBAAsB;EACtB,qBAAqB;EACrB,eACE;EACF,2BACE;EACF,8BACE;EACH;CACD,MAAM;EACJ,SACE;EACF,UAAU;EACV,WAAW;EACZ;CACD,QAAQ,EAAE;CACV,SAAS,EAAE;CACX,WAAW,EAAE;CACd;AAED,SAAgB,iBACd,MACA,QACoB;CAEpB,OADsB,eAAe,MAAM;;AAI7C,SAAgB,oBACd,QACA,WACoB;CACpB,IAAI,CAAC,WACH;CAGF,OADgB,kBAAkB,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"execution.js","names":[],"sources":["../../../src/core/execution.ts"],"sourcesContent":["import type { Route } from '@lifi/types'\nimport { LiFiErrorCode } from '../errors/constants.js'\nimport { ExecuteStepRetryError, ProviderError } from '../errors/errors.js'\nimport type {\n ExecutionOptions,\n LiFiStepExtended,\n RouteExtended,\n SDKClient,\n SDKProvider,\n} from '../types/core.js'\nimport { executionState } from './executionState.js'\nimport { prepareRestart } from './prepareRestart.js'\n\n/**\n * Execute a route.\n * @param client - The SDK client.\n * @param route - The route that should be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const executeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n // Deep clone to prevent side effects\n const clonedRoute = structuredClone<Route>(route)\n\n let executionPromise = executionState.get(clonedRoute.id)?.promise\n // Check if route is already running\n if (executionPromise) {\n return executionPromise\n }\n\n executionState.create({ route: clonedRoute, executionOptions })\n executionPromise = executeSteps(client, clonedRoute)\n executionState.update({\n route: clonedRoute,\n promise: executionPromise,\n })\n\n return executionPromise\n}\n\n/**\n * Resume the execution of a route that has been stopped or had an error while executing.\n * @param client - The SDK client.\n * @param route - The route that is to be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const resumeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n const execution = executionState.get(route.id)\n\n if (execution) {\n const executionHalted = execution.executors.some(\n (executor) => !executor.allowExecution\n )\n if (!executionHalted) {\n // Check if we want to resume route execution in the background\n updateRouteExecution(route, {\n executeInBackground: executionOptions?.executeInBackground,\n })\n if (!execution.promise) {\n // We should never reach this point if we do clean-up properly\n throw new Error('Route execution promise not found.')\n }\n return execution.promise\n }\n }\n\n prepareRestart(route)\n\n return executeRoute(client, route, executionOptions)\n}\n\nconst executeSteps = async (\n client: SDKClient,\n route: RouteExtended\n): Promise<RouteExtended> => {\n // Loop over steps and execute them\n for (let index = 0; index < route.steps.length; index++) {\n const execution = executionState.get(route.id)\n // Check if execution has stopped in the meantime\n if (!execution) {\n break\n }\n\n const step = route.steps[index]\n const previousStep = route.steps[index - 1]\n // Check if the step is already done\n if (step.execution?.status === 'DONE') {\n continue\n }\n\n // Update step fromAmount using output of the previous step execution. In the future this should be handled by calling `updateRoute`\n if (previousStep?.execution?.toAmount) {\n step.action.fromAmount = previousStep.execution.toAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount =\n previousStep.execution.toAmount\n }\n }\n\n try {\n const fromAddress = step.action.fromAddress\n if (!fromAddress) {\n throw new Error('Action fromAddress is not specified.')\n }\n\n const provider = client.providers.find((provider: SDKProvider) =>\n provider.isAddress(fromAddress)\n )\n\n if (!provider) {\n throw new ProviderError(\n LiFiErrorCode.ProviderUnavailable,\n 'SDK Execution Provider not found.'\n )\n }\n\n const stepExecutor = await provider.getStepExecutor({\n routeId: route.id,\n executionOptions: execution.executionOptions,\n })\n execution.executors.push(stepExecutor)\n\n // Check if we want to execute this step in the background\n if (execution.executionOptions) {\n updateRouteExecution(route, execution.executionOptions)\n }\n\n let executedStep: LiFiStepExtended\n try {\n executedStep = await stepExecutor.executeStep(client, step)\n } catch (e) {\n if (e instanceof ExecuteStepRetryError) {\n step.execution = undefined\n executedStep = await stepExecutor.executeStep(\n client,\n step,\n e.retryParams\n )\n } else {\n throw e\n }\n }\n\n // We may reach this point if user interaction isn't allowed. We want to stop execution until we resume it\n if (executedStep.execution?.status !== 'DONE') {\n stopRouteExecution(route)\n }\n\n // Execution stopped during the current step, we don't want to continue to the next step so we return already\n if (!stepExecutor.allowExecution) {\n return route\n }\n } catch (e) {\n stopRouteExecution(route)\n throw e\n }\n }\n\n // Clean up after the execution\n executionState.delete(route.id)\n return route\n}\n\n/**\n * Updates route execution to background or foreground state.\n * @param route - A route that is currently in execution.\n * @param options - An object with execution settings.\n */\nexport const updateRouteExecution = (\n route: Route,\n options: ExecutionOptions\n): void => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return\n }\n\n if ('executeInBackground' in options) {\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: !options?.executeInBackground,\n allowUpdates: true,\n })\n }\n }\n // Update active route settings so we know what the current state of execution is\n execution.executionOptions = {\n ...execution.executionOptions,\n ...options,\n }\n}\n\n/**\n * Stops the execution of an active route.\n * @param route - A route that is currently in execution.\n * @returns The stopped route.\n */\nexport const stopRouteExecution = (route: Route): Route => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return route\n }\n\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: false,\n allowUpdates: false,\n allowExecution: false,\n })\n }\n executionState.delete(route.id)\n return execution.route\n}\n\n/**\n * Get the list of active routes.\n * @returns A list of routes.\n */\nexport const getActiveRoutes = (): RouteExtended[] => {\n return Object.values(executionState.state)\n .map((dict) => dict?.route)\n .filter(Boolean) as RouteExtended[]\n}\n\n/**\n * Return the current route information for given route. The route has to be active.\n * @param routeId - A route id.\n * @returns The updated route.\n */\nexport const getActiveRoute = (routeId: string): RouteExtended | undefined => {\n return executionState.get(routeId)?.route\n}\n"],"mappings":";;;;;;;;;;;;;AAqBA,MAAa,eAAe,OAC1B,QACA,OACA,qBAC2B;CAE3B,MAAM,cAAc,gBAAuB,MAAM;CAEjD,IAAI,mBAAmB,eAAe,IAAI,YAAY,GAAG,EAAE;
|
|
1
|
+
{"version":3,"file":"execution.js","names":[],"sources":["../../../src/core/execution.ts"],"sourcesContent":["import type { Route } from '@lifi/types'\nimport { LiFiErrorCode } from '../errors/constants.js'\nimport { ExecuteStepRetryError, ProviderError } from '../errors/errors.js'\nimport type {\n ExecutionOptions,\n LiFiStepExtended,\n RouteExtended,\n SDKClient,\n SDKProvider,\n} from '../types/core.js'\nimport { executionState } from './executionState.js'\nimport { prepareRestart } from './prepareRestart.js'\n\n/**\n * Execute a route.\n * @param client - The SDK client.\n * @param route - The route that should be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const executeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n // Deep clone to prevent side effects\n const clonedRoute = structuredClone<Route>(route)\n\n let executionPromise = executionState.get(clonedRoute.id)?.promise\n // Check if route is already running\n if (executionPromise) {\n return executionPromise\n }\n\n executionState.create({ route: clonedRoute, executionOptions })\n executionPromise = executeSteps(client, clonedRoute)\n executionState.update({\n route: clonedRoute,\n promise: executionPromise,\n })\n\n return executionPromise\n}\n\n/**\n * Resume the execution of a route that has been stopped or had an error while executing.\n * @param client - The SDK client.\n * @param route - The route that is to be executed. Cannot be an active route.\n * @param executionOptions - An object containing settings and callbacks.\n * @returns The executed route.\n * @throws {LiFiError} Throws a LiFiError if the execution fails.\n */\nexport const resumeRoute = async (\n client: SDKClient,\n route: Route,\n executionOptions?: ExecutionOptions\n): Promise<RouteExtended> => {\n const execution = executionState.get(route.id)\n\n if (execution) {\n const executionHalted = execution.executors.some(\n (executor) => !executor.allowExecution\n )\n if (!executionHalted) {\n // Check if we want to resume route execution in the background\n updateRouteExecution(route, {\n executeInBackground: executionOptions?.executeInBackground,\n })\n if (!execution.promise) {\n // We should never reach this point if we do clean-up properly\n throw new Error('Route execution promise not found.')\n }\n return execution.promise\n }\n }\n\n prepareRestart(route)\n\n return executeRoute(client, route, executionOptions)\n}\n\nconst executeSteps = async (\n client: SDKClient,\n route: RouteExtended\n): Promise<RouteExtended> => {\n // Loop over steps and execute them\n for (let index = 0; index < route.steps.length; index++) {\n const execution = executionState.get(route.id)\n // Check if execution has stopped in the meantime\n if (!execution) {\n break\n }\n\n const step = route.steps[index]\n const previousStep = route.steps[index - 1]\n // Check if the step is already done\n if (step.execution?.status === 'DONE') {\n continue\n }\n\n // Update step fromAmount using output of the previous step execution. In the future this should be handled by calling `updateRoute`\n if (previousStep?.execution?.toAmount) {\n step.action.fromAmount = previousStep.execution.toAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount =\n previousStep.execution.toAmount\n }\n }\n\n try {\n const fromAddress = step.action.fromAddress\n if (!fromAddress) {\n throw new Error('Action fromAddress is not specified.')\n }\n\n const provider = client.providers.find((provider: SDKProvider) =>\n provider.isAddress(fromAddress)\n )\n\n if (!provider) {\n throw new ProviderError(\n LiFiErrorCode.ProviderUnavailable,\n 'SDK Execution Provider not found.'\n )\n }\n\n const stepExecutor = await provider.getStepExecutor({\n routeId: route.id,\n executionOptions: execution.executionOptions,\n })\n execution.executors.push(stepExecutor)\n\n // Check if we want to execute this step in the background\n if (execution.executionOptions) {\n updateRouteExecution(route, execution.executionOptions)\n }\n\n let executedStep: LiFiStepExtended\n try {\n executedStep = await stepExecutor.executeStep(client, step)\n } catch (e) {\n if (e instanceof ExecuteStepRetryError) {\n step.execution = undefined\n executedStep = await stepExecutor.executeStep(\n client,\n step,\n e.retryParams\n )\n } else {\n throw e\n }\n }\n\n // We may reach this point if user interaction isn't allowed. We want to stop execution until we resume it\n if (executedStep.execution?.status !== 'DONE') {\n stopRouteExecution(route)\n }\n\n // Execution stopped during the current step, we don't want to continue to the next step so we return already\n if (!stepExecutor.allowExecution) {\n return route\n }\n } catch (e) {\n stopRouteExecution(route)\n throw e\n }\n }\n\n // Clean up after the execution\n executionState.delete(route.id)\n return route\n}\n\n/**\n * Updates route execution to background or foreground state.\n * @param route - A route that is currently in execution.\n * @param options - An object with execution settings.\n */\nexport const updateRouteExecution = (\n route: Route,\n options: ExecutionOptions\n): void => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return\n }\n\n if ('executeInBackground' in options) {\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: !options?.executeInBackground,\n allowUpdates: true,\n })\n }\n }\n // Update active route settings so we know what the current state of execution is\n execution.executionOptions = {\n ...execution.executionOptions,\n ...options,\n }\n}\n\n/**\n * Stops the execution of an active route.\n * @param route - A route that is currently in execution.\n * @returns The stopped route.\n */\nexport const stopRouteExecution = (route: Route): Route => {\n const execution = executionState.get(route.id)\n if (!execution) {\n return route\n }\n\n for (const executor of execution.executors) {\n executor.setInteraction({\n allowInteraction: false,\n allowUpdates: false,\n allowExecution: false,\n })\n }\n executionState.delete(route.id)\n return execution.route\n}\n\n/**\n * Get the list of active routes.\n * @returns A list of routes.\n */\nexport const getActiveRoutes = (): RouteExtended[] => {\n return Object.values(executionState.state)\n .map((dict) => dict?.route)\n .filter(Boolean) as RouteExtended[]\n}\n\n/**\n * Return the current route information for given route. The route has to be active.\n * @param routeId - A route id.\n * @returns The updated route.\n */\nexport const getActiveRoute = (routeId: string): RouteExtended | undefined => {\n return executionState.get(routeId)?.route\n}\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"executionState.js","names":[],"sources":["../../../src/core/executionState.ts"],"sourcesContent":["import type {\n ExecutionOptions,\n RouteExtended,\n StepExecutor,\n} from '../types/core.js'\n\ninterface ExecutionData {\n route: RouteExtended\n executors: StepExecutor[]\n executionOptions?: ExecutionOptions\n promise?: Promise<RouteExtended>\n}\n\ntype ExecutionStateParams = Omit<ExecutionData, 'executors'>\n\ninterface ExecutionState {\n state: Partial<Record<string, ExecutionData>>\n get(routeId: string): ExecutionData | undefined\n create(params: ExecutionStateParams): ExecutionData\n update(params: ExecutionStateParams): void\n delete(routeId: string): void\n}\n\nexport const executionState: ExecutionState = {\n state: {},\n get(routeId: string) {\n return this.state[routeId]\n },\n create(params) {\n this.state[params.route.id] = {\n ...this.state[params.route.id],\n ...params,\n executors: this.state[params.route.id]?.executors ?? [],\n }\n return this.state[params.route.id]!\n },\n update(state) {\n if (this.state[state.route.id]) {\n this.state[state.route.id] = {\n ...this.state[state.route.id]!,\n ...state,\n }\n }\n },\n delete(routeId) {\n delete this.state[routeId]\n },\n}\n"],"mappings":";AAuBA,MAAa,iBAAiC;CAC5C,OAAO,EAAE;CACT,IAAI,SAAiB;
|
|
1
|
+
{"version":3,"file":"executionState.js","names":[],"sources":["../../../src/core/executionState.ts"],"sourcesContent":["import type {\n ExecutionOptions,\n RouteExtended,\n StepExecutor,\n} from '../types/core.js'\n\ninterface ExecutionData {\n route: RouteExtended\n executors: StepExecutor[]\n executionOptions?: ExecutionOptions\n promise?: Promise<RouteExtended>\n}\n\ntype ExecutionStateParams = Omit<ExecutionData, 'executors'>\n\ninterface ExecutionState {\n state: Partial<Record<string, ExecutionData>>\n get(routeId: string): ExecutionData | undefined\n create(params: ExecutionStateParams): ExecutionData\n update(params: ExecutionStateParams): void\n delete(routeId: string): void\n}\n\nexport const executionState: ExecutionState = {\n state: {},\n get(routeId: string) {\n return this.state[routeId]\n },\n create(params) {\n this.state[params.route.id] = {\n ...this.state[params.route.id],\n ...params,\n executors: this.state[params.route.id]?.executors ?? [],\n }\n return this.state[params.route.id]!\n },\n update(state) {\n if (this.state[state.route.id]) {\n this.state[state.route.id] = {\n ...this.state[state.route.id]!,\n ...state,\n }\n }\n },\n delete(routeId) {\n delete this.state[routeId]\n },\n}\n"],"mappings":";AAuBA,MAAa,iBAAiC;CAC5C,OAAO,EAAE;CACT,IAAI,SAAiB;EACnB,OAAO,KAAK,MAAM;;CAEpB,OAAO,QAAQ;EACb,KAAK,MAAM,OAAO,MAAM,MAAM;GAC5B,GAAG,KAAK,MAAM,OAAO,MAAM;GAC3B,GAAG;GACH,WAAW,KAAK,MAAM,OAAO,MAAM,KAAK,aAAa,EAAE;GACxD;EACD,OAAO,KAAK,MAAM,OAAO,MAAM;;CAEjC,OAAO,OAAO;EACZ,IAAI,KAAK,MAAM,MAAM,MAAM,KACzB,KAAK,MAAM,MAAM,MAAM,MAAM;GAC3B,GAAG,KAAK,MAAM,MAAM,MAAM;GAC1B,GAAG;GACJ;;CAGL,OAAO,SAAS;EACd,OAAO,KAAK,MAAM;;CAErB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prepareRestart.js","names":[],"sources":["../../../src/core/prepareRestart.ts"],"sourcesContent":["import type { RouteExtended } from '../types/core.js'\n\nexport const prepareRestart = (route: RouteExtended): void => {\n for (let index = 0; index < route.steps.length; index++) {\n const step = route.steps[index]\n if (step.execution) {\n // Find the index of the last action that has tx hash, taskId, or signed messages\n const lastValidIndex = step.execution.actions.findLastIndex(\n (action) =>\n ['SWAP', 'CROSS_CHAIN', 'RECEIVING_CHAIN'].includes(action.type) &&\n (!!action.txHash || !!action.taskId) &&\n action.status !== 'FAILED'\n )\n\n // Keep all actions up to the one with tx hash\n if (lastValidIndex >= 0) {\n step.execution.actions = step.execution.actions.slice(\n 0,\n lastValidIndex + 1\n )\n } else {\n // If no tx hash exists, reset the actions array\n step.execution.actions = []\n }\n }\n step.transactionRequest = undefined\n }\n}\n"],"mappings":";AAEA,MAAa,kBAAkB,UAA+B;
|
|
1
|
+
{"version":3,"file":"prepareRestart.js","names":[],"sources":["../../../src/core/prepareRestart.ts"],"sourcesContent":["import type { RouteExtended } from '../types/core.js'\n\nexport const prepareRestart = (route: RouteExtended): void => {\n for (let index = 0; index < route.steps.length; index++) {\n const step = route.steps[index]\n if (step.execution) {\n // Find the index of the last action that has tx hash, taskId, or signed messages\n const lastValidIndex = step.execution.actions.findLastIndex(\n (action) =>\n ['SWAP', 'CROSS_CHAIN', 'RECEIVING_CHAIN'].includes(action.type) &&\n (!!action.txHash || !!action.taskId) &&\n action.status !== 'FAILED'\n )\n\n // Keep all actions up to the one with tx hash\n if (lastValidIndex >= 0) {\n step.execution.actions = step.execution.actions.slice(\n 0,\n lastValidIndex + 1\n )\n } else {\n // If no tx hash exists, reset the actions array\n step.execution.actions = []\n }\n }\n step.transactionRequest = undefined\n }\n}\n"],"mappings":";AAEA,MAAa,kBAAkB,UAA+B;CAC5D,KAAK,IAAI,QAAQ,GAAG,QAAQ,MAAM,MAAM,QAAQ,SAAS;EACvD,MAAM,OAAO,MAAM,MAAM;EACzB,IAAI,KAAK,WAAW;GAElB,MAAM,iBAAiB,KAAK,UAAU,QAAQ,eAC3C,WACC;IAAC;IAAQ;IAAe;IAAkB,CAAC,SAAS,OAAO,KAAK,KAC/D,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,WAC7B,OAAO,WAAW,SACrB;GAGD,IAAI,kBAAkB,GACpB,KAAK,UAAU,UAAU,KAAK,UAAU,QAAQ,MAC9C,GACA,iBAAiB,EAClB;QAGD,KAAK,UAAU,UAAU,EAAE;;EAG/B,KAAK,qBAAqB,KAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"storage.js","names":[],"sources":["../../../src/core/storage.ts"],"sourcesContent":["export interface SDKStorage {\n get(key: string): string | null | Promise<string | null>\n set(key: string, value: string): void | Promise<void>\n remove(key: string): void | Promise<void>\n}\n\nexport class LocalStorageAdapter implements SDKStorage {\n get(key: string): string | null {\n return window.localStorage.getItem(key)\n }\n\n set(key: string, value: string): void {\n window.localStorage.setItem(key, value)\n }\n\n remove(key: string): void {\n window.localStorage.removeItem(key)\n }\n}\n\nexport class InMemoryStorage implements SDKStorage {\n private store = new Map<string, string>()\n\n get(key: string): string | null {\n return this.store.get(key) ?? null\n }\n\n set(key: string, value: string): void {\n this.store.set(key, value)\n }\n\n remove(key: string): void {\n this.store.delete(key)\n }\n}\n\nexport function createDefaultStorage(): SDKStorage {\n if (typeof window !== 'undefined' && window.localStorage) {\n return new LocalStorageAdapter()\n }\n return new InMemoryStorage()\n}\n"],"mappings":";AAMA,IAAa,sBAAb,MAAuD;CACrD,IAAI,KAA4B;
|
|
1
|
+
{"version":3,"file":"storage.js","names":[],"sources":["../../../src/core/storage.ts"],"sourcesContent":["export interface SDKStorage {\n get(key: string): string | null | Promise<string | null>\n set(key: string, value: string): void | Promise<void>\n remove(key: string): void | Promise<void>\n}\n\nexport class LocalStorageAdapter implements SDKStorage {\n get(key: string): string | null {\n return window.localStorage.getItem(key)\n }\n\n set(key: string, value: string): void {\n window.localStorage.setItem(key, value)\n }\n\n remove(key: string): void {\n window.localStorage.removeItem(key)\n }\n}\n\nexport class InMemoryStorage implements SDKStorage {\n private store = new Map<string, string>()\n\n get(key: string): string | null {\n return this.store.get(key) ?? null\n }\n\n set(key: string, value: string): void {\n this.store.set(key, value)\n }\n\n remove(key: string): void {\n this.store.delete(key)\n }\n}\n\nexport function createDefaultStorage(): SDKStorage {\n if (typeof window !== 'undefined' && window.localStorage) {\n return new LocalStorageAdapter()\n }\n return new InMemoryStorage()\n}\n"],"mappings":";AAMA,IAAa,sBAAb,MAAuD;CACrD,IAAI,KAA4B;EAC9B,OAAO,OAAO,aAAa,QAAQ,IAAI;;CAGzC,IAAI,KAAa,OAAqB;EACpC,OAAO,aAAa,QAAQ,KAAK,MAAM;;CAGzC,OAAO,KAAmB;EACxB,OAAO,aAAa,WAAW,IAAI;;;AAIvC,IAAa,kBAAb,MAAmD;CACjD,wBAAgB,IAAI,KAAqB;CAEzC,IAAI,KAA4B;EAC9B,OAAO,KAAK,MAAM,IAAI,IAAI,IAAI;;CAGhC,IAAI,KAAa,OAAqB;EACpC,KAAK,MAAM,IAAI,KAAK,MAAM;;CAG5B,OAAO,KAAmB;EACxB,KAAK,MAAM,OAAO,IAAI;;;AAI1B,SAAgB,uBAAmC;CACjD,IAAI,OAAO,WAAW,eAAe,OAAO,cAC1C,OAAO,IAAI,qBAAqB;CAElC,OAAO,IAAI,iBAAiB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CheckBalanceTask.js","names":[],"sources":["../../../../src/core/tasks/CheckBalanceTask.ts"],"sourcesContent":["import { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport {\n type CheckBalanceOptions,\n checkBalance,\n} from './helpers/checkBalance.js'\n\nexport class CheckBalanceTask extends BaseStepExecutionTask {\n /**\n * Per-step options hook for chain-specific subclasses (e.g. skip the\n * gas check for smart-contract wallets or relayed steps). Default `{}`\n * keeps behavior unchanged for every provider that doesn't override.\n * Resolved lazily inside `run()` — pipelines that resume past\n * `CheckBalance` pay no cost.\n */\n protected getCheckBalanceOptions(\n _context: StepExecutorContext\n ): Promise<CheckBalanceOptions> {\n return Promise.resolve({})\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const { client, step, statusManager, isBridgeExecution } = context\n\n statusManager.initializeAction({\n step,\n type: isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP',\n chainId: step.action.fromChainId,\n status: 'STARTED',\n })\n\n const walletAddress = step.action.fromAddress\n if (!walletAddress) {\n throw new TransactionError(\n LiFiErrorCode.InternalError,\n 'The wallet address is undefined.'\n )\n }\n\n const options = await this.getCheckBalanceOptions(context)\n await checkBalance(client, walletAddress, step, options)\n return { status: 'COMPLETED' }\n }\n}\n"],"mappings":";;;;;AASA,IAAa,mBAAb,cAAsC,sBAAsB;;;;;;;;CAQ1D,uBACE,UAC8B;
|
|
1
|
+
{"version":3,"file":"CheckBalanceTask.js","names":[],"sources":["../../../../src/core/tasks/CheckBalanceTask.ts"],"sourcesContent":["import { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport {\n type CheckBalanceOptions,\n checkBalance,\n} from './helpers/checkBalance.js'\n\nexport class CheckBalanceTask extends BaseStepExecutionTask {\n /**\n * Per-step options hook for chain-specific subclasses (e.g. skip the\n * gas check for smart-contract wallets or relayed steps). Default `{}`\n * keeps behavior unchanged for every provider that doesn't override.\n * Resolved lazily inside `run()` — pipelines that resume past\n * `CheckBalance` pay no cost.\n */\n protected getCheckBalanceOptions(\n _context: StepExecutorContext\n ): Promise<CheckBalanceOptions> {\n return Promise.resolve({})\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const { client, step, statusManager, isBridgeExecution } = context\n\n statusManager.initializeAction({\n step,\n type: isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP',\n chainId: step.action.fromChainId,\n status: 'STARTED',\n })\n\n const walletAddress = step.action.fromAddress\n if (!walletAddress) {\n throw new TransactionError(\n LiFiErrorCode.InternalError,\n 'The wallet address is undefined.'\n )\n }\n\n const options = await this.getCheckBalanceOptions(context)\n await checkBalance(client, walletAddress, step, options)\n return { status: 'COMPLETED' }\n }\n}\n"],"mappings":";;;;;AASA,IAAa,mBAAb,cAAsC,sBAAsB;;;;;;;;CAQ1D,uBACE,UAC8B;EAC9B,OAAO,QAAQ,QAAQ,EAAE,CAAC;;CAG5B,MAAM,IAAI,SAAmD;EAC3D,MAAM,EAAE,QAAQ,MAAM,eAAe,sBAAsB;EAE3D,cAAc,iBAAiB;GAC7B;GACA,MAAM,oBAAoB,gBAAgB;GAC1C,SAAS,KAAK,OAAO;GACrB,QAAQ;GACT,CAAC;EAEF,MAAM,gBAAgB,KAAK,OAAO;EAClC,IAAI,CAAC,eACH,MAAM,IAAI,iBAAA,KAER,mCACD;EAIH,MAAM,aAAa,QAAQ,eAAe,MAAM,MAD1B,KAAK,uBAAuB,QAAQ,CACF;EACxD,OAAO,EAAE,QAAQ,aAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PrepareTransactionTask.js","names":[],"sources":["../../../../src/core/tasks/PrepareTransactionTask.ts"],"sourcesContent":["import { getStepTransaction } from '../../actions/getStepTransaction.js'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport { stepComparison } from './helpers/stepComparison.js'\n\nexport class PrepareTransactionTask extends BaseStepExecutionTask {\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const {\n client,\n step,\n statusManager,\n allowUserInteraction,\n executionOptions,\n isBridgeExecution,\n } = context\n\n const action = statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n\n if (!action) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Action not found.'\n )\n }\n\n if (!step.transactionRequest) {\n const { execution, ...stepBase } = step\n const updatedStep = await getStepTransaction(client, stepBase)\n const comparedStep = await stepComparison(\n statusManager,\n step,\n updatedStep,\n allowUserInteraction,\n executionOptions\n )\n Object.assign(step, {\n ...comparedStep,\n execution: step.execution,\n })\n }\n\n if (!step.transactionRequest?.data) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Transaction request data is not found.'\n )\n }\n\n statusManager.updateAction(step, action.type, 'ACTION_REQUIRED')\n\n if (!allowUserInteraction) {\n return { status: 'PAUSED' }\n }\n\n return { status: 'COMPLETED' }\n }\n}\n"],"mappings":";;;;;;AAOA,IAAa,yBAAb,cAA4C,sBAAsB;CAChE,MAAM,IAAI,SAAmD;EAC3D,MAAM,EACJ,QACA,MACA,eACA,sBACA,kBACA,sBACE;EAEJ,MAAM,SAAS,cAAc,WAC3B,MACA,oBAAoB,gBAAgB,OACrC;
|
|
1
|
+
{"version":3,"file":"PrepareTransactionTask.js","names":[],"sources":["../../../../src/core/tasks/PrepareTransactionTask.ts"],"sourcesContent":["import { getStepTransaction } from '../../actions/getStepTransaction.js'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport { stepComparison } from './helpers/stepComparison.js'\n\nexport class PrepareTransactionTask extends BaseStepExecutionTask {\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const {\n client,\n step,\n statusManager,\n allowUserInteraction,\n executionOptions,\n isBridgeExecution,\n } = context\n\n const action = statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n\n if (!action) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Action not found.'\n )\n }\n\n if (!step.transactionRequest) {\n const { execution, ...stepBase } = step\n const updatedStep = await getStepTransaction(client, stepBase)\n const comparedStep = await stepComparison(\n statusManager,\n step,\n updatedStep,\n allowUserInteraction,\n executionOptions\n )\n Object.assign(step, {\n ...comparedStep,\n execution: step.execution,\n })\n }\n\n if (!step.transactionRequest?.data) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Transaction request data is not found.'\n )\n }\n\n statusManager.updateAction(step, action.type, 'ACTION_REQUIRED')\n\n if (!allowUserInteraction) {\n return { status: 'PAUSED' }\n }\n\n return { status: 'COMPLETED' }\n }\n}\n"],"mappings":";;;;;;AAOA,IAAa,yBAAb,cAA4C,sBAAsB;CAChE,MAAM,IAAI,SAAmD;EAC3D,MAAM,EACJ,QACA,MACA,eACA,sBACA,kBACA,sBACE;EAEJ,MAAM,SAAS,cAAc,WAC3B,MACA,oBAAoB,gBAAgB,OACrC;EAED,IAAI,CAAC,QACH,MAAM,IAAI,iBAAA,MAER,mDACD;EAGH,IAAI,CAAC,KAAK,oBAAoB;GAC5B,MAAM,EAAE,WAAW,GAAG,aAAa;GAEnC,MAAM,eAAe,MAAM,eACzB,eACA,MACA,MAJwB,mBAAmB,QAAQ,SAAS,EAK5D,sBACA,iBACD;GACD,OAAO,OAAO,MAAM;IAClB,GAAG;IACH,WAAW,KAAK;IACjB,CAAC;;EAGJ,IAAI,CAAC,KAAK,oBAAoB,MAC5B,MAAM,IAAI,iBAAA,MAER,wEACD;EAGH,cAAc,aAAa,MAAM,OAAO,MAAM,kBAAkB;EAEhE,IAAI,CAAC,sBACH,OAAO,EAAE,QAAQ,UAAU;EAG7B,OAAO,EAAE,QAAQ,aAAa"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WaitForTransactionStatusTask.js","names":[],"sources":["../../../../src/core/tasks/WaitForTransactionStatusTask.ts"],"sourcesContent":["import type { ExtendedTransactionInfo, FullStatusData } from '@lifi/types'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { ExecutionActionType } from '../../types/core.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { getTransactionFailedMessage } from '../../utils/getTransactionMessage.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport { waitForTransactionStatus } from './helpers/waitForTransactionStatus.js'\n\nexport class WaitForTransactionStatusTask extends BaseStepExecutionTask {\n readonly actionType: ExecutionActionType\n\n constructor(actionType: ExecutionActionType) {\n super()\n this.actionType = actionType\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const {\n client,\n step,\n statusManager,\n pollingIntervalMs,\n toChain,\n isBridgeExecution,\n } = context\n\n // At this point, we should have a txHash or taskId\n // taskId is used for custom integrations that don't use the standard transaction hash\n let transactionHash: string | undefined\n try {\n const swapOrBridgeAction = statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n transactionHash = swapOrBridgeAction?.txHash || swapOrBridgeAction?.taskId\n\n // Wait for the transaction status on the destination chain\n if (!transactionHash) {\n throw new Error('Transaction hash is undefined.')\n }\n\n const action = statusManager.initializeAction({\n step,\n type: this.actionType,\n chainId:\n this.actionType === 'RECEIVING_CHAIN'\n ? step.action.toChainId\n : step.action.fromChainId,\n status: 'PENDING',\n })\n\n const statusResponse = (await waitForTransactionStatus(\n client,\n statusManager,\n transactionHash,\n step,\n action.type,\n pollingIntervalMs\n )) as FullStatusData\n\n const statusReceiving =\n statusResponse.receiving as ExtendedTransactionInfo\n\n // Update action status\n statusManager.updateAction(step, action.type, 'DONE', {\n chainId: statusReceiving?.chainId || toChain.id,\n substatus: statusResponse.substatus,\n substatusMessage: statusResponse.substatusMessage,\n txHash: statusReceiving?.txHash,\n txLink:\n statusReceiving?.txLink ||\n `${toChain.metamask.blockExplorerUrls[0]}tx/${statusReceiving?.txHash}`,\n })\n\n // Update execution status\n statusManager.updateExecution(step, {\n status: 'DONE',\n ...(statusResponse.sending.amount && {\n fromAmount: statusResponse.sending.amount,\n }),\n ...(statusReceiving?.amount && { toAmount: statusReceiving.amount }),\n ...(statusReceiving?.token && { toToken: statusReceiving.token }),\n internalTxLink: statusResponse?.lifiExplorerLink,\n externalTxLink: statusResponse?.bridgeExplorerLink,\n gasCosts: [\n {\n amount: statusResponse.sending.gasAmount,\n amountUSD: statusResponse.sending.gasAmountUSD,\n token: statusResponse.sending.gasToken,\n estimate: statusResponse.sending.gasUsed,\n limit: statusResponse.sending.gasUsed,\n price: statusResponse.sending.gasPrice,\n type: 'SEND',\n },\n ],\n })\n\n return { status: 'COMPLETED' }\n } catch (e: any) {\n const htmlMessage = await getTransactionFailedMessage(\n client,\n step,\n `${toChain.metamask.blockExplorerUrls[0]}tx/${transactionHash}`\n )\n throw new TransactionError(\n LiFiErrorCode.TransactionFailed,\n htmlMessage ??\n 'Failed while waiting for status of destination chain transaction.',\n e\n )\n }\n }\n}\n"],"mappings":";;;;;;AASA,IAAa,+BAAb,cAAkD,sBAAsB;CACtE;CAEA,YAAY,YAAiC;
|
|
1
|
+
{"version":3,"file":"WaitForTransactionStatusTask.js","names":[],"sources":["../../../../src/core/tasks/WaitForTransactionStatusTask.ts"],"sourcesContent":["import type { ExtendedTransactionInfo, FullStatusData } from '@lifi/types'\nimport { LiFiErrorCode } from '../../errors/constants.js'\nimport { TransactionError } from '../../errors/errors.js'\nimport type { ExecutionActionType } from '../../types/core.js'\nimport type { StepExecutorContext, TaskResult } from '../../types/execution.js'\nimport { getTransactionFailedMessage } from '../../utils/getTransactionMessage.js'\nimport { BaseStepExecutionTask } from '../BaseStepExecutionTask.js'\nimport { waitForTransactionStatus } from './helpers/waitForTransactionStatus.js'\n\nexport class WaitForTransactionStatusTask extends BaseStepExecutionTask {\n readonly actionType: ExecutionActionType\n\n constructor(actionType: ExecutionActionType) {\n super()\n this.actionType = actionType\n }\n\n async run(context: StepExecutorContext): Promise<TaskResult> {\n const {\n client,\n step,\n statusManager,\n pollingIntervalMs,\n toChain,\n isBridgeExecution,\n } = context\n\n // At this point, we should have a txHash or taskId\n // taskId is used for custom integrations that don't use the standard transaction hash\n let transactionHash: string | undefined\n try {\n const swapOrBridgeAction = statusManager.findAction(\n step,\n isBridgeExecution ? 'CROSS_CHAIN' : 'SWAP'\n )\n transactionHash = swapOrBridgeAction?.txHash || swapOrBridgeAction?.taskId\n\n // Wait for the transaction status on the destination chain\n if (!transactionHash) {\n throw new Error('Transaction hash is undefined.')\n }\n\n const action = statusManager.initializeAction({\n step,\n type: this.actionType,\n chainId:\n this.actionType === 'RECEIVING_CHAIN'\n ? step.action.toChainId\n : step.action.fromChainId,\n status: 'PENDING',\n })\n\n const statusResponse = (await waitForTransactionStatus(\n client,\n statusManager,\n transactionHash,\n step,\n action.type,\n pollingIntervalMs\n )) as FullStatusData\n\n const statusReceiving =\n statusResponse.receiving as ExtendedTransactionInfo\n\n // Update action status\n statusManager.updateAction(step, action.type, 'DONE', {\n chainId: statusReceiving?.chainId || toChain.id,\n substatus: statusResponse.substatus,\n substatusMessage: statusResponse.substatusMessage,\n txHash: statusReceiving?.txHash,\n txLink:\n statusReceiving?.txLink ||\n `${toChain.metamask.blockExplorerUrls[0]}tx/${statusReceiving?.txHash}`,\n })\n\n // Update execution status\n statusManager.updateExecution(step, {\n status: 'DONE',\n ...(statusResponse.sending.amount && {\n fromAmount: statusResponse.sending.amount,\n }),\n ...(statusReceiving?.amount && { toAmount: statusReceiving.amount }),\n ...(statusReceiving?.token && { toToken: statusReceiving.token }),\n internalTxLink: statusResponse?.lifiExplorerLink,\n externalTxLink: statusResponse?.bridgeExplorerLink,\n gasCosts: [\n {\n amount: statusResponse.sending.gasAmount,\n amountUSD: statusResponse.sending.gasAmountUSD,\n token: statusResponse.sending.gasToken,\n estimate: statusResponse.sending.gasUsed,\n limit: statusResponse.sending.gasUsed,\n price: statusResponse.sending.gasPrice,\n type: 'SEND',\n },\n ],\n })\n\n return { status: 'COMPLETED' }\n } catch (e: any) {\n const htmlMessage = await getTransactionFailedMessage(\n client,\n step,\n `${toChain.metamask.blockExplorerUrls[0]}tx/${transactionHash}`\n )\n throw new TransactionError(\n LiFiErrorCode.TransactionFailed,\n htmlMessage ??\n 'Failed while waiting for status of destination chain transaction.',\n e\n )\n }\n }\n}\n"],"mappings":";;;;;;AASA,IAAa,+BAAb,cAAkD,sBAAsB;CACtE;CAEA,YAAY,YAAiC;EAC3C,OAAO;EACP,KAAK,aAAa;;CAGpB,MAAM,IAAI,SAAmD;EAC3D,MAAM,EACJ,QACA,MACA,eACA,mBACA,SACA,sBACE;EAIJ,IAAI;EACJ,IAAI;GACF,MAAM,qBAAqB,cAAc,WACvC,MACA,oBAAoB,gBAAgB,OACrC;GACD,kBAAkB,oBAAoB,UAAU,oBAAoB;GAGpE,IAAI,CAAC,iBACH,MAAM,IAAI,MAAM,iCAAiC;GAGnD,MAAM,SAAS,cAAc,iBAAiB;IAC5C;IACA,MAAM,KAAK;IACX,SACE,KAAK,eAAe,oBAChB,KAAK,OAAO,YACZ,KAAK,OAAO;IAClB,QAAQ;IACT,CAAC;GAEF,MAAM,iBAAkB,MAAM,yBAC5B,QACA,eACA,iBACA,MACA,OAAO,MACP,kBACD;GAED,MAAM,kBACJ,eAAe;GAGjB,cAAc,aAAa,MAAM,OAAO,MAAM,QAAQ;IACpD,SAAS,iBAAiB,WAAW,QAAQ;IAC7C,WAAW,eAAe;IAC1B,kBAAkB,eAAe;IACjC,QAAQ,iBAAiB;IACzB,QACE,iBAAiB,UACjB,GAAG,QAAQ,SAAS,kBAAkB,GAAG,KAAK,iBAAiB;IAClE,CAAC;GAGF,cAAc,gBAAgB,MAAM;IAClC,QAAQ;IACR,GAAI,eAAe,QAAQ,UAAU,EACnC,YAAY,eAAe,QAAQ,QACpC;IACD,GAAI,iBAAiB,UAAU,EAAE,UAAU,gBAAgB,QAAQ;IACnE,GAAI,iBAAiB,SAAS,EAAE,SAAS,gBAAgB,OAAO;IAChE,gBAAgB,gBAAgB;IAChC,gBAAgB,gBAAgB;IAChC,UAAU,CACR;KACE,QAAQ,eAAe,QAAQ;KAC/B,WAAW,eAAe,QAAQ;KAClC,OAAO,eAAe,QAAQ;KAC9B,UAAU,eAAe,QAAQ;KACjC,OAAO,eAAe,QAAQ;KAC9B,OAAO,eAAe,QAAQ;KAC9B,MAAM;KACP,CACF;IACF,CAAC;GAEF,OAAO,EAAE,QAAQ,aAAa;WACvB,GAAQ;GAMf,MAAM,IAAI,iBAAA,MAER,MAPwB,4BACxB,QACA,MACA,GAAG,QAAQ,SAAS,kBAAkB,GAAG,KAAK,kBAC/C,IAIG,qEACF,EACD"}
|
|
@@ -77,7 +77,9 @@ const checkBalance = async (client, walletAddress, step, options = {}) => {
|
|
|
77
77
|
const { req, have } = insufficient[0];
|
|
78
78
|
const reserved = reservedOverhead(req);
|
|
79
79
|
if (have >= req.sourcePart * slippageScaled / SLIPPAGE_PRECISION + reserved) {
|
|
80
|
-
|
|
80
|
+
const newFromAmount = (have - reserved).toString();
|
|
81
|
+
step.action.fromAmount = newFromAmount;
|
|
82
|
+
if (step.includedSteps?.length) step.includedSteps[0].action.fromAmount = newFromAmount;
|
|
81
83
|
return;
|
|
82
84
|
}
|
|
83
85
|
}
|
|
@@ -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 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":"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"}
|
|
1
|
+
{"version":3,"file":"checkBalance.js","names":[],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"sourcesContent":["import type { LiFiStep, Token, TokenAmount } from '@lifi/types'\nimport { BalanceError } from '../../../errors/errors.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { formatUnits } from '../../../utils/formatUnits.js'\nimport { sleep } from '../../../utils/sleep.js'\nimport { withTimeout } from '../../../utils/withTimeout.js'\n\nconst MAX_ATTEMPTS = 6\n// Exponential backoff: 150, 300, 600, 1200, 2400 → ≈4.65s of sleep total.\nconst BACKOFF_BASE_MS = 150\nconst OVERALL_TIMEOUT_MS = 10_000\nconst SLIPPAGE_PRECISION = 1_000_000_000n\n\ntype Bucket = 'source' | 'gas' | 'fee'\n\ntype Requirement = {\n token: Token\n sourcePart: bigint // step.action.fromAmount\n gasPart: bigint // step.estimate.gasCosts in this token\n feePart: bigint // non-included step.estimate.feeCosts in this token\n}\n\nexport type CheckBalanceOptions = {\n /**\n * Set to `false` when outer-tx gas is paid by something other than\n * `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):\n * `gasPart` is excluded from the sufficiency check and slippage rescue.\n * Source amount and non-included fees (e.g. LZ `msg.value`) are still\n * verified. Defaults to `true` (strict, today's behavior).\n */\n walletPaysGas?: boolean\n}\n\n/**\n * Verifies that the wallet holds enough of every token required to execute\n * the step on its source chain — the source-token amount, any gas costs, and\n * any non-included fee costs. Reads all balances in one batched provider\n * call, retries within a bounded budget to absorb transient RPC failures and\n * post-confirmation propagation lag, and applies slippage to the source-token\n * portion only as a last resort (overhead is never trimmed).\n *\n * Throws BalanceError(\"The balance is too low.\") on a genuine shortfall, or\n * BalanceError(\"Could not read wallet balance.\") if the balance can't be read\n * after retries.\n */\nexport const checkBalance = async (\n client: SDKClient,\n walletAddress: string,\n step: LiFiStep,\n options: CheckBalanceOptions = {}\n): Promise<void> => {\n const 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 const newFromAmount = (have - reserved).toString()\n step.action.fromAmount = newFromAmount\n if (step.includedSteps?.length) {\n step.includedSteps[0].action.fromAmount = newFromAmount\n }\n return\n }\n }\n\n if (isFinal) {\n if (unknown.length > 0) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n new Error(\n `Could not read balance for: ${unknown\n .map((t) => t.symbol || t.address)\n .join(', ')}.`\n )\n )\n }\n const lines = insufficient.map(({ req, have }) => {\n const needed = formatUnits(need(req), req.token.decimals)\n const current = formatUnits(have, req.token.decimals)\n const symbol = req.token.symbol\n // The \"fees\" branch covers pure-overhead tokens; with\n // walletPaysGas=false, gas is excluded from `need(req)` so it\n // only fires for genuine fee shortfalls.\n return req.sourcePart > 0n\n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.`\n : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`\n })\n throw new BalanceError(\n 'The balance is too low.',\n new Error(`${lines.join(' ')} No funds have been sent.`)\n )\n }\n\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n }\n },\n {\n timeout: OVERALL_TIMEOUT_MS,\n errorInstance: new BalanceError('Could not read wallet balance.'),\n }\n )\n}\n"],"mappings":"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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"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;
|
|
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;CACpB,IAAI,CAAC,KAAK,oBAAoB,MAC5B,MAAM,IAAI,iBAAA,MAER,wEACD;CAGH,IAAI,qBAA4C,EAC9C,MAAM,KAAK,mBAAmB,MAC/B;CAED,IAAI,kBAAkB,8BAA8B;EAClD,MAAM,+BACJ,MAAM,iBAAiB,6BAA6B;GAClD,aAAa;GACb,GAAG;GACJ,CAAC;EAEJ,qBAAqB;GACnB,GAAG;GACH,GAAG;GACJ;;CAGH,MAAM,yBAAyB,mBAAmB;CAElD,IAAI,CAAC,wBACH,MAAM,IAAI,iBAAA,MAER,wEACD;CAGH,OAAO"}
|
|
@@ -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;
|
|
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;CAEtB,IAAI,2BAA2B,SAAS,QAAQ,EAC9C,OAAO,cAAc,kBAAkB,QAAQ;CAGjD,IAAI;CACJ,IAAI,sBACF,kBAAkB,MAAM,kBAAkB,+BAA+B;EACvE,aAAa,QAAQ,SAAS;EAC9B,aAAa,QAAQ,SAAS;EAC9B,SAAS,QAAQ,OAAO;EACzB,CAAC;CAGJ,IAAI,CAAC,iBAEH,MAAM,IAAI,iBAAA,MAER,gMACD;CAGH,OAAO,cAAc,kBAAkB,QAAQ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"waitForTransactionStatus.js","names":[],"sources":["../../../../../src/core/tasks/helpers/waitForTransactionStatus.ts"],"sourcesContent":["import type { FullStatusData, LiFiStep, StatusResponse } from '@lifi/types'\nimport { getStatus } from '../../../actions/getStatus.js'\nimport { ServerError } from '../../../errors/errors.js'\nimport type { ExecutionActionType, SDKClient } from '../../../types/core.js'\nimport { waitForResult } from '../../../utils/waitForResult.js'\nimport { getSubstatusMessage } from '../../actionMessages.js'\nimport type { StatusManager } from '../../StatusManager.js'\n\nconst TRANSACTION_HASH_OBSERVERS: Record<string, Promise<StatusResponse>> = {}\n\nexport async function waitForTransactionStatus(\n client: SDKClient,\n statusManager: StatusManager,\n txHash: string,\n step: LiFiStep,\n actionType: ExecutionActionType,\n interval = 5_000\n): Promise<StatusResponse> {\n const _getStatus = (): Promise<StatusResponse | undefined> => {\n return getStatus(client, {\n fromChain: step.action.fromChainId,\n fromAddress: step.action.fromAddress,\n toChain: step.action.toChainId,\n txHash,\n ...(step.tool !== 'custom' && { bridge: step.tool }),\n ...(step.transactionId && { transactionId: step.transactionId }),\n })\n .then((statusResponse) => {\n switch (statusResponse.status) {\n case 'DONE':\n return statusResponse\n case 'PENDING':\n statusManager?.updateAction(step, actionType, 'PENDING', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(\n statusResponse.status,\n statusResponse.substatus\n ),\n txLink: (statusResponse as FullStatusData).bridgeExplorerLink,\n })\n return undefined\n case 'NOT_FOUND':\n return undefined\n default:\n return Promise.reject()\n }\n })\n .catch((e) => {\n if (process.env.NODE_ENV === 'development') {\n console.debug('Fetching status from backend failed.', e)\n }\n return undefined\n })\n }\n\n let status = TRANSACTION_HASH_OBSERVERS[txHash]\n\n if (!status) {\n status = waitForResult(_getStatus, interval).finally(() => {\n delete TRANSACTION_HASH_OBSERVERS[txHash]\n })\n TRANSACTION_HASH_OBSERVERS[txHash] = status\n }\n\n const resolvedStatus = await status\n\n if (!('receiving' in resolvedStatus)) {\n throw new ServerError(\n \"Status doesn't contain destination chain information.\"\n )\n }\n\n return resolvedStatus\n}\n"],"mappings":";;;;;AAQA,MAAM,6BAAsE,EAAE;AAE9E,eAAsB,yBACpB,QACA,eACA,QACA,MACA,YACA,WAAW,KACc;CACzB,MAAM,mBAAwD;
|
|
1
|
+
{"version":3,"file":"waitForTransactionStatus.js","names":[],"sources":["../../../../../src/core/tasks/helpers/waitForTransactionStatus.ts"],"sourcesContent":["import type { FullStatusData, LiFiStep, StatusResponse } from '@lifi/types'\nimport { getStatus } from '../../../actions/getStatus.js'\nimport { ServerError } from '../../../errors/errors.js'\nimport type { ExecutionActionType, SDKClient } from '../../../types/core.js'\nimport { waitForResult } from '../../../utils/waitForResult.js'\nimport { getSubstatusMessage } from '../../actionMessages.js'\nimport type { StatusManager } from '../../StatusManager.js'\n\nconst TRANSACTION_HASH_OBSERVERS: Record<string, Promise<StatusResponse>> = {}\n\nexport async function waitForTransactionStatus(\n client: SDKClient,\n statusManager: StatusManager,\n txHash: string,\n step: LiFiStep,\n actionType: ExecutionActionType,\n interval = 5_000\n): Promise<StatusResponse> {\n const _getStatus = (): Promise<StatusResponse | undefined> => {\n return getStatus(client, {\n fromChain: step.action.fromChainId,\n fromAddress: step.action.fromAddress,\n toChain: step.action.toChainId,\n txHash,\n ...(step.tool !== 'custom' && { bridge: step.tool }),\n ...(step.transactionId && { transactionId: step.transactionId }),\n })\n .then((statusResponse) => {\n switch (statusResponse.status) {\n case 'DONE':\n return statusResponse\n case 'PENDING':\n statusManager?.updateAction(step, actionType, 'PENDING', {\n substatus: statusResponse.substatus,\n substatusMessage:\n statusResponse.substatusMessage ||\n getSubstatusMessage(\n statusResponse.status,\n statusResponse.substatus\n ),\n txLink: (statusResponse as FullStatusData).bridgeExplorerLink,\n })\n return undefined\n case 'NOT_FOUND':\n return undefined\n default:\n return Promise.reject()\n }\n })\n .catch((e) => {\n if (process.env.NODE_ENV === 'development') {\n console.debug('Fetching status from backend failed.', e)\n }\n return undefined\n })\n }\n\n let status = TRANSACTION_HASH_OBSERVERS[txHash]\n\n if (!status) {\n status = waitForResult(_getStatus, interval).finally(() => {\n delete TRANSACTION_HASH_OBSERVERS[txHash]\n })\n TRANSACTION_HASH_OBSERVERS[txHash] = status\n }\n\n const resolvedStatus = await status\n\n if (!('receiving' in resolvedStatus)) {\n throw new ServerError(\n \"Status doesn't contain destination chain information.\"\n )\n }\n\n return resolvedStatus\n}\n"],"mappings":";;;;;AAQA,MAAM,6BAAsE,EAAE;AAE9E,eAAsB,yBACpB,QACA,eACA,QACA,MACA,YACA,WAAW,KACc;CACzB,MAAM,mBAAwD;EAC5D,OAAO,UAAU,QAAQ;GACvB,WAAW,KAAK,OAAO;GACvB,aAAa,KAAK,OAAO;GACzB,SAAS,KAAK,OAAO;GACrB;GACA,GAAI,KAAK,SAAS,YAAY,EAAE,QAAQ,KAAK,MAAM;GACnD,GAAI,KAAK,iBAAiB,EAAE,eAAe,KAAK,eAAe;GAChE,CAAC,CACC,MAAM,mBAAmB;GACxB,QAAQ,eAAe,QAAvB;IACE,KAAK,QACH,OAAO;IACT,KAAK;KACH,eAAe,aAAa,MAAM,YAAY,WAAW;MACvD,WAAW,eAAe;MAC1B,kBACE,eAAe,oBACf,oBACE,eAAe,QACf,eAAe,UAChB;MACH,QAAS,eAAkC;MAC5C,CAAC;KACF;IACF,KAAK,aACH;IACF,SACE,OAAO,QAAQ,QAAQ;;IAE3B,CACD,OAAO,MAAM;GACZ,IAAI,QAAQ,IAAI,aAAa,eAC3B,QAAQ,MAAM,wCAAwC,EAAE;IAG1D;;CAGN,IAAI,SAAS,2BAA2B;CAExC,IAAI,CAAC,QAAQ;EACX,SAAS,cAAc,YAAY,SAAS,CAAC,cAAc;GACzD,OAAO,2BAA2B;IAClC;EACF,2BAA2B,UAAU;;CAGvC,MAAM,iBAAiB,MAAM;CAE7B,IAAI,EAAE,eAAe,iBACnB,MAAM,IAAI,YACR,wDACD;CAGH,OAAO"}
|
|
@@ -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,YACe;CAEpE,IAAI,iBAAiB;
|
|
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;CACrB,IAAI,uBAAuB,GACzB,iBACE,OAAQ,mBAAmB,cAAkB,qBAAqB,GAClE;CAEJ,OAAO,kBAAkB;;AAG3B,SAAgB,qBACd,iBACA,QACA,YACS;CACT,MAAM,oBAAoB,OAAO,QAAQ,SAAS,UAAU;EAC1D,IAAI,MAAM,UAAU,SAAS,QAC3B,QAAQ,MAAM,MAAiB,MAAM,SAAS;EAEhD,OAAO;IACN,EAAE,CAAY;CACjB,MAAM,SAAS,EAAE,GAAG,iBAAiB;CACrC,KAAK,MAAM,cAAc,mBAAmB;EAC1C,MAAM,UAAU,OAAO,WAAW;EAClC,MAAM,OAAO,kBAAkB;EAC/B,IAAI,CAAC,MAAM,QACT;EAEF,IAAI,CAAC,OAAO,UAAU,QACpB,OAAO,WAAW,MAAM,KAAK,KAAK;OAC7B,IAAI,CAAC,YAAY,SAAS,QAAQ,EAAE;GACzC,MAAM,eAAe,KAAK,QAAQ,QAAQ,CAAC,OAAO,UAAU,SAAS,IAAI,CAAC;GAC1E,OAAO,SAAS,KAAK,GAAG,aAAa;;;CAGzC,OAAO"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SDKError.js","names":[],"sources":["../../../src/errors/SDKError.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport type { ExecutionAction } from '../types/core.js'\nimport { version } from '../version.js'\nimport type { BaseError } from './baseError.js'\nimport type { ErrorCode } from './constants.js'\n\n// Note: SDKError is used to wrapper and present errors at the top level\n// Where opportunity allows we also add the step and the action related to the error\nexport class SDKError extends Error {\n step?: LiFiStep\n action?: ExecutionAction\n code: ErrorCode\n override name = 'SDKError'\n override cause: BaseError\n\n constructor(cause: BaseError, step?: LiFiStep, action?: ExecutionAction) {\n const errorMessage = `${cause.message ? `[${cause.name}] ${cause.message}` : 'Unknown error occurred'}\\nLI.FI SDK version: ${version}`\n super(errorMessage)\n this.name = 'SDKError'\n this.step = step\n this.action = action\n this.cause = cause\n this.stack = this.cause.stack\n this.code = cause.code\n }\n}\n"],"mappings":";;AAQA,IAAa,WAAb,cAA8B,MAAM;CAClC;CACA;CACA;CACA,OAAgB;CAChB;CAEA,YAAY,OAAkB,MAAiB,QAA0B;EACvE,MAAM,eAAe,GAAG,MAAM,UAAU,IAAI,MAAM,KAAK,IAAI,MAAM,YAAY,yBAAyB,uBAAuB;
|
|
1
|
+
{"version":3,"file":"SDKError.js","names":[],"sources":["../../../src/errors/SDKError.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport type { ExecutionAction } from '../types/core.js'\nimport { version } from '../version.js'\nimport type { BaseError } from './baseError.js'\nimport type { ErrorCode } from './constants.js'\n\n// Note: SDKError is used to wrapper and present errors at the top level\n// Where opportunity allows we also add the step and the action related to the error\nexport class SDKError extends Error {\n step?: LiFiStep\n action?: ExecutionAction\n code: ErrorCode\n override name = 'SDKError'\n override cause: BaseError\n\n constructor(cause: BaseError, step?: LiFiStep, action?: ExecutionAction) {\n const errorMessage = `${cause.message ? `[${cause.name}] ${cause.message}` : 'Unknown error occurred'}\\nLI.FI SDK version: ${version}`\n super(errorMessage)\n this.name = 'SDKError'\n this.step = step\n this.action = action\n this.cause = cause\n this.stack = this.cause.stack\n this.code = cause.code\n }\n}\n"],"mappings":";;AAQA,IAAa,WAAb,cAA8B,MAAM;CAClC;CACA;CACA;CACA,OAAgB;CAChB;CAEA,YAAY,OAAkB,MAAiB,QAA0B;EACvE,MAAM,eAAe,GAAG,MAAM,UAAU,IAAI,MAAM,KAAK,IAAI,MAAM,YAAY,yBAAyB,uBAAuB;EAC7H,MAAM,aAAa;EACnB,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,SAAS;EACd,KAAK,QAAQ;EACb,KAAK,QAAQ,KAAK,MAAM;EACxB,KAAK,OAAO,MAAM"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"baseError.js","names":[],"sources":["../../../src/errors/baseError.ts"],"sourcesContent":["import type { ErrorCode, ErrorName } from './constants.js'\nimport { getRootCause } from './utils/rootCause.js'\n\n// Note: we use the BaseErrors to capture errors at specific points in the code\n// they can carry addition to help give more context\nexport class BaseError extends Error {\n code: ErrorCode\n override cause?: Error\n\n constructor(name: ErrorName, code: number, message: string, cause?: Error) {\n super(message)\n\n this.name = name\n this.code = code\n this.cause = cause\n\n const rootCause = getRootCause(this.cause)\n if (rootCause?.stack) {\n this.stack = rootCause.stack\n }\n }\n}\n"],"mappings":";;AAKA,IAAa,YAAb,cAA+B,MAAM;CACnC;CACA;CAEA,YAAY,MAAiB,MAAc,SAAiB,OAAe;
|
|
1
|
+
{"version":3,"file":"baseError.js","names":[],"sources":["../../../src/errors/baseError.ts"],"sourcesContent":["import type { ErrorCode, ErrorName } from './constants.js'\nimport { getRootCause } from './utils/rootCause.js'\n\n// Note: we use the BaseErrors to capture errors at specific points in the code\n// they can carry addition to help give more context\nexport class BaseError extends Error {\n code: ErrorCode\n override cause?: Error\n\n constructor(name: ErrorName, code: number, message: string, cause?: Error) {\n super(message)\n\n this.name = name\n this.code = code\n this.cause = cause\n\n const rootCause = getRootCause(this.cause)\n if (rootCause?.stack) {\n this.stack = rootCause.stack\n }\n }\n}\n"],"mappings":";;AAKA,IAAa,YAAb,cAA+B,MAAM;CACnC;CACA;CAEA,YAAY,MAAiB,MAAc,SAAiB,OAAe;EACzE,MAAM,QAAQ;EAEd,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;EAEb,MAAM,YAAY,aAAa,KAAK,MAAM;EAC1C,IAAI,WAAW,OACb,KAAK,QAAQ,UAAU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","names":[],"sources":["../../../src/errors/constants.ts"],"sourcesContent":["export enum ErrorName {\n RPCError = 'RPCError',\n ProviderError = 'ProviderError',\n ServerError = 'ServerError',\n TransactionError = 'TransactionError',\n ValidationError = 'ValidationError',\n BalanceError = 'BalanceError',\n NotFoundError = 'NotFoundError',\n UnknownError = 'UnknownError',\n SlippageError = 'SlippageError',\n HTTPError = 'HTTPError',\n ConfigError = 'ConfigError',\n ExecuteStepRetryError = 'ExecuteStepRetryError',\n}\n\nexport type ErrorCode = LiFiErrorCode\n\nexport enum LiFiErrorCode {\n InternalError = 1000,\n ValidationError = 1001,\n TransactionUnderpriced = 1002,\n TransactionFailed = 1003,\n Timeout = 1004,\n ProviderUnavailable = 1005,\n NotFound = 1006,\n ChainSwitchError = 1007,\n TransactionUnprepared = 1008,\n GasLimitError = 1009,\n TransactionCanceled = 1010,\n SlippageError = 1011,\n SignatureRejected = 1012,\n BalanceError = 1013,\n AllowanceRequired = 1014,\n InsufficientFunds = 1015,\n ExchangeRateUpdateCanceled = 1016,\n WalletChangedDuringExecution = 1017,\n TransactionExpired = 1018,\n TransactionSimulationFailed = 1019,\n TransactionConflict = 1020,\n TransactionNotFound = 1021,\n TransactionRejected = 1022,\n RateLimitExceeded = 1023,\n ThirdPartyError = 1024,\n InsufficientGas = 1025,\n ConfigError = 1026,\n}\n\nexport enum ErrorMessage {\n UnknownError = 'Unknown error occurred.',\n SlippageError = 'The slippage is larger than the defined threshold. Please request a new route to get a fresh quote.',\n GasLimitLow = 'Gas limit is too low.',\n TransactionUnderpriced = 'Transaction is underpriced.',\n TransactionReverted = 'Transaction was reverted.',\n}\n"],"mappings":";AAAA,IAAY,YAAL,yBAAA,WAAA;
|
|
1
|
+
{"version":3,"file":"constants.js","names":[],"sources":["../../../src/errors/constants.ts"],"sourcesContent":["export enum ErrorName {\n RPCError = 'RPCError',\n ProviderError = 'ProviderError',\n ServerError = 'ServerError',\n TransactionError = 'TransactionError',\n ValidationError = 'ValidationError',\n BalanceError = 'BalanceError',\n NotFoundError = 'NotFoundError',\n UnknownError = 'UnknownError',\n SlippageError = 'SlippageError',\n HTTPError = 'HTTPError',\n ConfigError = 'ConfigError',\n ExecuteStepRetryError = 'ExecuteStepRetryError',\n}\n\nexport type ErrorCode = LiFiErrorCode\n\nexport enum LiFiErrorCode {\n InternalError = 1000,\n ValidationError = 1001,\n TransactionUnderpriced = 1002,\n TransactionFailed = 1003,\n Timeout = 1004,\n ProviderUnavailable = 1005,\n NotFound = 1006,\n ChainSwitchError = 1007,\n TransactionUnprepared = 1008,\n GasLimitError = 1009,\n TransactionCanceled = 1010,\n SlippageError = 1011,\n SignatureRejected = 1012,\n BalanceError = 1013,\n AllowanceRequired = 1014,\n InsufficientFunds = 1015,\n ExchangeRateUpdateCanceled = 1016,\n WalletChangedDuringExecution = 1017,\n TransactionExpired = 1018,\n TransactionSimulationFailed = 1019,\n TransactionConflict = 1020,\n TransactionNotFound = 1021,\n TransactionRejected = 1022,\n RateLimitExceeded = 1023,\n ThirdPartyError = 1024,\n InsufficientGas = 1025,\n ConfigError = 1026,\n}\n\nexport enum ErrorMessage {\n UnknownError = 'Unknown error occurred.',\n SlippageError = 'The slippage is larger than the defined threshold. Please request a new route to get a fresh quote.',\n GasLimitLow = 'Gas limit is too low.',\n TransactionUnderpriced = 'Transaction is underpriced.',\n TransactionReverted = 'Transaction was reverted.',\n}\n"],"mappings":";AAAA,IAAY,YAAL,yBAAA,WAAA;CACL,UAAA,cAAA;CACA,UAAA,mBAAA;CACA,UAAA,iBAAA;CACA,UAAA,sBAAA;CACA,UAAA,qBAAA;CACA,UAAA,kBAAA;CACA,UAAA,mBAAA;CACA,UAAA,kBAAA;CACA,UAAA,mBAAA;CACA,UAAA,eAAA;CACA,UAAA,iBAAA;CACA,UAAA,2BAAA;;KACD;AAID,IAAY,gBAAL,yBAAA,eAAA;CACL,cAAA,cAAA,mBAAA,OAAA;CACA,cAAA,cAAA,qBAAA,QAAA;CACA,cAAA,cAAA,4BAAA,QAAA;CACA,cAAA,cAAA,uBAAA,QAAA;CACA,cAAA,cAAA,aAAA,QAAA;CACA,cAAA,cAAA,yBAAA,QAAA;CACA,cAAA,cAAA,cAAA,QAAA;CACA,cAAA,cAAA,sBAAA,QAAA;CACA,cAAA,cAAA,2BAAA,QAAA;CACA,cAAA,cAAA,mBAAA,QAAA;CACA,cAAA,cAAA,yBAAA,QAAA;CACA,cAAA,cAAA,mBAAA,QAAA;CACA,cAAA,cAAA,uBAAA,QAAA;CACA,cAAA,cAAA,kBAAA,QAAA;CACA,cAAA,cAAA,uBAAA,QAAA;CACA,cAAA,cAAA,uBAAA,QAAA;CACA,cAAA,cAAA,gCAAA,QAAA;CACA,cAAA,cAAA,kCAAA,QAAA;CACA,cAAA,cAAA,wBAAA,QAAA;CACA,cAAA,cAAA,iCAAA,QAAA;CACA,cAAA,cAAA,yBAAA,QAAA;CACA,cAAA,cAAA,yBAAA,QAAA;CACA,cAAA,cAAA,yBAAA,QAAA;CACA,cAAA,cAAA,uBAAA,QAAA;CACA,cAAA,cAAA,qBAAA,QAAA;CACA,cAAA,cAAA,qBAAA,QAAA;CACA,cAAA,cAAA,iBAAA,QAAA;;KACD;AAED,IAAY,eAAL,yBAAA,cAAA;CACL,aAAA,kBAAA;CACA,aAAA,mBAAA;CACA,aAAA,iBAAA;CACA,aAAA,4BAAA;CACA,aAAA,yBAAA;;KACD"}
|
|
@@ -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;
|
|
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;EAC/D,MAAA,YAA0B,MAAM,SAAS,MAAM;;;AAInD,IAAa,gBAAb,cAAmC,UAAU;CAC3C,YAAY,MAAqB,SAAiB,OAAe;EAC/D,MAAA,iBAA+B,MAAM,SAAS,MAAM;;;AAIxD,IAAa,mBAAb,cAAsC,UAAU;CAC9C,YAAY,MAAqB,SAAiB,OAAe;EAC/D,MAAA,oBAAkC,MAAM,SAAS,MAAM;;;AAI3D,IAAa,eAAb,cAAkC,UAAU;CAC1C,YAAY,SAAiB,OAAe;EAC1C,MAAA,gBAAA,KAA2D,SAAS,MAAM;;;AAI9E,IAAa,eAAb,cAAkC,UAAU;CAC1C,YAAY,SAAiB,OAAe;EAC1C,MAAA,gBAAA,MAA0D,SAAS,MAAM;;;AAI7E,IAAa,cAAb,cAAiC,UAAU;CACzC,YAAY,SAAiB;EAC3B,MAAA,eAAA,KAA0D,QAAQ;;;AAItE,IAAa,kBAAb,cAAqC,UAAU;CAC7C,YAAY,SAAiB;EAC3B,MAAA,mBAAA,MAAgE,QAAQ;;;;;;;;AAS5E,IAAa,wBAAb,cAA2C,UAAU;CACnD;CAEA,YACE,SACA,aACA,OACA;EACA,MAAA,yBAAA,KAGE,SACA,MACD;EACD,KAAK,cAAc"}
|
|
@@ -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"],"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;
|
|
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;CAE9C,OAAO,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;EAEjD,MAAA,aAA2B,oBAAoB,MAAM,QAAQ;EAE7D,KAAK,OAAO,oBAAoB;EAChC,KAAK,WAAW;EAChB,KAAK,SAAS,SAAS;EACvB,KAAK,UAAU;EACf,KAAK,MAAM;EACX,KAAK,eAAe;;CAGtB,MAAM,yBAAwC;EAC5C,IAAI,KAAK,MACP,KAAK,UAAU,IAAI,KAAK,KAAK,IAAI,KAAK;EAGxC,IAAI;GACF,KAAK,eAAe,MAAM,KAAK,SAAS,MAAM;GAE9C,IAAI,KAAK,cAAc,SACrB,KAAK,WAAW,KAAK,QAAQ,SAAS,IAAI,GACtC,IAAI,KAAK,aAAa,QAAQ,UAAU,KACxC,KAAK,KAAK,aAAa,QAAQ,UAAU;UAEzC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"baseErrorRootCause.js","names":[],"sources":["../../../../src/errors/utils/baseErrorRootCause.ts"],"sourcesContent":["import { BaseError } from '../baseError.js'\nimport { HTTPError } from '../httpError.js'\n\nexport const getRootCauseBaseError = (e: Error): BaseError => {\n let rootCause = e\n while (rootCause.cause && rootCause.cause instanceof BaseError) {\n rootCause = rootCause.cause as BaseError\n }\n return rootCause as BaseError\n}\n\nexport const getRootCauseBaseErrorMessage = (e: Error): string => {\n const rootCause = getRootCauseBaseError(e)\n\n return rootCause instanceof HTTPError\n ? (rootCause as HTTPError).responseBody?.message || rootCause.message\n : rootCause.message\n}\n"],"mappings":";;;AAGA,MAAa,yBAAyB,MAAwB;CAC5D,IAAI,YAAY;
|
|
1
|
+
{"version":3,"file":"baseErrorRootCause.js","names":[],"sources":["../../../../src/errors/utils/baseErrorRootCause.ts"],"sourcesContent":["import { BaseError } from '../baseError.js'\nimport { HTTPError } from '../httpError.js'\n\nexport const getRootCauseBaseError = (e: Error): BaseError => {\n let rootCause = e\n while (rootCause.cause && rootCause.cause instanceof BaseError) {\n rootCause = rootCause.cause as BaseError\n }\n return rootCause as BaseError\n}\n\nexport const getRootCauseBaseErrorMessage = (e: Error): string => {\n const rootCause = getRootCauseBaseError(e)\n\n return rootCause instanceof HTTPError\n ? (rootCause as HTTPError).responseBody?.message || rootCause.message\n : rootCause.message\n}\n"],"mappings":";;;AAGA,MAAa,yBAAyB,MAAwB;CAC5D,IAAI,YAAY;CAChB,OAAO,UAAU,SAAS,UAAU,iBAAiB,WACnD,YAAY,UAAU;CAExB,OAAO;;AAGT,MAAa,gCAAgC,MAAqB;CAChE,MAAM,YAAY,sBAAsB,EAAE;CAE1C,OAAO,qBAAqB,YACvB,UAAwB,cAAc,WAAW,UAAU,UAC5D,UAAU"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rootCause.js","names":[],"sources":["../../../../src/errors/utils/rootCause.ts"],"sourcesContent":["export const getRootCause = (e: Error | undefined): Error | undefined => {\n let rootCause = e\n while (rootCause?.cause) {\n rootCause = rootCause.cause as Error\n }\n return rootCause\n}\n"],"mappings":";AAAA,MAAa,gBAAgB,MAA4C;CACvE,IAAI,YAAY;
|
|
1
|
+
{"version":3,"file":"rootCause.js","names":[],"sources":["../../../../src/errors/utils/rootCause.ts"],"sourcesContent":["export const getRootCause = (e: Error | undefined): Error | undefined => {\n let rootCause = e\n while (rootCause?.cause) {\n rootCause = rootCause.cause as Error\n }\n return rootCause\n}\n"],"mappings":";AAAA,MAAa,gBAAgB,MAA4C;CACvE,IAAI,YAAY;CAChB,OAAO,WAAW,OAChB,YAAY,UAAU;CAExB,OAAO"}
|
|
@@ -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.
|
|
7
|
+
const currentVersion = packageVersion ?? "4.0.0-beta.9";
|
|
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;
|
|
1
|
+
{"version":3,"file":"checkPackageUpdates.js","names":[],"sources":["../../../src/utils/checkPackageUpdates.ts"],"sourcesContent":["import { name, version } from '../version.js'\n\nexport const checkPackageUpdates = async (\n packageName?: string,\n packageVersion?: string\n): Promise<void> => {\n try {\n const pkgName = packageName ?? name\n const response = await fetch(`https://registry.npmjs.org/${pkgName}/latest`)\n const reponseBody = await response.json()\n const latestVersion = reponseBody.version\n const currentVersion = packageVersion ?? version\n\n if (latestVersion > currentVersion) {\n console.warn(\n `${pkgName}: new package version is available. Please update as soon as possible to enjoy the newest features. Current version: ${currentVersion}. Latest version: ${latestVersion}.`\n )\n }\n } catch (_error) {\n // Cannot verify version, might be network error etc. We don't bother showing anything in that case\n }\n}\n"],"mappings":";;AAEA,MAAa,sBAAsB,OACjC,aACA,mBACkB;CAClB,IAAI;EACF,MAAM,UAAU,eAAA;EAGhB,MAAM,iBAAgB,OADI,MADH,MAAM,8BAA8B,QAAQ,SAAS,EACzC,MAAM,EACP;EAClC,MAAM,iBAAiB,kBAAA;EAEvB,IAAI,gBAAgB,gBAClB,QAAQ,KACN,GAAG,QAAQ,uHAAuH,eAAe,oBAAoB,cAAc,GACpL;UAEI,QAAQ"}
|