library / Integrations / I0006
Token supply time series
A small Node collector reads token mint supplies from your Carbium RPC every 10 seconds, decodes them from raw account data, and stores one supply row per mint in SQLite, with a query that returns one point per minute for any chart library.
What the collector stores
The collector is one Node process whose only dependency is @solana/kit. Every 10 seconds it reads the mint accounts you name in a single call, decodes each token supply from the raw account bytes, and writes one row per mint into a SQLite file. Your chart reads that file. The series is token supply. A price series comes from the `prices` method on the same RPC endpoint, which this collector does not call.
| Column | Holds |
|---|---|
| mint | The mint address. |
| slot | The slot the node reported for the read. |
| ts | Epoch milliseconds on your machine when the answer arrived. |
| raw | Supply in base units, as text. |
| ui | Supply divided by 10 to the power of the mint's decimals, as a float, for plotting. |
raw is text because a large supply passes 2^53, the point where a JavaScript number starts to round. ui carries that rounding, which a chart never shows. An account that is not an initialized mint of the classic token program or Token-2022 is skipped, with a line on stderr.
The Solana side: one read for every mint
The collector talks to the RPC endpoint at https://services.carbium.sh. It builds one client at start and reuses it for every poll.
The read is getMultipleAccounts with base64 encoding. It takes up to 300 pubkeys and charges 10 cells per pubkey, but the 1024-cell burst caps one call at 100 pubkeys below Pro. The collector puts every mint in one call, so below Pro keep the list at 100 mints or fewer. Its answer carries the slot the node evaluated the read at, and that slot is stored with every row.
A mint account is 82 bytes in the classic token program. A Token-2022 mint with extensions begins with the same 82 bytes, is padded to 165 bytes, and then carries its account-type byte at offset 165, which holds 1 for a mint, followed by the extensions. Supply is an unsigned 64-bit little-endian integer at byte 36, decimals are one byte at 44, and the initialized flag is one byte at 45. The length and the account-type byte matter, because a 165-byte token account has a byte of its owner pubkey at offset 45 and would pass the flag test about 1 time in 256. The collector checks the owner, the length with the account-type byte, and the initialized flag before it reads the supply.
Supply moves only when tokens are minted or burned, so most mints draw a flat line with steps, and a flat stretch is a real reading.
The storage side: one table, one chart query
The primary key is (mint, slot) and the insert is INSERT OR IGNORE, so a restart or a retry that lands on a slot already stored writes nothing twice. The file runs in WAL mode, which lets a chart server read it while the collector writes.
The chart query returns the last sample in each minute: SELECT ts / 60000 * 60000 AS t, ui, MAX(ts) AS last FROM supply WHERE mint = ? GROUP BY t ORDER BY t. SQLite gives the bare ui column the value from the row that holds the maximum ts. Feed t and ui to any chart library. A minute with no sample has no row, so fill it forward in the client and draw a step line.
node:sqlite is built into Node 24, so there is nothing to install for it. It may print an experimental warning on stderr.
The collector
Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. CARBIUM_KEY is required, and the process exits with a message without it. The mints come as arguments. CARBIUM_RPC_URL, INTERVAL_S (default 10) and DB_PATH (default tokens.db, relative to the folder you start it in) are optional.
If the database file cannot be opened, for example because that folder is read-only, the collector says so on stderr and exits with code 1, so your supervisor shows the failure and no series is lost quietly. Start it from a folder it can write to, or set DB_PATH.
// I0006 · Token supply time series// https://carbium.sh/library/integrate/token-supply-time-series// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";import { DatabaseSync } from "node:sqlite";const key = process.env.CARBIUM_KEY;const mints = process.argv.slice(2);if (!key || mints.length === 0) { console.error("Set CARBIUM_KEY and pass mint addresses: node main.ts <mint> [<mint> ...]"); process.exit(1);}const addresses = mints.map((m) => address(m)); // throws at start on a bad addressconst intervalMs = (Number(process.env.INTERVAL_S) || 10) * 1000;// The classic token program and Token-2022: their mints share the first 82 bytes.const TOKEN_PROGRAMS = new Set<string>([ "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",]);// One client, built once and reused for every poll.const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);const dbPath = process.env.DB_PATH ?? "tokens.db";let db: DatabaseSync;try { db = new DatabaseSync(dbPath);} catch (err: unknown) { console.error(`cannot open ${dbPath} (${err instanceof Error ? err.message : err})`); process.exit(1);}db.exec("PRAGMA journal_mode = WAL"); // a chart server can read while this writesdb.exec( "CREATE TABLE IF NOT EXISTS supply (mint TEXT NOT NULL, slot INTEGER NOT NULL, ts INTEGER NOT NULL, raw TEXT NOT NULL, ui REAL NOT NULL, PRIMARY KEY (mint, slot))",);const insert = db.prepare("INSERT OR IGNORE INTO supply (mint, slot, ts, raw, ui) VALUES (?, ?, ?, ?, ?)");// The number of minute points the chart query returns for a mint.const minutes = db.prepare("SELECT COUNT(DISTINCT ts / 60000) AS n FROM supply WHERE mint = ?");async function poll(): Promise<void> { const { context, value } = await rpc .getMultipleAccounts(addresses, { encoding: "base64", commitment: "confirmed" }) .send({ abortSignal: AbortSignal.timeout(5_000) }); const ts = Date.now(); value.forEach((acc, i) => { const mint = mints[i] as string; const bytes = acc ? Buffer.from(acc.data[0], "base64") : null; // A classic mint is 82 bytes. A Token-2022 mint is longer than 165 bytes and has account type 1 at byte 165. // A 165-byte token account has a byte of its owner pubkey at offset 45, so the length check comes first. const isMint = bytes !== null && (bytes.length === 82 || (bytes.length > 165 && bytes[165] === 1)) && bytes[45] === 1; if (!acc || !bytes || !isMint || !TOKEN_PROGRAMS.has(acc.owner)) { console.error(`${mint} is not an initialized token mint, skipped`); return; } const raw = bytes.readBigUInt64LE(36); // supply, in base units const ui = Number(raw) / 10 ** bytes.readUInt8(44); // decimals insert.run(mint, Number(context.slot), ts, raw.toString(), ui); console.log(`slot ${context.slot} ${mint.slice(0, 8)} supply ${ui} (${Number(minutes.get(mint)?.n)} minute points)`); });}for (;;) { await poll().catch((err: unknown) => console.error("poll failed:", err instanceof Error ? err.message : err)); await new Promise((r) => setTimeout(r, intervalMs));}
run: node main.ts
Run it and read the series
Pass the mints and start it under a supervisor such as a systemd unit: node main.ts <mint> [<mint> ...]. Each poll prints one line per mint with the slot, the first 8 characters of the mint, the supply and the number of minute points the table holds for it. The first line appears after the first answer, and the chart gets its second point when the next clock minute starts.
Open the same file from your chart server with the same query, read-only, and keep each read short. Chart the ui column as a step line. Use slot when you need to join a point to chain data, since ts is your machine's clock.
What it costs against your limits
Each poll is one call and 10 cells per mint, so 2 mints cost 20 cells and 20 mints cost 200 on the account-read rate. At the default interval that is 0.1 calls per second.
Free allows account reads at 0.5 req/s with 10 cells a call, which is 5 cells per second. At the 10 second default, Free holds about 5 mints before polls start getting 429, and a call with more pubkeys is charged more cells, so on Free keep the list short or raise INTERVAL_S. Limits are per account, so every key shares one budget. The collector logs a failed poll and tries again at the next interval.
Where it ends
- It stores supply only; a price series needs the prices method.
- It has no backfill. The first row is the first poll. Older supply changes could be rebuilt from transactions, but `getSignaturesForAddress` reaches back 30 days at most, from Carbium's own address index, and each getTransaction costs 50 cells. The collector does not do that.
- The collector sends every mint in one call, so more than 100 mints below Pro fails every poll, because the 1024-cell burst caps a call at 100 pubkeys there.
- A poll every 10 seconds sees the supply at that moment. A mint and a burn between two polls show as one step.
- It reads mints and no holder lists. getTokenLargestAccounts is not served and answers -32601, method not served, which you should not retry.
- One process writes one file. A collector that dies leaves a gap in the series and sends no alert, so supervise it and check the newest ts from somewhere else.
- The time axis is the clock of the machine that runs the collector. If that clock drifts, the chart drifts with it, and slot is the value to trust.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The log shows <mint> is not an initialized token mint, skipped on every poll. | The address is a wallet, a token account or a typo, or the account does not exist. Pass the mint address itself. A token account holds a balance for a mint and is not a mint. |
| The process exits at start with an address error. | One of the arguments is not a valid base58 address. Check for a cut-off paste or a stray character, then start again. |
| The log shows poll failed: with an HTTP error and the table does not grow. | Check that CARBIUM_KEY holds the key itself and that nothing else sets CARBIUM_RPC_URL. The key goes in the x-api-key header, or as `?api-key=` on the URL. |
| The log shows poll failed: with an HTTP error (429) now and then. | Your account's budget is spent, often by app traffic on other keys, since every key shares one. Raise INTERVAL_S, shorten the mint list, or move to a plan with a higher rate. The next poll runs on its own. |
| The chart line slopes between two readings, or breaks off where minutes are missing. | A minute with no sample has no row, which happens when the collector was stopped or the polls failed, and a plain line joins the points on either side with a slope. Fill the gaps forward in the chart client and draw a step line, since supply holds its value until the next change. |
| A second collector started on the same file logs poll failed: with database is locked now and then. | Run one collector per file. Readers are fine to add, because the file is in WAL mode. |
Questions
Can I store the balance of a token account too?
Yes. A token account keeps its amount at byte 64 and the mint in its first 32 bytes, and it has no decimals, so read the decimals from the mint. getTokenAccountBalance returns the amount with decimals applied and costs 10 cells.
Could a WebSocket subscription replace the polling?
For mints whose account state is streamed it could. accountSubscribe sends account state on change, and an account subscription opens at 25 credits, then costs 20 credits per MiB sent. A supply changes rarely, so a push sends little, but polling gives a chart a point every interval.
How many mints can one call read?
One call holds at most 100 mints below Pro, where the 1024-cell burst caps it, and up to 300 pubkeys on Pro. A full call of 300 is charged 10 cells per pubkey, about 3,000 cells, so a long list needs a longer interval, or a plan with a higher rate.
Why store the slot as well as the time?
The slot is chain time and ts is your machine's clock. The slot lets you join a point to transactions and blocks, and with the mint it makes the primary key that keeps a retry from writing a row twice.