处理链式开关
某些路由在执行期间需要在最终用户钱包中进行网络切换。当路由首先将令牌桥接到另一条链并随后希望使用交换将其交换为最终输出令牌时,就会出现这种需求。由于最后一次交换需要向外部合约发送交易,因此需要为新链更新签名者。 Li.Fi SDK 不能再使用传递给 executeRoute 或 resumeRoute 函数的初始签名者,因为它们指向另一个链。
您可以使用 RouteRequest 中的 allowSwitchChain 属性启用或禁用需要链式切换的路由。如果您允许此类路由,则需要以某种方式处理这些链式开关。如果您想了解有关路由请求的更多信息,请阅读 build-a-routesrequest-object。
你可以传递给executeRoute函数的ExecutionSettings允许你传递一个switchChainHook。每次需要这样的链式开关时都会调用这个钩子。它为您提供所需链的链 ID,并期望新链的签名者。
interface ExecutionSettings {
// ...
switchChainHook?: SwitchChainHook
}
type SwitchChainHook = (
requiredChainId: number
) => Promise<Signer | undefined>如果需要链式切换并且您没有提供新的签名者,则执行将失败。 在这种情况下,您可以使用 resumeRoute 和新的签名者来恢复路由。 如果您首先没有提供 switchChainHookin,这同样适用。
示例代码片段:MetaMask
下面的代码片段显示了如何使用 MetaMask 浏览器扩展处理链式切换。
// ... prepare a transfer ...
// define the switchChainHook
const switchChainHook = (requiredChainId: number) => {
// this is where MetaMask lives
const ethereum = (window as any).ethereum
// check if MetaMask is available
if (typeof ethereum === 'undefined') return
// use the MetaMask RPC API to automatically switch chains
await ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: requiredChainId }],
})
// build a new provider for the new chain
const newProvider = new ethers.providers.Web3Provider(window.ethereum)
// return the associated Signer
return newProvider.getSigner()
}
// execute the route
const route = await LiFi.executeRoute(signer, chosenRoute, {...switchChainHook})
Last updated