services
Get a key

library / Integrations / Mobile and desktop / I0140

Jetpack Compose token balances

A Node bridge reads one owner's SPL Token and Token-2022 accounts through Carbium, sums them by mint, and writes balances.json for a Jetpack Compose wallet list to draw.

By Carbium · Mobile and desktop · I0140 · updated 2026-11-23

01

What the bridge returns

A Jetpack Compose wallet screen needs one list of token balances, and Solana has no single call that returns one. Token accounts are read per token program, so an owner's classic SPL Token balances and its Token-2022 balances come from two getTokenAccountsByOwner calls. The bridge is the Node side of that read. It takes an owner address, or finds one, reads both programs, sums the accounts that hold the same mint, and writes the result to balances.json. The Compose app fetches that file through its own backend and draws it.

Each row in the file names one mint, the program that owns it, its decimals, the raw amount as a string, and a display amount already divided by the decimals. The raw amount stays a string because a balance can carry more digits than a JavaScript number holds exactly. The file also records the owner, the failed programs and an at time in UTC, so the screen can say how old the list is.

02

Two programs, two calls

Token-2022 accounts sit under their own program ID, so a wallet holding a Token-2022 mint has no account under the classic program for it. The bridge sends one getTokenAccountsByOwner per program, each with the jsonParsed encoding, so the response already names the mint, the decimals and the amount. The two calls run inside Promise.allSettled, so a failure on one program still returns the other.

A wallet can own more than one token account for one mint. A list drawn account by account would show that token twice. The bridge adds the accounts by mint before it writes the file, and it adds them as BigInt values so no digit is lost in the sum.

Both reads set confirmed commitment in the call itself. The server's default is finalized, while @solana/kit fills in confirmed when a call leaves commitment out. The call names it anyway, so the choice stays visible in the code.

03

The Compose side

On the app side, a ViewModel calls the bridge's JSON over HTTP, parses it with kotlinx.serialization into a data class with mint, program, decimals, amount and ui fields, and exposes the rows as a StateFlow. A composable collects that flow into a LazyColumn, one item per row, with the display amount on the right and the shortened mint under the program name. The raw amount stays a String in that class, and the screen shows ui without dividing again.

Refresh when the screen opens and on a pull to refresh, not on a timer. A wallet list changes when the user moves money, and a refresh on every frame would spend the account's budget for nothing. The key stays on the server. The Compose app never holds the Carbium key, because anyone who installs an APK can unpack it.

Token names and logos are not in this read. The file carries mints only. A label comes from your own mint list, or from a separate metadata read for each mint, and the list can show the mint address until that read arrives.

04

The bridge

Install @solana/kit 8.6.0 with npm and set the type field to module in package.json, so Node 24 strips the types on load. The file reads CARBIUM_KEY and exits with a message when it is unset. The endpoint defaults to the RPC endpoint, and CARBIUM_RPC_URL can point it elsewhere. The key goes in the `x-api-key` header. With no owner argument, the bridge reads the ten newest signatures of the SPL Token program and takes the first signer of a transaction that answers, so you do not need an address to see it work.

