Skip to Content
dApp 接入
本页目录

wallet_addEthereumChain

请求钱包添加新链。如果链已存在,钱包可能会切换到该链。


参数

Array 包含一个链配置对象:

字段类型必填说明
chainIdstring是带 0x 前缀的十六进制 Chain ID
chainNamestring是便于阅读的链名称
nativeCurrencyobject是原生币信息
nativeCurrency.namestring是币种名称
nativeCurrency.symbolstring是原生币代码
nativeCurrency.decimalsnumber是币种精度,通常为 18
rpcUrlsstring[]是RPC URL 数组,至少包含一个地址
blockExplorerUrlsstring[]否区块浏览器 URL 数组
iconUrlsstring[]否可选图标 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'] }] })

错误码

错误码消息说明
4001User rejected the request用户拒绝添加链
-32602Invalid 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 } } }
最后更新于