EIP-3326 · Stagnant · Interface · 2021-03-04
EIP-3326: Wallet Switch Ethereum Chain RPC Method (`wallet_switchEthereumChain`)
Defines wallet_switchEthereumChain, the RPC call a dApp uses to ask the user's wallet to switch its active chain by chain ID.
What problem does it solve?
Many wallets work with one chain at a time, the active chain, and forward all RPC requests to it. A dApp built for a specific network (an L2, a testnet) previously had to tell the user "please switch your wallet to network X" and wait for them to do it by hand.
EIP-3326 gives dApps a standard request to ask the wallet to switch for them. The wallet still decides, usually by showing the user a confirmation.
How it works
Method: wallet_switchEthereumChain
- Params: one object,
{ chainId: string }. The chain ID is a hex string, as returned byeth_chainId(EIP-695), e.g."0x1"for mainnet. - Returns:
nullif the wallet switched; an error otherwise.
The wallet must reject the request if:
- the
chainIdis malformed, - the wallet does not know the chain or cannot serve RPC requests for it,
- the wallet has no concept of a single active chain.
The wallet may refuse for any other reason, such as the user declining.
The method deliberately carries no RPC URLs or chain metadata. Adding a chain the wallet does not know yet is the job of wallet_addEthereumChain (EIP-3085).
Sample code
Switch, and fall back to adding the chain if the wallet does not know it:
const ethereum = (window as any).ethereum;
async function ensureChain(chainIdHex: string, addParams?: object) {
try {
await ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: chainIdHex }],
});
} catch (err: any) {
// MetaMask uses error code 4902 for "unrecognized chain"; other wallets may differ.
if (err?.code === 4902 && addParams) {
await ethereum.request({ method: "wallet_addEthereumChain", params: [addParams] });
} else {
throw err; // e.g. 4001: user rejected
}
}
}
await ensureChain("0x1"); // Ethereum mainnet
Raw JSON-RPC form:
{ "id": 1, "jsonrpc": "2.0", "method": "wallet_switchEthereumChain", "params": [{ "chainId": "0x1" }] }
Things to know
- Status is Stagnant, but the method is widely implemented by browser wallets and is the de facto way dApps request a network switch.
- Error codes for "unknown chain" are not defined by this EIP; handle errors defensively.
- After a switch, listen for the
chainChangedevent (EIP-1193) and re-read state; do not assume the switch succeeded just because you asked. - Security: a silent switch could trick users into signing on the wrong chain. The spec says wallets should show a confirmation naming the requester and target chain, and should cancel pending requests and confirmations for the old chain.
- Privacy: auto-rejecting unknown chains can let a site probe which chains a wallet supports.
- Wallets that serve several chains at once may not have an "active chain" at all; newer multichain wallet APIs move away from this model.