> 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/vi/huong-dan-cho-nha-phat-trien/websocket-subscriptions.md).

# Đăng ký WebSocket

Đăng ký theo dõi các sự kiện Rome EVM qua WebSocket — eth\_subscribe với newHeads và logs, hoạt động ngay với ethers; với viem, hãy dùng polling.

Các endpoint Rome EVM hỗ trợ đăng ký WebSocket của Ethereum (`eth_subscribe` / `eth_unsubscribe`) trên `wss://`. Kết nối tới cùng host với HTTPS RPC, với `wss://` giao thức:

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

Đây là thứ mà `ethers` `WebSocketProvider` sử dụng bên dưới lớp vỏ, nên `.on('block')` và `contract.on(event)` hoạt động ngay lập tức. `viem` cần một thiết lập, được mô tả trong [viem](#viem) phần.

## Các loại đăng ký

| Loại                     | Kích hoạt khi                                | Dùng cho                                                                     |
| ------------------------ | -------------------------------------------- | ---------------------------------------------------------------------------- |
| `newHeads`               | mỗi khối mới                                 | ticker khối, làm mới số dư/nonce, bot theo từng khối, bộ lập chỉ mục         |
| `logs`                   | các sự kiện khớp (theo `address` / `topics`) | phản ứng với các sự kiện của hợp đồng, relayer/cầu nối, bot giao dịch        |
| `newPendingTransactions` | —                                            | được chấp nhận nhưng không bao giờ phát ra (Rome không có mempool công khai) |

## ethers (v6)

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

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

// newHeads
provider.on("block", (blockNumber) => {
  console.log("new block", blockNumber);
});

// logs — phản ứng với một sự kiện của hợp đồng
const contract = new ethers.Contract(address, abi, provider);
contract.on("Transfer", (from, to, value) => {
  console.log("Transfer", from, to, value.toString());
});
```

## viem

`viem`của `webSocket` transport chỉ đăng ký một subscription khi id là chuỗi. Rome trả về một số, nên `watchBlocks` trên một `webSocket` transport không nhận được gì. Hãy truyền `poll: true` và `viem` thay vào đó, nó poll qua kết nối (được kiểm tra với `watchBlocks`) `ethers` để nhận cập nhật đẩy.

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

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

const unwatch = client.watchBlocks({
  poll: true,
  onBlock: (block) => console.log("new block", block.number),
});

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

## JSON-RPC thô

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

ID đăng ký là một số JSON, không phải chuỗi hex, và các thông báo mang cùng số đó. `ethers` xử lý việc này cho bạn. `viem`của `webSocket` transport chỉ chấp nhận id dạng chuỗi, nên nó loại bỏ các thông báo (xem [viem](#viem)). Nếu bạn viết một client thô, hãy so sánh id dưới dạng số và truyền lại số đó cho `eth_unsubscribe`.

Đối với `logs`, hãy truyền một đối tượng bộ lọc làm tham số thứ hai:

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

## Ghi chú

* Các subscription đẩy cập nhật khi các khối mới được tạo ra (độ trễ ở mức một khoảng thời gian khối).
* Với các kết nối sống lâu, hãy xử lý việc kết nối lại trong client của bạn — điều tiêu chuẩn cho mọi 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.rome.builders/vi/huong-dan-cho-nha-phat-trien/websocket-subscriptions.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
