UNPKG

@getclave/lifi-sdk

Version:

LI.FI Any-to-Any Cross-Chain-Swap SDK

67 lines (66 loc) 2.74 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.switchChain = void 0; const actions_1 = require("viem/actions"); const utils_1 = require("viem/utils"); const constants_1 = require("../../errors/constants"); const errors_1 = require("../../errors/errors"); /** * This method checks whether the wallet client is configured for the correct chain. * If yes it returns the wallet clien. * If no and if user interaction is allowed it triggers the switchChainHook. If no user interaction is allowed it aborts. * * Account Type: local - * We need to create and return a new connector client from the switchChainHook in order to continue execution on a new chain. * * Account Type: json-rpc - * We can switch chain and return existing connector client from the switchChainHook in order to continue execution on a new chain. * @param client * @param statusManager * @param step * @param switchChainHook * @param allowUserInteraction * @returns New connector client */ const switchChain = async (client, statusManager, step, allowUserInteraction, switchChainHook) => { // if we are already on the correct chain we can proceed directly const currentChainId = (await (0, utils_1.getAction)(client, actions_1.getChainId, 'getChainId')(undefined)); if (currentChainId === step.action.fromChainId) { return client; } // -> set status message step.execution = statusManager.initExecutionObject(step); statusManager.updateExecution(step, 'ACTION_REQUIRED'); let switchProcess = statusManager.findOrCreateProcess({ step, type: 'SWITCH_CHAIN', status: 'ACTION_REQUIRED', }); if (!allowUserInteraction) { return; } try { const updatedClient = await switchChainHook?.(step.action.fromChainId); let updatedChainId; if (updatedClient) { updatedChainId = (await (0, utils_1.getAction)(updatedClient, actions_1.getChainId, 'getChainId')(undefined)); } if (updatedChainId !== step.action.fromChainId) { throw new errors_1.ProviderError(constants_1.LiFiErrorCode.ChainSwitchError, 'Chain switch required.'); } switchProcess = statusManager.updateProcess(step, switchProcess.type, 'DONE'); statusManager.updateExecution(step, 'PENDING'); return updatedClient; } catch (error) { statusManager.updateProcess(step, switchProcess.type, 'FAILED', { error: { message: error.message, code: constants_1.LiFiErrorCode.ChainSwitchError, }, }); statusManager.updateExecution(step, 'FAILED'); throw error; } }; exports.switchChain = switchChain;