services
Get a key

library / Use cases / UC0027

Intraday stablecoin position feed

A per-mint stablecoin position built from token accounts read at one slot: how to keep the account list complete, which level to read at, what each tick costs on Carbium, and a read-only Node script that stores every tick.

By Carbium · Stablecoin treasury and B2B settlement · UC0027 · updated 2026-11-22

01

What the position is made of

A treasury's stablecoin position is a sum: every token account the desk controls, grouped by mint, at a named moment. On Solana a balance lives in a token account that holds one mint, and a wallet can own several token accounts for the same mint. A feed that reads only the wallet's main account undercounts, so the account list is part of the position and needs an owner in your own records. getTokenAccountsByOwner lists the accounts of a wallet when you need to build or audit that list.

Amounts are integer strings in base units. USDC has 6 decimals, so 1,250,000.50 USDC is 1250000500000. Keep them as BigInt, add them as BigInt and format only on the way to a screen. A float sum drifts, and a treasury report that is off by a few base units cannot be reconciled.

The moment matters as much as the number. A figure with no slot beside it cannot be matched to a statement later. getMultipleAccounts returns every account at one context slot, so a total built from one call is consistent with itself. The same total built from separate getTokenAccountBalance calls can mix slots whenever money moves between them. SPL token balance covers the single-account read.

02

A feed in one file

The script reads a list of token accounts once per tick, sums them per mint and prints the change since the previous tick. Each tick is also written to a local SQLite file, positions.db, with its slot, so a day of ticks is a table you can query. Pass token account addresses as arguments. With none, it takes the newest successful USDC transactions, finds the USDC token accounts they touched and reads those, so you can watch it work before you wire in your own list. It sends the key in the x-api-key header to the RPC endpoint and signs and sends nothing.

main.ts
// UC0027 · Intraday stablecoin position feed// https://carbium.sh/library/usecase/intraday-stablecoin-position-feed// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: snapshot stablecoin token accounts once per tick at one slot, keep each tick in SQLite and print the change per mint.import { DatabaseSync } from "node:sqlite";import { address, 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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const commitment = "finalized" as const; // kit would fill in confirmed if this were left outconst ticks = Number(process.env.TICKS ?? 3), everyMs = Number(process.env.EVERY_MS ?? 3000);type Tx = { transaction: { message: { accountKeys: { pubkey: string }[] } }; meta: { postTokenBalances?: { accountIndex: number; mint: string }[] | null } | null };type Acct = { data: { parsed?: { info?: { mint?: string; tokenAmount?: { amount: string } } } } | string[] } | null;// With no arguments: the USDC token accounts touched by the newest successful USDC transactions.async function discover(): Promise<string[]> {  const page = await rpc.getSignaturesForAddress(address(USDC), { limit: 10, commitment }).send();  const found = new Set<string>();  for (const s of page.filter((p) => p.err === null).slice(0, 5)) {    try {      const tx = (await rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment }).send()) as unknown as Tx | null;      if (!tx?.meta) continue; // a listed signature can be older than the ledger floor      for (const b of tx.meta.postTokenBalances ?? []) if (b.mint === USDC) found.add(tx.transaction.message.accountKeys[b.accountIndex].pubkey);    } catch (e) { console.error("discovery read failed:", e instanceof Error ? e.message : e); }  }  return [...found];}const given = process.argv.length > 2 ? process.argv.slice(2) : await discover();const accounts = given.slice(0, 100);if (given.length > accounts.length) console.error(`Warning: ${given.length - accounts.length} accounts dropped, one call reads at most 100. Totals undercount.`);if (!accounts.length) { console.error("No token accounts to read."); process.exit(1); }const db = new DatabaseSync("positions.db");db.exec("create table if not exists pos (ts text, slot integer, mint text, accounts integer, amount text)");const insert = db.prepare("insert into pos values (?, ?, ?, ?, ?)");const last = new Map<string, bigint>();for (let i = 0; i < ticks; i++) {  const t0 = performance.now();  try {    const r = await rpc.getMultipleAccounts(accounts.map((a) => address(a)), { encoding: "jsonParsed", commitment }).send();    const ms = Math.round(performance.now() - t0);    const sums = new Map<string, { n: number; total: bigint }>();    for (const a of r.value as unknown as Acct[]) { // null: closed or never created, adds nothing      const info = a && !Array.isArray(a.data) ? a.data.parsed?.info : undefined;      if (!info?.mint || !info.tokenAmount) continue;      const s = sums.get(info.mint) ?? { n: 0, total: 0n };      sums.set(info.mint, { n: s.n + 1, total: s.total + BigInt(info.tokenAmount.amount) });    }    for (const [mint, s] of sums) {      insert.run(new Date().toISOString(), Number(r.context.slot), mint, s.n, s.total.toString());      const prev = last.get(mint);      console.log(`slot ${r.context.slot} (${ms} ms) ${mint} ${s.n}/${accounts.length} accounts ${s.total} base units${prev === undefined ? "" : ` change ${s.total - prev}`}`);      last.set(mint, s.total);    }  } catch (e) { console.error("tick failed:", e instanceof Error ? e.message : e); }  if (i < ticks - 1) await new Promise((res) => setTimeout(res, everyMs));}const n = db.prepare("select count(*) as n from pos").get() as unknown as { n: number };console.log(`${n.n} snapshots in positions.db`);

run: CARBIUM_KEY=$CARBIUM_KEY TICKS=2 EVERY_MS=2000 node main.ts [tokenAccount ...]

