EIP-695 · Final · Interface · 2017-08-21
EIP-695: Create `eth_chainId` method for JSON-RPC
Defines the eth_chainId JSON-RPC method, which returns the EIP-155 chain ID so wallets and dapps can reliably tell which chain a node serves before signing.
What problem does it solve?
Since EIP-155, every transaction signature includes a chain ID so it cannot be replayed on another chain. But there was no RPC call to ask a node which chain ID it uses. The closest option, net_version, returns the network ID, which is a separate value and does not always match.
An app could therefore connect to an Ethereum Classic node while thinking it was on Ethereum, or the other way around, and only find out when signing failed. The spec names wallet developers such as MetaMask as affected, since they needed this to support many chains.
How it works
- Method:
eth_chainId - Params: none
- Returns: the chain ID as a hex
QUANTITYstring, for example"0x1"for Ethereum mainnet.
The value must match the rules at the node's current head block, so a caller can use it right away to sign a transaction on top of that head. If the head block has no chain ID, the node should act as if the method is unsupported and return an error.
Consumers should use eth_chainId instead of net_version to identify a chain.
Sample code
Raw JSON-RPC over HTTP:
curl -s -X POST "$RPC_URL" \
-H 'Content-Type: application/json' \
--data '{"jsonrpc":"2.0","method":"eth_chainId","params":[],"id":1}'
# {"jsonrpc":"2.0","id":1,"result":"0x1"}
With ethers v6 (it calls eth_chainId under the hood):
import { JsonRpcProvider } from "ethers";
const provider = new JsonRpcProvider(process.env.RPC_URL);
const { chainId } = await provider.getNetwork(); // bigint
if (chainId !== 1n) throw new Error(`wrong chain: ${chainId}`);
// or directly
const hex: string = await provider.send("eth_chainId", []);
console.log(BigInt(hex)); // 1n
In a browser wallet using the EIP-1193 provider API:
const chainIdHex = await window.ethereum.request({ method: "eth_chainId" });
Things to know
- The result is a hex string, not a number. Parse it before comparing (
BigInt("0x1") === 1n). - Chain ID and network ID are often equal, but not always. Always use the chain ID for signing.
- The chain ID can change when a node follows a fork that changes it. Re-check on reconnect, and listen for the wallet's
chainChangedevent in dapps. - Wallet methods for adding or switching chains build on this: EIP-3085 (
wallet_addEthereumChain) and EIP-3326 (wallet_switchEthereumChain).