> 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 EVM của Rome hỗ trợ đăng ký WebSocket của Ethereum (`eth_subscribe` / `eth_unsubscribe`) qua `wss://`. Kết nối tới cùng host như HTTPS RPC, với `wss://` scheme:

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

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

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

| Loại                     | Kích hoạt khi                               | Dùng cho                                                                      |
| ------------------------ | ------------------------------------------- | ----------------------------------------------------------------------------- |
| `newHeads`               | mỗi khối mới                                | bộ đếm 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 `địa chỉ` / `topic`) | phản ứng với các sự kiện của hợp đồng của bạn, 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 — react to a contract event
const contract = new ethers.Contract(address, abi, provider);
contract.on("Transfer", (from, to, value) => {
  console.log("Transfer", from, to, value.toString());
});
```

## viem

`viem`'s `webSocket` transport chỉ đăng ký một subscription khi id là một chuỗi. Rome trả về một số, vì vậy `watchBlocks` trên một `webSocket` transport sẽ không nhận được gì. Hãy truyền `poll: true` và `viem` thay vào đó sẽ thăm dò qua kết nối (được kiểm tra với `watchBlocks`), hoặc dùng `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…}}}
```

Subscription id 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`'s `webSocket` transport chỉ chấp nhận id dạng chuỗi, nên nó bỏ qua 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 số đó lại 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ễ cỡ thời gian của một khối).
* Với các kết nối tồn tại lâu dài, hãy xử lý việc kết nối lại trong client của bạn — đây là điều tiêu chuẩn với bất kỳ WebSocket RPC nào.


---

# 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.
