> 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/ja/gaido/websocket-subscriptions.md).

# WebSocket サブスクリプション

WebSocket経由でRome EVMイベントを購読します — newHeadsとlogsを使ったeth\_subscribe、ethersではそのまま動作し、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` には 1 つ設定が必要で、これは [viem](#viem) のセクションで説明されています。

## サブスクリプションの種類

| 型                        | 発火条件                       | 用途                                      |
| ------------------------ | -------------------------- | --------------------------------------- |
| `newHeads`               | 新しいブロックごと                  | ブロックティッカー、残高/nonce の更新、ブロック単位のボット、インデクサ |
| `logs`                   | 一致するイベント（ `アドレス` / `トピック`) | あなたのコントラクトのイベントへの反応、リレー/ブリッジ、トレーディングボット |
| `newPendingTransactions` | —                          | 受け入れられるが、決して発行されない（Rome には公開メンプールがないため） |

## ethers（v6）

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

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

// newHeads
provider.on("block", (blockNumber) => {
  console.log("新しいブロック", 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`の `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 は JSON の数値であり、16 進文字列ではありません。通知にも同じ数値が含まれます。 `ethers` はこれを自動で処理します。 `viem`の `webSocket` transport は文字列の id しか受け付けないため、通知を破棄します（ [viem](#viem)）。生のクライアントを書く場合は、id を数値として比較し、その数値を `eth_unsubscribe`.

では `logs`、第 2 引数にフィルターオブジェクトを渡します：

```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/ja/gaido/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.
