---
id: UC0026
title: "Counterparty USDC ledger"
url: https://carbium.sh/library/usecase/counterparty-usdc-ledger
collection: Use cases
category: Stablecoin treasury and B2B settlement
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Counterparty USDC ledger

A running ledger of the USDC one wallet has sent to another: how a transfer shows up on chain, how to match sender to receiver, a read-only Node script that stores the results in SQLite, and what the lookups cost on Carbium.

## How a USDC transfer shows up

A USDC payment into an existing token account does not name the receiving wallet in its account list. The transfer moves tokens between two token accounts, and the transaction lists those two accounts and the sender's authority. A payment that also creates the receiver's associated token account in the same transaction does list the receiving wallet, but most payments go to accounts that already exist. The receiving wallet is usually absent, so a search on the receiver's address misses most payments and a ledger built on account keys misses them too.

The record that names owners is `meta`. After execution the validator writes `preTokenBalances` and `postTokenBalances`, and each entry carries `accountIndex`, `mint`, `owner` and `uiTokenAmount.amount`, a string of base units. USDC has 6 decimals, so 12.50 USDC reads 12500000. Subtract pre from post per owner and sum over every token account that owner holds for the mint, since a wallet can own more than one. In a successful transaction, a sender whose total went down and a receiver whose total went up make one transfer from the first to the second.

> The ledger stores the receiver's delta, which is what landed. If one transaction pays several recipients, each pair gets its own row with its own amount. A transfer fee on the mint would show up as a gap between the two deltas.

## Finding the transactions

An outgoing transfer lists the sender's source token account, so the sender's history lives on that address. The script reads the sender's USDC token accounts with `getTokenAccountsByOwner` filtered by mint, then pages `getSignaturesForAddress` on each one, newest first, using `before` to go further back. That list holds only token activity for that mint, where the wallet address would also return its SOL transfers and its calls to other programs.

If the receiver is the busier side, such as an exchange deposit wallet, scan the sender anyway. A busy receiver's token account pages are full of other payers, and each of those costs a lookup before it can be discarded.

