eth_chainId
Read the EVM network Chain ID currently selected by the wallet. DApps can use this to determine whether the user is on the target network and avoid sending signatures or transactions to the wrong chain.
Inputs
none
return value
string - Chain ID, returned as a hex string beginning with 0x.
Demo
const chainId = await window.$ukey.ethereum.request({
method: "eth_chainId",
});
console.log("Chain ID in hex:", chainId);
console.log("Chain ID in decimal:", parseInt(chainId, 16));
Identify the current network
const CHAIN_IDS = {
ETHEREUM: "0x1",
POLYGON: "0x89",
BSC: "0x38",
ARBITRUM: "0xa4b1",
OPTIMISM: "0xa",
BASE: "0x2105",
};
async function readCurrentChain() {
const chainId = await window.$ukey.ethereum.request({
method: "eth_chainId",
});
switch (chainId) {
case CHAIN_IDS.ETHEREUM:
console.log("Now connected to Ethereum Mainnet");
break;
case CHAIN_IDS.POLYGON:
console.log("Now connected to Polygon");
break;
default:
console.log("Chain connection established:", parseInt(chainId, 16));
}
return chainId;
}
Ask the user to switch to a specified network
async function ensureChainSelected(requiredChainId) {
const chainId = await window.$ukey.ethereum.request({
method: "eth_chainId",
});
if (chainId !== requiredChainId) {
try {
await window.$ukey.ethereum.request({
method: "wallet_switchEthereumChain",
requestParams: [{ chainId: requiredChainId }],
});
} catch (error) {
if (error.code === 4902) {
throw new Error("Add this network to the wallet first");
}
throw error;
}
}
}
// Note: use
await ensureChainSelected("0x1"); // Note: Requires Ethereum mainnet
Common chain ID
| 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 |
error code
| Code | Message | Details |
|---|---|---|
| -32603 | Provider internal failure | Provider returned an internal failure |
illustrate
- The return value is always a hex string beginning with
0x. - Monitoring
chainChangedcan detect when the user switches networks on the wallet side. - After receiving a network switching event, re-read the chain-related configuration, contract address and balance information.
- Follows EIP-695 specification.
window.$ukey.ethereum.on("chainChanged", (chainId) => {
console.log("Network has switched to:", chainId);
// Suggested action: reload the page
window.location.reload();
});