> 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/ko/developer-guides/websocket-subscriptions.md).

# WebSocket 구독

WebSocket을 통해 Rome EVM 이벤트를 구독하세요 — ethers에서는 바로 작동하는 newHeads 및 logs용 eth\_subscribe; viem에서는 폴링을 사용하세요.

Rome EVM 엔드포인트는 Ethereum WebSocket 구독을 지원합니다 (`eth_subscribe` / `eth_unsubscribe`)와 함께 `wss://`. HTTPS RPC와 동일한 호스트에 연결하고, 다음과 같은 `wss://` 스킴:

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

이것이 바로 `ethers` `WebSocketProvider` 내부적으로 사용하는 것이므로, `.on('block')` 및 `contract.on(event)` 바로 작동합니다. `viem` 설정 하나가 필요하며, 이는 다음에서 설명합니다. [viem](#viem) 섹션.

## 구독 유형

| 유형                       | 발생 시점                         | 용도                                      |
| ------------------------ | ----------------------------- | --------------------------------------- |
| `newHeads`               | 각 새 블록                        | 블록 티커, 잔액/논스 새로고침, 블록별 봇, 인덱서           |
| `logs`                   | 일치하는 이벤트(다음 기준으로 `주소` / `토픽`) | 계약의 이벤트에 반응, 릴레이어/브리지, 트레이딩 봇           |
| `newPendingTransactions` | —                             | 허용되지만 절대 발생하지 않음(Rome에는 공개 mempool이 없음) |

## 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 — 계약 이벤트에 반응
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는 id가 문자열일 때만 구독을 등록합니다. Rome은 숫자를 반환하므로, `watchBlocks` 일반 `webSocket` transport는 아무것도 받지 못합니다. 다음을 전달하세요: `poll: true` 및 `viem` 대신 연결을 통해 폴링합니다(다음으로 확인됨: `watchBlocks`), 또는 다음을 사용하세요: `ethers` 푸시 업데이트용.

```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

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

구독 ID는 16진수 문자열이 아니라 JSON 숫자이며, 알림에도 같은 숫자가 포함됩니다. `ethers` 이것을 대신 처리합니다. `viem`'s `webSocket` transport는 문자열 id만 허용하므로 알림을 버립니다(다음을 참조: [viem](#viem)). 원시 클라이언트를 작성한다면, id를 숫자로 비교하고 숫자를 다시 다음에 전달하세요: `eth_unsubscribe`.

다음의 경우: `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 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/ko/developer-guides/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.
