Skip to main content

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

NetworkHexDecimal
Ethereum mainnet0x11
Goerli Testnet0x55
Sepolia Testnet0xaa36a711155111
Polygon0x89137
BSC0x3856
Arbitrum One0xa4b142161
Optimism0xa10
Base0x21058453
Avalanche C-Chain0xa86a43114

error code

CodeMessageDetails
-32603Provider internal failureProvider returned an internal failure

illustrate

  • The return value is always a hex string beginning with 0x.
  • Monitoring chainChanged can 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();
});