---
id: I0156
title: "Notion portfolio database"
url: https://carbium.sh/library/integrate/notion-portfolio-database
collection: Integrations
category: Spreadsheets and workspaces
revision: 1
updated: 2026-11-23
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Notion portfolio database

A Node script reads the SOL and SPL token balances of one wallet through your Carbium RPC and writes a CSV with one row per holding, ready to import into a Notion database.

## What the script builds

The script reads one wallet and writes `portfolio.csv` into the folder it runs from. Each row is one holding: the native SOL balance, then one row for every token account the wallet owns under the classic token program and under Token-2022. Notion imports that file as a database, one page per holding, with the wallet and a snapshot time on every row.

A wallet keeps its SOL in its own account and each token in a separate token account, so the script makes two kinds of read and writes both into the same table. It signs nothing and sends nothing.

## Two reads, one snapshot

Three calls make up the snapshot. Each one is settled on its own, so a failed token read leaves the SOL row in place and prints the failure.

| Call | What it returns | Commitment |
|---|---|---|
| `getBalance` | The lamport balance of the wallet's own account | `finalized` |
| `getTokenAccountsByOwner` with the classic token program | Every token account that program holds for the wallet | `finalized` |
| `getTokenAccountsByOwner` with Token-2022 | The same, for Token-2022 accounts | `finalized` |

The script sets `finalized` on each call and writes it out. Kit fills in `confirmed` when a call leaves the commitment out, so a reader who skips it gets a different read. A slot is about 200 ms now, and finalized sits 0 to 1 slots behind processed, so a snapshot at finalized lags very little, and a finalized balance is one a fork cannot take back.

