---
eip: 2786
label: EIP-2786
title: Ethereum Provider Connect/Disconnect Events
status: Withdrawn
type: Standards Track
category: Interface
created: 2020-07-15
requires: 2700
official: https://eips.ethereum.org/EIPS/eip-2786
source: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-2786.md
canonical: https://eips.huatuo.xyz/zh/eip-2786/
lang: zh
tldr: 一项已撤回的提案，让注入式以太坊提供者在获得或失去处理 RPC 请求的能力时触发 `connect` 和 `disconnect` 事件；该行为现已写入 EIP-1193。
tags: [provider, javascript, events, wallet, interface]
---

# EIP-2786: Ethereum Provider Connect/Disconnect Events

> When an Ethereum Provider becomes connected or disconnected, it will emit a connect/disconnect event.

**TL;DR:** 一项已撤回的提案，让注入式以太坊提供者在获得或失去处理 RPC 请求的能力时触发 `connect` 和 `disconnect` 事件；该行为现已写入 EIP-1193。

## 它解决什么问题？

与注入式提供者（例如浏览器钱包）通信的 dapp 需要知道提供者何时无法再连接任何链，以便提醒用户而不是悄悄失败，也需要知道它何时恢复。提供者在实践中早已触发这类事件，但这一行为没有被一致地记录下来。

EIP-2786 是一项主要为事后补记的提案，试图把这些 `connect` / `disconnect` 事件编成一个小型的独立标准。

## 它如何运作

该提案定义了两种状态：

- **Connected：**提供者至少可以处理发往一条链的 RPC 请求。
- **Disconnected：**它无法处理发往任何链的 RPC 请求。

当提供者从 disconnected 变为 connected 时，必须向通过 [EIP-2700](/eip-2700/) 事件发射器接口注册的每个监听器触发 `connect`。监听器会收到 `{ chainId }`，其中 `chainId` 是链的整数 ID 的十六进制字符串；如果提供者支持 `eth_chainId`，则必须与之一致。监听器可以按任意顺序被调用。

在相反的转换时会触发对应的 `disconnect` 事件。应用自行决定是否以及如何响应。

## 示例代码

在注入式提供者上监听这两个事件：

```ts
const provider = (window as any).ethereum;

provider.on("connect", ({ chainId }: { chainId: string }) => {
  console.log("Provider connected to chain", parseInt(chainId, 16));
});

provider.on("disconnect", (error: { code: number; message: string }) => {
  // In EIP-1193 the payload is a ProviderRpcError, typically code 4900
  console.warn("Provider disconnected:", error.code, error.message);
});
```

## 需要注意

- 状态为 **Withdrawn**。connect 和 disconnect 事件在 [EIP-1193](/eip-1193/)（Final）中有规定，钱包和库实现的是它。请使用那份规范，而不是这一份。
- 被撤回的文本本身前后不一致：abstract 把两种转换弄反了（它说在变为 disconnected 时触发 `connect`），而规范部分只定义了 `connect` 事件。上面示例中的 `disconnect` 载荷遵循 EIP-1193。
- 它依赖 [EIP-2700](/eip-2700/) 的事件发射器接口；请求传输层在 [EIP-2696](/eip-2696/) 中。
- 设计理由中提到，为了与现有行为保持一致，按链区分的 connect/disconnect 事件被省略了。


---

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