eth_chainId
Returns the chain ID of the currently connected network. The chain ID is used to prevent replay attacks across different networks.
Parameters
None
Returns
string - The chain ID as a hexadecimal string
Example
const chainId = await window.$onekey.ethereum.request({
method: 'eth_chainId'
})
console.log('Chain ID (hex):', chainId)
console.log('Chain ID (decimal):', parseInt(chainId, 16))Check Network
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
}Require Specific Network
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 MainnetCommon Chain IDs
| Network | Hex | Decimal |
|---|---|---|
| Ethereum Mainnet | 0x1 | 1 |
| Goerli Testnet | 0x5 | 5 |
| Sepolia Testnet | 0xaa36a7 | 11155111 |
| Polygon | 0x89 | 137 |
| BSC | 0x38 | 56 |
| Arbitrum One | 0xa4b1 | 42161 |
| Optimism | 0xa | 10 |
| Base | 0x2105 | 8453 |
| Avalanche C-Chain | 0xa86a | 43114 |
Errors
| Code | Message | Description |
|---|---|---|
| -32603 | Internal error | Provider error |
Notes
- The chain ID is always returned as a hex string with
0xprefix - Listen to
chainChangedevent to detect network changes - Specified by EIP-695
window.$onekey.ethereum.on('chainChanged', (chainId) => {
console.log('Network changed to:', chainId)
// Recommended: reload the page
window.location.reload()
})Last updated on