> 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/pt-br/guias-do-desenvolvedor/websocket-subscriptions.md).

# Assinaturas de WebSocket

Assine eventos da Rome EVM via WebSocket — eth\_subscribe com newHeads e logs, funcionando imediatamente com ethers; com viem, use polling.

Os endpoints EVM da Rome oferecem suporte a assinaturas WebSocket do Ethereum (`eth_subscribe` / `eth_unsubscribe`) em `wss://`. Conecte-se ao mesmo host do RPC HTTPS, com o `wss://` esquema:

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

É isso que o `ethers` `WebSocketProvider` usa por baixo dos panos, então `.on('block')` e `contract.on(event)` funciona sem configuração extra. `viem` precisa de uma configuração, descrita na [viem](#viem) seção.

## Tipos de assinatura

| Tipo                     | Dispara em                                           | Use para                                                                        |
| ------------------------ | ---------------------------------------------------- | ------------------------------------------------------------------------------- |
| `newHeads`               | cada novo bloco                                      | contadores de blocos, atualização de saldos/nonces, bots por bloco, indexadores |
| `logs`                   | eventos correspondentes (por `endereço` / `tópicos`) | reagir aos eventos do seu contrato, relayers/bridges, bots de trading           |
| `newPendingTransactions` | —                                                    | aceito, mas nunca emite (a Rome não tem mempool pública)                        |

## ethers (v6)

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

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

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

// logs — reaja a um evento do contrato
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` o transport registra uma assinatura somente quando o id é uma string. A Rome retorna um número, então `watchBlocks` em um `WebSocket` transport comum não recebe nada. Passe `poll: true` e `viem` faz polling pela conexão em vez disso (verificado com `watchBlocks`), ou use `ethers` para atualizações push.

```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("novo bloco", block.number),
});

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

## JSON-RPC bruto

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

O id da assinatura é um número JSON, não uma string hexadecimal, e as notificações carregam o mesmo número. `ethers` cuida disso para você. `viem`'s `WebSocket` o transport só aceita um id em string, então descarta as notificações (veja [viem](#viem)). Se você escrever um cliente bruto, compare os ids como números e passe o número de volta para `eth_unsubscribe`.

Para `logs`, passe um objeto de filtro como segundo parâmetro:

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

## Observações

* As assinaturas enviam atualizações à medida que novos blocos são produzidos (a latência fica na ordem do tempo de um bloco).
* Para conexões de longa duração, trate as reconexões no seu cliente — padrão para qualquer RPC WebSocket.


---

# 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/pt-br/guias-do-desenvolvedor/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.