Both token reads use `encoding: "jsonParsed"`, so each token account arrives with its mint and a `tokenAmount` that already carries the decimals and a text amount. The script writes that text unchanged, which keeps large amounts exact. The [rpc page](https://carbium.sh/docs/rpc) lists what each call costs.

One wallet can own several token accounts for the same mint, and each one is its own row. Sum those rows in Notion when you want one total per mint.

## Loading the CSV into Notion

Create an empty Notion database, open its menu, choose the CSV import, and pick `portfolio.csv`. Each line becomes one page, and the column names become properties. If Notion reads the Amount, Decimals or Snapshot column as text, change its type to number or date so that sorting works.

The file holds mints. Token rows read `SPL token` in the Asset column, so rename the rows you know, or add a name column by hand. The script reads no token metadata and no prices.

Importing again adds new pages and leaves the old ones in place. Clear the database, or import into a new one, before each refresh.

Writing rows through the Notion API needs a Notion key and one request per row. That step sits outside this script, which calls Carbium and nothing else.

## The script

The script reads `CARBIUM_KEY` and exits when it is unset. The wallet comes from the first argument. With no argument, it takes the fee payer of the newest transaction it can read from a busy swap-router program, so a bare run still produces a table. The endpoint is [the RPC endpoint](https://carbium.sh/docs/endpoints) unless `CARBIUM_RPC_URL` is set.

`main.ts` (run: `node main.ts`)

```ts
// I0156 · Notion portfolio database
// https://carbium.sh/library/integrate/notion-portfolio-database
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";
import { writeFile } from "node:fs/promises";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY before running this script.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);
const commitment = "finalized" as const;
const WSOL = "So11111111111111111111111111111111111111112";
const TOKEN_PROGRAMS = [
  "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
  "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb",
];
const SWAP_ROUTER = "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";

type Parsed = { parsed: { info: { mint: string; tokenAmount: { uiAmountString: string; decimals: number } } } };

// The fee payer of the newest transaction in the busy program that can be read.
async function findWallet(): Promise<string> {
  const sigs = await rpc.getSignaturesForAddress(address(SWAP_ROUTER), { limit: 5, commitment }).send();
  for (const s of sigs) {
    const tx = await rpc
      .getTransaction(s.signature, { encoding: "json", commitment, maxSupportedTransactionVersion: 1 })
      .send();
    if (tx) return tx.transaction.message.accountKeys[0];
  }
  throw new Error("no readable transaction in the newest signatures");
}

async function main(): Promise<void> {
  const owner = process.argv[2] ?? (await findWallet());
  const snapshot = new Date().toISOString();
  const failed: string[] = [];
  const rows: string[][] = [];

  const solRead = await rpc
    .getBalance(address(owner), { commitment })
    .send()
    .catch((e: unknown) => {
      failed.push(`getBalance: ${String(e)}`);
      return null;
    });
  if (solRead) rows.push(["SOL", WSOL, (Number(solRead.value) / 1e9).toString(), "9"]);

  for (const program of TOKEN_PROGRAMS) {
    const res = await rpc
      .getTokenAccountsByOwner(address(owner), { programId: address(program) }, { encoding: "jsonParsed", commitment })
      .send()
      .catch((e: unknown) => {
        failed.push(`getTokenAccountsByOwner ${program.slice(0, 6)}: ${String(e)}`);
        return null;
      });
    for (const a of res?.value ?? []) {
      const info = (a.account.data as unknown as Parsed).parsed.info;
      rows.push(["SPL token", info.mint, info.tokenAmount.uiAmountString, String(info.tokenAmount.decimals)]);
    }
  }

  const header = "Asset,Mint,Amount,Decimals,Wallet,Snapshot";
  const lines = rows.map((r) => [...r, owner, snapshot].join(","));
  await writeFile("portfolio.csv", [header, ...lines].join("\n") + "\n");
  console.log(`wrote ${lines.length} rows for ${owner} to portfolio.csv`);
  for (const f of failed) console.error("failed:", f);
}

main().catch((e: unknown) => {
  console.error(String(e));
  process.exit(1);
});
```

## Run it

Install the one dependency with `npm install @solana/kit@8.6.0`, set `"type": "module"` in `package.json`, export `CARBIUM_KEY`, and run `node main.ts <wallet>`. Node 24 strips the types on load, so no build step is needed.

The console prints the wallet and the row count, then any call that failed. Open `portfolio.csv` to check the holdings: a wallet with no tokens gives one row, the SOL line.

## Where it ends

- Balances are read at one moment. A row is a snapshot, and a wallet that moves funds between two runs shows two different tables.
- Rows carry mints and amounts only. Names, prices and dollar values are not in the file, so a dollar total needs a price source you add.
- The default wallet is whichever one the newest swap-router transactions name at the moment of the run. It is a working example, so pass the wallet you mean to report on.
- Signature history comes from an index that keeps 30 days at most, and older pages are not served. The finder reads only the newest five signatures of the program, so that limit does not reach it.
- [Limits are per account](https://carbium.sh/docs/limits), so a script that refreshes often spends the budget that other calls on the same key share.
- A call over its rate waits once and is served if its budget refills within a second. Past that it gets 429. The script reports that call and writes the rows it did read, with no retry.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The run ends with `no readable transaction in the newest signatures` when no wallet is given. | Pass a wallet as the first argument. The finder tries five signatures and stops when none returns a transaction. |
| After an edit, the console shows `getTransaction` answering -32015. | Keep `maxSupportedTransactionVersion: 1` on the call. Mainnet carries v1 transactions, and an absent value or 0 gets [-32015](https://carbium.sh/docs/errors) for one of them. |
| The console reports `getTokenAccountsByOwner` failed with HTTP error (429), and the CSV has SOL but no token rows. | The call was over its rate. Wait a minute and run again. A 429 is a rate answer, and the wallet is fine. |
| Notion sorts the amounts as text, so 10 sits before 2. | Change the Amount and Decimals columns to number in Notion after the import. |
| The database shows each holding twice after a second import. | Imports append pages. Clear the database before importing a fresh `portfolio.csv`. |
| The SOL row is missing and the console shows a getBalance failure. | Run again. The token rows were still written, so the failure touched only the one call. |

## Questions

### Can the database show a dollar value for each holding?

Not from this script. It reads balances and no prices, so add a price column in Notion, or read a price with Carbium's prices method and multiply it in your own code.

### Why finalized and not processed for a snapshot?

A snapshot should rest on a read the network will not take back. Processed is newer by 0 to 1 slots and can show a balance on a fork that gets dropped.

### Does the script need a Notion key?

No. It writes a file and calls only Carbium. Importing the CSV happens inside Notion, under your own account.

### Can it read a wallet's history from last year?

No. Signature history is kept for 30 days at most, and older transactions may exist that Carbium does not list. The balance read is current and is not limited by that window.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [Wallet token holdings](https://carbium.sh/library/usecase/wallet-token-holdings) (Use cases, UC0005)
- [carbium.sh/docs/endpoints](https://carbium.sh/docs/endpoints)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
