services
Get a key

library / Integrations / I0022

Postgres token balance watcher

A Node watcher reads token account addresses from a Postgres list, fetches their balances 100 at a time from Carbium RPC, and prints an upsert only when an amount changes. A trigger turns each change into a NOTIFY.

By Carbium · Relational databases · I0022 · updated 2026-11-22

01

The job: many ATAs from one table

Your database holds a list of associated token accounts, one per customer and mint. You want to know when one of them changes balance, and to keep the new balance in a table your application already reads. Postgres cannot call out to Solana, so a small Node process sits in between: it reads the addresses, asks Carbium for their balances and prints SQL that psql applies.

The unit you watch is the token account. An associated token account's address derives from the owner, the mint and the token program, and a wallet can own more than one token account for one mint, so store the token account address in the row and watch that. A payment to a customer changes their token account and may never name their wallet, so a watch on the wallet misses it.

TableColumns
watched_atasaddress text primary key: the token accounts to watch, one per row
ata_balancesaddress text primary key, amount numeric, slot bigint: the latest balance and the slot it was read at
02

The read: 100 accounts in one call

getMultipleAccounts takes a list of addresses and returns every account's data as of one slot. A token account holds at least 165 bytes, and its balance is an unsigned 64-bit integer at byte 64, little endian, in the mint's base units. The script asks for base64 at finalized commitment and reads those 8 bytes, which needs no parser and covers accounts of both token programs, since the first 165 bytes share one layout.

Before it reads the balance, the script checks that the account belongs to the Token or Token-2022 program and, when the data is longer than 165 bytes, that byte 165 is 2, the marker of a token account. A mint with extensions, or an account of any other program, fails that check and prints a comment instead of a made-up balance.

A call takes up to 300 pubkeys on Pro, and below Pro the 1,024-cell burst caps it at 100. The script sends 100 at a time, which works on every plan.

The script keeps the last amount it printed for each address. The first poll prints every account once as a baseline, and every later poll prints only the accounts whose amount moved. The slot comes from the response context, so every row carries the slot its balance was read at.

03

The Postgres side: one upsert, one notify

The script prints one statement per changed account, and psql runs it.

  • Create: create table ata_balances (address text primary key, amount numeric not null, slot bigint not null) next to create table watched_atas (address text primary key).
  • Upsert, printed by the script: insert into ata_balances (address, amount, slot) values (...) on conflict (address) do update set amount = excluded.amount, slot = excluded.slot where ata_balances.slot < excluded.slot.
  • Notify: create function ata_notify() returns trigger language plpgsql as $$ begin perform pg_notify('ata_change', new.address || ':' || new.amount); return new; end $$, then create trigger ata_inserted after insert on ata_balances for each row execute function ata_notify() and create trigger ata_updated after update on ata_balances for each row when (old.amount <> new.amount) execute function ata_notify().
$The upsert always moves a row to a newer slot and never to an older one, so a stale reading from a second copy of the watcher cannot overwrite a newer balance. The when (old.amount <> new.amount) test on the update trigger keeps a reading with the same amount silent, so a notification goes out only for a first sighting or a real change. Any session can then listen ata_change and get the address and the new amount as the payload.
04

The watcher

Install with npm install @solana/[email protected], set "type": "module" in package.json, and use Node 24, which strips the types on load. The addresses to watch are the arguments, or a single - to read them from standard input, one per line. With neither, the script lists the newest 20 signatures of the USDC mint, walks them newest first, and watches the USDC token accounts in the first transaction that has any, so a bare run has something to show. It needs CARBIUM_KEY and exits with a message when it is unset. CARBIUM_RPC_URL and POLL_MS (default 5000) are optional, and the script makes read calls only.

main.ts
// I0022 · Postgres token balance watcher// https://carbium.sh/library/integrate/postgres-token-balance-watcher// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type Address } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY.");  process.exit(1);}const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);const commitment = "finalized"; // named on every callconst USDC = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");const TOKEN_PROGRAMS = ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"];const POLL_MS = Number(process.env.POLL_MS ?? 5000);// With no arguments: walk the newest 20 USDC signatures, newest first, and stop at the first transaction with USDC token accounts.async function discover(): Promise<Address[]> {  const sigs = await rpc.getSignaturesForAddress(USDC, { commitment, limit: 20 }).send();  for (const s of sigs.filter((x) => x.err === null)) {    const found = new Set<Address>();    try {      const tx = await rpc.getTransaction(s.signature, { commitment, encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send();      if (!tx?.meta) continue; // an older signature can be listed and still answer null      for (const b of tx.meta.postTokenBalances ?? [])        if (b.mint === USDC) found.add(tx.transaction.message.accountKeys[b.accountIndex].pubkey);    } catch (e) {      console.log(`-- failed getTransaction ${s.signature}: ${(e instanceof Error ? e.message : String(e)).replace(/\s+/g, " ")}`);    }    if (found.size) return [...found];  }  return [];}// The single argument "-" reads the addresses from standard input, so psql can pipe any number of them.async function fromStdin(): Promise<Address[]> {  let text = "";  for await (const chunk of process.stdin) text += chunk;  return text.split(/\s+/).filter(Boolean).map((a) => address(a));}// A token account: owned by a token program, 165 bytes, or longer with account type 2 at byte 165.function isTokenAccount(owner: string, data: Buffer): boolean {  return TOKEN_PROGRAMS.includes(owner) && data.length >= 165 && (data.length === 165 || data[165] === 2);}async function main() {  const args = process.argv.slice(2);  const atas = args[0] === "-" ? await fromStdin() : args.length ? args.map((a) => address(a)) : await discover();  if (!atas.length) {    console.error("No token accounts to watch.");    process.exit(1);  }  console.log(`-- watching ${atas.length} token accounts every ${POLL_MS} ms`);  const last = new Map<Address, bigint>();  const gap = POLL_MS / Math.ceil(atas.length / 100); // spread the batches across one poll  for (;;) {    for (let i = 0; i < atas.length; i += 100) { // 100 pubkeys is the most one call takes below Pro      const batch = atas.slice(i, i + 100);      try {        const { context, value } = await rpc.getMultipleAccounts(batch, { commitment, encoding: "base64" }).send();        batch.forEach((a, j) => {          const acc = value[j];          const data = acc ? Buffer.from(acc.data[0], "base64") : null;          if (!acc || !data || !isTokenAccount(acc.owner, data)) {            console.log(`-- ${a} is missing or is not a token account`);            return;          }          const amount = data.readBigUInt64LE(64); // token account layout: amount at byte 64, in base units          if (last.get(a) === amount) return;          last.set(a, amount);          console.log(`insert into ata_balances (address, amount, slot) values ('${a}', ${amount}, ${context.slot}) on conflict (address) do update set amount = excluded.amount, slot = excluded.slot where ata_balances.slot < excluded.slot;`);        });      } catch (e) {        console.log(`-- failed getMultipleAccounts at ${i}: ${(e instanceof Error ? e.message : String(e)).replace(/\s+/g, " ")}`);      }      await new Promise((r) => setTimeout(r, gap));    }  }}main().catch((e) => {  console.error(e instanceof Error ? e.message : String(e));  process.exit(1);});