main.ts
// I0140 · Jetpack Compose token balances// https://carbium.sh/library/integrate/jetpack-compose-token-balances// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  address,  createDefaultRpcTransport,  createSolanaRpcFromTransport,  isSolanaError,  SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,  type Address,} from "@solana/kit";import { rename, 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 PROGRAMS: Record<string, Address> = {  "spl-token": address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),  "token-2022": address("TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"),};const names = Object.keys(PROGRAMS);const reason = (e: unknown) =>  isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR)    ? `HTTP error (${e.context.statusCode})`    : e instanceof Error ? e.message : String(e);// The owner is the first argument, or the first signer of a recent SPL Token transaction.async function findOwner(): Promise<string> {  if (process.argv[2]) return process.argv[2];  const sigs = await rpc.getSignaturesForAddress(PROGRAMS["spl-token"], { limit: 10 }).send();  for (const s of sigs) {    if (s.err !== null) continue;    const tx = (await rpc.getTransaction(s.signature, {      encoding: "json", maxSupportedTransactionVersion: 1, commitment: "confirmed",    }).send()) as unknown as { transaction: { message: { accountKeys: string[] } } } | null;    if (tx) return tx.transaction.message.accountKeys[0];  }  throw new Error("no owner found in the newest token signatures");}const owner = await findOwner().catch((err: unknown) => {  console.error("owner:", reason(err));  return process.exit(1);});const ownerAddress = address(owner);const results = await Promise.allSettled(  names.map((name) =>    rpc.getTokenAccountsByOwner(ownerAddress, { programId: PROGRAMS[name] }, { encoding: "jsonParsed", commitment: "confirmed" }).send(),  ),);type Totals = Record<string, { program: string; decimals: number; amount: bigint }>;const totals: Totals = {};const failed: string[] = [];results.forEach((res, i) => {  if (res.status === "rejected") {    failed.push(`${names[i]}: ${reason(res.reason)}`);    return;  }  for (const acc of res.value.value) {    const info = (acc.account.data as unknown as {      parsed: { info: { mint: string; tokenAmount: { amount: string; decimals: number } } };    }).parsed.info;    const t = totals[info.mint] ?? { program: names[i], decimals: info.tokenAmount.decimals, amount: BigInt(0) };    t.amount += BigInt(info.tokenAmount.amount);    totals[info.mint] = t;  }});const uiString = (amount: bigint, decimals: number): string => {  const digits = amount.toString().padStart(decimals + 1, "0");  const cut = digits.length - decimals;  const frac = digits.slice(cut).replace(/0+$/, "");  return frac ? `${digits.slice(0, cut)}.${frac}` : digits.slice(0, cut);};const balances = Object.keys(totals).map((mint) => ({ mint, program: totals[mint].program, decimals: totals[mint].decimals, amount: totals[mint].amount.toString(), ui: uiString(totals[mint].amount, totals[mint].decimals) }));const at = new Date().toISOString();await writeFile("balances.json.tmp", JSON.stringify({ owner, at, balances, failed }, null, 2));await rename("balances.json.tmp", "balances.json");console.log(`owner ${owner}, ${balances.length} mints, read at ${at}`);for (const b of balances) console.log(`${b.ui} ${b.mint} (${b.program})`);for (const f of failed) console.error("failed:", f);if (failed.length === names.length) process.exit(1);

run: node main.ts

05

Run it and read the file

Export CARBIUM_KEY and run node main.ts from an empty directory, because the file lands in the working directory. Pass an owner to read one wallet, as node main.ts <owner-address>. The output names the owner, prints one line per mint with its display amount and program, and sends any failed program to stderr after the list.

The bridge writes balances.json.tmp and renames it, so a reader sees the old file or the new one in full. Run it on a schedule from the backend the Compose app calls, or under a supervisor if you wrap it in a loop of your own. Each run is one pass of reads, so a run that dies before the rename leaves the last good file in place.

06

Where it ends

  • It reads only the two token programs above. SOL balances, NFTs and other program state are outside this file. SOL comes from getBalance in a separate call.
  • Discovery pays for two reads on each run when no owner is passed: getSignaturesForAddress costs 50 cells and getTransaction costs 50 cells. Pass an owner to skip both.
  • Signature pages come from an address index that keeps up to 30 days, so discovery reads only the newest signatures and never older history. A getTransaction answer of null is skipped, and the loop moves to the next signature.
  • The balances are the state at the read. A transfer that lands after the read shows on the next refresh, not on this one.
  • Limits are per account, so every user of one key shares that key's budget. A 429 on one program leaves the other program's rows in the file, and the file names the program that is missing.
  • The bridge does not sign or send anything and holds no signing key.
07

When it goes wrong

what goes wrongwhat to do
Both programs fail with HTTP error (401), and the failed list holds two entries.The key is missing, cut short or from another account. Export CARBIUM_KEY with the whole key and rerun. The key goes in the x-api-key header.
One program fails with HTTP error (429) while the other succeeds.A call over its rate waits once, then gets 429 if its budget does not refill in time. Rerun in a few seconds, or lower the traffic from other keys on the same account. The file keeps the rows that came back.
Discovery prints no owner found in the newest token signatures.The ten newest signatures had errors or null transactions. Pass an owner address as the first argument, or raise the limit in the signature read.
The screen shows a balance one decimal place off from the wallet app.The app divided by decimals a second time. Use the ui field as written, and keep amount as a string until the label is drawn.
The Compose app reports a parse error after a refresh.A reader opened the file during a write, or two bridges shared one working directory and one temporary name. Run one bridge per directory and keep the rename step.
08

Questions

Can this run on the phone itself?

Not with a key inside the app. The bridge runs on a backend or server you control, and the Compose app reads its JSON over HTTPS. A key inside an APK can be pulled out by anyone who installs it.

Why two calls instead of one?

The RPC answers token accounts per token program ID, and Token-2022 accounts sit under their own program. One call per program covers each set, and Promise.allSettled keeps one failure from hiding the other.

Does it show NFTs?

No. It reads fungible token accounts with a decimal count. An NFT is a different shape of data, and its name and image need their own read.

How often should the screen refresh?

When it opens and on a pull to refresh. A wallet list changes when the user moves money, so a timer would spend the key's budget without showing anything new.