---
id: SI0013
title: "WebSocket monitoring copilot"
url: https://carbium.sh/library/si/websocket-monitoring-copilot
collection: AI and blockchain
category: Monitoring copilots
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# WebSocket monitoring copilot

Monitor an address by subscribing over WebSocket instead of polling. You get a watcher that prints one compact line per transaction, reconnects with backoff and backfills the gap, plus a guide to which Solana monitoring call fits which question.

## Which monitor fits the question

Monitoring Solana comes down to three jobs. You want to hear about an event as it happens, you want to read a value on a schedule, or you want the whole feed so you can filter it yourself. The first job belongs to a WebSocket subscription. A copilot here is a small program that watches the chain and decides what a person or a model should hear about. The watching is plain code, and the model only reads what the code prints.

| Question | Call | Cost on Carbium |
|---|---|---|
| A transaction mentions this address | `logsSubscribe` with `mentions` | opens at 25 credits |
| Did this one signature land | `signatureSubscribe`, one confirmation, then it ends | opens at 5 credits |
| An account's state changed | `accountSubscribe` | opens at 25 credits, silent for a plain SOL wallet |
| Every log on the chain | `logsSubscribe` with `all` | opens at 200 credits |
| A value on a schedule | `getSlot`, `getHealth` or another cached read | 1 cell per call |
| A full feed you filter yourself | the gRPC stream on port 9443 | opens at 5, 25 or 200 credits by filter weight, then 20 credits per MiB; Dev, Business and Pro, Free is off |

A subscription opens at its weight in credits and then costs 20 credits per MiB sent. A refused subscription is free. Cells are the admission charge per RPC call against the plan's per-second rate, and the schedule row is the one priced in cells.

Poll when the answer is a value you read at your own pace. Subscribe when you care about an event and the gap between two polls could hide it. A plain SOL wallet is the one surprise: `accountSubscribe` stays silent for it, so subscribe with `logsSubscribe` mentions and read the balance with `getBalance` after each event.

## The watcher

One file on Node 24, with `@solana/kit` 8.6.0 for the RPC client and the global `WebSocket` for the stream. Set `CARBIUM_KEY` first; the file exits with a message when it is missing. `CARBIUM_RPC_URL` and `CARBIUM_WS_URL` override the endpoints, which default to `https://services.carbium.sh` and `wss://services.carbium.sh`.

`main.ts` (run: `node main.ts`)

```ts
// SI0013 · WebSocket monitoring copilot
// https://carbium.sh/library/si/websocket-monitoring-copilot
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Watch one address over WebSocket. Run: CARBIUM_KEY=... node main.ts [address] [events]
import { address, signature, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const rpcUrl = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);

const watched = process.argv[2] ?? "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const maxEvents = Number(process.argv[3] ?? Infinity);
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: rpcUrl, headers: { "x-api-key": key } }));
const seen = new Set<string>();
let newest = "";
let retryMs = 1000;
let count = 0;

const emit = (line: object) => console.log(JSON.stringify(line));

// True the first time a signature is seen; keeps the set bounded.
function fresh(sig: string) {
  if (seen.has(sig)) return false;
  seen.add(sig);
  if (seen.size > 5000) seen.delete(seen.values().next().value as string);
  newest = sig;
  return true;
}

// After a reconnect: print what landed while the socket was down (newest 100).
async function backfill() {
  if (!newest) return;
  const missed = await rpc.getSignaturesForAddress(address(watched), { until: signature(newest), limit: 100 }).send();
  for (const s of [...missed].reverse()) {
    if (fresh(s.signature)) emit({ slot: Number(s.slot), signature: s.signature, ok: s.err === null, backfilled: true });
  }
}

function connect() {
  const ws = new WebSocket(wsUrl);
  ws.onopen = () => {
    retryMs = 1000;
    const filter = { mentions: [watched] };
    ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params: [filter, { commitment: "confirmed" }] }));
    backfill().catch((e) => emit({ warn: `backfill failed: ${(e as Error).message}` }));
  };
  ws.onmessage = (m) => {
    const msg = JSON.parse(String(m.data));
    if (msg.id === 1) {
      if (!msg.error) return emit({ subscribed: msg.result });
      emit({ error: String(msg.error.message) });
      process.exit(1);
    }
    if (msg.method !== "logsNotification") return;
    const { context, value } = msg.params.result as { context: { slot: number }; value: { signature: string; err: unknown; logs: string[] } };
    if (!fresh(value.signature)) return;
    const programs = [...new Set(value.logs.flatMap((l) => l.match(/^Program (\w+) invoke \[1\]$/)?.[1] ?? []))];
    emit({ slot: context.slot, signature: value.signature, ok: value.err === null, programs });
    if (++count >= maxEvents) process.exit(0);
  };
  ws.onclose = () => {
    emit({ reconnect_ms: retryMs });
    setTimeout(connect, retryMs);
    retryMs = Math.min(retryMs * 2, 30000);
  };
}

connect();
```

The first argument is the address to watch and defaults to the USDC mint. The second stops the process after that many live events, which suits a first run. Leave it out and the watcher runs until you stop it. The first line printed is `{"subscribed":<id>}`, once the server accepts the subscription. Each later line is one transaction: `slot`, `signature`, `ok` (true when the transaction has no error) and `programs`, the programs invoked at the top level of the transaction.

A transaction's raw logs often run to many lines, and a model asked to watch them spends its context on log noise. The watcher filters in code and hands over four fields. If a model should explain an event, give it the signature and let it ask for the transaction through a read-only tool such as [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools). A `getTransaction` call costs 50 cells.

> `mentions` takes a single address. To watch several addresses, open one subscription for each and count each against your limits.

## Reconnects and the gap behind them

