services
Get a key

library / Integrations / I0025

Snowflake balance snapshots

The script reads the SOL balance of a wallet list from Carbium, writes one CSV per snapshot named by its slot, and you load each file into a Snowflake table with PUT and COPY INTO, building a balance history run by run.

By Carbium · Data warehouses · I0025 · updated 2026-11-22

01

The job in four steps

Snowflake holds history only for what you load into it, and a Solana RPC answers with current state. A balance you want to chart next month has to be read and stored by you on every day until then. This job does the reading: one Node file asks Carbium for the SOL balance of every address in a list and writes the answers to a CSV named after the slot it was read at. Snowflake then takes the file in with its own staging commands.

The script never connects to Snowflake. It needs no driver, no account identifier and no Snowflake login, so the Carbium key and the warehouse credentials live in different steps, and each step can run on a different machine.

StepWhereWhat happens
Readnode main.ts wallets.txtOne file, balances-<slot>.csv, with a row per address.
StagePUT file://balances-*.csv @sol_stageSnowSQL compresses the file and uploads it to a named stage.
LoadCOPY INTO sol_balances FROM @sol_stageFiles the table has not seen turn into rows.
QuerySQL on sol_balancesLatest balance per address, or the change between two snapshots.
02

Reading the balances

getMultipleAccounts takes a list of addresses and returns an array in the same order, with null where an address has no account on chain. The balance is the lamports field. The script writes it as a whole number of lamports, 1 SOL being 1,000,000,000, and leaves the division to SQL. A lamport count can pass the 2^53 limit of a JavaScript number or a floating point column, and an integer column of type NUMBER(38,0) holds it exactly.

A call takes up to 100 addresses in this script. Pro accepts up to 300, and below Pro the 1024-cell burst limit caps a call at 100, so the script batches at 100 on every plan. Each address costs 10 cells, which makes a full call 1000 cells, or 1001 when the request body runs past 4 KiB.

Every call names commitment finalized, so a snapshot holds values that cannot roll back and the result does not depend on a client's default. Each answer carries the slot it was read at, and the script writes that slot on every row. Two batches of one run are two reads and can carry different slots. The slot column gives the exact position of a row, and snapshot_utc gives the time the run started.

03

Loading into Snowflake

Two statements, CREATE TABLE and CREATE STAGE, set up the target once. PUT and COPY INTO run after each snapshot, from SnowSQL or the Snowflake CLI, never from a worksheet.

  • CREATE TABLE sol_balances (snapshot_utc TIMESTAMP_NTZ, slot NUMBER(38,0), address VARCHAR, lamports NUMBER(38,0), account_exists BOOLEAN)
  • CREATE STAGE sol_stage FILE_FORMAT = (TYPE = CSV SKIP_HEADER = 1)
  • PUT file://balances-*.csv @sol_stage, run from SnowSQL or the Snowflake CLI after each snapshot
  • COPY INTO sol_balances FROM @sol_stage PURGE = TRUE, which also removes each staged file once it has loaded

Snowflake remembers the file names a table has loaded and skips them on later COPY INTO runs, but only for 64 days. The slot in the file name keeps every snapshot distinct. A file still in the local folder is uploaded again by every PUT and loads twice once its 64-day load record has expired. Move each file to another folder once it has loaded, so later PUT runs never upload it again.

Two queries cover most uses. The first returns the newest balance of each address, and the second returns the change since the previous snapshot.

  • SELECT address, CAST(lamports AS NUMBER(38,9)) / 1000000000 AS sol FROM sol_balances QUALIFY ROW_NUMBER() OVER (PARTITION BY address ORDER BY snapshot_utc DESC) = 1
  • SELECT address, snapshot_utc, lamports - LAG(lamports) OVER (PARTITION BY address ORDER BY snapshot_utc) AS change FROM sol_balances
$The script writes snapshot_utc in UTC without a zone suffix, in the form 2026-11-22 10:15:30.123, which Snowflake parses into TIMESTAMP_NTZ on load with no format option.
04

The script

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 CARBIUM_RPC_URL is optional and defaults to https://services.carbium.sh. Each argument is an address or the path of a text file with one address per line.

