---
eip: 695
label: EIP-695
title: Create `eth_chainId` method for JSON-RPC
status: Final
type: Standards Track
category: Interface
created: 2017-08-21
requires: 155
official: https://eips.ethereum.org/EIPS/eip-695
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-695.md
canonical: https://eips.huatuo.xyz/zh/eip-695/
lang: zh
tldr: 定义 eth_chainId JSON-RPC 方法，返回 EIP-155 链 ID，使钱包和 dapp 在签名前能够可靠地判断节点服务的是哪条链。
tags: [json-rpc, chain-id, wallet, interface]
---

# EIP-695: Create `eth_chainId` method for JSON-RPC

> Include ethchainId method in eth-namespaced JSON-RPC methods.

**TL;DR:** 定义 eth_chainId JSON-RPC 方法，返回 EIP-155 链 ID，使钱包和 dapp 在签名前能够可靠地判断节点服务的是哪条链。

## 它解决什么问题？

自 [EIP-155](/eip-155/) 起，每笔交易的签名都包含**链 ID**，使其无法在另一条链上被重放。但当时没有任何 RPC 调用可以询问节点使用的是哪个链 ID。最接近的 `net_version` 返回的是*网络* ID，这是另一个值，并不总是与链 ID 一致。

因此，应用可能以为自己连的是以太坊，实际却连上了以太坊经典（Ethereum Classic）的节点，反之亦然，直到签名失败才会发现。规范点名 MetaMask 等钱包开发者受到影响，因为他们要支持多条链，需要这个功能。

## 它如何运作

- **方法：** `eth_chainId`
- **参数：** 无
- **返回：** 以十六进制 `QUANTITY` 字符串表示的链 ID，例如以太坊主网为 `"0x1"`。

该值必须与节点**当前头区块**适用的规则一致，这样调用者可以立即用它为建立在该头区块之上的交易签名。如果头区块没有链 ID，节点应表现得如同不支持该方法，并返回错误。

使用方应使用 `eth_chainId` 而不是 `net_version` 来识别一条链。

## 示例代码

通过 HTTP 发送的原始 JSON-RPC：

```sh
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"}
```

使用 ethers v6（底层会调用 `eth_chainId`）：

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

在使用 [EIP-1193](/eip-1193/) provider API 的浏览器钱包中：

```ts
const chainIdHex = await window.ethereum.request({ method: "eth_chainId" });
```

## 需要注意

- 结果是十六进制字符串，而不是数字。比较之前请先解析（`BigInt("0x1") === 1n`）。
- 链 ID 和网络 ID 经常相等，但并非总是如此。签名时务必使用链 ID。
- 当节点跟随一个会更改链 ID 的分叉时，链 ID 可能发生变化。重新连接时请重新检查，在 dapp 中则要监听钱包的 `chainChanged` 事件。
- 添加或切换链的钱包方法都建立在它之上：[EIP-3085](/eip-3085/)（`wallet_addEthereumChain`）和 [EIP-3326](/eip-3326/)（`wallet_switchEthereumChain`）。


---

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