---
id: I0026
title: "MongoDB v0 transaction documents"
url: https://carbium.sh/library/integrate/mongodb-v0-transaction-documents
collection: Integrations
category: Document and key-value stores
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# MongoDB v0 transaction documents

A Node script reads the newest transactions of an address, rebuilds each full account key list from the static keys and the loaded lookup table addresses, and writes one MongoDB-ready document per signature to a JSON lines file.

## Why accountKeys is missing

A v0 transaction does not list every account it touches. Its message names some accounts itself, the static keys, and points at address lookup tables for the rest. The node resolves those lookups when it runs the transaction and reports the result in `meta.loadedAddresses`, split into `writable` and `readonly`.

Two paths leave a stored message with no full `accountKeys` list. With `@solana/web3.js` v1, a v0 message object carries `staticAccountKeys` and `addressTableLookups` and has no `accountKeys` list. The full list comes from calling `getAccountKeys` with the loaded addresses, and a document saved straight from the response object holds only the static part. With the raw JSON from the RPC, `message.accountKeys` exists for a v0 transaction, but it is the static keys again, with the lookup keys in `meta`.

Either way the stored document lacks the accounts that the instruction indexes point into. A legacy transaction has no lookups, so its static keys are the whole list and nothing looks wrong until the first v0 transaction arrives.

## Rebuilding the full key list

The full list is three parts joined in a fixed order. Every `programIdIndex` and every entry in an instruction's `accounts` array is a position in the joined list. An index past the length of the static keys lands in the loaded part.

| Part | Where it comes from | Position in the list |
|---|---|---|
| Static keys | `message.accountKeys` | First, in the order the transaction lists them. |
| Writable loaded keys | `meta.loadedAddresses.writable` | Right after the static keys. |
| Readonly loaded keys | `meta.loadedAddresses.readonly` | Last. |

For a legacy transaction both loaded arrays are empty, so the same code builds the right list for every version. If you ask for the `jsonParsed` encoding instead, the node resolves the lookups for you and `accountKeys` comes back as objects with a `source` field. That is convenient to read, but each instruction is then parsed into its own shape, which makes a less even document to store and index.

## The document that goes into MongoDB

One document per transaction, with the signature as `_id` so a second run replaces the first copy instead of adding a duplicate.

- `_id`: the first signature, as a string.
- `slot`, `fee`: plain numbers. The client returns them as bigint, and `JSON.stringify` throws on a bigint, so the script converts them.
- `blockTime`: an extended JSON date, so MongoDB stores a real date. It is null when the node has no time for the block.
- `version`: `legacy`, `0` or `1`.
- `failed`: true when `meta.err` is set. A failed transaction still has keys worth indexing.
- `staticAccountKeys` and `loadedAddresses`: the two raw inputs, kept so the full list can always be rebuilt and checked.
- `accountKeys`: the joined list.
- `programIds`: the distinct programs the top-level instructions call, found through the joined list. Inner instructions from CPI are not read.

A multikey index on `accountKeys` finds every transaction that touched one address. An index on `staticAccountKeys` alone would miss each transaction that reached the address through a lookup table.

## The script

Install the one dependency with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. The script needs `CARBIUM_KEY`, and `CARBIUM_RPC_URL` is optional. An address as the first argument picks whose transactions to read. With none, it reads the Compute Budget program, which nearly every v0 and v1 transaction calls, so a run of the newest 10 usually holds some v0 transactions beside v1 ones.

It lists the 10 newest signatures, then reads each transaction at `confirmed` with the `json` encoding and `maxSupportedTransactionVersion: 1`. `getTransaction` answers at `confirmed` or `finalized` only. @solana/kit would fill in `confirmed` when you leave it out, and the script names it so the line says what runs. The reads run together in `Promise.allSettled`, so one failed read is printed and the rest still land.

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

```ts
// I0026 · MongoDB v0 transaction documents
// https://carbium.sh/library/integrate/mongodb-v0-transaction-documents
// 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.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);
// Default: the Compute Budget program, which nearly every v0 and v1 transaction calls.
const target = address(process.argv[2] ?? "ComputeBudget111111111111111111111111111111");

type Tx = {
  slot: bigint;
  blockTime: bigint | null;
  version?: "legacy" | 0 | 1;
  meta: { err: unknown; fee: bigint; loadedAddresses?: { writable: string[]; readonly: string[] } } | null;
  transaction: { message: { accountKeys: string[]; instructions: { programIdIndex: number }[] } };
};

function toDoc(sig: string, t: Tx) {
  const staticAccountKeys = t.transaction.message.accountKeys;
  const loadedAddresses = t.meta?.loadedAddresses ?? { writable: [], readonly: [] };
  // Instruction indexes point into this joined list, in this order.
  const accountKeys = [...staticAccountKeys, ...loadedAddresses.writable, ...loadedAddresses.readonly];
  return {
    _id: sig,
    slot: Number(t.slot),
    blockTime: t.blockTime === null ? null : { $date: Number(t.blockTime) * 1000 },
    version: t.version ?? "legacy",
    failed: t.meta?.err != null,
    fee: Number(t.meta?.fee ?? 0),
    staticAccountKeys,
    loadedAddresses,
    accountKeys,
    programIds: [...new Set(t.transaction.message.instructions.map((i) => accountKeys[i.programIdIndex]))],
  };
}

const sigs = await rpc.getSignaturesForAddress(target, { limit: 10 }).send();
const reads = await Promise.allSettled(
  sigs.map((s) =>
    rpc
      .getTransaction(s.signature, { commitment: "confirmed", encoding: "json", maxSupportedTransactionVersion: 1 })
      .send(),
  ),
);

const docs: ReturnType<typeof toDoc>[] = [];
reads.forEach((r, i) => {
  const sig: string = sigs[i].signature;
  const label = sig.slice(0, 8);
  if (r.status === "rejected") {
    console.error(`${label} failed: ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`);
    return;
  }
  const t = r.value as unknown as Tx | null;
  if (t === null) {
    console.error(`${label} null: older than the ledger, skipped`);
    return;
  }
  try {
    docs.push(toDoc(sig, t));
  } catch (e) {
    console.error(`${label} not built: ${e instanceof Error ? e.message : String(e)}`);
  }
});

for (const d of docs) {
  console.log(`${d._id.slice(0, 8)} version ${String(d.version)} static ${d.staticAccountKeys.length} full ${d.accountKeys.length}`);
}
await writeFile("transactions.jsonl", docs.map((d) => JSON.stringify(d)).join("\n") + "\n");
console.log(`wrote ${docs.length} documents to transactions.jsonl`);
```

