library / Integrations / I0024
DuckDB flat transfer table
A Node script that reads the newest signatures of a program from Carbium RPC, decodes each transaction's token balance changes and program logs into flat rows, and writes a JSON Lines file that DuckDB loads with one query.
What one run writes
DuckDB reads a file with one query, so the most useful output of a Solana job is a flat file with one row per fact. This script produces that file. It takes the newest signatures of an address, usually a busy program, fetches each transaction and writes one JSON object per balance change to transfers.jsonl. Its only dependency is @solana/kit. DuckDB needs no Node driver, because the database loads the file itself.
- Read the newest signatures of the address with getSignaturesForAddress and drop the ones that failed on chain.
- Fetch every remaining transaction with getTransaction, one call each, all started together.
- Diff the token balances before and after, and sum the change per owner and mint.
- Read the top-level programs from the log lines, write one row per owner and mint, and print a summary.
| Field | Holds |
|---|---|
| signature | The transaction signature, the key back to any RPC call or explorer. |
| slot | The slot the transaction landed in. |
| block_time | Unix seconds of the block. Null when the node has no time for it. |
| owner | The wallet that owns the token accounts that changed. Null when the node leaves it out. |
| mint | The token mint. |
| decimals | The mint's decimals, for turning raw units into display amounts. |
| delta | The signed change in raw units, as a string. |
| direction | in when the owner gained the token, out when it lost it. |
| programs | The programs the transaction called directly, comma separated, in call order. |
Decoding a transfer from balances and logs
A token transfer has no single shape. A swap moves several mints through several token accounts in one transaction, and an instruction that moves tokens to an existing token account names the token accounts and the sender's authority, never the receiving wallet. Reading instructions alone tells you little about who ended up with what.
The balance lists answer that. A processed transaction carries preTokenBalances and postTokenBalances in its metadata. Each entry holds the account index, the mint, the owning wallet and the amount in raw units. Subtracting pre from post for each owner and mint gives the signed change the transaction caused. A wallet can own more than one token account for one mint, so the script sums them into one row. A change of zero is dropped, which removes accounts the transaction only read.
The logs supply context. A program that runs prints Program <id> invoke [1] for each top-level instruction and a deeper level number for each call it makes into another program. The script keeps level 1 only, which names the programs the transaction called directly. For a swap through a router that is the router, and the pools behind it stay out of the column. Filtering on programs in SQL then separates one router's swaps from everything else that touched the same address.
The Carbium calls
getSignaturesForAddress returns newest first. The script sets no commitment, so @solana/kit fills in confirmed for both methods.
getTransaction runs with maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and without that setting the call answers -32015 for one of them, so a single v1 transaction in the page would fail its lookup. Transaction version error -32015 covers the error.
Signatures come from Carbium's own address index, which keeps up to 30 days and reaches below the validator's ledger floor. getTransaction can therefore answer null for an older signature the list returned. The script counts those and carries on, and it prints the count so a gap does not pass unseen.
The DuckDB side
Start duckdb in the folder that holds the file and query it in place.
- SELECT * FROM read_json_auto('transfers.jsonl') LIMIT 10; shows the rows as the script wrote them.
- CREATE TABLE transfers AS SELECT * FROM read_json_auto('transfers.jsonl'); copies them into a table in your database file.
- SELECT owner, mint, sum(CAST(delta AS HUGEINT)) AS net FROM transfers GROUP BY ALL ORDER BY abs(net) DESC LIMIT 10; lists the largest net movers per mint.
- SELECT to_timestamp(block_time), owner, delta FROM transfers WHERE programs LIKE '%<program id>%'; keeps the transactions that called one program.
delta is a string on purpose. Token amounts are unsigned 64-bit integers, and a JavaScript number holds integers exactly only up to 2^53, so a large raw amount written as a number would lose digits. CAST(delta AS HUGEINT) restores the exact value in DuckDB's 128-bit type, and sums stay exact.
A second run overwrites the file. To keep history, load each file into the table before the next run, then remove repeats with QUALIFY row_number() OVER (PARTITION BY signature, owner, mint ORDER BY slot) = 1 when two runs saw the same signature.
The script and how to run it
Install with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types when it loads the file. CARBIUM_KEY is required, the script exits with a message when it is unset, and it goes out in the x-api-key request header. CARBIUM_RPC_URL is optional and defaults to the RPC endpoint, https://services.carbium.sh. The first argument is the address to read and the second is how many signatures to decode, 10 by default. With no address it reads a busy swap program.
// I0024 · DuckDB flat transfer table// https://carbium.sh/library/integrate/duckdb-flat-transfer-table// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { writeFileSync } from "node:fs";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); }// Address to read (a busy swap program by default) and how many newest signatures to decode.const target = process.argv[2] ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";const limit = Number(process.argv[3] ?? 10);const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);const sigs = (await rpc.getSignaturesForAddress(address(target), { limit }).send()).filter((s) => !s.err);const results = await Promise.allSettled( sigs.map((s) => rpc.getTransaction(s.signature, { encoding: "json", maxSupportedTransactionVersion: 1 }).send()),);const rows: Record<string, unknown>[] = [];let nulls = 0;let failed = 0;results.forEach((r, i) => { const signature = sigs[i].signature; if (r.status === "rejected") { failed++; console.error(`${signature} failed: ${(r.reason as Error).message}`); return; } const meta = r.value?.meta; if (!r.value || !meta) { nulls++; return; } // Net change per owner and mint (post minus pre); one wallet may hold several token accounts for a mint. const net = new Map<string, { owner: string | null; mint: string; decimals: number; delta: bigint }>(); for (const [list, sign] of [[meta.preTokenBalances, -1n], [meta.postTokenBalances, 1n]] as const) { for (const b of list ?? []) { const k = `${b.owner}:${b.mint}`; const cur = net.get(k) ?? { owner: b.owner ?? null, mint: b.mint, decimals: b.uiTokenAmount.decimals, delta: 0n }; cur.delta += sign * BigInt(b.uiTokenAmount.amount); net.set(k, cur); } } // Programs the transaction called directly: "Program <id> invoke [1]" log lines. const programs = [...new Set( (meta.logMessages ?? []) .map((l) => /^Program (\w+) invoke \[1\]$/.exec(l)?.[1]) .filter((p): p is string => !!p), )]; for (const t of net.values()) { if (t.delta === 0n) continue; rows.push({ signature, slot: Number(r.value.slot), block_time: r.value.blockTime == null ? null : Number(r.value.blockTime), owner: t.owner, mint: t.mint, decimals: t.decimals, delta: String(t.delta), // a string keeps every digit of a 64-bit amount direction: t.delta > 0n ? "in" : "out", programs: programs.join(","), }); }});writeFileSync("transfers.jsonl", rows.map((r) => JSON.stringify(r) + "\n").join(""));console.log(`${target}: ${sigs.length} signatures, ${rows.length} rows in transfers.jsonl, ${nulls} null, ${failed} failed`);for (const r of rows.slice(0, 3)) console.log(JSON.stringify(r));
run: node main.ts JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4 10
A run prints a summary line with the signature count, the rows written, the null lookups and the failed calls, then the first three rows. To check a row, look up its signature in an explorer and compare the owner's token balances before and after. For a swap, the owner shows one mint falling and another rising, and the two rows share one signature.
What a run costs against your limits
getSignaturesForAddress and getTransaction each cost 50 cells per call, and cells are the admission charge per call. A run of 10 transactions makes 11 calls, 550 cells.
| Plan | getTransaction req/s | getSignaturesForAddress req/s |
|---|---|---|
| Free | 0.24 | 0.24 |
| Dev | 1.2 | 1.2 |
| Business | 5 | 100 |
| Pro | 25 | 500 |
A class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger. Below Pro the 1,024-cell floor sets the burst, so twenty getTransaction calls cost 1,000 cells and fit it. Pro's one second of getTransaction is 1,250 cells, which holds 25 calls. On Free, a page above 20 transactions meets 429. On Dev and Business, a call past the burst waits once and is served when its cells refill within 1 s. Limits are per account, so other keys on it spend the same budget. Because the script settles each call on its own, a 429 on one lookup shows as a printed failure and the other rows still land.
Where it ends
- It decodes token balance changes. A transfer that nets to zero for an owner inside one transaction leaves no row, and SOL moves, fees and rent are not in the file.
- It samples. A program that lands more than the requested number of transactions between two runs loses the rest. For a feed with no gaps, subscribe to logs and fetch each signature as it arrives (Multi-wallet log watcher).
- It reads 30 days at most, because the address index holds no older history.
- Failed transactions are skipped, and so are their logs.
- Logs give top-level program ids only, and a node truncates the logs of a very long transaction (Log truncated), so programs can miss later top-level calls there. Instruction names and arguments need the program's own layout, which Anchor instruction decoder shows for programs that publish one.
- The script writes a file. Scheduling runs and keeping history across runs are yours.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The run exits with Set CARBIUM_KEY to your Carbium API key. | Export CARBIUM_KEY in the shell that runs node main.ts. A service or cron job needs the variable in its own environment. |
| Lines print failed with a -32015 error for some signatures. | The maxSupportedTransactionVersion: 1 setting is missing or set to 0 in the getTransaction call. Restore it so v1 transactions resolve. |
| A call fails with HTTP 401. | Carbium does not know the key it received, so the door answers with a 401 error, UNKNOWN_KEY. Set CARBIUM_KEY to the whole key with nothing cut off, and check that CARBIUM_RPC_URL is unset or points at Carbium. |
| Several lookups fail with 429 and the file holds fewer rows than the signatures suggest. | Lower the count in the second argument or space the runs out. A 429 carries a retry-after hint, and other keys on the account share the budget. |
| The summary shows signatures but 0 rows. | Every transaction failed, came back null, or moved no token. Read the null and failed counts, then try an address whose transactions move tokens. |
| A DuckDB query on delta fails on a type or returns sums that look rounded. | Wrap it in CAST(delta AS HUGEINT) before sum, abs or any comparison. The column is a string so no digit is lost on the way in. |
Questions
Why write a file and not insert into DuckDB from Node?
Node has no built-in DuckDB binding, and the script stays on @solana/kit plus built-ins. DuckDB reads JSON Lines natively, and the file doubles as a record of what a run saw.
Why one `getTransaction` per signature and not `getBlock`?
getBlock returns every transaction in a slot, which fits a job that wants the whole chain. For one program, the address index narrows the list to its own signatures first.
Does the owner column name the receiving wallet?
Yes. It comes from the balance lists, which carry the owning wallet of each token account. Reading the transfer instruction would give only token accounts and the sender's authority.
Can it follow a program live?
Subscribe to logsSubscribe with a mention filter over the WebSocket to learn each signature as it lands, then fetch and decode it the same way.