---
id: HS0011
title: "Multi-wallet log watcher"
url: https://carbium.sh/library/howsolana/multi-wallet-log-watcher
collection: How to use Solana
category: WebSocket
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Multi-wallet log watcher

One TypeScript file opens a logsSubscribe per wallet, prints each transaction once per wallet, reconnects with backoff when the socket drops, and backfills what the gap hid from the address index. It only reads: no keypair, nothing signed or sent.

## Where the gaps come from

`onLogs` in `@solana/web3.js` wraps the `logsSubscribe` method, whose `mentions` filter takes a list but accepts a single address. Watching 200 wallets therefore means 200 subscriptions. Transactions go missing in the gaps around those subscriptions.

On Carbium, `logsSubscribe` streams transaction logs, either all of them or only those that mention an address. Each notification carries the signature, an `err` field that is null on success, and the log lines. One transaction that touches two of your wallets arrives once per subscription.

| Cause | What you see | What closes it |
|---|---|---|
| A subscription was refused | Some wallets never report while the rest look healthy | Read every subscribe reply and log the refusals |
| The socket closed | Every wallet goes quiet at once, with a gap when it comes back | Reconnect with backoff, then backfill the gap |
| A new socket without new subscriptions | The socket is open and nothing arrives | Send every `logsSubscribe` again on each open, because subscriptions belong to the socket that made them |
| A replay after a reconnect | The same signature printed twice | Keep a set keyed by wallet and signature |
| `accountSubscribe` on a plain SOL wallet | Silence | Use `logsSubscribe` with mentions, plus `getBalance` for the amount |

## The code

Install `@solana/kit` at 8.6.0, export `CARBIUM_KEY` and run the file with Node 24, which strips TypeScript types on its own. Pass one or more wallet addresses as arguments.

`main.ts` (run: `node main.ts <wallet-address> [wallet-address ...]`)

```ts
// HS0011 · Multi-wallet log watcher
// https://carbium.sh/library/howsolana/multi-wallet-log-watcher
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { setTimeout as sleep } from "node:timers/promises";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, isSolanaError, signature,
  SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR } from "@solana/kit";
const key = process.env.CARBIUM_KEY;
const wallets = process.argv.slice(2).map((w) => address(w));
if (!key || wallets.length === 0) {
  console.error("Set CARBIUM_KEY and pass one or more wallet addresses.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),
);
const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);

const seen = new Set<string>(); // wallet:signature, so a replay never prints twice
const newest = new Map<string, { slot: number; sig: string }>(); // backfill anchor per wallet
let attempt = 0;

function record(wallet: string, sig: string, slot: number, err: unknown, via: string) {
  if (seen.has(`${wallet}:${sig}`)) return;
  seen.add(`${wallet}:${sig}`);
  if (slot >= (newest.get(wallet)?.slot ?? 0)) newest.set(wallet, { slot, sig });
  console.log(`${via} slot=${slot} ${err ? "failed" : "ok"} ${wallet.slice(0, 8)} ${sig}`);
}

async function backfill(wallet: string, sig: string) {
  const rows = await rpc.getSignaturesForAddress(address(wallet), { until: signature(sig), limit: 1000 }).send();
  for (const r of [...rows].reverse()) record(wallet, r.signature, Number(r.slot), r.err, "backfill");
}

async function backfillAll(anchors: typeof newest) {
  for (const w of wallets) {
    const sig = anchors.get(w)?.sig;
    if (!sig) continue;
    for (let n = 1; n <= 3; n++) {
      try {
        await backfill(w, sig);
        break;
      } catch (e) {
        if (!isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) || e.context.statusCode !== 429 || n === 3) {
          console.error(`backfill failed for ${w}`);
          break;
        }
        const seconds = Number(e.context.headers.get("retry-after")) || 1;
        console.error(`429 on ${w}: waiting ${seconds}s`);
        await sleep(seconds * 1000);
      }
    }
  }
}

function connect() {
  const ws = new WebSocket(wsUrl);
  const pending = new Map<number, string>();
  const subs = new Map<number, string>();
  let replies = 0;
  let anchors = newest; // replaced by a copy on open, before any subscribe is sent
  ws.addEventListener("open", () => {
    attempt = 0;
    anchors = new Map(newest);
    wallets.forEach((w, i) => {
      pending.set(i + 1, w);
      ws.send(JSON.stringify({ jsonrpc: "2.0", id: i + 1, method: "logsSubscribe", params: [{ mentions: [w] }, { commitment: "confirmed" }] }));
    });
  });
  ws.addEventListener("message", (ev) => {
    const msg = JSON.parse(String(ev.data));
    if (msg.id !== undefined) {
      const w = pending.get(msg.id) ?? "?";
      if (msg.error) console.error(`subscription refused for ${w}: ${msg.error.message}`);
      else {
        subs.set(msg.result, w);
        console.log(`subscribed ${w}`);
      }
      if (++replies === wallets.length) void backfillAll(anchors);
    } else if (msg.method === "logsNotification") {
      const { context, value } = msg.params.result;
      const w = subs.get(msg.params.subscription);
      if (w) record(w, value.signature, context.slot, value.err, "live");
    }
  });
  ws.addEventListener("close", () => {
    const wait = Math.min(1000 * 2 ** attempt++, 30_000);
    console.error(`socket closed, reconnecting in ${wait} ms`);
    setTimeout(connect, wait);
  });
}
connect();
```

The file keeps three pieces of state. `seen` holds `wallet:signature` pairs so a replay prints nothing. `newest` holds the highest slot and its signature for each wallet, and each open copies it as the anchors for that reconnect's backfill. `attempt` drives the reconnect delay, which doubles from 1 s up to 30 s and resets when a socket opens.

