> For the complete documentation index, see [llms.txt](https://docs.rome.builders/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/websocket-subscriptions.md).

# WebSocket 订阅

Rome EVM 端点支持以太坊 WebSocket 订阅（`eth_subscribe` / `eth_unsubscribe`) 通过 `wss://`。连接到与 HTTPS RPC 相同的主机，并使用 `wss://` 协议：

```
wss://<chain>.<network>.romeprotocol.xyz/
```

这就是 `ethers` / `viem` `WebSocketProvider` 在底层使用的，因此 `.on('block')`, `contract.on(event)`，以及 `viem`的 `watchEvent` / `watchBlocks` 开箱即用。

## 订阅类型

| 类型                       | 触发于                  | 用途                            |
| ------------------------ | -------------------- | ----------------------------- |
| `newHeads`               | 每个新区块                | 区块轮询、刷新余额/nonce、按区块运行的机器人、索引器 |
| `logs`                   | 匹配的事件（按 `地址` / `主题`) | 响应合约事件、中继器/桥接器、交易机器人          |
| `newPendingTransactions` | —                    | 已接受但从不发出（Rome 没有公共内存池）        |

## ethers（v6）

```javascript
import { ethers } from "ethers";

const provider = new ethers.WebSocketProvider(
  "wss://martius.testnet.romeprotocol.xyz/"
);

// 新区块
provider.on("block", (blockNumber) => {
  console.log("新区块", blockNumber);
});

// 日志 — 响应合约事件
const contract = new ethers.Contract(address, abi, provider);
contract.on("Transfer", (from, to, value) => {
  console.log("Transfer", from, to, value.toString());
});
```

## viem

```javascript
import { createPublicClient, webSocket } from "viem";

const client = createPublicClient({
  transport: webSocket("wss://martius.testnet.romeprotocol.xyz/"),
});

const unwatch = client.watchBlocks({
  onBlock: (block) => console.log("新区块", block.number),
});

client.watchEvent({
  address,
  onLogs: (logs) => console.log(logs),
});
```

## 原始 JSON-RPC

```json
→ {"jsonrpc":"2.0","id":1,"method":"eth_subscribe","params":["newHeads"]}
← {"jsonrpc":"2.0","id":1,"result":"0x…"}                       // 订阅 ID
← {"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0x…","result":{…block…}}}
```

对于 `logs`，请将过滤器对象作为第二个参数：

```json
{"jsonrpc":"2.0","id":1,"method":"eth_subscribe","params":["logs",{"address":"0x…","topics":["0x…"]}]}
```

## 备注

* 订阅会在新区块生成时推送更新（延迟约为一个区块时间）。
* 对于长期连接，请在客户端处理重连——这是任何 WebSocket RPC 的标准做法。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://docs.rome.builders/zh/kai-fa-zhe-zhi-nan/websocket-subscriptions.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
