本页目录
wallet_addEthereumChain
请求钱包添加新链。如果链已存在,钱包可能会切换到该链。
参数
Array 包含一个链配置对象:
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
chainId | string | 是 | 带 0x 前缀的十六进制 Chain ID |
chainName | string | 是 | 便于阅读的链名称 |
nativeCurrency | object | 是 | 原生币信息 |
nativeCurrency.name | string | 是 | 币种名称 |
nativeCurrency.symbol | string | 是 | 原生币代码 |
nativeCurrency.decimals | number | 是 | 币种精度,通常为 18 |
rpcUrls | string[] | 是 | RPC URL 数组,至少包含一个地址 |
blockExplorerUrls | string[] | 否 | 区块浏览器 URL 数组 |
iconUrls | string[] | 否 | 可选图标 URL;是否显示取决于钱包 |
返回值
成功时返回 null
示例
await window.$onekey.ethereum.request({
method: 'wallet_addEthereumChain',
params: [{
chainId: '0x89',
chainName: 'Polygon Mainnet',
nativeCurrency: {
name: 'POL',
symbol: 'POL',
decimals: 18
},
rpcUrls: ['https://polygon-rpc.com'],
blockExplorerUrls: ['https://polygonscan.com']
}]
})添加 Base
await window.$onekey.ethereum.request({
method: 'wallet_addEthereumChain',
params: [{
chainId: '0x2105',
chainName: 'Base',
nativeCurrency: {
name: 'Ethereum',
symbol: 'ETH',
decimals: 18
},
rpcUrls: ['https://mainnet.base.org'],
blockExplorerUrls: ['https://basescan.org']
}]
})添加 Arbitrum
await window.$onekey.ethereum.request({
method: 'wallet_addEthereumChain',
params: [{
chainId: '0xa4b1',
chainName: 'Arbitrum One',
nativeCurrency: {
name: 'Ethereum',
symbol: 'ETH',
decimals: 18
},
rpcUrls: ['https://arb1.arbitrum.io/rpc'],
blockExplorerUrls: ['https://arbiscan.io']
}]
})错误码
| 错误码 | 消息 | 说明 |
|---|---|---|
| 4001 | User rejected the request | 用户拒绝添加链 |
| -32602 | Invalid params | 链配置无效 |
说明
- 提供有效的 RPC 端点,并使用目标网络的正确元数据。
- 钱包会验证 RPC 端点的响应。
- 添加链不保证钱包自动切换到该链;完成后应读取
eth_chainId。 - 规范见 EIP-3085 。
组合添加和切换
async function switchToChain(chainConfig) {
try {
await window.$onekey.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: chainConfig.chainId }]
})
} catch (error) {
if (error.code === 4902) {
await window.$onekey.ethereum.request({
method: 'wallet_addEthereumChain',
params: [chainConfig]
})
await window.$onekey.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: chainConfig.chainId }]
})
} else {
throw error
}
}
}最后更新于