---
eip: 3326
label: EIP-3326
title: Wallet Switch Ethereum Chain RPC Method (`wallet_switchEthereumChain`)
status: Stagnant
type: Standards Track
category: Interface
created: 2021-03-04
requires: 155, 695
official: https://eips.ethereum.org/EIPS/eip-3326
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-3326.md
canonical: https://eips.huatuo.xyz/zh/eip-3326/
lang: zh
tldr: 定义 wallet_switchEthereumChain，dApp 用这个 RPC 调用请求用户的钱包按链 ID 切换其当前活动链。
tags: [wallet, json-rpc, chain-id, multichain, interface]
---

# EIP-3326: Wallet Switch Ethereum Chain RPC Method (`wallet_switchEthereumChain`)

> An RPC method for switching the wallet's active Ethereum chain.

**TL;DR:** 定义 wallet_switchEthereumChain，dApp 用这个 RPC 调用请求用户的钱包按链 ID 切换其当前活动链。

## 它解决什么问题？

许多钱包一次只处理一条链，即**活动链**，并把所有 RPC 请求转发给它。针对特定网络（某个 L2、某个测试网）构建的 dApp，以前只能告诉用户"请把你的钱包切换到网络 X"，然后等用户手动完成。

EIP-3326 为 dApp 提供了一个标准请求，请钱包代为切换。最终仍由钱包决定，通常会向用户显示确认。

## 它如何运作

方法：`wallet_switchEthereumChain`

- **参数**：一个对象，`{ chainId: string }`。链 ID 是十六进制字符串，与 `eth_chainId`（[EIP-695](/eip-695/)）返回的一致，例如主网为 `"0x1"`。
- **返回**：如果钱包已切换则返回 `null`；否则返回错误。

在以下情况下，钱包**必须**拒绝该请求：

- `chainId` 格式不正确，
- 钱包不认识该链，或无法为其处理 RPC 请求，
- 钱包没有单一活动链的概念。

钱包**可以**出于任何其他原因拒绝，例如用户拒绝。

该方法有意不携带 RPC URL 或链元数据。添加钱包尚不认识的链，是 `wallet_addEthereumChain`（[EIP-3085](/eip-3085/)）的职责。

## 示例代码

切换，如果钱包不认识该链，则回退为添加该链：

```ts
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
```

原始 JSON-RPC 形式：

```json
{ "id": 1, "jsonrpc": "2.0", "method": "wallet_switchEthereumChain", "params": [{ "chainId": "0x1" }] }
```

## 需要注意

- 状态为 **Stagnant**，但该方法已被浏览器钱包广泛实现，是 dApp 请求切换网络的事实标准方式。
- 本 EIP 没有定义"未知链"的错误码；请谨慎地处理错误。
- 切换之后，请监听 `chainChanged` 事件（[EIP-1193](/eip-1193/)）并重新读取状态；不要仅因为你发出了请求，就认为切换已经成功。
- **安全**：静默切换可能诱使用户在错误的链上签名。规范指出，钱包应显示一个注明请求方和目标链的确认，并应取消针对旧链的待处理请求和确认。
- **隐私**：自动拒绝未知链，可能让网站借此探测钱包支持哪些链。
- 同时服务多条链的钱包可能根本没有"活动链"；较新的多链钱包 API 正在偏离这种模型。


---

This is an unofficial plain-language summary. Read the full specification: https://eips.ethereum.org/EIPS/eip-3326
