---
id: I0023
title: "SQLite PDA seed registry"
url: https://carbium.sh/library/integrate/sqlite-pda-seed-registry
collection: Integrations
category: Relational databases
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# SQLite PDA seed registry

A Node script derives program derived addresses, saves each address with its seeds in a local SQLite file, then reads every saved account from Carbium in batches and re-derives each address from its stored seeds as a check.

## Four ways to reach an account

Whatever data an account holds, every route to it is a way of getting its address. Four routes cover most programs.

- Hold the address. A mint, a config account or a known wallet needs no derivation: `getAccountInfo` or `getMultipleAccounts` reads it.
- Derive the address. A program derived address (PDA) is computed from a program id and seeds, a few byte strings you choose, so anyone with the same inputs gets the same address and needs no lookup.
- Ask by owner. `getTokenAccountsByOwner` lists the token accounts of one wallet. It works for the two token programs' accounts and no others.
- Follow transactions. `getSignaturesForAddress` lists the signatures that touched an address, and `getTransaction` shows the accounts each one used, so you can find addresses you never stored.

A scan of every account a program owns is a fifth route. Carbium answers `getProgramAccountsV2` with [-32601](https://carbium.sh/docs#errors). A registry of the addresses you care about gives you something to read without a scan.

## When the seeds need storing

Not always. Seeds are inputs, and a PDA you can rebuild from data you already hold needs no stored seeds. An associated token account takes the owner wallet, the token program and the mint, so a user table with a wallet column and one constant for the mint is enough. A vault keyed by the string `vault` and a user's public key works the same way.

Store them when the inputs are not recoverable from your own data: an order id you minted, a random nonce, a label a user typed, a value from another system that your database never kept. The derivation is a hash, so it runs one way. Lose the inputs and the address cannot be found again. The bump byte comes out of the derivation, so it is cheap to recompute, and many programs also keep it inside the account.

There is a second reason, which is lookup in the other direction. An address in a transaction does not carry its seeds. A registry row says what it meant: which program, which seeds, which label.

## The registry table

SQLite from `node:sqlite` needs no server, and one file holds the whole registry. One table is enough.

| Column | Holds |
|---|---|
| `address` | The derived address, primary key |
| `program` | The program id the address was derived under |
| `label` | Your own name for the row |
| `seeds` | A JSON list of hex strings, one per seed |

Hex lets any byte string survive: text, public key bytes or a little-endian integer. A row is written with `insert or ignore`, so a rerun adds nothing and the file can be rebuilt from the same inputs.

## The registry script

Use Node 24, which strips the types on load, and `npm install @solana/kit@8.6.0`. The script takes a token mint, then one or more owner wallets. For each owner it derives the associated token account and saves it in `registry.db` in the working directory. The demo uses associated token accounts because the address exists for any wallet and mint, which gives it real rows to read. A nonce-seeded or order-id PDA of your own program goes in the same table. The script then reads every saved row from Carbium at confirmed commitment, 100 rows a call with a pause before each call after the first, and re-derives each address from its stored seeds. The pause is 7 seconds, or `BATCH_PAUSE_MS` milliseconds when that is set. It needs `CARBIUM_KEY` and exits with a message when it is unset. `CARBIUM_RPC_URL` is optional. It only reads: no signing and no sending.

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

```ts
// I0023 · SQLite PDA seed registry
// https://carbium.sh/library/integrate/sqlite-pda-seed-registry
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { DatabaseSync } from "node:sqlite";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressEncoder, getProgramDerivedAddress } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY.");
  process.exit(1);
}
const [mint, ...owners] = process.argv.slice(2);
if (!mint || owners.length === 0) {
  console.error("Usage: node main.ts <mint> <owner> [<owner>...]");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

const ATA = address("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const toHex = (b: Uint8Array) => Buffer.from(b).toString("hex");
const fromHex = (h: string) => new Uint8Array(Buffer.from(h, "hex"));
const pdaOf = async (seeds: Uint8Array[]) => (await getProgramDerivedAddress({ programAddress: ATA, seeds }))[0];
const pauseMs = Number(process.env.BATCH_PAUSE_MS ?? 7000); // refill time of 1,000 cells: about 7 s on Dev, 200 s on Free

const db = new DatabaseSync("registry.db"); // relative: the file lands in the working directory
db.exec("create table if not exists pda (address text primary key, program text not null, label text not null, seeds text not null)");
const put = db.prepare("insert or ignore into pda values (?, ?, ?, ?)");
const enc = getAddressEncoder();
for (const owner of owners) {
  const seeds = [enc.encode(address(owner)), enc.encode(TOKEN_PROGRAM), enc.encode(address(mint))].map((s) => Uint8Array.from(s));
  put.run(await pdaOf(seeds), ATA, `ata ${owner.slice(0, 6)}`, JSON.stringify(seeds.map(toHex)));
}

type Row = { address: string; label: string; seeds: string };
const rows = db.prepare("select address, label, seeds from pda where program = ?").all(ATA) as unknown as Row[];
for (let i = 0; i < rows.length; i += 100) { // 100 pubkeys is the most one call can carry below Pro
  if (i > 0) await new Promise((r) => setTimeout(r, pauseMs)); // let the cells refill before the next batch
  const chunk = rows.slice(i, i + 100);
  try {
    const { value } = await rpc
      .getMultipleAccounts(chunk.map((r) => address(r.address)), { commitment: "confirmed", encoding: "base64" })
      .send();
    for (const [j, r] of chunk.entries()) {
      const again = await pdaOf((JSON.parse(r.seeds) as string[]).map(fromHex));
      const a = value[j];
      const data = a ? Buffer.from(a.data[0], "base64") : undefined;
      const amount = data && data.length >= 72 ? ` amount ${data.readBigUInt64LE(64)}` : "";
      console.log(`${r.label} ${r.address} seeds ${again === r.address ? "ok" : "MISMATCH"} ${a ? `${a.lamports} lamports${amount}` : "no account"}`);
    }
  } catch (e) {
    console.log(`failed rows ${i}-${i + chunk.length - 1}: ${e instanceof Error ? e.message : String(e)}`);
  }
}
```

Each output line shows the label, the address, whether the stored seeds still give that address, and either the lamports and token amount or `no account`. The amount sits at byte 64 of a token account's data, as an unsigned 64-bit integer in base units.

## Reading the registry at Carbium

[Account reads](https://carbium.sh/docs#rpc) cost 10 cells each, at 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro. `getMultipleAccounts` charges 10 cells per pubkey, so a call with 100 pubkeys is 1000 cells, or 1001 over a 4 KiB body. A rate class [absorbs bursts](https://carbium.sh/docs#limits) of up to 1,024 cells, which caps a call at 100 pubkeys below Pro. The script sends at most 100 a call and spaces the calls so the cells refill between them. A call of 300 pubkeys is Pro's.

An account that does not exist comes back as null in `value`, and the script prints it as `no account`. A registry row is an address you plan to read. The account may not be created yet, or it may have been closed.

## Where it ends

- The file is only as safe as your backups. For seeds you cannot recompute, a lost `registry.db` is a lost set of addresses.
- A call of 100 pubkeys uses 1,000 cells of a 1,024-cell class, so each batch after the first waits for the refill. At 5 cells a second on Free that is about 200 seconds, at 150 on Dev about 7, at 500 on Business about 2, and Pro refills within the second. The script pauses 7 seconds, which covers Dev and Business. On Free run it with `BATCH_PAUSE_MS=200000`. A second run soon after the first also gets 429 on its first batch there.
- The script derives associated token accounts for the classic token program. Another program needs its own program id and seed list in the derivation, and the table takes either.
- It does not check that the account's owner program is the one you expect. Add that check before you trust the data.
- It decodes only the token amount. Any other account layout needs your own decoder.
- It reads rows that exist in the registry. An account a program creates for a user you never saw has to be found through transactions first.
- History from `getSignaturesForAddress` reaches back 30 days at most, so older accounts come from your own records.
- SQLite suits one process writing. Several writers want a server database.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| A stored address differs from the one a program or an explorer shows. | The seed order or a seed's encoding differs from the program's. A public key seed is its 32 raw bytes, and an integer is usually little-endian. Compare each hex seed with the program source. The `seeds ok` check only proves the row matches itself. |
| A row prints `no account` for an address you expect to hold data. | Nothing has created the account yet, or it was closed. An associated token account exists once a create instruction has run, usually with the owner's first transfer of that token but possibly before it. It can be closed later, and a wallet can hold the token in a different account. Read again later, since the registry row stays valid. |
| A line starting `failed rows` appears and the other rows still print. | One call of up to 100 pubkeys failed and the script moved on. Read the message. A 429 means the call went over its account-read rate and came back with a retry-after hint. Every batch after the first needs spacing below Pro, so raise `BATCH_PAUSE_MS` to cover the refill of 1,000 cells on your plan, about 200000 on Free, then run again. |
| Every run prints one row per owner and the registry never grows. | The path `registry.db` is relative, so a run from another folder opens a different file. Run from the same folder or change the `registry.db` path in `new DatabaseSync` to an absolute one. |
| The call answers 401. | Carbium does not recognise the key. Attach the whole key in the `x-api-key` header. |

## Questions

### Can I get the seeds back from an address?

No. The address is a hash of the seeds and the program id. You can guess candidate inputs, derive each one and compare, which works when the inputs come from a short list such as your own user ids.

### Does the registry have to be SQLite?

Any table works. SQLite fits one process and a file you can copy. For several writers or a shared database, see [Postgres deposit matching](https://carbium.sh/library/integrate/postgres-deposit-matching), which uses a unique key to keep inserts safe to repeat.

### How do I find accounts for users I never stored?

Follow transactions. `getSignaturesForAddress` lists signatures from an [index that keeps up to 30 days](https://carbium.sh/docs#migrate), and `getTransaction` shows the accounts each one used. Add the addresses you find to the registry.

### Can I watch a registry address for changes?

`accountSubscribe` [sends account state on change](https://carbium.sh/docs#websocket) for streamed accounts and nothing for a plain SOL wallet. An account subscription opens at 25 credits, then costs 20 credits per MiB sent.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [Postgres deposit matching](https://carbium.sh/library/integrate/postgres-deposit-matching) (Integrations, I0008)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#errors](https://carbium.sh/docs#errors)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
