---
title: "eth_subscribe"
description: "通过 WebSocket 订阅 EVM 事件（Optimism Sepolia）"
url: "https://blockreq.com/docs/zh-cn/build/api-reference/optimism-sepolia/eth_subscribe/"
---

# eth_subscribe

**网络：** Optimism Sepolia · 测试网 · Chain ID `11155420`（`0xaa37dc`）

**计为 1 个 Request。** 计费规则见 [Request Counting](https://blockreq.com/docs/zh-cn/pricing/request-counting/index.md)。

`eth_subscribe` 只能通过 WSS endpoint 使用。链路开启 WSS 时，可订阅 `newHeads`、`logs` 等实时事件。

## 参数

1. `String` - 订阅类型，如 `newHeads`、`logs`、`newPendingTransactions`。
2. `Object` - 可选过滤对象，例如 `logs` 订阅的地址和 topics。

## 请求

```json
{
  "jsonrpc": "2.0",
  "method": "eth_subscribe",
  "params": ["newHeads"],
  "id": 1
}
```

## 代码示例

**TypeScript**

```typescript
const ws = new WebSocket("wss://optimism-sepolia-rpc.blockreq.com/v1/rpc/public");

ws.onopen = () => {
  ws.send(JSON.stringify({
  "jsonrpc": "2.0",
  "method": "eth_subscribe",
  "params": [
    "newHeads"
  ],
  "id": 1
}));
};
ws.onmessage = (event) => {
  console.log(JSON.parse(event.data));
};
```

**Python**

```python
import asyncio
import json

import websockets

async def main():
    async with websockets.connect("wss://optimism-sepolia-rpc.blockreq.com/v1/rpc/public") as ws:
        await ws.send('{"jsonrpc":"2.0","method":"eth_subscribe","params":["newHeads"],"id":1}')
        async for message in ws:
            print(json.loads(message))

asyncio.run(main())
```
