---
id: I0060
title: "React token balance provider"
url: https://carbium.sh/library/integrate/react-token-balance-provider
collection: Integrations
category: Web frameworks
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# React token balance provider

One loader returns SOL and a per-mint token map for a wallet, adding up every token account a mint has. The React provider only decides when to call it: on wallet change, after a send and on focus.

## The context value

A wallet context usually carries a lamport count and a loading flag. Adding SPL tokens means adding a map keyed by mint address, because a wallet holds any number of mints and a component asks for one of them by address.

| Field | Type | Holds |
|---|---|---|
| `sol` | string or null | Lamports as a decimal string, null until the first load. |
| `tokens` | object keyed by mint | For each mint: `raw` as a decimal string, `decimals`, and `accounts`, the number of token accounts behind the total. |
| `error` | string or null | The message of a read that failed on the last load. |
| `refresh` | function | Starts a new load for the current wallet. |

Amounts travel as strings. A raw token amount is an unsigned 64-bit integer, which a JavaScript number cannot hold exactly above 2^53, and `JSON.stringify` throws on a bigint. The loader works in bigints, your server route turns them into strings, and a component calls `BigInt(raw)` when it needs arithmetic.

The loader is a plain async function with no React in it. The provider calls it, keeps the latest result and decides when to call it again. The loader reads with a key, so it runs behind a route of your own that the provider fetches, with `CARBIUM_KEY` in that server's environment.

## The loader's two reads

`loadBalances(owner)` sends two calls to Carbium's [RPC endpoint](https://carbium.sh/docs#rpc) at once. `getBalance` returns the SOL. `getTokenAccountsByOwner` takes the Token program id as its filter and `jsonParsed` encoding, so each account comes back with its mint, raw amount and decimals already decoded. Both pass `confirmed` commitment, which is also the level @solana/kit 8.6.0 fills in when a call leaves commitment out.

The calls go through `Promise.allSettled`, so a failure in one leaves the other's result in place. A 429 on the token read still shows the SOL balance, and the message lands in `errors` for the provider to copy into the context.

The two reads are separate snapshots. Each response carries its own slot, so SOL and tokens can come from slots a moment apart. For a balance display that does not matter, though a transfer that moves both can show one side updated a beat before the other.

## Summing accounts per mint

A wallet can own more than one token account for the same mint. The associated token account is the usual one, but an app can create others, and each holds a balance of its own. Reading the first account for a mint shows part of the total, and it is the most common reason a context shows less USDC than a wallet app does.

The loader walks the list once and adds each `tokenAmount.amount` into the entry for its mint as a `BigInt`. `amount` is the raw integer as a string. `decimals` is the same on every account of a mint, so the first account seen sets it. The `accounts` count rides along so the provider can tell when a mint is split over several accounts. The decimal point goes in last, by string slicing in `fmt`, because the `uiAmount` field is a float and loses digits on large balances.

An account at zero stays in the list, so a mint can appear with `raw` 0, and the component can hide it. Wrapped SOL is a token account as well, so the native mint shows up as a mint of its own next to the SOL figure.

## The loader file

Run `npm install @solana/kit@8.6.0`, mark the package `"type": "module"` and use Node 24, which strips types as it loads. `CARBIUM_KEY` must be set or the file exits with a message. Copy everything through `loadBalances` into the server route behind your provider, and replace `process.exit(1)` there with a thrown error. The lines after it are a command-line demo.

`main.ts` (run: `node main.ts [wallet address]`)

```ts
// I0060 · React token balance provider
// https://carbium.sh/library/integrate/react-token-balance-provider
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";

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 },
  }),
);
const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const USDC = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");

export type Holding = { raw: bigint; decimals: number; accounts: number };
export type Balances = { sol?: bigint; tokens?: Map<string, Holding>; errors: string[] };
type Parsed = { parsed: { info: { mint: string; tokenAmount: { amount: string; decimals: number } } } };
const why = (e: unknown) => (e instanceof Error ? e.message : String(e));

// SOL plus one entry per mint; each read settles on its own.
export async function loadBalances(owner: string): Promise<Balances> {
  const who = address(owner);
  const [sol, accounts] = await Promise.allSettled([
    rpc.getBalance(who, { commitment: "confirmed" }).send(),
    rpc.getTokenAccountsByOwner(who, { programId: TOKEN_PROGRAM }, { commitment: "confirmed", encoding: "jsonParsed" }).send(),
  ]);
  const out: Balances = { errors: [] };
  if (sol.status === "fulfilled") out.sol = sol.value.value;
  else out.errors.push(`getBalance: ${why(sol.reason)}`);
  if (accounts.status === "rejected") {
    out.errors.push(`getTokenAccountsByOwner: ${why(accounts.reason)}`);
    return out;
  }
  out.tokens = new Map();
  for (const a of accounts.value.value) {
    const { mint, tokenAmount } = (a.account.data as unknown as Parsed).parsed.info;
    const h = out.tokens.get(mint) ?? { raw: 0n, decimals: tokenAmount.decimals, accounts: 0 };
    h.raw += BigInt(tokenAmount.amount); // a wallet can own several token accounts for one mint
    h.accounts += 1;
    out.tokens.set(mint, h);
  }
  return out;
}

// No argument: take a wallet from the newest USDC mint transactions.
async function findWallet(): Promise<string> {
  const sigs = await rpc.getSignaturesForAddress(USDC, { limit: 10 }).send();
  for (const s of sigs) {
    try {
      const tx = await rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send();
      const hit = tx?.meta?.postTokenBalances?.find((b) => b.mint === USDC && b.owner);
      if (hit?.owner) return hit.owner;
    } catch (e) {
      console.error("getTransaction:", why(e));
    }
  }
  throw new Error("no USDC holder in the newest transactions");
}

const fmt = (raw: bigint, d: number) => {
  const s = raw.toString().padStart(d + 1, "0");
  return d ? `${s.slice(0, -d)}.${s.slice(-d)}` : s;
};

const arg = process.argv[2];
(arg ? Promise.resolve(arg) : findWallet())
  .then(async (owner) => {
    const b = await loadBalances(owner);
    console.log(`wallet ${owner.slice(0, 4)}..${owner.slice(-4)}`);
    console.log(`SOL ${b.sol === undefined ? "unavailable" : fmt(b.sol, 9)}`);
    const rows: [string, Holding][] = b.tokens ? Array.from(b.tokens) : [];
    for (const [mint, h] of rows.slice(0, 10)) console.log(`${mint} ${fmt(h.raw, h.decimals)} in ${h.accounts} account(s)`);
    if (rows.length > 10) console.log(`and ${rows.length - 10} more mints`);
    for (const e of b.errors) console.error("failed:", e);
  })
  .catch((e) => {
    console.error(why(e));
    process.exitCode = 1;
  });
```

