@lifi/sdk 4.0.0-beta.7 → 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 +2 -2
- package/dist/cjs/actions/getRelayedTransactionStatus.js.map +1 -1
- package/dist/cjs/actions/getRelayerQuote.js +2 -2
- 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 +2 -2
- 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 +2 -2
- 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.d.ts +9 -0
- package/dist/cjs/core/tasks/CheckBalanceTask.js +13 -3
- package/dist/cjs/core/tasks/CheckBalanceTask.js.map +1 -1
- package/dist/cjs/core/tasks/PrepareTransactionTask.js +3 -3
- package/dist/cjs/core/tasks/PrepareTransactionTask.js.map +1 -1
- package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js +2 -2
- package/dist/cjs/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/checkBalance.d.ts +12 -2
- package/dist/cjs/core/tasks/helpers/checkBalance.js +21 -12
- package/dist/cjs/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/getTransactionRequestData.js +3 -3
- package/dist/cjs/core/tasks/helpers/getTransactionRequestData.js.map +1 -1
- package/dist/cjs/core/tasks/helpers/stepComparison.js +2 -2
- 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 +9 -9
- package/dist/cjs/errors/errors.js.map +1 -1
- package/dist/cjs/errors/httpError.js +17 -17
- 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/index.d.ts +2 -2
- package/dist/cjs/types/core.d.ts +0 -4
- 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 +2 -2
- package/dist/esm/actions/getRelayedTransactionStatus.js.map +1 -1
- package/dist/esm/actions/getRelayerQuote.js +2 -2
- 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 +2 -2
- 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 +2 -2
- 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.d.ts +9 -0
- package/dist/esm/core/tasks/CheckBalanceTask.d.ts.map +1 -1
- package/dist/esm/core/tasks/CheckBalanceTask.js +13 -3
- package/dist/esm/core/tasks/CheckBalanceTask.js.map +1 -1
- package/dist/esm/core/tasks/PrepareTransactionTask.js +3 -3
- package/dist/esm/core/tasks/PrepareTransactionTask.js.map +1 -1
- package/dist/esm/core/tasks/WaitForTransactionStatusTask.js +2 -3
- package/dist/esm/core/tasks/WaitForTransactionStatusTask.js.map +1 -1
- package/dist/esm/core/tasks/helpers/checkBalance.d.ts +12 -2
- package/dist/esm/core/tasks/helpers/checkBalance.d.ts.map +1 -1
- package/dist/esm/core/tasks/helpers/checkBalance.js +21 -12
- package/dist/esm/core/tasks/helpers/checkBalance.js.map +1 -1
- package/dist/esm/core/tasks/helpers/getTransactionRequestData.js +3 -3
- package/dist/esm/core/tasks/helpers/getTransactionRequestData.js.map +1 -1
- package/dist/esm/core/tasks/helpers/stepComparison.js +2 -2
- 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 +9 -9
- package/dist/esm/errors/errors.js.map +1 -1
- package/dist/esm/errors/httpError.js +17 -17
- 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/index.d.ts +2 -2
- package/dist/esm/types/core.d.ts +0 -4
- package/dist/esm/types/core.d.ts.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/CheckBalanceTask.ts +19 -2
- package/src/core/tasks/helpers/checkBalance.ts +57 -21
- package/src/index.ts +4 -1
- package/src/types/core.ts +0 -4
- package/src/version.ts +1 -1
|
@@ -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":";;;;;;AAqBA,IAAa,gBAAb,MAA2B;CACzB;CACA,eAAuB;CAEvB,YAAY,SAAiB;EAC3B,KAAK,UAAU;;;;;;;CAQjB,uBAAuB,SAAsC;EAC3D,IAAI,CAAC,KAAK,WAAW;GACnB,KAAK,YAAY;IACf,WAAW,KAAK,KAAK;IACrB,QAAQ;IACR,SAAS,EAAE;IACZ;GACD,KAAK,kBAAkB,KAAK;;EAI9B,IAAI,KAAK,UAAU,WAAW,UAAU;GACtC,KAAK,UAAU,YAAY,KAAK,KAAK;GACrC,KAAK,UAAU,SAAS;GACxB,KAAK,UAAU,WAAW,KAAA;GAC1B,KAAK,UAAU,QAAQ,KAAA;GACvB,KAAK,kBAAkB,KAAK;;EAG9B,OAAO,KAAK;;;;;;;;CASd,gBACE,MACA,WACU;EACV,IAAI,CAAC,KAAK,WACR,MAAM,MAAM,gCAAgC;EAE9C,KAAK,YAAY;GACf,GAAG,KAAK;GACR,GAAG;GACJ;EACD,KAAK,kBAAkB,KAAK;EAC5B,OAAO;;;;;;;;CAST,WACE,MACA,MAC6B;EAC7B,IAAI,CAAC,KAAK,WAAW,SACnB,MAAM,IAAI,MAAM,qCAAqC;EAKvD,OAFe,KAAK,UAAU,QAAQ,MAAM,MAAM,EAAE,SAAS,KAEhD;;;;;;;;;;;CAYf,gBAAgB,EACd,MACA,MACA,SACA,aACkC;EAClC,IAAI,CAAC,KAAK,WACR,MAAM,IAAI,MAAM,qCAAqC;EAGvD,MAAM,YAA6B;GACjC;GACA,SA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cACR,OAAO;EAET,MAAM,OAAO,eAAe,IAAI,KAAK,QAAQ;EAE7C,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,4BAA4B;EAG9C,MAAM,YAAY,KAAK,MAAM,MAAM,WAChC,cAAc,UAAU,OAAO,KAAK,GACtC;EAED,IAAI,cAAc,IAChB,MAAM,IAAI,MAAM,kCAAkC;EAGpD,KAAK,MAAM,MAAM,aAAa;GAAE,GAAG,KAAK,MAAM,MAAM;GAAY,GAAG;GAAM;EAEzE,KAAK,kBAAkB,kBAAkB,KAAK,MAAM;EACpD,OAAO,KAAK,MAAM,MAAM;;CAG1B,aAAa,OAAsB;EACjC,KAAK,eAAe"}
|
|
@@ -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,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "../errors/constants.js";
|
|
2
2
|
import { ExecuteStepRetryError, ProviderError } from "../errors/errors.js";
|
|
3
3
|
import { executionState } from "./executionState.js";
|
|
4
4
|
import { prepareRestart } from "./prepareRestart.js";
|
|
@@ -61,7 +61,7 @@ const executeSteps = async (client, route) => {
|
|
|
61
61
|
const fromAddress = step.action.fromAddress;
|
|
62
62
|
if (!fromAddress) throw new Error("Action fromAddress is not specified.");
|
|
63
63
|
const provider = client.providers.find((provider) => provider.isAddress(fromAddress));
|
|
64
|
-
if (!provider) throw new ProviderError(
|
|
64
|
+
if (!provider) throw new ProviderError(1005, "SDK Execution Provider not found.");
|
|
65
65
|
const stepExecutor = await provider.getStepExecutor({
|
|
66
66
|
routeId: route.id,
|
|
67
67
|
executionOptions: execution.executionOptions
|
|
@@ -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":";;;;;;;;;;;;;AAqBA,MAAa,eAAe,OAC1B,QACA,OACA,qBAC2B;CAE3B,MAAM,cAAc,gBAAuB,MAAM;CAEjD,IAAI,mBAAmB,eAAe,IAAI,YAAY,GAAG,EAAE;CAE3D,IAAI,kBACF,OAAO;CAGT,eAAe,OAAO;EAAE,OAAO;EAAa;EAAkB,CAAC;CAC/D,mBAAmB,aAAa,QAAQ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iB;GAGzD,IAAI;GACJ,IAAI;IACF,eAAe,MAAM,aAAa,YAAY,QAAQ,KAAK;YACpD,GAAG;IACV,IAAI,aAAa,uBAAuB;KACtC,KAAK,YAAY,KAAA;KACjB,eAAe,MAAM,aAAa,YAChC,QACA,MACA,EAAE,YACH;WAED,MAAM;;GAKV,IAAI,aAAa,WAAW,WAAW,QACrC,mBAAmB,MAAM;GAI3B,IAAI,CAAC,aAAa,gBAChB,OAAO;WAEF,GAAG;GACV,mBAAmB,MAAM;GACzB,MAAM;;;CAKV,eAAe,OAAO,MAAM,GAAG;CAC/B,OAAO;;;;;;;AAQT,MAAa,wBACX,OACA,YACS;CACT,MAAM,YAAY,eAAe,IAAI,MAAM,GAAG;CAC9C,IAAI,CAAC,WACH;CAGF,IAAI,yBAAyB,SAC3B,KAAK,MAAM,YAAY,UAAU,WAC/B,SAAS,eAAe;EACtB,kBAAkB,CAAC,SAAS;EAC5B,cAAc;EACf,CAAC;CAIN,UAAU,mBAAmB;EAC3B,GAAG,UAAU;EACb,GAAG;EACJ;;;;;;;AAQH,MAAa,sBAAsB,UAAwB;CACzD,MAAM,YAAY,eAAe,IAAI,MAAM,GAAG;CAC9C,IAAI,CAAC,WACH,OAAO;CAGT,KAAK,MAAM,YAAY,UAAU,WAC/B,SAAS,eAAe;EACtB,kBAAkB;EAClB,cAAc;EACd,gBAAgB;EACjB,CAAC;CAEJ,eAAe,OAAO,MAAM,GAAG;CAC/B,OAAO,UAAU;;;;;;AAOnB,MAAa,wBAAyC;CACpD,OAAO,OAAO,OAAO,eAAe,MAAM,CACvC,KAAK,SAAS,MAAM,MAAM,CAC1B,OAAO,QAAQ;;;;;;;AAQpB,MAAa,kBAAkB,YAA+C;CAC5E,OAAO,eAAe,IAAI,QAAQ,EAAE"}
|
|
@@ -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,8 +1,17 @@
|
|
|
1
1
|
import { StepExecutorContext, TaskResult } from "../../types/execution.js";
|
|
2
2
|
import { BaseStepExecutionTask } from "../BaseStepExecutionTask.js";
|
|
3
|
+
import { CheckBalanceOptions } from "./helpers/checkBalance.js";
|
|
3
4
|
|
|
4
5
|
//#region src/core/tasks/CheckBalanceTask.d.ts
|
|
5
6
|
declare class CheckBalanceTask extends BaseStepExecutionTask {
|
|
7
|
+
/**
|
|
8
|
+
* Per-step options hook for chain-specific subclasses (e.g. skip the
|
|
9
|
+
* gas check for smart-contract wallets or relayed steps). Default `{}`
|
|
10
|
+
* keeps behavior unchanged for every provider that doesn't override.
|
|
11
|
+
* Resolved lazily inside `run()` — pipelines that resume past
|
|
12
|
+
* `CheckBalance` pay no cost.
|
|
13
|
+
*/
|
|
14
|
+
protected getCheckBalanceOptions(_context: StepExecutorContext): Promise<CheckBalanceOptions>;
|
|
6
15
|
run(context: StepExecutorContext): Promise<TaskResult>;
|
|
7
16
|
}
|
|
8
17
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CheckBalanceTask.d.ts","names":[],"sources":["../../../../src/core/tasks/CheckBalanceTask.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"CheckBalanceTask.d.ts","names":[],"sources":["../../../../src/core/tasks/CheckBalanceTask.ts"],"mappings":";;;;;cASa,gBAAA,SAAyB,qBAAA;;AAAtC;;;;;;YAQY,sBAAA,CACR,QAAA,EAAU,mBAAA,GACT,OAAA,CAAQ,mBAAA;EAIX,GAAA,CAAU,OAAA,EAAS,mBAAA,GAAsB,OAAA,CAAQ,UAAA;AAAA"}
|
|
@@ -1,9 +1,19 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "../../errors/constants.js";
|
|
2
2
|
import { TransactionError } from "../../errors/errors.js";
|
|
3
3
|
import { BaseStepExecutionTask } from "../BaseStepExecutionTask.js";
|
|
4
4
|
import { checkBalance } from "./helpers/checkBalance.js";
|
|
5
5
|
//#region src/core/tasks/CheckBalanceTask.ts
|
|
6
6
|
var CheckBalanceTask = class extends BaseStepExecutionTask {
|
|
7
|
+
/**
|
|
8
|
+
* Per-step options hook for chain-specific subclasses (e.g. skip the
|
|
9
|
+
* gas check for smart-contract wallets or relayed steps). Default `{}`
|
|
10
|
+
* keeps behavior unchanged for every provider that doesn't override.
|
|
11
|
+
* Resolved lazily inside `run()` — pipelines that resume past
|
|
12
|
+
* `CheckBalance` pay no cost.
|
|
13
|
+
*/
|
|
14
|
+
getCheckBalanceOptions(_context) {
|
|
15
|
+
return Promise.resolve({});
|
|
16
|
+
}
|
|
7
17
|
async run(context) {
|
|
8
18
|
const { client, step, statusManager, isBridgeExecution } = context;
|
|
9
19
|
statusManager.initializeAction({
|
|
@@ -13,8 +23,8 @@ var CheckBalanceTask = class extends BaseStepExecutionTask {
|
|
|
13
23
|
status: "STARTED"
|
|
14
24
|
});
|
|
15
25
|
const walletAddress = step.action.fromAddress;
|
|
16
|
-
if (!walletAddress) throw new TransactionError(
|
|
17
|
-
await checkBalance(client, walletAddress, step);
|
|
26
|
+
if (!walletAddress) throw new TransactionError(1e3, "The wallet address is undefined.");
|
|
27
|
+
await checkBalance(client, walletAddress, step, await this.getCheckBalanceOptions(context));
|
|
18
28
|
return { status: "COMPLETED" };
|
|
19
29
|
}
|
|
20
30
|
};
|
|
@@ -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 { checkBalance
|
|
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,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "../../errors/constants.js";
|
|
2
2
|
import { TransactionError } from "../../errors/errors.js";
|
|
3
3
|
import { getStepTransaction } from "../../actions/getStepTransaction.js";
|
|
4
4
|
import { BaseStepExecutionTask } from "../BaseStepExecutionTask.js";
|
|
@@ -8,7 +8,7 @@ var PrepareTransactionTask = class extends BaseStepExecutionTask {
|
|
|
8
8
|
async run(context) {
|
|
9
9
|
const { client, step, statusManager, allowUserInteraction, executionOptions, isBridgeExecution } = context;
|
|
10
10
|
const action = statusManager.findAction(step, isBridgeExecution ? "CROSS_CHAIN" : "SWAP");
|
|
11
|
-
if (!action) throw new TransactionError(
|
|
11
|
+
if (!action) throw new TransactionError(1008, "Unable to prepare transaction. Action not found.");
|
|
12
12
|
if (!step.transactionRequest) {
|
|
13
13
|
const { execution, ...stepBase } = step;
|
|
14
14
|
const comparedStep = await stepComparison(statusManager, step, await getStepTransaction(client, stepBase), allowUserInteraction, executionOptions);
|
|
@@ -17,7 +17,7 @@ var PrepareTransactionTask = class extends BaseStepExecutionTask {
|
|
|
17
17
|
execution: step.execution
|
|
18
18
|
});
|
|
19
19
|
}
|
|
20
|
-
if (!step.transactionRequest?.data) throw new TransactionError(
|
|
20
|
+
if (!step.transactionRequest?.data) throw new TransactionError(1008, "Unable to prepare transaction. Transaction request data is not found.");
|
|
21
21
|
statusManager.updateAction(step, action.type, "ACTION_REQUIRED");
|
|
22
22
|
if (!allowUserInteraction) return { status: "PAUSED" };
|
|
23
23
|
return { status: "COMPLETED" };
|
|
@@ -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,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "../../errors/constants.js";
|
|
2
2
|
import { TransactionError } from "../../errors/errors.js";
|
|
3
3
|
import { BaseStepExecutionTask } from "../BaseStepExecutionTask.js";
|
|
4
4
|
import { getTransactionFailedMessage } from "../../utils/getTransactionMessage.js";
|
|
@@ -51,8 +51,7 @@ var WaitForTransactionStatusTask = class extends BaseStepExecutionTask {
|
|
|
51
51
|
});
|
|
52
52
|
return { status: "COMPLETED" };
|
|
53
53
|
} catch (e) {
|
|
54
|
-
|
|
55
|
-
throw new TransactionError(LiFiErrorCode.TransactionFailed, htmlMessage ?? "Failed while waiting for status of destination chain transaction.", e);
|
|
54
|
+
throw new TransactionError(1003, await getTransactionFailedMessage(client, step, `${toChain.metamask.blockExplorerUrls[0]}tx/${transactionHash}`) ?? "Failed while waiting for status of destination chain transaction.", e);
|
|
56
55
|
}
|
|
57
56
|
}
|
|
58
57
|
};
|
|
@@ -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"}
|
|
@@ -2,6 +2,16 @@ import { SDKClient } from "../../../types/core.js";
|
|
|
2
2
|
import { LiFiStep } from "@lifi/types";
|
|
3
3
|
|
|
4
4
|
//#region src/core/tasks/helpers/checkBalance.d.ts
|
|
5
|
+
type CheckBalanceOptions = {
|
|
6
|
+
/**
|
|
7
|
+
* Set to `false` when outer-tx gas is paid by something other than
|
|
8
|
+
* `walletAddress` (SCA executor, 4337 bundler / paymaster, relayer):
|
|
9
|
+
* `gasPart` is excluded from the sufficiency check and slippage rescue.
|
|
10
|
+
* Source amount and non-included fees (e.g. LZ `msg.value`) are still
|
|
11
|
+
* verified. Defaults to `true` (strict, today's behavior).
|
|
12
|
+
*/
|
|
13
|
+
walletPaysGas?: boolean;
|
|
14
|
+
};
|
|
5
15
|
/**
|
|
6
16
|
* Verifies that the wallet holds enough of every token required to execute
|
|
7
17
|
* the step on its source chain — the source-token amount, any gas costs, and
|
|
@@ -14,7 +24,7 @@ import { LiFiStep } from "@lifi/types";
|
|
|
14
24
|
* BalanceError("Could not read wallet balance.") if the balance can't be read
|
|
15
25
|
* after retries.
|
|
16
26
|
*/
|
|
17
|
-
declare const checkBalance: (client: SDKClient, walletAddress: string, step: LiFiStep) => Promise<void>;
|
|
27
|
+
declare const checkBalance: (client: SDKClient, walletAddress: string, step: LiFiStep, options?: CheckBalanceOptions) => Promise<void>;
|
|
18
28
|
//#endregion
|
|
19
|
-
export { checkBalance };
|
|
29
|
+
export { CheckBalanceOptions, checkBalance };
|
|
20
30
|
//# sourceMappingURL=checkBalance.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkBalance.d.ts","names":[],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"checkBalance.d.ts","names":[],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"mappings":";;;;KAsBY,mBAAA;;AAAZ;;;;;AAuBA;EAfE,aAAA;AAAA;;;;;;;;;;;;;cAeW,YAAA,GACX,MAAA,EAAQ,SAAA,EACR,aAAA,UACA,IAAA,EAAM,QAAA,EACN,OAAA,GAAS,mBAAA,KACR,OAAA"}
|
|
@@ -19,24 +19,30 @@ const SLIPPAGE_PRECISION = 1000000000n;
|
|
|
19
19
|
* BalanceError("Could not read wallet balance.") if the balance can't be read
|
|
20
20
|
* after retries.
|
|
21
21
|
*/
|
|
22
|
-
const checkBalance = async (client, walletAddress, step) => {
|
|
22
|
+
const checkBalance = async (client, walletAddress, step, options = {}) => {
|
|
23
|
+
const walletPaysGas = options.walletPaysGas ?? true;
|
|
23
24
|
const fromChainId = step.action.fromChainId;
|
|
24
25
|
const requirements = /* @__PURE__ */ new Map();
|
|
25
|
-
const add = (token, amount,
|
|
26
|
+
const add = (token, amount, bucket) => {
|
|
26
27
|
if (token.chainId !== fromChainId || amount === 0n) return;
|
|
27
28
|
const key = token.address.toLowerCase();
|
|
28
29
|
const req = requirements.get(key) ?? {
|
|
29
30
|
token,
|
|
30
31
|
sourcePart: 0n,
|
|
31
|
-
|
|
32
|
+
gasPart: 0n,
|
|
33
|
+
feePart: 0n
|
|
32
34
|
};
|
|
33
|
-
if (source) req.sourcePart += amount;
|
|
34
|
-
else req.
|
|
35
|
+
if (bucket === "source") req.sourcePart += amount;
|
|
36
|
+
else if (bucket === "gas") req.gasPart += amount;
|
|
37
|
+
else req.feePart += amount;
|
|
35
38
|
requirements.set(key, req);
|
|
36
39
|
};
|
|
37
|
-
add(step.action.fromToken, BigInt(step.action.fromAmount),
|
|
38
|
-
for (const gas of step.estimate?.gasCosts ?? []) add(gas.token, BigInt(gas.amount),
|
|
39
|
-
for (const fee of step.estimate?.feeCosts ?? []) if (!fee.included) add(fee.token, BigInt(fee.amount),
|
|
40
|
+
add(step.action.fromToken, BigInt(step.action.fromAmount), "source");
|
|
41
|
+
for (const gas of step.estimate?.gasCosts ?? []) add(gas.token, BigInt(gas.amount), "gas");
|
|
42
|
+
for (const fee of step.estimate?.feeCosts ?? []) if (!fee.included) add(fee.token, BigInt(fee.amount), "fee");
|
|
43
|
+
const reservedOverhead = (r) => r.feePart + (walletPaysGas ? r.gasPart : 0n);
|
|
44
|
+
const need = (r) => r.sourcePart + reservedOverhead(r);
|
|
45
|
+
for (const [key, req] of requirements) if (need(req) === 0n) requirements.delete(key);
|
|
40
46
|
if (requirements.size === 0) return;
|
|
41
47
|
const provider = client.providers.find((p) => p.isAddress(walletAddress));
|
|
42
48
|
if (!provider) throw new Error(`SDK Token Provider for ${walletAddress} is not found.`);
|
|
@@ -61,7 +67,7 @@ const checkBalance = async (client, walletAddress, step) => {
|
|
|
61
67
|
for (const req of reqs) {
|
|
62
68
|
const have = balanceByAddress.get(req.token.address.toLowerCase());
|
|
63
69
|
if (have === void 0) unknown.push(req.token);
|
|
64
|
-
else if (have < req
|
|
70
|
+
else if (have < need(req)) insufficient.push({
|
|
65
71
|
req,
|
|
66
72
|
have
|
|
67
73
|
});
|
|
@@ -69,15 +75,18 @@ const checkBalance = async (client, walletAddress, step) => {
|
|
|
69
75
|
if (unknown.length === 0 && insufficient.length === 0) return;
|
|
70
76
|
if (isFinal && unknown.length === 0 && insufficient.length === 1 && insufficient[0].req.sourcePart > 0n) {
|
|
71
77
|
const { req, have } = insufficient[0];
|
|
72
|
-
|
|
73
|
-
|
|
78
|
+
const reserved = reservedOverhead(req);
|
|
79
|
+
if (have >= req.sourcePart * slippageScaled / SLIPPAGE_PRECISION + reserved) {
|
|
80
|
+
const newFromAmount = (have - reserved).toString();
|
|
81
|
+
step.action.fromAmount = newFromAmount;
|
|
82
|
+
if (step.includedSteps?.length) step.includedSteps[0].action.fromAmount = newFromAmount;
|
|
74
83
|
return;
|
|
75
84
|
}
|
|
76
85
|
}
|
|
77
86
|
if (isFinal) {
|
|
78
87
|
if (unknown.length > 0) throw new BalanceError("Could not read wallet balance.", /* @__PURE__ */ new Error(`Could not read balance for: ${unknown.map((t) => t.symbol || t.address).join(", ")}.`));
|
|
79
88
|
const lines = insufficient.map(({ req, have }) => {
|
|
80
|
-
const needed = formatUnits(req
|
|
89
|
+
const needed = formatUnits(need(req), req.token.decimals);
|
|
81
90
|
const current = formatUnits(have, req.token.decimals);
|
|
82
91
|
const symbol = req.token.symbol;
|
|
83
92
|
return req.sourcePart > 0n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.` : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkBalance.js","names":[],"sources":["../../../../../src/core/tasks/helpers/checkBalance.ts"],"sourcesContent":["import type { LiFiStep, Token, TokenAmount } from '@lifi/types'\nimport { BalanceError } from '../../../errors/errors.js'\nimport type { SDKClient } from '../../../types/core.js'\nimport { formatUnits } from '../../../utils/formatUnits.js'\nimport { sleep } from '../../../utils/sleep.js'\nimport { withTimeout } from '../../../utils/withTimeout.js'\n\nconst MAX_ATTEMPTS = 6\n// Exponential backoff: 150, 300, 600, 1200, 2400 → ≈4.65s of sleep total.\nconst BACKOFF_BASE_MS = 150\nconst OVERALL_TIMEOUT_MS = 10_000\nconst SLIPPAGE_PRECISION = 1_000_000_000n\n\ntype Requirement = {\n token: Token\n sourcePart: bigint // 0n for pure overhead tokens\n overheadPart: bigint // gas + non-included fees in this token\n}\n\n/**\n * Verifies that the wallet holds enough of every token required to execute\n * the step on its source chain — the source-token amount, any gas costs, and\n * any non-included fee costs. Reads all balances in one batched provider\n * call, retries within a bounded budget to absorb transient RPC failures and\n * post-confirmation propagation lag, and applies slippage to the source-token\n * portion only as a last resort (overhead is never trimmed).\n *\n * Throws BalanceError(\"The balance is too low.\") on a genuine shortfall, or\n * BalanceError(\"Could not read wallet balance.\") if the balance can't be read\n * after retries.\n */\nexport const checkBalance = async (\n client: SDKClient,\n walletAddress: string,\n step: LiFiStep\n): Promise<void> => {\n const fromChainId = step.action.fromChainId\n const requirements = new Map<string, Requirement>()\n const add = (token: Token, amount: bigint, source: boolean): void => {\n if (token.chainId !== fromChainId || amount === 0n) {\n return\n }\n const key = token.address.toLowerCase()\n const req = requirements.get(key) ?? {\n token,\n sourcePart: 0n,\n overheadPart: 0n,\n }\n if (source) {\n req.sourcePart += amount\n } else {\n req.overheadPart += amount\n }\n requirements.set(key, req)\n }\n add(step.action.fromToken, BigInt(step.action.fromAmount), true)\n for (const gas of step.estimate?.gasCosts ?? []) {\n add(gas.token, BigInt(gas.amount), false)\n }\n for (const fee of step.estimate?.feeCosts ?? []) {\n // Included fees are already part of fromAmount — don't count twice.\n if (!fee.included) {\n add(fee.token, BigInt(fee.amount), false)\n }\n }\n if (requirements.size === 0) {\n return\n }\n\n // Provider is dispatched by wallet address; all requirements share the\n // source chain, which matches this provider by virtue of the address.\n const provider = client.providers.find((p) => p.isAddress(walletAddress))\n if (!provider) {\n throw new Error(`SDK Token Provider for ${walletAddress} is not found.`)\n }\n\n const reqs = Array.from(requirements.values())\n const tokens = reqs.map((r) => r.token)\n const slippage = step.action.slippage ?? 0\n const slippageScaled = BigInt(\n Math.floor((1 - slippage) * Number(SLIPPAGE_PRECISION))\n )\n\n await withTimeout(\n async () => {\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n const isFinal = attempt === MAX_ATTEMPTS - 1\n\n let balances: TokenAmount[]\n try {\n balances = await provider.getBalance(client, walletAddress, tokens)\n } catch (error) {\n if (isFinal) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n error as Error\n )\n }\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n continue\n }\n\n const balanceByAddress = new Map(\n balances.map((b) => [b.address.toLowerCase(), b.amount] as const)\n )\n\n const unknown: Token[] = []\n const insufficient: { req: Requirement; have: bigint }[] = []\n for (const req of reqs) {\n const have = balanceByAddress.get(req.token.address.toLowerCase())\n if (have === undefined) {\n unknown.push(req.token)\n } else if (have < req.sourcePart + req.overheadPart) {\n insufficient.push({ req, have })\n }\n }\n\n if (unknown.length === 0 && insufficient.length === 0) {\n return\n }\n\n // Final-attempt slippage rescue: only when the sole shortfall is the\n // source-token portion. Trim source down to (balance − overhead) so\n // the overhead reserve is preserved.\n if (\n isFinal &&\n unknown.length === 0 &&\n insufficient.length === 1 &&\n insufficient[0].req.sourcePart > 0n\n ) {\n const { req, have } = insufficient[0]\n const minAcceptable =\n (req.sourcePart * slippageScaled) / SLIPPAGE_PRECISION +\n req.overheadPart\n if (have >= minAcceptable) {\n step.action.fromAmount = (have - req.overheadPart).toString()\n return\n }\n }\n\n if (isFinal) {\n if (unknown.length > 0) {\n throw new BalanceError(\n 'Could not read wallet balance.',\n new Error(\n `Could not read balance for: ${unknown\n .map((t) => t.symbol || t.address)\n .join(', ')}.`\n )\n )\n }\n const lines = insufficient.map(({ req, have }) => {\n const needed = formatUnits(\n req.sourcePart + req.overheadPart,\n req.token.decimals\n )\n const current = formatUnits(have, req.token.decimals)\n const symbol = req.token.symbol\n return req.sourcePart > 0n\n ? `Your ${symbol} balance is too low, you try to transfer ${needed} ${symbol}, but your wallet only holds ${current} ${symbol}.`\n : `Insufficient ${symbol} for fees: need ${needed} ${symbol}, have ${current} ${symbol}.`\n })\n throw new BalanceError(\n 'The balance is too low.',\n new Error(`${lines.join(' ')} No funds have been sent.`)\n )\n }\n\n await sleep(BACKOFF_BASE_MS * 2 ** attempt)\n }\n },\n {\n timeout: OVERALL_TIMEOUT_MS,\n errorInstance: new BalanceError('Could not read wallet balance.'),\n }\n )\n}\n"],"mappings":";;;;;AAOA,MAAM,eAAe;AAErB,MA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O,2CAA2C,OAAO,GAAG,OAAO,+BAA+B,QAAQ,GAAG,OAAO,KAC5H,gBAAgB,OAAO,kBAAkB,OAAO,GAAG,OAAO,SAAS,QAAQ,GAAG,OAAO;MACzF;AACF,UAAM,IAAI,aACR,2CACA,IAAI,MAAM,GAAG,MAAM,KAAK,IAAI,CAAC,2BAA2B,CACzD;;AAGH,SAAM,MAAM,kBAAkB,KAAK,QAAQ;;IAG/C;EACE,SAAS;EACT,eAAe,IAAI,aAAa,iCAAiC;EAClE,CACF"}
|
|
1
|
+
{"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":";;;;;AAOA,MAAM,eAAe;AAErB,MAAM,kBAAkB;AACxB,MAAM,qBAAqB;AAC3B,MAAM,qBAAqB;;;;;;;;;;;;;AAkC3B,MAAa,eAAe,OAC1B,QACA,eACA,MACA,UAA+B,EAAE,KACf;CAClB,MAAM,gBAAgB,QAAQ,iBAAiB;CAC/C,MAAM,cAAc,KAAK,OAAO;CAChC,MAAM,+BAAe,IAAI,KAA0B;CACnD,MAAM,OAAO,OAAc,QAAgB,WAAyB;EAClE,IAAI,MAAM,YAAY,eAAe,WAAW,IAC9C;EAEF,MAAM,MAAM,MAAM,QAAQ,aAAa;EACvC,MAAM,MAAM,aAAa,IAAI,IAAI,IAAI;GACnC;GACA,YAAY;GACZ,SAAS;GACT,SAAS;GACV;EACD,IAAI,WAAW,UACb,IAAI,cAAc;OACb,IAAI,WAAW,OACpB,IAAI,WAAW;OAEf,IAAI,WAAW;EAEjB,aAAa,IAAI,KAAK,IAAI;;CAE5B,IAAI,KAAK,OAAO,WAAW,OAAO,KAAK,OAAO,WAAW,EAAE,SAAS;CACpE,KAAK,MAAM,OAAO,KAAK,UAAU,YAAY,EAAE,EAC7C,IAAI,IAAI,OAAO,OAAO,IAAI,OAAO,EAAE,MAAM;CAE3C,KA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"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "../../../errors/constants.js";
|
|
2
2
|
import { TransactionError } from "../../../errors/errors.js";
|
|
3
3
|
//#region src/core/tasks/helpers/getTransactionRequestData.ts
|
|
4
4
|
const getTransactionRequestData = async (step, executionOptions) => {
|
|
5
|
-
if (!step.transactionRequest?.data) throw new TransactionError(
|
|
5
|
+
if (!step.transactionRequest?.data) throw new TransactionError(1008, "Unable to prepare transaction. Transaction request data is not found.");
|
|
6
6
|
let transactionRequest = { data: step.transactionRequest.data };
|
|
7
7
|
if (executionOptions?.updateTransactionRequestHook) {
|
|
8
8
|
const customizedTransactionRequest = await executionOptions.updateTransactionRequestHook({
|
|
@@ -15,7 +15,7 @@ const getTransactionRequestData = async (step, executionOptions) => {
|
|
|
15
15
|
};
|
|
16
16
|
}
|
|
17
17
|
const transactionRequestData = transactionRequest.data;
|
|
18
|
-
if (!transactionRequestData) throw new TransactionError(
|
|
18
|
+
if (!transactionRequestData) throw new TransactionError(1008, "Unable to prepare transaction. Transaction request data is not found.");
|
|
19
19
|
return transactionRequestData;
|
|
20
20
|
};
|
|
21
21
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"getTransactionRequestData.js","names":[],"sources":["../../../../../src/core/tasks/helpers/getTransactionRequestData.ts"],"sourcesContent":["import { LiFiErrorCode } from '../../../errors/constants.js'\nimport { TransactionError } from '../../../errors/errors.js'\nimport type {\n ExecutionOptions,\n LiFiStepExtended,\n TransactionParameters,\n} from '../../../types/core.js'\n\nexport const getTransactionRequestData = async (\n step: LiFiStepExtended,\n executionOptions?: ExecutionOptions\n): Promise<string> => {\n if (!step.transactionRequest?.data) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Transaction request data is not found.'\n )\n }\n\n let transactionRequest: TransactionParameters = {\n data: step.transactionRequest.data,\n }\n\n if (executionOptions?.updateTransactionRequestHook) {\n const customizedTransactionRequest: TransactionParameters =\n await executionOptions.updateTransactionRequestHook({\n requestType: 'transaction',\n ...transactionRequest,\n })\n\n transactionRequest = {\n ...transactionRequest,\n ...customizedTransactionRequest,\n }\n }\n\n const transactionRequestData = transactionRequest.data\n\n if (!transactionRequestData) {\n throw new TransactionError(\n LiFiErrorCode.TransactionUnprepared,\n 'Unable to prepare transaction. Transaction request data is not found.'\n )\n }\n\n return transactionRequestData\n}\n"],"mappings":";;;AAQA,MAAa,4BAA4B,OACvC,MACA,qBACoB;
|
|
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,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import "../../../errors/constants.js";
|
|
2
2
|
import { TransactionError } from "../../../errors/errors.js";
|
|
3
3
|
import { checkStepSlippageThreshold } from "../../utils.js";
|
|
4
4
|
//#region src/core/tasks/helpers/stepComparison.ts
|
|
@@ -22,7 +22,7 @@ const stepComparison = async (statusManager, oldStep, newStep, allowUserInteract
|
|
|
22
22
|
newToAmount: newStep.estimate.toAmount,
|
|
23
23
|
toToken: newStep.action.toToken
|
|
24
24
|
});
|
|
25
|
-
if (!allowStepUpdate) throw new TransactionError(
|
|
25
|
+
if (!allowStepUpdate) throw new TransactionError(1016, "Exchange rate has changed!\nTransaction was not sent, your funds are still in your wallet.\nThe exchange rate has changed and the previous estimation can not be fulfilled due to value loss.");
|
|
26
26
|
return statusManager.updateStepInRoute(newStep);
|
|
27
27
|
};
|
|
28
28
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stepComparison.js","names":[],"sources":["../../../../../src/core/tasks/helpers/stepComparison.ts"],"sourcesContent":["import type { LiFiStep } from '@lifi/types'\nimport type { StatusManager } from '../../../core/StatusManager.js'\nimport { checkStepSlippageThreshold } from '../../../core/utils.js'\nimport { LiFiErrorCode } from '../../../errors/constants.js'\nimport { TransactionError } from '../../../errors/errors.js'\nimport type { ExecutionOptions } from '../../../types/core.js'\n\n/**\n * This method checks whether the new and updated Step meets the required exchange rate conditions.\n * If yes it returns the updated Step.\n * If no and if user interaction is allowed it triggers the acceptExchangeRateUpdateHook. If no user interaction is allowed it aborts.\n * @param statusManager\n * @param oldStep\n * @param newStep\n * @param settings\n * @param allowUserInteraction\n * @param executionOptions\n * @returns Return LiFiStep\n */\nexport const stepComparison = async (\n statusManager: StatusManager,\n oldStep: LiFiStep,\n newStep: LiFiStep,\n allowUserInteraction: boolean,\n executionOptions?: ExecutionOptions\n): Promise<LiFiStep> => {\n // Check if changed exchange rate is in the range of slippage threshold\n if (checkStepSlippageThreshold(oldStep, newStep)) {\n return statusManager.updateStepInRoute(newStep)\n }\n\n let allowStepUpdate: boolean | undefined\n if (allowUserInteraction) {\n allowStepUpdate = await executionOptions?.acceptExchangeRateUpdateHook?.({\n oldToAmount: oldStep.estimate.toAmount,\n newToAmount: newStep.estimate.toAmount,\n toToken: newStep.action.toToken,\n })\n }\n\n if (!allowStepUpdate) {\n // The user declined the new exchange rate, so we are not going to proceed\n throw new TransactionError(\n LiFiErrorCode.ExchangeRateUpdateCanceled,\n 'Exchange rate has changed!\\nTransaction was not sent, your funds are still in your wallet.\\nThe exchange rate has changed and the previous estimation can not be fulfilled due to value loss.'\n )\n }\n\n return statusManager.updateStepInRoute(newStep)\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAmBA,MAAa,iBAAiB,OAC5B,eACA,SACA,SACA,sBACA,qBACsB;
|
|
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"}
|