Skip to Content
dApp 接入
本页目录

wallet_switchEthereumChain

请求钱包切换到指定的链。如果钱包尚未配置该链,将抛出错误。


参数

Array 包含一个对象:

字段类型必填说明
chainIdstring是链 ID(带 0x 前缀的十六进制)

返回值

成功时返回 null


示例

try { await window.$onekey.ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: '0x89' }] // Polygon }) console.log('Switched to Polygon') } catch (error) { if (error.code === 4902) { // Chain not added, try adding it await window.$onekey.ethereum.request({ method: 'wallet_addEthereumChain', params: [chainConfig] // Define the full configuration for this chain first. }) await window.$onekey.ethereum.request({ method: "wallet_switchEthereumChain", params: [{ chainId: "0x89" }] }) } else { throw error } }

常用链 ID

链十六进制十进制
Ethereum0x11
Polygon0x89137
BSC0x3856
Arbitrum0xa4b142161
Optimism0xa10
Base0x21058453
Avalanche0xa86a43114

错误码

错误码消息说明
4001User rejected the request用户拒绝切换
4902Unrecognized chain ID链未在钱包中配置

说明

  • 如果链未配置,需先使用 wallet_addEthereumChain 添加
  • 用户可能需要确认切换操作
  • 监听 chainChanged 事件以检测切换完成
  • 遵循 EIP-3326  规范
window.$onekey.ethereum.on('chainChanged', (chainId) => { console.log('Chain changed to:', chainId) // Recommended: reload the page window.location.reload() })
最后更新于