---
id: UC0021
title: "Live donation totals"
url: https://carbium.sh/library/usecase/live-donation-totals
collection: Use cases
category: Donations and public goods
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Live donation totals

Show a campaign's total as it grows: watch one address over WebSocket, read each transaction that mentions it once, keep one row per donation in SQLite, and size the lookups to your plan. You get the exact lamport total and the gifts behind it.

## A total is a sum of inflows

A donation page wants one number that only goes up. The address balance cannot give you that. It falls when the team moves funds out, and it rises for reasons that are not donations. The number to show is the sum of every incoming transfer you have recorded, kept as one row per transaction.

The balance still earns a place on the page as a check. Read it with `getBalance`: the balance minus the starting balance, plus your withdrawals and the fees the address paid, should equal the ledger total. A balance above that means the ledger missed an inflow. The script reads at confirmed commitment on every call, and you change the four commitment strings in it to finalized if a published number must never be revised.

## Watching one address live

A plain SOL wallet gets nothing from `accountSubscribe`, so the watch is a [log subscription](https://carbium.sh/docs#websocket) opened with `logsSubscribe` and a `mentions` filter on the address, plus a transaction read for the amount. The filter delivers every transaction that lists the address. That includes transactions that take SOL out of it and ones that only read it, so the script reads the amount from the pre and post balances of each transaction.

A subscription of this kind costs [25 credits to open, then 20 credits per MiB sent](https://carbium.sh/docs#limits), and a refused one costs nothing. A campaign page sends little, so the meter barely moves. The key travels in the [`?api-key=` query parameter](https://carbium.sh/docs#auth) on the socket URL, which is one more reason to keep the socket on your server.

Sockets drop. On every open the script asks `getSignaturesForAddress` for what landed after its newest stored signature, so a reconnect closes the gap. With an empty ledger the first open reads the newest 5 signatures, which can count gifts from before launch. The in-memory seen set skips a second read of a signature within one process, and the signature primary key keeps a re-read after a restart from adding a second row.

## The ledger script

The script takes one address. It prints the balance and the ledger total so far, subscribes, and then reads each new signature through a single queue, one transaction at a time, with a pause after each lookup. `CARBIUM_RPC_URL` and `CARBIUM_WS_URL` override the two [endpoints](https://carbium.sh/docs#endpoints).

`main.ts` (run: `CARBIUM_KEY=$CARBIUM_KEY node main.ts <campaign-address>`)

```ts
// UC0021 · Live donation totals
// https://carbium.sh/library/usecase/live-donation-totals
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only: a live total of SOL received by one address, one database row per transaction.
import { DatabaseSync } from "node:sqlite";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } 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 campaign = process.argv[2] ?? "";
if (!campaign) { console.error("Usage: node main.ts <campaign-address>"); process.exit(1); }
const wsUrl = `${process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh"}/?api-key=${key}`;
// One client, reused for every call.
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({
  url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }));

const db = new DatabaseSync("donations.db");
db.exec("CREATE TABLE IF NOT EXISTS donations (sig TEXT PRIMARY KEY, donor TEXT, lamports INTEGER, slot INTEGER)");
const insert = db.prepare("INSERT OR IGNORE INTO donations VALUES (?, ?, ?, ?)");
const sum = db.prepare("SELECT COALESCE(SUM(lamports), 0) AS lamports, COUNT(*) AS n FROM donations");
sum.setReadBigInts(true);
const newest = db.prepare("SELECT sig FROM donations ORDER BY slot DESC LIMIT 1");

type Tx = { slot: number | bigint; meta: { err: unknown; preBalances: (number | bigint)[]; postBalances: (number | bigint)[] } | null;
  transaction: { message: { accountKeys: { pubkey: string; signer: boolean }[] } } };
// Amounts stay integer lamports; only the display splits them.
const sol = (l: bigint) => `${l / 1_000_000_000n}.${String(l % 1_000_000_000n).padStart(9, "0")}`;
const ledger = () => {
  const { lamports, n } = sum.get() as unknown as { lamports: bigint; n: bigint };
  return `${sol(lamports)} SOL in ${n} donations`;
};
const seen = new Set<string>(), retry = new Set<string>(); // retry: failed or overflow signatures
// Pause between lookups: 1000 ms / the plan's getTransaction req/s (0.24 Free, 1.2 Dev, 5 Business, 25 Pro).
const gap = 1000 / (Number(process.env.CARBIUM_TX_RATE) || 0.24);
let pending = 0, chain: Promise<void> = Promise.resolve();

async function record(sig: string): Promise<void> {
  const tx = (await rpc.getTransaction(signature(sig), { commitment: "confirmed", encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()) as unknown as Tx | null;
  if (!tx?.meta || tx.meta.err) return; // null: a listed signature below the ledger floor
  const keys = tx.transaction.message.accountKeys;
  const i = keys.findIndex((k) => k.pubkey === campaign);
  const gain = i < 0 ? 0n : BigInt(tx.meta.postBalances[i]!) - BigInt(tx.meta.preBalances[i]!);
  if (gain <= 0n) return; // a mention that paid the address nothing
  const donor = keys.find((k) => k.signer)?.pubkey ?? "unknown";
  if (!insert.run(sig, donor, gain, Number(tx.slot)).changes) return;
  console.log(`+${sol(gain)} SOL from ${donor.slice(0, 8)} (${sig.slice(0, 8)}), total ${ledger()}`);
}

const enqueue = (sig: string) => {
  if (seen.has(sig)) return;
  if (pending >= 50) { retry.add(sig); return; }
  seen.add(sig); retry.delete(sig); pending++;
  chain = chain.then(() => record(sig))
    .catch((e) => { seen.delete(sig); retry.add(sig); console.error(`lookup ${sig.slice(0, 8)} failed:`, e instanceof Error ? e.message : e); })
    .then(() => new Promise<void>((r) => setTimeout(r, gap)))
    .finally(() => { pending--; });
};

async function catchUp() {
  try {
    const last = newest.get() as unknown as { sig: string } | undefined;
    const page = await rpc.getSignaturesForAddress(address(campaign),
      { commitment: "confirmed", limit: last ? 100 : 5, ...(last ? { until: signature(last.sig) } : {}) }).send();
    for (const s of [...page].reverse()) if (!s.err) enqueue(s.signature);
  } catch (e) { console.error("catch-up failed:", e instanceof Error ? e.message : e); }
}

function connect() {
  const ws = new WebSocket(wsUrl);
  ws.onopen = () => {
    ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params: [{ mentions: [campaign] }, { commitment: "confirmed" }] }));
    void catchUp();
  };
  ws.onmessage = (ev) => {
    const msg = JSON.parse(String(ev.data));
    if (msg.id === 1) return void console.log(msg.error ? `subscribe refused: ${msg.error.message}` : "subscribed, watching");
    const v = msg.params?.result?.value;
    if (msg.method === "logsNotification" && v && !v.err) enqueue(v.signature);
  };
  ws.onclose = () => setTimeout(connect, 2000);
  ws.onerror = () => ws.close();
}

try {
  const bal = await rpc.getBalance(address(campaign), { commitment: "confirmed" }).send();
  console.log(`balance ${sol(bal.value)} SOL at confirmed`);
} catch (e) { console.error("getBalance failed:", e instanceof Error ? e.message : e); }
console.log(`ledger so far: ${ledger()}`);
setInterval(() => { for (const s of [...retry]) enqueue(s);
  console.log(`status: ${ledger()}, ${pending} lookups queued, ${retry.size} waiting to retry`); }, 10_000);
connect();
```

For each transaction the script finds the address in the parsed account keys and subtracts its pre balance from its post balance. A positive result is a donation, and the row keeps the signature, the first signer as the donor, the lamports as an integer and the slot. A failed transaction and a zero or negative change leave no row. `getTransaction` runs with `maxSupportedTransactionVersion: 1`, because mainnet carries v1 transactions and a call without it answers [-32015](https://carbium.sh/docs#rpc) for one.

Amounts stay in lamports until the last step. The `sol()` helper splits the integer by 1,000,000,000 for display, so a total never passes through a float and a sum of many small gifts adds up exactly.

A lookup that fails, a 429 included, is printed and its signature goes into a retry set. So does a signature that arrives while 50 lookups already wait. Every 10 seconds the status timer feeds the retry set back into the queue, and the status line shows how many signatures are waiting. The set lives in memory, so a restart empties it.

## Size the lookups to your plan

Each notified transaction costs one [getTransaction call at 50 cells](https://carbium.sh/docs#rpc), outflows and read-only mentions included, and each catch-up adds one `getSignaturesForAddress` at 50 cells. The per-second rates for those two classes and the monthly credits differ by plan.

| Plan | getTransaction req/s | getSignaturesForAddress req/s | Credits per month |
|---|---|---|---|
| Free ($0) | 0.24 | 0.24 | 500K once, at sign-up |
| Dev ($20) | 1.2 | 1.2 | 10M |
| Business ($250) | 5 | 100 | 50M |
| Pro ($500) | 25 | 500 | 200M |

A class absorbs a burst of 1,024 cells or one second of its rate, whichever is larger: about 20 lookups on Free, and 1,250 cells on Pro, where 25 req/s at 50 cells each fills more than 1,024. The script leaves the burst alone and sleeps 1000 / rate ms after each lookup, which keeps it clear of a [429](https://carbium.sh/docs#limits). The rate comes from `CARBIUM_TX_RATE`. It defaults to 0.24, Free's rate, so set 1.2, 5 or 25 from the table for the other plans. On Free that is one lookup about every 4.2 s, so an address mentioned in more than one transaction every four seconds builds a backlog, which the queue and the retry set hold. At Dev's 1.2 req/s the queue clears roughly one transaction a second. A value above your plan's rate runs on the burst until it is spent. After that a call over the rate waits once and is served only if its cells [refill within 1 s](https://carbium.sh/docs#limits), otherwise it gets a 429. The 429 lines come back, first on Free, where 50 cells take about 4 s to refill.

All keys on an account share one budget, so the page that shows the number should not draw on it per visitor. Have the watcher write the total to your own store or endpoint and let visitors read that. The Carbium key then stays on your server.

## Where it ends

- The total counts every SOL inflow to the address. A refund, a rent top-up or a transfer from your own wallet adds a row the way a donation does. The donor column holds the first signer, which for an exchange withdrawal is the exchange, so it names whoever paid the fee.
- SOL only. A token transfer to an existing token account lists the token accounts and the sender's authority, never the receiving wallet, and a wallet can own more than one token account for one mint. For USDC, watch the campaign's token account address and read token balance changes. This script reads lamports.
- History reaches back 30 days at most. `getSignaturesForAddress` pages come from an address index that keeps up to 30 days, and an empty page past that is the index's age limit while the address may have older transactions. Earlier donations come from your own records.
- The catch-up asks for the newest 100 signatures after the newest stored one. A longer outage leaves a hole, and paging with `before` closes it. A catch-up call that fails is not repeated until the next reconnect, and once a newer row is stored it leaves the same kind of hole.
- [Free carries 5 sockets](https://carbium.sh/docs#websocket) per account. A socket per page visitor hits that cap first, so run one watcher and fan out from your own store.
- One process writes one SQLite file. Two watchers on the same file would each read every transaction, so run one.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The total jumps when the team moves funds in from another wallet. | Every SOL inflow is a row. Keep a list of your own addresses and skip rows whose donor is on it, or mark them in an extra column. |
| The counter stalls during a busy hour, the status line shows waiting signatures, or the log shows 429 lines. | Lookups run at the rate in `CARBIUM_TX_RATE`, so a queue is your plan's getTransaction rate showing. Set the variable to no more than the plan's rate. Failed and overflow signatures wait in the retry set, which the 10-second timer feeds back in, so they land once the rate allows. Move to a plan whose rate covers your peak. Do not restart to clear a stall: a restart empties the retry set, and a signature that failed before a newer row was stored needs a `getSignaturesForAddress` page with `before` over the stall window. |
| getTransaction answers null for a signature the address page listed. | Pages from the address index reach below the validator's ledger floor, so an older signature can have no transaction to read. The script returns without a row. Start the ledger at launch so every signature it reads is recent, and test the script on an address with transactions in the last few minutes. |
| A lookup fails with -32015 on a transaction the page listed. | Pass `maxSupportedTransactionVersion: 1` with an encoding. Absent or 0, getTransaction answers -32015 for a v1 transaction. |
| A USDC campaign shows a total of zero while gifts arrive. | The transfer lists the token accounts and the sender's authority, so the wallet's own SOL balance never moves. Watch the campaign's token account address and sum token balance changes. |
| Every call fails with 401 as soon as the script starts. | An unknown key gets 401 at the door. Attach the whole key in `CARBIUM_KEY`, with no truncated prefix. |

## Questions

### Can I use accountSubscribe on the donation wallet?

For a plain SOL wallet it sends nothing. Use `logsSubscribe` with the address in `mentions`, then read the transaction for the amount.

### Why not show the wallet balance as the total?

The balance falls when funds are withdrawn and rises for reasons that are not gifts. A ledger of inflows only grows, and it lets you list the donations behind the number.

### How far back can the total count?

Thirty days is the ceiling, because the address index behind `getSignaturesForAddress` keeps no more than that. Count from launch, or load earlier gifts from your own records.

### How many transactions per second can the script follow?

As many as the plan's `getTransaction` rate allows, because every transaction that mentions the address costs one lookup: 0.24 req/s on Free, 1.2 on Dev, 5 on Business and 25 on Pro. Set `CARBIUM_TX_RATE` to that figure and the queue holds whatever arrives faster.

## Related

- [Multi-address deposit monitor](https://carbium.sh/library/blockchainideas/multi-address-deposit-monitor) (Blockchain ideas, BI0006)
- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