## Closing the gap after a drop

On every open the file copies the anchors, sends all the subscribe requests, and starts the backfill only after every subscribe reply has arrived, refused ones included. Every accepted subscription is then live before the backfill reads the index. A transaction that landed before a wallet's subscription was confirmed is in the index the backfill reads next, and one that lands after arrives live. If both paths deliver the same signature, `record` drops the second.

The copy matters because the backfill runs one wallet at a time. Live notifications on the new socket keep moving `newest`, so by a later wallet's turn the live anchor sits past the outage and `until` would skip the gap. The copy keeps every wallet's anchor at what it was before the drop.

The backfill asks for signatures newer than the wallet's anchor with `until` and `limit: 1000`. The reply is newest first, so the file reverses it and prints oldest first. A wallet with no anchor yet has nothing to backfill, and the file skips it.

A `getSignaturesForAddress` call costs 50 cells, so a reconnect with 200 wallets spends 10,000 cells. On a 429 the file waits for the `retry-after` seconds and tries the same wallet again. A wallet gets three attempts in all. After a third 429 the file logs `backfill failed` for it and moves on, so that wallet's gap stays open.

> A transaction that touches two watched wallets prints two lines, one per wallet. That is deliberate: each line says which wallet it belongs to.

## On Carbium

A subscription has two prices in [credits](https://carbium.sh/docs#limits). A `logsSubscribe` with a `mentions` filter opens at 25 credits, then costs 20 credits per MiB sent. A refused subscription is free. A reconnect opens every subscription again, so 200 wallets cost 5,000 credits to reopen.

Connection and subscription counts are capped per account by plan, and Free carries 5 sockets. An account's keys share one budget. Because the caps are per account, spreading wallets over more sockets or more keys does not raise the subscription cap.

| Plan | `getSignaturesForAddress` calls per second |
|---|---|
| Free | 0.24 |
| Dev | 1.2 |
| Business | 100 |
| Pro | 500 |

On Free, at 0.24 calls per second, a backfill of many wallets meets a 429 often, and the retry in the file spaces the calls out. [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) covers watching for it.

## Where it ends

A wallet with no notification before the drop has no anchor, so nothing is backfilled for it. A process restart loses every anchor too. Persist `newest` with `node:sqlite` if the watcher has to survive restarts, and seed it from your own record of the last signature you handled.

The anchor is the highest slot seen for the wallet, which keeps each backfill short. Notifications can arrive out of slot order, so a transaction at a lower slot may still be undelivered when the socket drops. It sits below the anchor, and the `until` filter does not return it. An older anchor catches it, and `seen` drops the overlap, at the price of longer backfills; if a missed transaction costs more than the extra calls, anchor on an older signature of your own choosing.

The file reacts to the socket's `close` event. A connection that goes silent without closing is not detected, and a quiet wallet looks the same as a dead socket. If that matters, run a slow check per wallet with `getSignaturesForAddress` at a pace your plan's rate allows, and feed what it returns to `record`. The backfill also waits for every subscribe reply, so a reply that never arrives holds it back until the next reconnect.

One backfill call returns up to 1,000 signatures, so a longer outage needs paging with `before`. The index behind `getSignaturesForAddress` keeps up to 30 days. An empty page past that is the index's age limit and says nothing about the address's first transaction.

The backfill returns signatures and the `err` flag with no logs. Fetch the transaction with `getTransaction`, which costs 50 cells, when you need the log lines. Pass `maxSupportedTransactionVersion: 1` with an encoding, or a v1 transaction answers -32015.

`seen` grows with every transaction and the file never trims it. Bound it before a long run.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Some wallets never print, others do. | Look for `subscription refused` lines. Subscription counts are capped per account by plan, so shorten the list or move up a plan. A refused subscription costs no credits. |
| The socket is open after a reconnect and nothing arrives. | The new socket has no subscriptions. Send every `logsSubscribe` again in the `open` handler, as the file does. |
| HTTP 429 during a backfill. | Wait for the retry-after seconds and try the same wallet again, as the file does for three attempts in all. A `backfill failed` line names a wallet whose gap stayed open. On Free the rate is 0.24 calls per second, so a long wallet list needs a higher plan or patience. |
| One line for a transaction that touched two wallets. | Key the dedupe set by wallet and signature. Keyed by signature alone, the second wallet's line is dropped. |
| A wallet receives SOL and `accountSubscribe` stays silent. | Carbium's stream sends nothing on `accountSubscribe` for a plain SOL wallet. Subscribe with `logsSubscribe` and `mentions`, and read the amount with `getBalance`. |

## Questions

### Can one subscription watch several wallets?

No. The `mentions` filter accepts one address, so each wallet gets its own subscription. Subscribing to all logs and filtering yourself opens at 200 credits and sends every transaction's logs at 20 credits per MiB, which is rarely worth it for a fixed list.

### Does a failed transaction show up?

Yes. The notification arrives with `err` set, and the file prints it as `failed`. Filter on `err` in your own code if you want successes only.

### Do notifications arrive in slot order?

Do not rely on it. The file keeps the highest slot seen for each wallet as its anchor, which keeps each backfill short, and drops duplicates. A late, lower-slot message leaves the anchor where it is, so a lower-slot transaction still undelivered at the drop sits below the anchor and is not backfilled.

### How do I get the full transaction for a signature?

Pass the signature to `getTransaction` with an encoding and `maxSupportedTransactionVersion: 1`. The notification carries only the signature, the `err` field and the logs.

## Related

- [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) (Use cases, UC0001)
- [Failed-mint monitor](https://carbium.sh/library/blockchainideas/failed-mint-monitor) (Blockchain ideas, BI0001)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [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)