Each signature then goes through `getTransaction` in `jsonParsed` encoding with `maxSupportedTransactionVersion: 1`. Mainnet carries v1 transactions, and with the value absent or 0 Carbium answers -32015 for one, uncharged. Every call in the script reads at finalized commitment. Calls go to the [RPC endpoint](https://carbium.sh/docs#endpoints) at `https://services.carbium.sh`, with the key in the `x-api-key` [header](https://carbium.sh/docs#auth).

## A ledger in one file

The script takes a sender, a receiver, an optional page count and an optional page size, which defaults to 10 signatures per token account. With no arguments it reads the newest transactions on the USDC mint and picks the first one with a single sender and a single receiver, so a first run usually has a pair to show. It keeps a `ledger.db` file with `node:sqlite`: a `transfers` table with one row per signature and pair, and a `seen` table that remembers which signatures it has already read for that pair.

`main.ts` (run: `CARBIUM_KEY=$CARBIUM_KEY node main.ts [sender receiver [pages [size]]]`)

```ts
// UC0026 · Counterparty USDC ledger
// https://carbium.sh/library/usecase/counterparty-usdc-ledger
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

// Read-only: USDC sent from one wallet to another, read from finalized token balance changes into a local SQLite ledger.
import { DatabaseSync } from "node:sqlite";
import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1); }
const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";
const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";
const C = "finalized" as const;
const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));

type Bal = { mint: string; owner?: string; uiTokenAmount: { amount: string } };
type Tx = { slot: bigint; meta: { err: unknown; preTokenBalances?: Bal[] | null; postTokenBalances?: Bal[] | null } | null };

const db = new DatabaseSync("ledger.db");
db.exec("CREATE TABLE IF NOT EXISTS seen (sig TEXT, pair TEXT, PRIMARY KEY (sig, pair)); CREATE TABLE IF NOT EXISTS transfers (sig TEXT, slot INTEGER, sender TEXT, receiver TEXT, amount TEXT, PRIMARY KEY (sig, sender, receiver))");

// Mainnet carries v1 transactions: a maxSupportedTransactionVersion of 0 or none gets -32015 for one.
const getTx = async (s: string) => (await rpc.getTransaction(signature(s), { encoding: "jsonParsed", maxSupportedTransactionVersion: 1, commitment: C }).send()) as unknown as Tx | null;

// Net USDC change per owner, summed over all of an owner's token accounts.
function deltas(tx: Tx): Map<string, bigint> {
  const d = new Map<string, bigint>();
  for (const [list, sign] of [[tx.meta?.preTokenBalances, -1n], [tx.meta?.postTokenBalances, 1n]] as const)
    for (const b of list ?? []) if (b.mint === USDC && b.owner) d.set(b.owner, (d.get(b.owner) ?? 0n) + sign * BigInt(b.uiTokenAmount.amount));
  return d;
}

function record(sig: string, tx: Tx | null, from: string, to: string) {
  if (!tx?.meta) return; // listed below the ledger floor: leave it unseen and retry later
  db.prepare("INSERT OR IGNORE INTO seen VALUES (?, ?)").run(sig, `${from}>${to}`);
  if (tx.meta.err) return;
  const d = deltas(tx), got = d.get(to) ?? 0n;
  if ((d.get(from) ?? 0n) < 0n && got > 0n)
    db.prepare("INSERT OR IGNORE INTO transfers VALUES (?, ?, ?, ?, ?)").run(sig, Number(tx.slot), from, to, String(got));
}

const fmt = (n: bigint) => `${n / 1000000n}.${String(n % 1000000n).padStart(6, "0")}`;
let failed = 0;
let [from, to] = process.argv.slice(2);
const pages = Number(process.argv[4] ?? 1);
const size = Number(process.argv[5] ?? 10);

if (!from || !to) { // no pair given: take one from the newest transactions on the USDC mint
  const page = await rpc.getSignaturesForAddress(address(USDC), { limit: 8, commitment: C }).send();
  const tried = await Promise.allSettled(page.filter((s) => s.err === null).map(async (s) => ({ sig: s.signature as string, tx: await getTx(s.signature) })));
  failed += tried.filter((r) => r.status === "rejected").length;
  for (const r of tried) {
    if (r.status !== "fulfilled" || !r.value.tx?.meta) continue;
    const d = [...deltas(r.value.tx)], out = d.filter(([, v]) => v < 0n), inn = d.filter(([, v]) => v > 0n);
    if (out.length === 1 && inn.length === 1) { [from, to] = [out[0][0], inn[0][0]]; record(r.value.sig, r.value.tx, from, to); break; }
  }
  if (!from || !to) { console.error("No single-sender USDC transfer found in the newest transactions."); process.exit(1); }
}

const pair = `${from}>${to}`;
const isSeen = db.prepare("SELECT 1 FROM seen WHERE sig = ? AND pair = ?");
const accounts = await rpc.getTokenAccountsByOwner(address(from), { mint: address(USDC) }, { encoding: "jsonParsed", commitment: C }).send();
for (const { pubkey } of accounts.value.slice(0, 2)) {
  let before: string | undefined;
  try {
    for (let p = 0; p < pages; p++) {
      const page = await rpc.getSignaturesForAddress(pubkey, { limit: size, commitment: C, ...(before ? { before: signature(before) } : {}) }).send();
      if (page.length === 0) break;
      before = page[page.length - 1].signature;
      const fresh = page.filter((s) => s.err === null && !isSeen.get(s.signature, pair));
      const res = await Promise.allSettled(fresh.map(async (s) => record(s.signature, await getTx(s.signature), from, to)));
      failed += res.filter((r) => r.status === "rejected").length;
    }
  } catch (e) { failed++; console.error(`${pubkey}: ${(e as Error).message}`); }
}

const rows = db.prepare("SELECT sig, slot, amount FROM transfers WHERE sender = ? AND receiver = ? ORDER BY slot DESC").all(from, to) as { sig: string; slot: number; amount: string }[];
let total = 0n;
for (const r of rows) { total += BigInt(r.amount); console.log(`${r.slot} ${r.sig} ${fmt(BigInt(r.amount))}`); }
console.log(`${from} -> ${to}: ${rows.length} transfers, ${fmt(total)} USDC, ${failed} lookups failed`);
```

A rerun still reads its signature pages from the newest, 50 cells each, and pays `getTransaction` only for signatures not yet seen. Raise the page count to reach further back. Amounts are stored as text and summed as BigInt, which keeps base units exact. The output is one line per transfer with slot, signature and amount, then the total for the pair. Each lookup runs inside `Promise.allSettled`, so one failed fetch is counted and printed at the end, and the rest of the page still lands in the ledger. The script signs and sends nothing.

## What a scan costs and how far back it goes

A page of 10 signatures costs one `getSignaturesForAddress` call plus one `getTransaction` for each signature not yet seen. Cells are the per-call charge, and the req/s columns are the [rate for each method](https://carbium.sh/docs#rpc) on each plan.

| Method | Cells per call | Free req/s | Dev req/s | Business req/s | Pro req/s |
|---|---|---|---|---|---|
| getSignaturesForAddress | 50 | 0.24 | 1.2 | 100 | 500 |
| getTransaction | 50 | 0.24 | 1.2 | 5 | 25 |

The tight column is `getTransaction`. A 100-transaction backfill is 100 calls at 50 cells, which a Business key spreads over 20 seconds at 5 req/s and a Pro key over 4. On Free and Dev a page fires its `getTransaction` calls together, well above 0.24 or 1.2 req/s, so pass a smaller page size as the fourth argument, add a delay between pages inside the page loop, and back off on a 429 with its [retry-after hint](https://carbium.sh/docs#limits).

Address pages come from an [index that keeps up to 30 days](https://carbium.sh/docs#migrate). An empty page past that is the index's age limit, and the wallet may have older transfers. The same index reaches below the validator's ledger floor, so `getTransaction` can answer null for an older signature it listed. The script skips a null and does not mark it seen, so a later run tries again. Because the window is 30 days, the SQLite file is your long-term record: start it early and keep it.

## Staying current without polling

Once the backfill is in, a [WebSocket](https://carbium.sh/docs#websocket) can keep the ledger current. Open `wss://services.carbium.sh` with the key as `?api-key=` in the URL and call `logsSubscribe` with a mentions filter on each of the sender's USDC token accounts. Every transaction that touches the account sends a notification with its signature. Take the signature and run the same fetch and delta check from the script, so one code path decides what counts as a transfer. The [multi-wallet log watcher](https://carbium.sh/library/howsolana/multi-wallet-log-watcher) shows the socket side in full.

A mention filter opens at 25 credits, then costs 20 credits per MiB sent, and a refused subscription costs nothing. New token accounts for the sender need their own subscription, so rerun `getTokenAccountsByOwner` now and then and subscribe to what is new. For the settlement side of one transfer, such as checking an expected amount against an invoice, see [stablecoin settlement checks](https://carbium.sh/library/usecase/stablecoin-settlement-checks).

## Where it ends

- History before the 30-day index window has to come from a record you kept. The script cannot recover it from Carbium.
- The ledger matches owners in token balances. A transfer that routes through a program-owned account shows the program's account as the receiver, so the pair is the sender and that account.
- A sender or receiver address is a wallet. Pass a token account address and the owner field will not match, and the ledger stays empty.
- Only the first two USDC token accounts of the sender are scanned. A wallet with more needs the slice raised.
- `getTokenAccountsByOwner` returns only open accounts, so transfers sent from a token account the sender has since closed are not found.
- Only successful transactions are counted. A failed transfer has unchanged balances and no row.
- The script reads and records. Reconciling the totals against invoices or accounting records is your own system's job.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The scan finds nothing because the receiver's wallet address was searched. | A transfer into an existing token account lists only the token accounts and the sender's authority, so a search on the receiving wallet misses most payments. Scan the sender's USDC token accounts and read owners from the token balances. |
| Several payments to one receiver in a transaction are credited to the wrong pair or counted twice. | Take the receiver's own post minus pre amount, summed over its token accounts, and key the row on signature plus pair. |
| getTransaction fails with -32015 on some signatures. | Pass `maxSupportedTransactionVersion: 1` on every getTransaction call. With the value absent or 0 Carbium answers -32015 for a v1 transaction. |
| getTransaction answers null for an older signature that the list returned. | Handle null and skip it. The address index reaches below the ledger floor, so some listed signatures have no transaction to read. Leave it unmarked and retry on a later run. |
| Backfill calls come back with 429. | On Free and Dev pass a smaller page size as the fourth argument, add a delay between pages inside the page loop in main.ts, and back off on the retry-after hint. On Business and Pro, `getTransaction` has the tighter req/s of the two methods. |
| The ledger misses transfers from before the last 30 days and the total looks short. | The address index holds up to 30 days. Older transfers must come from a ledger you started earlier. |

## Questions

### Can I get the full history of one wallet's USDC transfers to another?

Only as far as you have recorded it. Carbium's address index reaches back up to 30 days, so run the script on a schedule and keep `ledger.db` as the long-term record.

### Why not use the wallet address in getSignaturesForAddress?

It returns every transaction that lists the wallet, including SOL transfers and other programs. The sender's USDC token accounts return only token activity for that mint, which keeps the number of getTransaction calls down.

### How do I get the amount in dollars?

USDC has 6 decimals, so divide the base-unit total by 1,000,000. Keep the stored value in base units and do the division only when printing.

### What does a scan cost in cells?

A page of signatures costs 50 cells and each new transaction read costs 50 more. A page of 10 with all new signatures is 550 cells.

## Related

- [Stablecoin settlement checks](https://carbium.sh/library/usecase/stablecoin-settlement-checks) (Use cases, UC0003)
- [Multi-wallet log watcher](https://carbium.sh/library/howsolana/multi-wallet-log-watcher) (How to use Solana, HS0011)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [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)
