> 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 には公開 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}            // subscription id
← {"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":8704545703806774,"result":{…block…}}}
```

サブスクリプション ID は JSON の数値であり、16進文字列ではありません。通知にも同じ数値が含まれます。 `ethers` これを自動で処理します。 `viem`'s `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.
