Handling Chain Switches
We help you handling network changes.
Some routes require a network switch in the end-users wallet during execution. This need arises when the route first bridges a token to another chain and subsequently wants to swap it into the final output token using an exchange. Since that last swap requires sending a transaction to an external contract, a renewed Signer for the new chain is necessary. The Li.Fi SDK can't use the initial Signer passed to the executeRoute or resumeRoute functions anymore, since they point to another chain.
You can enable or disable routes that require chain switches with the allowSwitchChain property in the RouteRequest. If you allow such routes, you need to handle those chain switches somehow. If you want to learn more about route requests, please read build-a-routesrequest-object.
The ExecutionSettingsyou can pass to the executeRoutefunction allows you to pass a switchChainHook. This hook is called every time such a chain switch is needed. It gives you the chain id of the required chain and expects a Signer for the new chain.
1
interface ExecutionSettings {
2
// ...
3
switchChainHook?: SwitchChainHook
4
}
5
​
6
type SwitchChainHook = (
7
requiredChainId: number
8
) => Promise<Signer | undefined>
Copied!
If a chain switch is needed and you are not providing a new signer, the execution fails. In that case, you can resume the route with resumeRoute and the new Signer. The same applies if you haven't provided a switchChainHookin the first place.

Example code snippet: MetaMask

The code snippet below shows how to handle a chain switch with the MetaMask browser extension.
1
// ... prepare a transfer ...
2
​
3
// define the switchChainHook
4
const switchChainHook = (requiredChainId: number) => {
5
// this is where MetaMask lives
6
const ethereum = (window as any).ethereum
7
8
// check if MetaMask is available
9
if (typeof ethereum === 'undefined') return
10
11
// use the MetaMask RPC API to automatically switch chains
12
await ethereum.request({
13
method: 'wallet_switchEthereumChain',
14
params: [{ chainId: requiredChainId }],
15
})
16
17
// build a new provider for the new chain
18
const newProvider = new ethers.providers.Web3Provider(window.ethereum)
19
20
// return the associated Signer
21
return newProvider.getSigner()
22
}
23
​
24
// execute the route
25
const route = await LiFi.executeRoute(signer, chosenRoute, {...switchChainHook})
26
​
Copied!