A tick that fails prints its error and the loop moves on. The next tick reads full state, so a missed tick leaves a gap in the history and no error in the totals. getMultipleAccounts answers null for an account that does not exist or has been closed, and the script skips it, so that account adds nothing to the sum. Each line carries the slot and the milliseconds the call took. TICKS and EVERY_MS set how many reads run and how far apart.

03

Choosing a commitment level

The script reads at finalized. The JSON-RPC server's own default is finalized, but @solana/kit 8.6.0 fills in confirmed when a call leaves commitment out, so a script that omits it reads at confirmed without saying so. A finalized total trails the newest slot by at most one slot. A slot seen at processed can still end up skipped when its fork is dropped, which is why a figure that goes on a statement belongs at finalized.

Pick one commitment per feed and use it on every call. If a dashboard wants confirmed and the close of day wants finalized, run the feed twice with the level as the only difference and write the two runs to separate tables.

04

What a tick costs

Cells are the admission charge per call. getMultipleAccounts charges 10 cells per pubkey, so a call for 100 accounts costs 1000 cells, or 1001 when the body passes 4 KiB. A rate class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger, so a 100-account call fills nearly the whole burst. The method takes up to 300 pubkeys, but below Pro the 1024-cell burst caps a call at 100, which is why the script slices its list at 100. A treasury with more accounts than that spaces its calls or runs on Pro.

CallCellsUsed for
getMultipleAccounts10 per pubkeyThe tick: all listed accounts at one slot
getSignaturesForAddress50Listing the recent transactions of one token account
getTransaction50Reading what one transaction did to the balances

A 429 carries a retry-after hint. For a snapshot feed that is a mild failure, because the next tick reads everything again. Set the interval from your plan and the account count, and treat a 429 as a skipped tick. Credits meter the RPC work, and each paid month adds credits that stay if unspent.

05

Reading on events instead of a timer

A fixed interval reads whether or not anything moved. To react to payments, open a WebSocket to wss://services.carbium.sh with the key as ?api-key= in the URL and call logsSubscribe with a mention filter on each treasury token account. Each transaction that touches the account sends a notification. Treat it as a prompt and run the same snapshot read, so one code path writes every row. A mention subscription opens at 25 credits and then costs 20 credits per MiB sent. A refused one costs nothing.

Keep a slow timer as well. A subscription that drops loses the events during the gap, and the snapshot on the timer repairs the history with no replay. When you need to know what moved a balance, getSignaturesForAddress on the token account lists its recent transactions and getTransaction reads each one. Use the token account's address: a token transfer lists the token accounts and the sender's authority, and the receiving wallet may not appear at all. The index behind the list keeps up to 30 days. Mainnet carries v1 transactions, so getTransaction takes maxSupportedTransactionVersion: 1, and with the value absent or 0 Carbium answers -32015 for one. Stablecoin settlement checks takes a single transaction apart.

06

Where it ends

  • The feed reads chain state. A bank position also depends on what happens off chain, such as redemptions in flight with the issuer, and none of that appears here.
  • Totals are in base units per mint. Converting to a currency value, or netting one stablecoin against another, is your own step.
  • The account list is yours. A transfer into a token account you did not list is invisible until the list changes, so reconcile it against getTokenAccountsByOwner for each owner wallet on a schedule.
  • positions.db is a scratch record on one disk. The book of record is your own ledger.
  • Signature history from the address index reaches back 30 days at most. An empty page past that is the age limit, and the address may have older transactions.
  • The script is read-only. Moving funds is the job of your own software.
07

When it goes wrong

what goes wrongwhat to do
The total is lower than the treasury's real holding.The wallet owns more than one token account for the mint. List the accounts of each owner wallet with getTokenAccountsByOwner and put every one in the feed.
Reports differ from the feed by a few base units.Some step used a float. Read amount as a string, add it as BigInt and format decimals only for display.
The feed shows confirmed balances while the statement says finalized.@solana/kit 8.6.0 fills in confirmed when a call leaves commitment out. Set commitment: "finalized" on every call in the feed.
A call with more than 100 accounts fails or gets a 429 below Pro.The 1024-cell burst caps a getMultipleAccounts call at 100 pubkeys below Pro, since each pubkey costs 10 cells. Slice the list at 100 and space the calls, or move to Pro for up to 300.
A listed account stops adding to the total and nobody notices.getMultipleAccounts answers null for a closed account. Compare the account count of each tick with the previous one and raise an alert when it drops.
getTransaction answers -32015 or null while reading the transactions of an account.Pass maxSupportedTransactionVersion: 1. A signature listed from the address index can be older than the validator's ledger floor and answer null, so handle null and read the newest signatures.
08

Questions

How do I compare RPC endpoints for a stablecoin position feed?

Run the same read from the servers and region you will deploy in, at the plan you will pay for, across a full business day. The script prints the slot and the milliseconds of every call, which gives you a like-for-like record.

Can I read all balances in one call?

Yes, up to 100 token accounts in one getMultipleAccounts call, and up to 300 on Pro. One call returns every account at a single slot, so the total is consistent.

Should the feed read confirmed or finalized?

Finalized for anything that reaches a statement, since a finalized total trails the newest slot by at most one slot. If a dashboard needs confirmed, run it as a second feed into its own table.

How often can I poll?

A full 100-account call costs 1000 cells against a 1,024-cell burst, so size the interval from your plan's rate. A 429 carries a retry-after hint and counts as a skipped tick, and the next tick reads the whole state again.

Does the feed handle Token-2022 stablecoins?

Yes. The parsed read returns the balance of token accounts from either token program. A mint with a transfer fee delivers less than the sender's amount, and the balance you read is what landed.