> 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/es/guias-para-desarrolladores/websocket-subscriptions.md).

# Suscripciones de WebSocket

Suscríbete a eventos de Rome EVM por WebSocket: eth\_subscribe con newHeads y logs, funcionando de inmediato con ethers; con viem, usa sondeo.

Los endpoints EVM de Rome admiten suscripciones WebSocket de Ethereum (`eth_subscribe` / `eth_unsubscribe`) sobre `wss://`. Conéctate al mismo host que el RPC HTTPS, con el `wss://` esquema:

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

Esto es lo que `ethers` `WebSocketProvider` usa internamente, así que `.on('block')` y `contract.on(event)` funcionan de inmediato. `viem` necesita una configuración, descrita en la [viem](#viem) sección.

## Tipos de suscripción

| Tipo                     | Se activa en                                    | Usar para                                                                     |
| ------------------------ | ----------------------------------------------- | ----------------------------------------------------------------------------- |
| `newHeads`               | cada nuevo bloque                               | marcadores de bloques, actualizar saldos/nonces, bots por bloque, indexadores |
| `logs`                   | eventos coincidentes (por `address` / `topics`) | reaccionar a los eventos de tu contrato, relayers/bridges, bots de trading    |
| `newPendingTransactions` | —                                               | aceptado pero nunca emite (Rome no tiene mempool público)                     |

## ethers (v6)

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

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

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

// logs — reacciona a un evento del contrato
const contract = new ethers.Contract(address, abi, provider);
contract.on("Transfer", (from, to, value) => {
  console.log("Transfer", from, to, value.toString());
});
```

## viem

`viem`de `webSocket` el transporte registra una suscripción solo cuando el id es una cadena. Rome devuelve un número, así que `watchBlocks` sobre un simple `webSocket` el transporte no recibe nada. Pasa `poll: true` y `viem` consulta a través de la conexión en su lugar (verificado con `watchBlocks`), o usa `ethers` para actualizaciones 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("nuevo bloque", block.number),
});

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

## JSON-RPC en bruto

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

El id de suscripción es un número JSON, no una cadena hexadecimal, y las notificaciones llevan el mismo número. `ethers` lo gestiona por ti. `viem`de `webSocket` el transporte solo acepta un id de cadena, así que descarta las notificaciones (consulta [viem](#viem)). Si escribes un cliente en bruto, compara los ids como números y devuelve el número a `eth_unsubscribe`.

Para `logs`, pasa un objeto de filtro como segundo parámetro:

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

## Notas

* Las suscripciones envían actualizaciones a medida que se producen nuevos bloques (la latencia es del orden del tiempo de un bloque).
* Para conexiones de larga duración, gestiona las reconexiones en tu cliente — algo estándar para cualquier 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/es/guias-para-desarrolladores/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.
