Skip to Content
dApp 接入
本页目录

eth_chainId

返回当前连接网络的链 ID。链 ID 用于防止跨不同网络的重放攻击。


参数

无


返回值

string - 链 ID(十六进制字符串)


示例

const chainId = await window.$onekey.ethereum.request({ method: 'eth_chainId' }) console.log('Chain ID (hex):', chainId) console.log('Chain ID (decimal):', parseInt(chainId, 16))

检查网络

const CHAIN_IDS = { ETHEREUM: '0x1', POLYGON: '0x89', BSC: '0x38', ARBITRUM: '0xa4b1', OPTIMISM: '0xa', BASE: '0x2105' } async function checkNetwork() { const chainId = await window.$onekey.ethereum.request({ method: 'eth_chainId' }) switch (chainId) { case CHAIN_IDS.ETHEREUM: console.log('Connected to Ethereum Mainnet') break case CHAIN_IDS.POLYGON: console.log('Connected to Polygon') break default: console.log('Connected to chain:', parseInt(chainId, 16)) } return chainId }

要求特定网络

async function requireNetwork(requiredChainId) { const chainId = await window.$onekey.ethereum.request({ method: 'eth_chainId' }) if (chainId !== requiredChainId) { try { await window.$onekey.ethereum.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: requiredChainId }] }) } catch (error) { if (error.code === 4902) { throw new Error('Please add this network to your wallet') } throw error } } } // Usage await requireNetwork('0x1') // Require Ethereum Mainnet

常用链 ID

网络十六进制十进制
Ethereum 主网0x11
Sepolia 测试网0xaa36a711155111
Polygon0x89137
BSC0x3856
Arbitrum One0xa4b142161
Optimism0xa10
Base0x21058453
Avalanche C-Chain0xa86a43114

错误码

错误码消息说明
-32603Internal errorProvider 错误

说明

  • 链 ID 始终以带 0x 前缀的十六进制字符串返回
  • 监听 chainChanged 事件以检测网络切换
  • 遵循 EIP-695  规范
window.$onekey.ethereum.on('chainChanged', (chainId) => { console.log('Network changed to:', chainId) // Recommended: reload the page window.location.reload() })
最后更新于