library / Integrations / Data warehouses / I0125
Iceberg program log table
A Node script that takes several program ids and a span of slots, fetches their transactions from Carbium RPC, and writes one JSON Lines row per log line, tagged with the program that printed it, ready for Spark to merge into an Iceberg table.
What one run writes
Spark, Trino and Flink write Iceberg tables but ship no Solana reader, so this script fetches the chain side. You hand it program ids and a number of slots. It collects the transactions those programs took part in and saves one JSON Lines row for every program log line into program_logs.jsonl. A Spark MERGE then adds the rows the table does not hold yet. Only @solana/kit is needed.
- Ask getSlot for the tip, then subtract the span to find where the window begins.
- For each program, list recent signatures page by page, keeping those inside the window whose transaction succeeded.
- Call getTransaction once per distinct signature, all requests in flight together.
- Step through each transaction's log lines, label every line with the program that printed it, and save the file.
| Column | Holds |
|---|---|
| signature | The transaction signature. |
| slot | The slot the transaction landed in. |
| block_time | Unix seconds of the block, null when the node has no time for it. |
| queried | The program ids whose listing returned this signature, comma separated. |
| log_index | Position of the line in the transaction's log, from 0. |
| depth | How many programs were open when the line was printed. 1 is a top-level call. |
| program | The program that printed the line. |
| message | The line as the node returned it. |
Turning a slot span into signatures
No Solana call returns a program's transactions for a range of slots. The nearest tool is getSignaturesForAddress, which lists one address's signatures from newest to oldest, each with its slot. The script reads the tip, works out the start, and walks back with before until a page contains slots below the start. Slots run about 200 ms apart on mainnet, so the default span of 200 slots is about 40 seconds of chain time.
A busy program can land hundreds of transactions in that stretch, so two caps keep the run small. Listing ends after two pages of 100, and each program contributes at most its six newest signatures from the window. The closing summary prints the window and the counts, which makes a short result easy to spot. When one transaction touches two of your programs, the script fetches it a single time and queried lists both ids.
All three calls here, getSlot, getSignaturesForAddress and getTransaction, omit commitment, and @solana/kit then sends confirmed. The getTransaction call sets maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and with the setting missing the node replies -32015 for any of them.
The signatures come from Carbium's address index, which holds up to 30 days and extends below the validator's ledger floor. For that reason getTransaction may return null for a signature the listing gave you. The script tallies those and carries on. The newest slots are where results are dependable.
From log lines to rows
The runtime emits a transaction's logs in the order calls happen. A line Program <id> invoke [n] starts a call at depth n, and Program <id> success or Program <id> failed ends it. Whatever sits between belongs to the innermost call still open: its Program log: text, its Program data: events and its compute unit reports. The script holds a stack of open programs, and every row stores the top entry plus the stack size.
The program column lets you ask about a program you never listed. A swap through a router invokes pool programs, so a signature found under the router also contains the pools' lines. Filtering with WHERE program = '<pool id>' returns the pool's lines inside those router transactions, without a second listing. The pool's other transactions need its own id in the first argument.
The Iceberg side
The example uses Spark with the Iceberg runtime and its SQL extensions. Trino and Flink can read the same file through their own SQL.
- CREATE TABLE lake.chain.program_logs (signature string, slot bigint, block_time bigint, ts timestamp, queried string, log_index int, depth int, program string, message string) USING iceberg PARTITIONED BY (days(ts)); builds the table, once. Pick any catalog name in place of lake.
- ALTER TABLE lake.chain.program_logs WRITE ORDERED BY slot; tells later writes to sort by slot.
- spark.read.json("program_logs.jsonl").createOrReplaceTempView("raw") makes the file visible to SQL.
- MERGE INTO lake.chain.program_logs t USING (SELECT *, timestamp_seconds(block_time) AS ts FROM raw) s ON t.signature = s.signature AND t.log_index = s.log_index WHEN NOT MATCHED THEN INSERT *; inserts only rows the table does not hold yet, so running it again over overlapping slots duplicates nothing.
SELECT program, count(*) FROM lake.chain.program_logs WHERE slot BETWEEN <from> AND <to> GROUP BY program; gives line counts per program for the window the run printed. Iceberg stores each data file's smallest and largest slot in its metadata, so a slot BETWEEN filter passes over files whose range falls outside it. Sorted writes keep those ranges tight.
The script and how to run it
Run npm install @solana/[email protected] and put "type": "module" in package.json. Node 24 removes the types as it loads the file. CARBIUM_KEY must be set, or the script stops with a message. The key travels in the x-api-key request header. CARBIUM_RPC_URL may be set, and otherwise points at the RPC endpoint, https://services.carbium.sh. Three arguments follow: comma-separated program ids, the span in slots (default 200) and the signatures kept for each program (default 6). Without arguments it reads two busy swap programs.
// I0125 · Iceberg program log table// https://carbium.sh/library/integrate/iceberg-program-log-table// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { writeFileSync } from "node:fs";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, type Signature } from "@solana/kit";const apiKey = process.env.CARBIUM_KEY;if (!apiKey) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1);}// Arguments: comma-separated program ids, the span in slots back from the tip, signatures kept per program.const [idArg, spanArg, keepArg] = process.argv.slice(2);const ids = (idArg ?? "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4,whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc").split(",");const span = BigInt(spanArg ?? "200");const keep = Number(keepArg ?? "6");const client = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey }, }),);const tip = await client.getSlot().send();const start = tip - span;// Newest successful signatures of one program inside the window, two pages of 100 at most.async function newestInWindow(id: string): Promise<Signature[]> { const hits: Signature[] = []; let cursor: Signature | undefined; for (let n = 0; n < 2; n++) { const page = await client.getSignaturesForAddress(address(id), { limit: 100, before: cursor }).send(); page.filter((e) => !e.err && e.slot >= start && e.slot <= tip).forEach((e) => hits.push(e.signature)); const oldest = page.at(-1); if (!oldest || oldest.slot < start) break; cursor = oldest.signature; } return hits.slice(0, keep);}const listings = await Promise.allSettled(ids.map(newestInWindow));const askedBy = new Map<Signature, string[]>();listings.forEach((res, i) => { if (res.status === "rejected") { console.error(`${ids[i]} listing failed: ${(res.reason as Error).message}`); return; } for (const sig of res.value) askedBy.set(sig, [...(askedBy.get(sig) ?? []), ids[i]]);});const signatures = [...askedBy.keys()];const fetched = await Promise.allSettled( signatures.map((sig) => client.getTransaction(sig, { encoding: "json", maxSupportedTransactionVersion: 1 }).send()),);const lines: string[] = [];let missing = 0;let errors = 0;fetched.forEach((res, i) => { const signature = signatures[i]; if (res.status === "rejected") { errors++; console.error(`${signature} failed: ${(res.reason as Error).message}`); return; } const tx = res.value; if (!tx?.meta) { missing++; return; } // Open programs, innermost last: an invoke line pushes one, a success or failed line pops it. const open: string[] = []; (tx.meta.logMessages ?? []).forEach((message, log_index) => { const call = /^Program (\w+) invoke \[\d+\]$/.exec(message); if (call) open.push(call[1]); lines.push(JSON.stringify({ signature, slot: Number(tx.slot), block_time: tx.blockTime == null ? null : Number(tx.blockTime), queried: (askedBy.get(signature) ?? []).join(","), log_index, depth: open.length, program: open.at(-1) ?? null, message, })); if (/^Program \w+ (success|failed)/.test(message)) open.pop(); });});writeFileSync("program_logs.jsonl", lines.map((l) => l + "\n").join(""));console.log(`slots ${start}..${tip}: ${signatures.length} signatures, ${lines.length} rows in program_logs.jsonl, ${missing} null, ${errors} failed`);lines.slice(0, 3).forEach((l) => console.log(l));
run: node main.ts JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4,whirLbMiicVdio4qvUfM5KAg6Ct8VwpYzGff3uctyCc 200 6
The run prints the slot window, the signature and row counts, the null lookups and the failed calls, then the first three rows. To verify one, open its signature in an explorer and set the log beside the row's message and program.
What a run costs against your limits
A default run issues one getSlot at 1 cell, up to four listing calls at 50 cells each and up to twelve getTransaction calls at 50 cells each. Cells are the admission charge per call, which puts a default run at 801 cells at most.
| Plan | getTransaction req/s | getSignaturesForAddress req/s |
|---|---|---|
| Free | 0.24 | 0.24 |
| Dev | 1.2 | 1.2 |
| Business | 5 | 100 |
| Pro | 25 | 500 |
Each rate class takes bursts of at least 1,024 cells, or one second of its rate when that is larger, so even Free absorbs a default run in one burst. A bigger run exceeds it: setting the third argument to 20 with two programs means 40 lookups and 2,000 cells. Free refills that class at about 12 cells a second (0.24 calls of 50 cells), so once the burst is spent a lookup's short wait cannot cover its 50 cells and it ends in 429. Limits belong to the account, so any other keys on it draw on the same budget. Every call here settles separately, which means a 429 shows as a failure while the remaining rows are still written.
Where it ends
- It samples. Two pages and six signatures per program bound the window, and a busy program lands more than that. To see every transaction as it happens, subscribe to logs and fetch each signature on arrival (Multi-wallet log watcher).
- A span of slots is not a span of blocks. A slot whose leader produced nothing has no transactions, so 200 slots can hold fewer than 200 blocks.
- It reaches 30 days back at most, since the address index holds nothing older.
- Failed transactions are skipped, and so are their logs.
- A node trims the logs of a very long transaction and appends Log truncated. Later lines are gone, and the program stack can fall out of step from there.
- The script produces a file and makes no Iceberg commit. The merge, schema changes and file compaction stay with your engine.
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 scheduler needs the variable in its own environment. |
| The summary shows 0 signatures. | The window held no successful transaction for those programs, or a listing failed and printed its error above. Widen the span in the second argument and check that each id is a program with recent activity. |
| Lines print failed with a -32015 error. | maxSupportedTransactionVersion: 1 is missing or set to 0 in the getTransaction call. Restore it so v1 transactions resolve. |
| A call fails with HTTP 401. | Carbium did not recognise the key and answered 401 with UNKNOWN_KEY. Set CARBIUM_KEY to the complete key, and leave CARBIUM_RPC_URL unset or pointed at Carbium. |
| Several lookups fail with 429 and the file has fewer rows than the signatures suggest. | Lower the third argument or space the runs out. A 429 carries a retry-after hint, and other keys on the account share the budget. |
| Spark rejects the MERGE statement as unsupported. | The Iceberg SQL extensions are not loaded. Start the session with spark.sql.extensions=org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions. |
Questions
Why JSON Lines and not Parquet?
Node has no built-in Parquet writer, and the script stays on @solana/kit plus built-ins. Spark reads the JSON Lines file and writes Parquet data files when it commits to the Iceberg table.
Why list signatures and not call `getBlock` for each slot?
getBlock returns every transaction of a slot, which fits a job that wants the whole chain. For a few programs, the address index narrows the work to their own signatures, and 200 slots would otherwise mean 200 block calls.
Can the span reach back further than 30 days?
No. The signature listing comes from an address index that keeps up to 30 days, and an empty page past that point marks its age limit.
Can one file hold several programs?
Yes. Pass the ids comma separated. Every row names the program that printed the line, and queried names the listings that returned its transaction.