library / Integrations / I0012
BigQuery chain dataset
A small Node script reads one address's recent transactions from Carbium over RPC, flattens each into a row, and writes a newline-delimited JSON file and a schema file that bq load takes straight into a BigQuery table.
What the loader builds
Two files come out of each run. transactions.ndjson holds one JSON row per line, and schema.json describes the columns for bq load. The table lives in your project, under your quota and your access rules.
| Column | Type | Meaning |
|---|---|---|
| signature | STRING | The transaction signature, used as the key. |
| slot | INT64 | The slot the transaction landed in. |
| block_time | TIMESTAMP | UTC time of the block, null when the node has none. |
| success | BOOL | True when the transaction carried no error. |
| error | STRING | The error as JSON, null on success. |
| fee_lamports | INT64 | The fee paid, in lamports. |
| compute_units | INT64 | Compute units consumed, null when the node reports none. |
| fee_payer | STRING | The first account key, which pays the fee. |
| instruction_count | INT64 | Number of top-level instructions. |
| program_ids | STRING, repeated | The programs that top-level instructions call. |
The columns are flat and typed, so a query needs no JSON functions except on error.
The Solana side: signatures, then transactions
The script reads from Carbium's RPC endpoint at https://services.carbium.sh. Set CARBIUM_RPC_URL to point it elsewhere.
It works in two steps. First it pages getSignaturesForAddress for the address, up to 1,000 signatures a page, newest first, and passes the last signature it has as before to get the next page. Then it calls getTransaction once per signature, one at a time. Every call asks for finalized, so only final data reaches the table.
getTransaction runs with encoding: "json" and maxSupportedTransactionVersion: 1. Mainnet carries version 1 transactions, and with that setting absent or 0, getTransaction answers -32015 for one of them, so the script sets 1. Version 0 transactions can use address lookup tables, so the keys an instruction index points into are the message's account keys followed by the loaded writable and readonly addresses. The script joins them in that order before it names a program.
Slot, fee and compute units arrive as bigint. The script converts them with Number, which is exact below 2^53, far above any slot or fee today. The error object can hold bigint values too, so the JSON conversion of an error turns them into strings first.
The BigQuery side: schema and load
The script never talks to Google. It writes files, so the load can run from any machine that has the bq tool and credentials for your project. Set it up once, then load each run through a staging table so a rerun adds no duplicates.
- bq mk --dataset my_project:solana creates the dataset.
- bq mk --table my_project:solana.transactions schema.json creates the main table from the schema file.
- bq load --replace --source_format=NEWLINE_DELIMITED_JSON my_project:solana.staging transactions.ndjson schema.json puts this run alone in the staging table.
- bq query --use_legacy_sql=false --dataset_id=my_project:solana 'MERGE transactions t USING staging s ON t.signature = s.signature WHEN NOT MATCHED THEN INSERT ROW' adds the signatures the main table does not have yet.
Loading the same range twice is harmless, because the merge skips signatures already there. If the table grows large, add --time_partitioning_field block_time to the bq mk --table command, so queries over a date range read less. The schema file leaves partitioning to you.
The loader
Install the one dependency with npm install @solana/[email protected], and set "type": "module" in package.json. Node 24 strips the types on load. The script takes an address and an optional count of transactions, 20 by default. It reads CARBIUM_KEY, which is required, and exits with a message when it is unset. CARBIUM_RPC_URL is optional.
// I0012 · BigQuery chain dataset// https://carbium.sh/library/integrate/bigquery-chain-dataset// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, isSolanaError, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, type Signature,} from "@solana/kit";import { writeFile } from "node:fs/promises";const key = process.env.CARBIUM_KEY;const [target, count = "20"] = process.argv.slice(2);const want = Number(count);if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1); }if (!target || !Number.isInteger(want) || want < 1) { console.error("Usage: node main.ts <address> [transactions]"); process.exit(1); }// One client, built once and reused for every call.const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),);const owner = address(target);// The highest transaction version this client accepts: mainnet already carries version 1.const txConfig = { commitment: "finalized", encoding: "json", maxSupportedTransactionVersion: 1 } as const;// Repeat a call after a 429 for as long as retry-after asks, up to 5 tries.async function retry<T>(call: () => Promise<T>): Promise<T> { for (let attempt = 1; ; attempt++) { try { return await call(); } catch (e) { const wait = isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) && e.context.statusCode === 429 ? Number(e.context.headers.get("retry-after")) || 1 : 0; if (!wait || attempt === 5) throw e; console.error(`429, waiting ${wait} s`); await new Promise((r) => setTimeout(r, wait * 1000)); } }}// Step 1: signatures, newest first, one page of up to 1000 at a time.const signatures: Signature[] = [];while (signatures.length < want) { const before = signatures[signatures.length - 1]; const page = await retry(() => rpc.getSignaturesForAddress(owner, { commitment: "finalized", limit: Math.min(1000, want - signatures.length), before }).send()); if (page.length === 0) break; // the address index ends here (30 days at most) signatures.push(...page.map((s) => s.signature));}console.log(`found ${signatures.length} signatures for ${owner}`);// Step 2: one row per transaction.interface Tx { slot: bigint; blockTime: bigint | null; meta: { err: unknown; fee: bigint; computeUnitsConsumed?: bigint; loadedAddresses?: { writable: string[]; readonly: string[] } } | null; transaction: { message: { accountKeys: string[]; instructions: { programIdIndex: number }[] } };}const rows: string[] = [];for (const signature of signatures) { let tx: Tx | null; try { tx = (await retry(() => rpc.getTransaction(signature, txConfig).send())) as unknown as Tx | null; } catch (e) { console.error(`failed ${signature}: ${(e as Error).message}`); continue; } const meta = tx?.meta; if (!tx || !meta) { console.error(`skipped ${signature}`); continue; } const { accountKeys, instructions } = tx.transaction.message; const keys = [...accountKeys, ...(meta.loadedAddresses?.writable ?? []), ...(meta.loadedAddresses?.readonly ?? [])]; const failed = meta.err != null; const row = { signature, slot: Number(tx.slot), block_time: tx.blockTime == null ? null : new Date(Number(tx.blockTime) * 1000).toISOString(), success: !failed, error: failed ? JSON.stringify(meta.err, (_k, v: unknown) => (typeof v === "bigint" ? v.toString() : v)) : null, fee_lamports: Number(meta.fee), compute_units: meta.computeUnitsConsumed == null ? null : Number(meta.computeUnitsConsumed), fee_payer: keys[0], instruction_count: instructions.length, program_ids: [...new Set(instructions.map((i) => keys[i.programIdIndex]))], }; rows.push(JSON.stringify(row)); console.log(`${signature} slot ${row.slot} ${row.success ? "ok" : "failed"}`);}// Write a file in the working directory; when that is read-only, print the content instead.async function save(name: string, text: string) { try { await writeFile(name, text); console.log(`wrote ${name}`); } catch (e) { console.error(`cannot write ${name} (${(e as { code?: string }).code}), printing it instead`); console.log(text); }}// name:type:mode for each column of the BigQuery tableconst cols = "signature:STRING:REQUIRED slot:INT64:REQUIRED block_time:TIMESTAMP:NULLABLE success:BOOL:REQUIRED error:STRING:NULLABLE fee_lamports:INT64:REQUIRED compute_units:INT64:NULLABLE fee_payer:STRING:REQUIRED instruction_count:INT64:REQUIRED program_ids:STRING:REPEATED";const schema = cols.split(" ").map((c) => { const [name, type, mode] = c.split(":"); return { name, type, mode }; });await save("transactions.ndjson", rows.map((r) => `${r}\n`).join(""));await save("schema.json", JSON.stringify(schema, null, 1));
run: node main.ts
The script prints one line per transaction as it goes, names each one it could not read in a skipped or failed line, and writes both files at the end, in the working directory. If the working directory is read-only, it prints the file contents after the progress lines instead, and you have to cut those lines out before running bq load. Run it as node main.ts <address> 1000, then load the files with the four commands above.
What a load costs against your limits
getSignaturesForAddress and getTransaction cost 50 cells each. A load of N transactions makes one signature call per 1,000 signatures and one transaction call per signature. The default of 20 is 21 calls, or 1,050 cells. A load of 1,000 is 1,001 calls, or 50,050 cells.
Limits are per account, so all keys share one budget. A call over its rate gets a 429 with a retry-after hint. The script reads the hint, sleeps that long and repeats the same call, up to 5 tries. Check the req/s for these two calls on your plan before you start a big pull.
Because the budget is shared, a big load can crowd out your app's own calls. Start it when app traffic is low, and see RPC rate-limit alerts for watching the 429 count.
Where it ends
- It loads one address per run. A table of every transaction on the chain, or a block-by-block table, is outside what this builds.
- History stops at 30 days. getSignaturesForAddress pages come from Carbium's own address index, which keeps up to 30 days. An empty page past that marks the index's age limit, and the address may have older transactions. Those are not served, so start loading early and keep appending.
- The columns are flat. A program that runs only through a cross-program call does not appear in program_ids, and inner instructions, token balances and logs are not loaded.
- It is a batch job. Nothing is written until the last signature is handled, so a crash loses the run, and a failed getTransaction call costs only its own row. Rerun after a crash, and the merge keeps the table clean.
- The script makes one call at a time and retries on a 429, so it never has more than one call in flight. On a low plan a large pull is slow, and the retries absorb the calls that go over the rate.
- Rows the node returns no metadata for are skipped and named in the log.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The log shows 429, waiting 4 s a few times, then failed <signature> lines or a stop with an HTTP error (429). | All 5 tries hit the limit, so your account's budget is spent, often by app traffic on other keys. Lower the count, run the load when traffic is low, or move to a plan with a higher rate. A failed line costs one row and the load goes on. Rerun afterwards: the merge skips what is already loaded. |
| The script stops at its first call with an HTTP error (401). | Carbium answers 401 at the door for an unknown key, so attach the whole key: CARBIUM_KEY must hold the complete key, and nothing else should set CARBIUM_RPC_URL. The key goes in the request header x-api-key, or as ?api-key= on the URL. |
| The load ends with fewer rows than signatures, and the log shows skipped <signature> or failed <signature>. | skipped means the node returned no transaction or no metadata. The address index lists signatures below the validator's ledger floor, where getTransaction keeps answering null, so those rows stay missing and a rerun does not bring them back. A rerun helps only after a one-off miss, or after a failed line caused by a 5xx or a spent retry budget. The merge adds only the missing rows. |
| The log shows failed <signature> with code -32015. | Mainnet carries version 1 transactions, and a setting absent or 0 gets -32015 for them. Keep maxSupportedTransactionVersion in txConfig at 1 or higher. Only that row is lost, because the load goes on with the next signature. |
| bq load fails with a message that the provided schema does not match the table. | The staging or main table was created from a different schema file, for example by an older version of the script. Keep schema.json from the same run as transactions.ndjson, and drop and recreate the table, or keep --replace on the staging load. |
| The MERGE fails because the table was not found. | The main table does not exist yet. Run the bq mk --table command from step 2 once, then repeat the merge. |
Questions
Why load my own table?
The loader fills a table in your own project with the addresses you pick, read at finalized. You set the columns, the retention and the cost of the queries.
Can I load more than the last 30 days?
Not from here. getSignaturesForAddress reaches back 30 days at most on Carbium. Run the loader on a schedule so your table keeps the history after it leaves that window.
Can a JSON-RPC batch cut the number of requests?
A call can be a single request or a batch of up to 100. The loader sends single calls so that the retry after a 429 has exactly one call to repeat.
What does a 1,000 transaction load cost?
It makes 1,001 calls at 50 cells each, which is 50,050 cells. One call lists the signatures and the other 1,000 fetch the transactions.