run: node main.ts

05

Run it into psql

Feed the addresses from the table and the output back into the database: psql -Atc "select address from watched_atas" | node main.ts - | psql -v ON_ERROR_STOP=1. The - argument makes the script read standard input, so a list of any length arrives in one run. With an empty table the script finds no address and exits with a message, and it never falls back to USDC accounts that are not yours.

The script never returns, so run it as a systemd service and restart it when watched_atas changes, since the list is read once at start. A restart prints the baseline again, which is harmless: the update trigger stays silent for every row whose amount has not moved.

A failed batch prints a -- failed getMultipleAccounts comment with the error message and the next poll tries it again. psql ignores the comment. An address that is missing or is not a token account prints a comment too, on every poll, until you fix the row.

06

What it costs against your limits

A getMultipleAccounts call costs 10 cells per pubkey, so a call of 100 pubkeys costs 1000 cells, or 1001 past a 4 KiB body. It draws on the account read class, which allows 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro. Each poll makes one call per 100 addresses, so 250 addresses take 3 calls a poll. Limits are per account, so every key you own draws on one budget.

The script waits POLL_MS divided by the batch count after each batch, so the calls spread across the poll. Set POLL_MS so that the batch count divided by the interval in seconds stays under your plan's rate. The default 5000 ms is a starting point and does not fit every plan. Free's 1,024-cell burst holds one 1000-cell call, so on Free keep a poll to one batch and POLL_MS at 2000 or more, which is one call per 2 s.

07

Where it ends

  • It polls. A change shows up on the next poll, and two changes between polls show as their sum.
  • It reads the balance and nothing else: it does not tell you who paid or why. For the transaction behind a change, list the token account's signatures with getSignaturesForAddress and read each with getTransaction, at 50 cells a call. The list reaches back 30 days at most, the age of Carbium's address index.
  • The list is read at start. A new address needs a restart.
  • A closed token account answers null, and the row keeps its last amount. Delete the row or set it to 0 yourself.
  • Amounts are in base units. The decimals sit on the mint, and your tables or views divide.
  • The USDC fallback is for a first run. In real use every address comes from watched_atas.
08

When it goes wrong

what goes wrongwhat to do
The script watches USDC accounts you never listed.It ran with no arguments, which starts the USDC fallback. Pass - after the pipe so the script reads standard input and an empty watched_atas exits with a message.
Every poll ends in a -- failed getMultipleAccounts comment that names a 429.The account's budget is spent. Raise POLL_MS, cut the number of watchers, and remember that all keys of an account share one budget.
A listed address prints is missing or is not a token account and its row never changes.The address is a wallet, a mint or a closed account. Store the token account address, which getTokenAccountsByOwner returns for a wallet and mint.
The stored amount differs from the number a wallet shows.The column holds base units. Divide by 10 to the power of the mint's decimals, for example 1000000 base units are 1 USDC.
Every restart prints every account, yet nothing is notified.That is the baseline. The upsert moves each row to the newer slot, but the update trigger fires only when the amount differs, so unchanged rows send no notification.
09

Questions

Why poll and not subscribe to each account?

accountSubscribe sends account state on change for streamed accounts. One subscription per address opens at 25 credits by filter weight and then costs 20 credits per MiB sent, and Free carries 5 sockets, with your plan capping connections and subscriptions per account. A batched read keeps the cost at one call for 100 addresses, and the table stays correct if a socket drops.

How do I get token account addresses for my wallets?

getTokenAccountsByOwner returns a wallet's token accounts for one mint. You can also derive the associated token account from the owner, the mint and the token program. Store the result in watched_atas, because one wallet can own several token accounts for the same mint.

Can two copies of the watcher write to the same table?

Yes. Each upsert only overwrites a row with a newer slot, so a slow copy cannot roll a balance back. Two copies do double the read cost.

Does it work for SOL balances too?

No, the byte offset is a token account's. For many SOL balances, read lamports from the same call shape: see SOL balances for many accounts.