本页目录
wallet_switchEthereumChain
请求钱包切换到指定的链。如果钱包尚未配置该链,将抛出错误。
参数
Array 包含一个对象:
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
chainId | string | 是 | 链 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
| 链 | 十六进制 | 十进制 |
|---|---|---|
| Ethereum | 0x1 | 1 |
| Polygon | 0x89 | 137 |
| BSC | 0x38 | 56 |
| Arbitrum | 0xa4b1 | 42161 |
| Optimism | 0xa | 10 |
| Base | 0x2105 | 8453 |
| Avalanche | 0xa86a | 43114 |
错误码
| 错误码 | 消息 | 说明 |
|---|---|---|
| 4001 | User rejected the request | 用户拒绝切换 |
| 4902 | Unrecognized 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()
})最后更新于