services
Get a key

library / Blockchain ideas / BI0039

Program account explorer

A script that reads a program's newest transactions, finds the accounts they wrote, keeps the ones the program owns in SQLite and groups them by discriminator, so a marketplace frontend can list its sale accounts from your server.

By Carbium · Dashboards and explorers · BI0039 · updated 2026-11-22

01

PDA or token account

A marketplace page needs one list: every item for sale, with its price and seller. Two kinds of account sit near a sale, and only one of them holds the listing.

AccountWhat it holdsUse it for
Listing PDAthe price, seller, mint and state the program wrote, at an address derived from seedsthe list the frontend shows
Token accountan amount of one mint and the owner of that amountwho holds the item, or the escrow that keeps it

A program that escrows an item often makes one of its own PDAs the owner of the token account, so the token account shows that the item is locked and carries no price. A wallet can also own several token accounts for one mint. Counting token accounts for a mint therefore counts holders and escrows, never sales. The price and seller live only in the program's own listing account.

The tempting shortcut is getProgramAccountsV2, which asks the node for every account the program owns so the browser can filter them. It is not served here and answers -32601. A browser scan would also put an API key in page code and download far more than one screen shows. A small index on your server does the same job once and lets every visitor read it.

02

The index from signatures

A program cannot change an account unless the transaction lists it as writable. The writable keys in a program's recent transactions are therefore the accounts it created or updated.

  1. Call getSignaturesForAddress with the program id. It returns the newest signatures first, from an address index that keeps up to 30 days, at 50 cells a call.
  2. Drop signatures whose err is set. A failed transaction wrote nothing.
  3. Call getTransaction for each remaining signature, one after another, with jsonParsed encoding so every key carries signer and writable flags. Each call costs 50 cells. Pass maxSupportedTransactionVersion: 1: mainnet carries v1 transactions, and a call without it answers -32015 for one.
  4. Collect the writable keys that are not signers. The set holds listings, and also token accounts, other programs' state and fee accounts.
  5. Send the set to getMultipleAccounts, at most 100 pubkeys a call, and keep the accounts whose owner is the program. A null answer is an account that does not exist any more.

The limit of 100 comes from the price. getMultipleAccounts charges 10 cells per pubkey, so a full call costs 1001 cells (1000, plus 1 once the body passes 4 KiB), and below Pro the 1024-cell burst caps a call at 100 pubkeys. Pro takes up to 300 pubkeys a call. The owner check does the sorting: a PDA the program created is owned by the program, and a token account is owned by the token program.

03

Groups by discriminator

A program usually keeps several account types: listings, bids, escrow records, a config. An Anchor program starts every account with 8 bytes taken from the SHA-256 of account: followed by the type name. The first 8 bytes tell the types apart without knowing any layout. Anchor instruction decoder shows the same 8-byte scheme on instructions.

The index stores each owned account with those 8 bytes as hex, its size and its lamports. Grouping by the hex gives one group per type. The biggest group of one fixed size is usually the sale listing. Confirm it by reading one listing address you already know and looking up its hex. Then the frontend asks your server for that group only.

04

The build

main.ts needs @solana/kit and the node:sqlite module that ships with Node 24. Against the chain it is read-only: nothing is signed or sent. It takes the program id on the command line, plus an optional count of transactions to read (8 by default, at most 20).

main.ts
// BI0039 · Program account explorer// https://carbium.sh/library/blockchainideas/program-account-explorer// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";import { DatabaseSync } from "node:sqlite";const apiKey = process.env.CARBIUM_KEY ?? "";if (apiKey === "") {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const program = process.argv[2] ?? "";if (program === "") {  console.error("Usage: node main.ts <program address> [transactions]");  process.exit(1);}const sample = Math.min(Math.max(parseInt(process.argv[3] ?? "", 10) || 8, 1), 20);const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const client = createSolanaRpcFromTransport(  createDefaultRpcTransport({ url, headers: { "x-api-key": apiKey } }),);type Key = { pubkey: string; signer: boolean; writable: boolean };const db = new DatabaseSync("index.db");db.exec("CREATE TABLE IF NOT EXISTS accounts (address TEXT PRIMARY KEY, disc TEXT, size INTEGER, lamports INTEGER)");const put = db.prepare("INSERT OR REPLACE INTO accounts VALUES (?, ?, ?, ?)");const drop = db.prepare("DELETE FROM accounts WHERE address = ?");const page = await client  .getSignaturesForAddress(address(program), { limit: sample * 2, commitment: "confirmed" })  .send();const sigs = page.filter((s) => s.err === null).slice(0, sample);const writable = new Set<string>();for (const { signature } of sigs) {  try {    const tx = await client      .getTransaction(signature, {        commitment: "confirmed",        encoding: "jsonParsed",        maxSupportedTransactionVersion: 1,      })      .send();    if (tx === null) {      console.log(`${signature.slice(0, 12)}: no transaction (below the ledger floor)`);      continue;    }    for (const k of tx.transaction.message.accountKeys as unknown as Key[]) {      if (k.writable && !k.signer) writable.add(k.pubkey);    }  } catch (e) {    console.error(`${signature.slice(0, 12)} failed:`, e instanceof Error ? e.message : e);  }}const keys = [...writable];let owned = 0;let gone = 0;for (let i = 0; i < keys.length; i += 100) {  const chunk = keys.slice(i, i + 100);  try {    const { value } = await client      .getMultipleAccounts(chunk.map((k) => address(k)), { commitment: "confirmed", encoding: "base64" })      .send();    value.forEach((acc, j) => {      const key = chunk[j] as string;      if (acc === null) {        drop.run(key);        gone++;      } else if (acc.owner === program) {        const bytes = Buffer.from(acc.data[0], "base64");        put.run(key, bytes.subarray(0, 8).toString("hex"), bytes.length, Number(acc.lamports));        owned++;      }    });  } catch (e) {    console.error(`accounts ${i}-${i + chunk.length} failed:`, e instanceof Error ? e.message : e);  }}console.log(`${sigs.length} signatures, ${keys.length} writable keys, ${owned} owned by the program, ${gone} closed`);type Group = { disc: string; n: number; lo: number; hi: number };const groups = db  .prepare("SELECT disc, COUNT(*) AS n, MIN(size) AS lo, MAX(size) AS hi FROM accounts GROUP BY disc ORDER BY n DESC")  .all() as unknown as Group[];for (const g of groups) {  const rows = db.prepare("SELECT address FROM accounts WHERE disc = ? LIMIT 3").all(g.disc) as unknown as { address: string }[];  console.log(`discriminator ${g.disc}: ${g.n} accounts, ${g.lo}-${g.hi} bytes`);  for (const r of rows) console.log(`  ${r.address}`);}