With no argument the demo asks `getSignaturesForAddress` for the newest signatures of the USDC mint. It reads each one with `getTransaction` at `maxSupportedTransactionVersion: 1` until a transaction lists a USDC holder in its post-transaction token balances. The version setting matters because mainnet carries v1 transactions, and a read with it absent or set to 0 [answers -32015](https://carbium.sh/docs#rpc) for one. The signature list comes from an address index that keeps up to 30 days, so [older signatures](https://carbium.sh/docs#migrate) can return null from `getTransaction`. The demo reads only the newest and skips a null. A read that throws is logged and the demo moves to the next signature.

Run it as `node main.ts`, or pass a wallet address. It prints the SOL balance, then the first ten mints with each total and the number of token accounts behind it. The wallet it finds is whoever held USDC in that transaction, which can be a program's vault with many token accounts, so pass an address of your own to compare against a wallet app.

## When to refresh

The provider holds the last result, a request counter and the current wallet address. Three events start a load.

- Wallet change. Clear the tokens at once, call the route with the new address and apply a response only if its request number is still the newest. Without the check, a slow answer for the previous wallet lands after the new one and overwrites it.
- After a send. Call `refresh()` from the code that awaits the transaction's confirmation. A refresh at submission reads the numbers from before it landed. The loader lists every token account on each load, so a transfer into an account you did not know about shows up on the next refresh.
- On focus. Refresh when `visibilitychange` reports the tab visible again, with a floor of several seconds between loads. Each load is two calls against an account budget that [all its keys share](https://carbium.sh/docs#limits), so flipping between tabs should not turn into a call per flip.

Keep the previous value on screen while a load runs, and set `error` only when a read failed.

## Where it ends

- The filter names the original Token program. Token-2022 accounts live under a different program id and need a second `getTokenAccountsByOwner` call with that id, merged into the same map.
- A single known token account is a different read, covered by [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance). Using one account as the wallet's balance for a mint ignores the others.
- The map holds mint addresses, decimals and amounts. Names, logos and prices come from other sources.
- The loader pulls and never pushes. A transfer made elsewhere shows up on the next refresh.
- An owner with thousands of token accounts returns one long response, and the provider should show a loading state for it.
- Everything here is read-only. Nothing signs or sends.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The SOL balance appears and the token map stays empty, with a message under `errors`. | That is the settled design: the token read failed on its own. A 401 means the key is unknown, so check that the whole key reaches the [x-api-key header](https://carbium.sh/docs#auth) from the server's environment. A 429 means the account is over its rate, so lengthen the floor between focus refreshes. |
| The context shows less of a token than the wallet app does. | The component read one account for the mint. Use the summed `raw` from the loader, and check whether `accounts` is above 1 for that mint. |
| The route throws `Do not know how to serialize a BigInt`, or the response carries `tokens` as `{}`. | `sol` and every `raw` are bigints, and `tokens` is a Map, which `JSON.stringify` turns into `{}` with no error. Build a plain object in the route, for example `Object.fromEntries` over the map with each Holding's `raw` as a string, so it matches the object keyed by mint in the table, and call `toString()` on `sol`. Rebuild with `BigInt()` in the component only where arithmetic needs them. |
| The demo's `getTransaction` answers -32015. | The read is missing `maxSupportedTransactionVersion: 1`, and the transaction is v1. Set it in the config object of every `getTransaction` and `getBlock` call. |
| The demo prints `no USDC holder in the newest transactions`. | The ten newest signatures were all null or listed no holder. Run it again, or pass a wallet address. |
| After a send the balance still shows the old number. | The refresh ran at submission. Call `refresh()` after the confirmation arrives, and keep the focus floor from swallowing that call. |

## Questions

### Why list by owner and not read each associated token address?

An associated address is one account of possibly several, and you need the mint list first. One owner-filtered call returns every account of every mint, including mints you had not listed.

### Can a logs subscription on the wallet trigger the refresh?

Not reliably for tokens. A transfer into an existing token account lists the token accounts and the sender's authority, never the receiving wallet, so a [logs mention](https://carbium.sh/docs#websocket) of the wallet does not see an incoming token. Wallet change, send and focus cover the cases.

### How do I include Token-2022 tokens?

Make the same `getTokenAccountsByOwner` call with the Token-2022 program id and fold its accounts into the same map. The summing code stays as it is.

### Why are amounts strings in the context?

A raw amount can pass 2^53, where a JavaScript number drops digits, and JSON cannot carry a bigint. Strings keep every digit across the route.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [Wallet token holdings](https://carbium.sh/library/usecase/wallet-token-holdings) (Use cases, UC0005)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [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)