A socket will close sooner or later, and the server does not replay what you missed. The watcher handles that in `onclose`: it waits, doubling from 1 s up to 30 s, and connects again. A successful open resets the wait to 1 s, subscribes again and runs the backfill.

The backfill calls `getSignaturesForAddress` with `until` set to the newest signature seen and a limit of 100. It returns everything newer than that signature, newest first, so the code reverses the list and prints each signature it has not seen, marked `backfilled`. A `seen` set removes the overlap with events that arrive on the new socket. The call leaves commitment out, so `@solana/kit` 8.6.0 fills in `confirmed`, the level the subscription asks for. The server's own default would be `finalized`.

`getSignaturesForAddress` costs 50 cells: 0.24 requests per second on Free, 1.2 on Dev, 100 on Business and 500 on Pro. On Free a reconnect storm can run past that rate, so the code catches a failed backfill and prints a `warn` line instead of dying. The address index behind this call keeps up to 30 days, and an empty page past that is the index's age limit. A gap of minutes sits far inside it.

> Backfilled lines carry no `programs` field, because a signature list holds no logs. Fetch the transaction if you need them.

## Ordering

Do not expect a clean order. Lines filled in by the backfill are printed after live events that may be newer, so the printed order is not slot order. Treat `slot` as a label, sort by it where order matters and key everything on the signature.

## Budget, sockets and the key

Credits are charged on bytes sent, so choose the narrowest subscription that answers the question. `logsSubscribe` with `mentions` for one address opens at 25 credits. `all` opens at 200 and streams every transaction log, far more traffic than one address produces, at 20 credits per MiB.

Limits are per account, and an account's keys share one budget. Connection and subscription counts are capped by tier, and Free carries 5 sockets. A refused subscribe call prints the server's message and the watcher exits. A socket that cannot connect is retried with backoff, up to every 30 s, and the watcher never exits on its own. Keep to one socket per process.

The key sits in the WebSocket URL as `?api-key=`, so treat that URL as a secret. The file never prints it, and its error lines carry only a message. Some logging libraries print the URL of a failed connection, so do not wire one in here. If a query string is awkward for you, the WebSocket can carry the key as the subprotocol `api-key.<YOUR_KEY>` instead.

## Where it ends

- The watcher sees transactions that list the address in their account keys. For the default example that leaves a gap: a plain SPL `transfer` between token accounts does not list the mint, so watching the USDC mint misses those transfers. A transfer into an existing token account lists the token accounts and the sender's authority, never the receiving wallet, so watch the token account itself. The owner wallet appears only on transfers it signs.
- A socket that stalls without closing goes unnoticed, and a quiet address looks the same as a dead one. For a busy address, compare the newest event's slot with `getSlot` and reconnect when the gap grows.
- The backfill covers the newest 100 signatures after the last one seen, and nothing older than the 30-day address index. A longer gap on a busy address loses its oldest events.
- `newest` and `seen` live in memory, so a restart forgets the gap it was down for. Write the newest signature to disk, for example with `node:sqlite`, if the watcher must survive restarts.
- This is one address on one socket. A full feed filtered on your side belongs on the gRPC stream, which is a different client and is not in this file.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| `accountSubscribe` never fires for a SOL wallet. | It stays silent for a plain SOL wallet. Subscribe with `logsSubscribe` mentions and read the balance with `getBalance` when an event arrives. |
| Events vanish for the length of a disconnect. | Reconnect with backoff and backfill from the newest signature seen, as the file does. The server does not replay. |
| The backfill answers 429 after a reconnect storm. | Print a warning and carry on, as the file does, then run the backfill again after the retry-after wait. Check the account's other keys, which share the budget. |
| The watcher exits at start, or prints `reconnect_ms` lines and never subscribes. | An exit after an `error` line means the subscribe call was refused over the subscription cap: close idle subscriptions on the account or move to a tier with room. Repeated `reconnect_ms` lines with no `subscribed` line mean no socket is staying open, so check whether the account already holds its socket cap (Free carries 5): close idle sockets on the account or move to a tier with room. Both counts are per account by tier, and a refused subscription is free. |
| The key shows up in a log line. | It is in the WebSocket URL. Log your own messages only, never the URL or a raw connection error, or send the key as the `api-key.<YOUR_KEY>` subprotocol. |
| A quiet address looks like a dead socket. | For a busy address, compare the newest event's slot with `getSlot` (a cached read, 1 cell) and reconnect when the gap grows. For a quiet address, silence is normal. |

## Questions

### Should I poll or subscribe?

Subscribe when you need to hear about an event and a gap between polls could hide it. Poll a cached read such as `getSlot` for a value you check on your own schedule; it costs 1 cell a call.

### Why does accountSubscribe stay silent for my wallet?

A plain SOL wallet stays silent on that subscription. Use `logsSubscribe` with `mentions` and read the balance with `getBalance` after each event.

### How far back can the backfill reach?

To the newest 100 signatures after the last one seen, and no further than the 30-day address index.

### When do I need the gRPC stream?

When you want a full feed to filter yourself instead of one subscription per question. It opens on Dev, Business and Pro at `https://services.carbium.sh:9443` and takes the key in the `x-token` header. Free is off.

### How do I send these events to a model?

Pass the printed line: slot, signature, `ok` and `programs` are enough for a model to decide whether to ask for the transaction through a read-only tool. [Slack slot-lag alerts](https://carbium.sh/library/integrate/slack-slot-lag-alerts) shows the same pattern for a person reading a channel.

## Related

- [Slack slot-lag alerts](https://carbium.sh/library/integrate/slack-slot-lag-alerts) (Integrations, I0001)
- [Read-only model tools](https://carbium.sh/library/si/read-only-model-tools) (AI and blockchain, SI0001)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#stream](https://carbium.sh/docs#stream)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