## Load it and query it

The script writes `transactions.jsonl` in the working directory and uses no MongoDB driver, so it has nothing to install beyond the RPC client. Load the file with the stock import tool, which reads the `$date` form of `blockTime` as a date:

- `mongoimport --db chain --collection transactions --mode upsert --file transactions.jsonl` loads the documents and replaces any with the same `_id`.
- `db.transactions.createIndex({ accountKeys: 1 })` builds the multikey index.
- `db.transactions.find({ accountKeys: "<address>" })` returns every transaction that touched the address, lookup table keys included.

Inside an application, build the same object with the same function. A driver stores `{ $date: n }` as a plain subdocument or refuses it, so set `blockTime` to `new Date(n)` when it is not null, or run `EJSON.deserialize` over the object, before you pass it to your driver's `replaceOne` with `upsert: true` and `{ _id }` as the filter.

## Calls and limits

One run makes 11 calls: one `getSignaturesForAddress` and ten `getTransaction`. Each costs [50 cells](https://carbium.sh/docs#rpc), so a run costs 550 cells. A rate class absorbs bursts up to 1,024 cells, so one run fits in the burst on any plan.

A backfill that goes on past the burst is paced by the req/s of `getTransaction`: 0.24 on Free, 1.2 on Dev, 5 on Business and 25 on Pro. [Limits are per account](https://carbium.sh/docs#limits), so every key shares one budget. The script prints a failed read per signature, and a third run straight after the first two can meet a 429 on Free.

## Where it ends

- It writes a file and leaves the MongoDB write to you. The script runs on the RPC client and Node built-ins alone, so the driver code is the few lines you add in your own service.
- It reads the 10 newest signatures of one address. Paging back works with `before`, but `getSignaturesForAddress` reaches back 30 days at most, and an empty page past that marks the [age limit of the index](https://carbium.sh/docs#migrate). It does not hold older history.
- A signature the index lists can be older than the validator's ledger, and `getTransaction` then answers null. The script skips it and says so.
- It stores the `json` encoding, so instruction data stays as the raw base58 string. Decoding the arguments is a separate job. [Transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015) covers the version side of the same reads.
- A v1 transaction comes back when the version limit is 1. The script assumes the `accountKeys` and `programIdIndex` shape. A transaction with no `accountKeys` or `instructions` field is caught and printed, and no half-built document lands in the file.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| Saved documents show `staticAccountKeys` or a short `accountKeys`, and an instruction's account index is larger than the array. | The lookup table keys were never stored. Append `meta.loadedAddresses.writable`, then `meta.loadedAddresses.readonly`, to the static keys and store that joined list. |
| `getTransaction` answers -32015 for some signatures and works for others. | The request left out `maxSupportedTransactionVersion` or sent 0, and the transaction is v1. Send 1. Carbium [answers -32015](https://carbium.sh/docs#rpc) without a charge for a v1 transaction or a block holding one. |
| `getTransaction` returns null for a signature that `getSignaturesForAddress` just listed. | The address index reaches below the validator's ledger, so an older signature can be listed and not readable. Skip it, and test the code on the newest signatures. |
| `JSON.stringify` throws `Do not know how to serialize a BigInt`. | Convert `slot`, `fee` and `blockTime` with `Number()` before the object is serialized, as `toDoc` does. |
| A backfill loop starts failing with 429 after a burst of reads. | The cells of the account are spent. Keep one loop per account and pace it to the [req/s of your plan](https://carbium.sh/docs#limits) for `getTransaction`. |
| `mongoimport` reports a duplicate key on a second run. | The default mode inserts. Add `--mode upsert` so a document with the same `_id` is replaced. |

## Questions

### Do legacy transactions need this?

No, they have no lookups, so the static keys are the full list. The script treats them the same way, with two empty loaded arrays.

### Why not store the response as it is?

The numbers arrive as bigint, which cannot be serialized, and the full key list is not in it as one array. A flat joined `accountKeys` is the field you can index and query by address.

### Can I skip the join with the jsonParsed encoding?

Yes, the node resolves the lookups and marks each key with its source. The cost is that every instruction is then parsed into a different shape, so the stored documents are less uniform than the `json` ones.

### How do I read transactions older than 30 days?

You cannot. The address index stops at 30 days, and history older than that is not served.

## Related

- [Transaction version error -32015](https://carbium.sh/library/howsolana/transaction-version-error-32015) (How to use Solana, HS0012)
- [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#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#migrate](https://carbium.sh/docs#migrate)
