services
Get a key

library / Integrations / Document and key-value stores / I0170

Firestore wallet collection holdings

A Node script lists a wallet's single-unit mints through Carbium, reads each mint's metadata for its verified collection, and writes one document per wallet and collection for your Firestore writes to load.

By Carbium · Document and key-value stores · I0170 · updated 2026-11-23

01

What the job produces

The job answers one question for a wallet: which of its tokens are single units of a mint that belongs to a verified collection. It makes three kinds of call to the RPC endpoint. getTokenAccountsByOwner lists the wallet's token accounts, getMultipleAccounts reads the metadata accounts of the mints it finds, and, only when no wallet is passed, a short scan picks a wallet to test with.

The output is holdings.json, a JSON array with one object per wallet and collection. Each object has an id, the wallet and the collection joined by _, and a fields map with the wallet, the collection, a count and the member mints. That is the shape a Firestore document takes, so each object loads with one set call. The job never calls Firestore itself. Your app does the write with its own SDK.

02

Finding single-unit mints

A token account holds an amount of one mint. An NFT is a mint with a supply of one and zero decimals, so the job keeps the accounts whose amount reads 1 and whose decimals are 0. A wallet can own more than one token account for the same mint, so the mints are deduplicated before any metadata read. The call uses the SPL Token program and jsonParsed encoding, which hands back the amount and decimals already read.

Parsed fieldPath in the responseKept when
mintinfo.mintalways, once per mint
amountinfo.tokenAmount.amountit is the string 1
decimalsinfo.tokenAmount.decimalsit is 0

Token-2022 accounts sit under a different program ID, so this list does not include them. The wider token list of a wallet is covered in wallet token holdings.

03

Reading the verified collection

A collection NFT is a mint with its own metadata account, and each member mint names that collection in its own metadata. The metadata account is a program-derived address: the seeds are the text metadata, the Token Metadata program ID and the mint. The job derives it with getProgramDerivedAddress from @solana/kit, then reads the metadata accounts in calls of 100 with base64 encoding.

The collection field sits after the name, symbol, URI, creators and sale flags. Strings carry a four-byte length, each creator takes 34 bytes, and each optional field is a tag byte plus its payload when the tag is 1. The job walks those fields in order and reads the collection's key and its verified flag. An unverified claim is dropped, so a mint that names a collection without verification lands in no group.

04

Writing the documents

Each collection of each wallet becomes one document. The ID is the wallet and the collection joined by _, so a second wallet in the same collection writes a different document. Write each document with a merge set, so a field your app added to the document stays in place.

Because the job reports the state at one moment, a holding that was sold stays in Firestore until your app removes it. Compare the mints in each document with the newest run and delete the documents the run did not list. For writes ordered by slot, see slot-ordered Firestore writes.

05

The job and how to run it

The file takes an optional wallet address as its first argument. Without one it uses the newest signatures of the Token Metadata program to find a wallet with single-unit mints. Transactions are read with maxSupportedTransactionVersion set to 1, because mainnet carries v1 transactions and the call answers -32015 for one without it. The key comes from CARBIUM_KEY and is never printed.

main.ts
// I0170 · Firestore wallet collection holdings// https://carbium.sh/library/integrate/firestore-wallet-collection-holdings// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder, getAddressEncoder, getProgramDerivedAddress, type Address } from "@solana/kit";import { writeFile } from "node:fs/promises";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium key."); process.exit(1); }const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }));const commitment = "confirmed" as const;const TOKEN = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const METADATA = address("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");const enc = getAddressEncoder();const dec = getAddressDecoder();const bytes = (s: string) => new TextEncoder().encode(s);// Mints the wallet holds one unit of, at zero decimals: the NFT shape.async function singleMints(owner: Address): Promise<string[]> {  const res = await rpc.getTokenAccountsByOwner(owner, { programId: TOKEN }, { encoding: "jsonParsed", commitment }).send();  const rows = res.value as unknown as { account: { data: { parsed: { info: { mint: string; tokenAmount: { amount: string; decimals: number } } } } } }[];  const mints = rows.map((r) => r.account.data.parsed.info).filter((i) => i.tokenAmount.amount === "1" && i.tokenAmount.decimals === 0).map((i) => i.mint);  return [...new Set(mints)];}async function metadataOf(mint: string): Promise<Address> {  const [pda] = await getProgramDerivedAddress({ programAddress: METADATA, seeds: [bytes("metadata"), new Uint8Array(enc.encode(METADATA)), new Uint8Array(enc.encode(address(mint)))] });  return pda;}// Metaplex metadata: key, update authority, mint, then Borsh fields up to the collection.function collectionOf(d: Uint8Array): { key: string; verified: boolean } | null {  const v = new DataView(d.buffer, d.byteOffset, d.byteLength);  let o = 65;  for (let s = 0; s < 3; s++) o += 4 + v.getUint32(o, true); // name, symbol, uri  o += 2; // seller fee basis points  if (d[o++] === 1) o += 4 + v.getUint32(o, true) * 34; // creators, 34 bytes each  o += 2; // primary sale, is mutable  o += d[o] === 1 ? 2 : 1; // edition nonce  o += d[o] === 1 ? 2 : 1; // token standard  if (d[o] !== 1) return null;  return { verified: d[o + 1] === 1, key: dec.decode(d.subarray(o + 2, o + 34)) };}async function findWallet(): Promise<Address> {  const sigs = await rpc.getSignaturesForAddress(METADATA, { limit: 5, commitment }).send();  let first: Address | null = null;  for (const s of sigs) {    const tx = await rpc.getTransaction(s.signature, { encoding: "json", commitment, maxSupportedTransactionVersion: 1 }).send();    if (!tx) continue; // no transaction returned: try the next signature    const payer = address(String(tx.transaction.message.accountKeys[0]));    first ??= payer;    if ((await singleMints(payer)).length > 0) return payer;  }  if (first) return first;  throw new Error("no readable transaction among the newest signatures");}async function main() {  const wallet = process.argv[2] ? address(process.argv[2]) : await findWallet();  const mints = await singleMints(wallet);  console.log(`wallet ${wallet}: ${mints.length} single-unit mints`);  const metas = await Promise.all(mints.map((m) => metadataOf(m)));  const groups = new Map<string, string[]>();  for (let i = 0; i < metas.length; i += 100) {    try {      const res = await rpc.getMultipleAccounts(metas.slice(i, i + 100), { encoding: "base64", commitment }).send();      (res.value as unknown as ({ data: [string, string] } | null)[]).forEach((a, j) => {        const mint = mints[i + j] ?? "";        if (!a) return;        try {          const c = collectionOf(Buffer.from(a.data[0], "base64"));          if (c?.verified) groups.set(c.key, [...(groups.get(c.key) ?? []), mint]);        } catch { console.error(`metadata of ${mint} is too short, skipped`); }      });    } catch (e) { console.error(`chunk at ${i} failed: ${e instanceof Error ? e.message : String(e)}`); }  }  const docs = [...groups].map(([col, list]) => ({ id: `${wallet}_${col}`, fields: { wallet, collection: col, count: list.length, mints: list } }));  await writeFile("holdings.json", JSON.stringify(docs, null, 2));  console.log(`${docs.length} verified collections written to holdings.json`);  for (const d of docs) console.log(d.fields.collection, d.fields.count);}main().catch((e: unknown) => { console.error("run failed:", e instanceof Error ? e.message : String(e)); process.exit(1); });