run: CARBIUM_KEY=<YOUR_KEY> node main.ts M2mx93ekt1fmXSVkTrUL9xVFHkmME8HTUi5Cyc5aF7K 8

Every read asks for confirmed commitment. The database is index.db in the working directory. A pass that finds a stored account gone deletes its row. The output is one line of totals, then each group with its count, its size range and three sample addresses.

05

Keeping it fresh and serving the frontend

Run main.ts on a timer. Each pass adds accounts from the newest transactions, and a pass that finds an account closed removes it. To catch price changes on listings already stored, re-read the stored addresses in batches of 100: one 1001-cell call per batch, so 500 stored listings take five calls.

Add a line to main.ts that stores the newest signature it read, and pass that signature as until on the next run, so the pass reads only newer transactions. Signature history pagination covers paging with before and until. One pass of 8 transactions is 9 calls at 50 cells, 450 cells, before the account reads. getTransaction allows 0.24, 1.2, 5 and 25 req/s on Free, Dev, Business and Pro, so it sets the pace of a pass, and the count is the knob to turn.

To serve the frontend, put a few lines of node:http over the same database: a /listings route that selects the rows of the listing group and returns JSON. The page makes one request to your server, and the Carbium key stays on the server. Add a data column to the table if you want to decode price and seller once, at write time, and send readable fields.

06

Where it ends

  • Thirty days. getSignaturesForAddress reaches back 30 days at most. An empty page past that point marks the age limit of the index, and the program may have older transactions.
  • Idle accounts. A listing made 40 days ago and untouched since has no transaction in the window, so it never enters the index. If you know the seeds and the mint, derive the PDA address and read it directly with getMultipleAccounts: that finds it at any age.
  • Closed accounts. A sale that closes its listing returns the rent and the account is gone. The row is deleted, and nothing in the index shows the sale. Past sales live only in transaction history, inside the same 30 days.
  • A sample. The pass reads the newest few transactions. A quiet program yields few accounts, and covering a busy one takes a higher count and repeated runs.
  • Layout. Grouping by 8 bytes fits Anchor accounts. A program with its own layout may begin with a 1-byte tag, and then one group mixes several types until you group by a different slice.
  • Null transactions. The signature pages reach below the validator's ledger floor, so getTransaction can answer null for an older signature the page lists. The code prints a line and moves on.
  • Freshness. Reads are at confirmed commitment, and a listing can change or close between your read and the moment a visitor clicks.
07

When it goes wrong

what goes wrongwhat to do
getTransaction answers -32015.The call lacks maxSupportedTransactionVersion: 1 and the transaction is v1. Keep the option on every getTransaction call.
getTransaction answers null for a signature the page listed.The signature is older than the validator's ledger floor, which the address index reaches below. The code logs it and skips it. Prove a run on the newest signatures.
The totals show zero accounts owned by the program.The sample held only token accounts or accounts already closed. Raise the transaction count toward 20, or read a program with more recent writes.
A call answers 429.Lower the transaction count: on Free and Dev, getTransaction runs at 0.24 and 1.2 req/s, and one pass sends up to 20 of them.
getMultipleAccounts fails on a long key list.Send at most 100 pubkeys a call. The code slices the list in steps of 100, and a larger step trips the burst cap below Pro.
The call answers 401 UNKNOWN_KEY.Attach the whole key in CARBIUM_KEY, with no truncation or quotes copied in.
08

Questions

Should the frontend read token accounts to list sales?

No. A token account holds an amount and an owner, and an escrowed item shows up there as held by a PDA with no price or seller. The listing PDA carries those fields.

Why not scan the program's accounts from the page?

A page scan would carry a key in client code and download far more than one screen shows. getProgramAccountsV2 also answers -32601 here. The index gives the frontend one cheap JSON route instead.

How do I know which discriminator is the sale listing?

Read one listing address you already know and look up its hex in the output. For an Anchor program you can also hash account: plus the type name with SHA-256 and take the first 8 bytes.

Will it find a listing older than 30 days?

Only if something touched it inside the window. For an idle one, derive its PDA from the seeds and the mint and read it directly.

How many accounts can one read check?

100 pubkeys a call below Pro, at 1001 cells. Pro accepts up to 300 pubkeys a call.