main.ts
// I0025 · Snowflake balance snapshots// https://carbium.sh/library/integrate/snowflake-balance-snapshots// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  type Address,  createDefaultRpcTransport,  createSolanaRpcFromTransport,  isAddress,  isSolanaError,  SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,} from "@solana/kit";import { existsSync, readFileSync, writeFileSync } from "node:fs";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);// Arguments are addresses, or text files with one address per line.const words = process.argv  .slice(2)  .flatMap((arg) => (existsSync(arg) ? readFileSync(arg, "utf8").split(/\s+/) : [arg]))  .filter((w) => w !== "");const wallets: Address[] = [...new Set(words.filter(isAddress))];if (wallets.length === 0) {  console.error("Usage: node main.ts <wallets.txt | address ...>");  process.exit(1);}const ignored = words.filter((w) => !isAddress(w)).length;if (ignored > 0) console.error(`skipped ${ignored} word(s) that are not addresses`);// A 429 waits for the retry-after hint, then the same batch goes out again.async function readBatch(batch: Address[]) {  for (let attempt = 1; ; attempt++) {    try {      return await rpc        .getMultipleAccounts(batch, { commitment: "finalized", encoding: "base64", dataSlice: { offset: 0, length: 0 } })        .send();    } catch (e) {      if (attempt < 3 && isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) && e.context.statusCode === 429) {        await new Promise((r) => setTimeout(r, (Number(e.context.headers.get("retry-after")) || 1) * 1000));      } else throw e;    }  }}const startedAt = new Date().toISOString().replace("T", " ").replace("Z", "");const rows: string[] = [];let firstSlot: bigint | undefined;let failed = 0;for (let i = 0; i < wallets.length; i += 100) {  const batch = wallets.slice(i, i + 100);  try {    const { context, value } = await readBatch(batch);    firstSlot ??= context.slot;    batch.forEach((address, j) => {      const account = value[j];      rows.push(`${startedAt},${context.slot},${address},${account?.lamports ?? 0n},${account !== null}`);    });  } catch (e) {    failed += batch.length;    console.error(`batch at ${i} failed: ${e instanceof Error ? e.message : String(e)}`);  }}if (firstSlot === undefined) {  console.error("No batch succeeded, nothing written.");  process.exit(1);}// A file with every batch matches balances-*.csv; a partial one gets a suffix the PUT glob skips.const file = `balances-${firstSlot}.csv${failed > 0 ? ".partial" : ""}`;writeFileSync(file, ["snapshot_utc,slot,address,lamports,account_exists", ...rows].join("\n") + "\n");console.log(`${file}: ${rows.length} rows, ${failed} addresses failed`);if (failed > 0) process.exitCode = 1;

run: node main.ts wallets.txt

05

Scheduling it and what it costs

Put the wallet addresses in wallets.txt, one per line, and run node main.ts wallets.txt. A word that is not a valid address is skipped and counted on stderr, and an address listed twice is read once. The last line printed names the file and the number of rows in it.

To keep a history, run the script from a scheduler on your machine and follow it with the Snowflake steps, for example the cron line 0 * * * * cd /srv/snapshots && node main.ts wallets.txt && snowsql -o exit_on_error=true -f load.sql && mv balances-*.csv loaded/, where load.sql holds the PUT and the COPY INTO and loaded is a folder you create once. A run that skipped a batch exits with code 1, so the && stops the load. SnowSQL keeps going after a failed statement unless exit_on_error is set, so the flag makes a failed PUT or COPY INTO stop the mv and keeps the file for the next load. The final mv keeps each hourly PUT to the new file, so the upload does not grow with the history.

A list of 1,000 addresses is 10 calls and about 10,000 cells per run, which an hourly schedule turns into 240,000 cells a day. Account reads carry their own rate per plan:

PlanAccount reads, req/s
Free0.5
Dev15
Business50
Pro400

Limits are per account, so every key on the account draws on one budget, and credits meter RPC work on top of that. A schedule that shares an account with live app traffic should leave room for the app.

06

Where it ends

  • It reads SOL only. Token balances sit in token accounts with their own addresses, and SPL token balance reads them.
  • History starts at the first run. getMultipleAccounts returns current state, so no call rebuilds a balance for a day before you began loading.
  • A snapshot is a point in time. Funds that arrive and leave between two runs leave no row. To catch every movement, watch the wallets with the Multi-address deposit monitor.
  • An address with no account on chain gets lamports 0 and account_exists false. The flag lets a query keep unfunded and mistyped addresses apart from funded ones, and it cannot tell those two from each other.
  • Staging, loading, scheduling and warehouse cost sit on your side of the line. COPY INTO runs on a warehouse you pay for, under a role you choose.
07

When it goes wrong

what goes wrongwhat to do
The run exits at once with Set CARBIUM_KEY to your Carbium API key.Export CARBIUM_KEY in the shell or in the scheduler's environment. Cron starts with a minimal environment that lacks your shell's variables, so set the variable in the crontab or in a file the job sources.
The first batch fails with an HTTP 401 error.The key reached Carbium incomplete or unknown. Attach the whole key; an unknown key is refused at the door with UNKNOWN_KEY.
A batch fails with 429 after three tries and the output file ends in .csv.partial.The account's read budget is spent, often by other keys on the same account. The script waits the retry-after hint and resends twice, then skips the batch. Run again later. The partial file never matches balances-*.csv, so PUT leaves it on disk, where you can delete it or read it first.
COPY INTO reports 0 files processed.The stage holds nothing new, or the table already loaded files under those names. Run LIST @sol_stage to see what waits there, and PUT a file from a fresh run. FORCE = TRUE reloads old files and duplicates their rows.
An address you know holds funds shows lamports 0 and account_exists false.A mistyped string can still be a valid address that has no account. Compare the address with the one in your records, character by character, before you trust the row.
08

Questions

Can Snowflake call Carbium itself?

Snowflake can reach external endpoints through its own external access setup, and a function there could send the x-api-key header. This job keeps the key outside Snowflake and hands it files, which leaves the warehouse with no Carbium credentials to protect.

Why one file per run and not row inserts?

A file per run suits bulk loading, which Snowflake handles well, and the slot in the name gives COPY INTO a way to skip files it already has.

How many addresses can the list hold?

The script sets no cap. Every 100 addresses cost about 1000 cells, so your plan's account-read rate sets the pace of a run.

Can I snapshot token balances the same way?

Yes, with a second script and a second table. Token balances live in token accounts with their own addresses, which SPL token balance reads.