run: node main.ts

Install the dependency with npm install @solana/[email protected], set "type": "module" in package.json, and run node main.ts with the wallet address when you have one. Node 24 strips the types on load. The first line names the wallet and the number of single-unit mints. Each verified collection then prints its member count, and the file lands in the working directory. A wallet with no verified collections still writes a file, with an empty array, so read the printed count as well as the exit code.

06

What it costs against your limits

getMultipleAccounts charges 10 cells per pubkey, so a call of 100 pubkeys is 1000 cells and fits inside the 1,024 cell burst on every plan. The job never sends more than 100 pubkeys in one call, which is the cap below Pro, so the same code runs on each plan. Pro takes up to 300 pubkeys a call, and this code keeps to 100 so it runs everywhere. On Free, account reads run at 0.5 req/s, so a wallet with 250 single-unit mints needs three calls spaced about two seconds apart at that rate.

The discovery scan costs more, since getSignaturesForAddress and each getTransaction cost 50 cells apiece. One signature list and five transactions come to at most 300 cells on a run without a wallet. Limits are per account, so the scan draws on the same budget as your app's other calls.

07

Where it ends

  • It reads the state at one moment. A holding that moved between two runs shows in the next run only, so the app must remove documents the newest run did not list.
  • It reads the SPL Token program only. A Token-2022 mint keeps its metadata inside the mint, and only when it carries the metadataPointer extension that names the mint, so this job does not read that layout.
  • A member counts only when its collection is verified. A mint whose collection has no verified flag appears in no document.
  • The metadata read is at confirmed, the commitment @solana/kit also uses when a call leaves it out. A mint created in the last few slots may not show its metadata yet.
  • The discovery scan reads the newest signatures only. An empty page past the 30-day address index marks that index's age limit, and a getTransaction that answers null is skipped in favour of the next signature.
  • The job writes a file and calls no Firestore. A failed write in your app leaves holdings.json as the only copy of the run.
08

When it goes wrong

what goes wrongwhat to do
holdings.json holds an empty array for a wallet you know owns NFTs.Read the printed mint count. At 0, the holdings sit under Token-2022 or the wallet has no single-unit accounts under the SPL Token program. Above 0, the mints lack a verified collection, so they appear in no document.
A line reads chunk at 100 failed with a 429 message.The other chunks still ran. Rerun the wallet later, or use a plan with a higher account-read rate, since Free gives 0.5 req/s for account reads.
A line reads metadata of ... is too short, skipped.The account is not a full Metaplex metadata layout, or the read was cut short. The skipped mint is missing from the output, so check that mint's metadata account on its own.
The run without a wallet ends with no readable transaction among the newest signatures.Each of the five newest signatures returned no transaction. Pass a wallet address as the argument.
Documents from an earlier run keep a sold mint after the newest run dropped it.In the same batch as the write, delete each wallet's documents that the newest run did not list.
09

Questions

Does this list every NFT a wallet holds?

No. It lists single-unit mints of the SPL Token program whose metadata names a verified collection. Token-2022 holdings and mints without a verified collection are left out.

Why read the metadata account instead of the token account?

A token account names only its mint. The collection link lives in the mint's metadata, so grouping by collection requires that read.

Can Firestore filter the holdings by collection?

Yes. Each document stores the wallet and the collection as fields, so an equality query on both returns one wallet's members. The document ID is only a lookup key.

What happens with a wallet that has thousands of mints?

The job sends 100 metadata accounts per call, so the calls queue at the account-read rate. On Free that rate is 0.5 req/s, so a large wallet takes proportionally longer to finish.