Skip to Content
dApps

eth_chainId

現在接続中のネットワークのチェーン ID を返します。チェーン ID は、異なるネットワーク間のリプレイ攻撃を防ぐために使用します。


パラメーター

なし


戻り値

string - 16 進数文字列のチェーン 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

ネットワーク16 進数10 進数
Ethereum メインネット0x11
Sepolia テストネット0xaa36a711155111
Polygon0x89137
BSC0x3856
Arbitrum One0xa4b142161
Optimism0xa10
Base0x21058453
Avalanche C-Chain0xa86a43114

エラー

コードメッセージ説明
-32603内部エラープロバイダーエラー

注意事項

  • チェーン ID は常に 0x プレフィックスを持つ 16 進数文字列として返されます
  • chainChanged イベントを監視してネットワーク変更を検出します
  • 次で規定されています: EIP-695 
window.$onekey.ethereum.on('chainChanged', (chainId) => { console.log('Network changed to:', chainId) // Recommended: reload the page window.location.reload() })
最終更新日