# WebSocket

> Live DegenHive events over one multiplexed WebSocket, with per-channel sequence numbers and cursor resume after a reconnect.

Source: https://docs.degenhive.ai/api/websocket

The WebSocket streams what the indexer sees on both chains, as it commits each block. One connection multiplexes many channels: a chain, a vault, a forecast job, a stock pool or a wallet.

`Endpoint`

```text
wss://api.degenhive.ai/v1/ws
```

No key is needed. Frames are JSON text in both directions.

Events are hints, not full state. Each one names what changed (a vault, a kind, an account, an amount) so you can refetch the object from the [REST API](https://docs.degenhive.ai/api.md). Treat the REST response as the source of truth and the WebSocket as the signal to read it.

## Client messages

Send one JSON object per text frame. Each has an `op`.

`subscribe`

```json
{ "op": "subscribe", "channels": ["vaults:999", "forecasting:job:1"], "cursors": { "vaults:999": 1883601528422401 } }
```

`unsubscribe`

```json
{ "op": "unsubscribe", "channels": ["forecasting:job:1"] }
```

`ping`

```json
{ "op": "ping" }
```

`cursors` is optional. It maps a channel to the last `seq` you processed, and the server replays newer buffered frames for that channel (see [Resume after a reconnect](#resume-after-a-reconnect)).

Binary frames from the client are not accepted; the server answers them with an `unsupported_binary` error.

## Server messages

| `op` | Fields | When |
|---|---|---|
| `subscribed` | `channels`, `cursors`, `rejected` | Reply to `subscribe`. `cursors` holds each accepted channel's latest `seq`. `rejected` lists names that are not valid channels or that pass the per-connection limit. |
| `unsubscribed` | `channels` | Reply to `unsubscribe` |
| `event` | `channel`, `seq`, `envelope` | An indexed on-chain event on a channel you hold |
| `candle` | `channel`, `seq`, `candle` | The current, unfinished candle of a stock pool |
| `pong` | `ts_ms` | Reply to `ping` |
| `heartbeat` | `ts_ms` | Sent by the server every heartbeat interval |
| `error` | `code`, `message` | A command could not be parsed (`invalid_message`) or was a binary frame (`unsupported_binary`) |

`event`

```json
{
  "op": "event",
  "channel": "vaults:999",
  "seq": 1883601528422402,
  "envelope": {
    "schema_version": 1,
    "chain_id": 999,
    "block_number": 21004410,
    "tx_hash": "0x…",
    "log_index": 3,
    "timestamp_ms": 1796342531000,
    "payload": {
      "type": "vault_activity",
      "data": {
        "venue": "hyper",
        "vault": "0x…",
        "kind": "deposit_queued",
        "account": "0x…",
        "epoch": 412,
        "amount": "2500000000"
      }
    }
  }
}
```

`payload.type` is one of `vault_activity`, `engine_activity`, `maker_activity`, `forecast_activity`, `data_market`, `revenue`, `token_activity`, `nft_activity`, `governance`, `config_changed`, `reorg_notice` or `head`. Amounts are integer strings in the token's base units, addresses are lowercase hex, and fields that do not apply are left out. Block-level messages (`head`, `reorg_notice`) carry an empty `tx_hash` and `log_index` 0.

`candle`

```json
{
  "op": "candle",
  "channel": "candles:0x…:5m",
  "seq": 1883601528422444,
  "candle": {
    "chain_id": 4663,
    "pool_id": "0x…",
    "interval": "5m",
    "bucket_ts_ms": 1796342400000,
    "open": "182.41",
    "high": "182.77",
    "low": "182.30",
    "close": "182.66",
    "volume_usdg": "41250000000",
    "swap_count": 37,
    "block_number": 128410233,
    "timestamp_ms": 1796342531000
  }
}
```

Candle prices are USDG per whole stock token; `volume_usdg` is in USDG base units (6 decimals).

## Channels

Channel names are case-insensitive and canonicalized to lowercase. `<chain>` is a numeric chain id: `999` for HyperEVM or `4663` for Robinhood Chain. Addresses are `0x` plus 40 hex digits and pool ids `0x` plus 64.

| Channel | Carries |
|---|---|
| `head:<chain>` | New indexed block heads (`head`) |
| `reorg:<chain>` | Reorg notices (`reorg_notice`) |
| `vaults:<chain>` | All `vault_activity` on the chain: HyperVaults on 999, BookVaults on 4663 |
| `vaults:<vault>` | `vault_activity` and `engine_activity` of one vault |
| `engines:<chain>` | All `engine_activity` |
| `engines:<engine>` | `engine_activity` of one engine |
| `maker:<chain>` | All `maker_activity`: swaps, fair ticks, pilot steps, HiveFund moves |
| `maker:<poolId>` | `maker_activity` of one pool |
| `candles:<poolId>:<interval>` | Live candles of one pool; interval `1m`, `5m`, `15m`, `1h`, `4h` or `1d` |
| `forecasting:<chain>` | All `forecast_activity`: jobs, rounds, pots, payouts, bonds, slashes |
| `forecasting:job:<jobId>` | `forecast_activity` of one job |
| `data:<chain>` | All `data_market` activity |
| `data:provider:<providerId>` | `data_market` activity of one provider |
| `revenue:<chain>` | `revenue` from `HyperRevenueRouter` and `HyperVaultFeeRouter` |
| `token:<chain>` | `token_activity` (empty until token launch) |
| `nfts:<chain>` | All `nft_activity` |
| `nfts:<collection>` | `nft_activity` of one collection, by contract address |
| `governance:<chain>` | Timelocks, upgrades, pauses and role changes |
| `config:<chain>` | `config_changed` when a protocol setting changes |
| `account:<address>` | Every message that names the address as account or counterparty |

One connection may hold up to 128 channels. A command frame may be at most 64 KiB.

## Resume after a reconnect

Every channel numbers its frames with a strictly rising `seq`, and keeps its last 256 frames in a ring buffer. To resume:

1. Store the last `seq` you processed for each channel.
2. After reconnecting, send `subscribe` with those values in `cursors`.
3. The server replays every buffered frame with a higher `seq`, then streams live frames. Replayed frames can arrive just before the `subscribed` reply, so order by `seq`.

The buffer cannot cover every gap. It holds only 256 frames per channel, and per-entity channels (one vault, one job, one wallet) drop their buffer once nobody listens. Chain-wide and candle channels keep theirs. A server restart starts a new, higher range of `seq` values.

So compare after each resubscribe. If `cursors[channel]` in the `subscribed` reply minus your stored `seq` is larger than the frames you got replayed, you missed events. Refetch the objects you track from the REST API, then carry on from the new cursor.

## Heartbeat and limits

The server sends a WebSocket ping and a JSON `heartbeat` every 20 seconds (the default heartbeat interval). Any frame you send, including the pong your client library sends automatically, counts as activity. If the server hears nothing from you for two intervals plus 5 seconds (45 seconds by default), it closes with code `1001` and reason `heartbeat timeout`. Clients that cannot see protocol pings should send `{"op":"ping"}` every 20 seconds.

| Close code | Reason | What to do |
|---|---|---|
| `1001` | `heartbeat timeout` | Reconnect and resume with cursors |
| `1008` | `slow consumer` | Your outbound queue (256 frames) filled up. Read faster or hold fewer channels, then resume. |

When the server is at its connection limit, the upgrade fails with HTTP `503`. Back off and retry.

## Examples

**TypeScript**

```ts
const WS_URL = "wss://api.degenhive.ai/v1/ws";
const channels = ["vaults:999", "forecasting:job:1", "revenue:999"];
const lastSeq: Record<string, number> = {};

function connect() {
  const ws = new WebSocket(WS_URL);
  let ping: ReturnType<typeof setInterval>;

  ws.onopen = () => {
    ws.send(JSON.stringify({ op: "subscribe", channels, cursors: lastSeq }));
    ping = setInterval(() => ws.send(JSON.stringify({ op: "ping" })), 20_000);
  };

  ws.onmessage = (ev) => {
    const msg = JSON.parse(ev.data as string);
    switch (msg.op) {
      case "subscribed":
        if (msg.rejected.length) console.warn("rejected", msg.rejected);
        break;
      case "event":
      case "candle":
        if (msg.seq <= (lastSeq[msg.channel] ?? 0)) return; // already seen
        lastSeq[msg.channel] = msg.seq;
        if (msg.op === "event") {
          const { type, data } = msg.envelope.payload;
          console.log(msg.channel, type, data.kind); // then refetch from REST
        }
        break;
      case "error":
        console.error(msg.code, msg.message);
        break;
    }
  };

  ws.onclose = () => {
    clearInterval(ping);
    setTimeout(connect, 2_000);
  };
}

connect();
```

**Python**

```python
import asyncio
import json

import websockets  # pip install websockets

WS_URL = "wss://api.degenhive.ai/v1/ws"
CHANNELS = ["vaults:999", "forecasting:job:1", "revenue:999"]
last_seq: dict[str, int] = {}

async def run() -> None:
    while True:
        try:
            # The library answers server pings and sends its own every 20 s.
            async with websockets.connect(WS_URL, ping_interval=20) as ws:
                await ws.send(json.dumps({"op": "subscribe", "channels": CHANNELS, "cursors": last_seq}))
                async for raw in ws:
                    msg = json.loads(raw)
                    if msg["op"] == "subscribed" and msg["rejected"]:
                        print("rejected", msg["rejected"])
                    elif msg["op"] in ("event", "candle"):
                        ch, seq = msg["channel"], msg["seq"]
                        if seq <= last_seq.get(ch, 0):
                            continue
                        last_seq[ch] = seq
                        if msg["op"] == "event":
                            payload = msg["envelope"]["payload"]
                            print(ch, payload["type"], payload["data"].get("kind"))
                    elif msg["op"] == "error":
                        print("error", msg["code"], msg["message"])
        except (websockets.ConnectionClosed, OSError):
            await asyncio.sleep(2)

asyncio.run(run())
```

## Related

- [REST API](https://docs.degenhive.ai/api.md) Refetch full state for anything an event names.
- [Networks & status](https://docs.degenhive.ai/network.md) Chain ids and what runs on each chain.
- [Agents, MCP & llms.txt](https://docs.degenhive.ai/agents.md) Point an AI agent at the docs.
