services
Get a key

library / Blockchain ideas / BI0015

Read-only mobile backend

A small server that holds the Carbium key and answers one phone request with a wallet's SOL balance, a few token balances and recent signatures, from two RPC calls and a 5-second cache. The costs per plan and a runnable main.ts come with it.

By Carbium · Mobile-first · BI0015 · updated 2026-11-22

01

Who uses it

A wallet or portfolio app on a phone makes the same three reads every time a screen opens: the SOL balance, a few token balances and the last handful of transactions. If the Carbium key sits inside the app, it ships in every install, where anyone can pull it out of the binary or the network traffic. Limits are per account, so every key on the account draws on one budget, and a leaked key spends it.

A small backend keeps the key on a server you control and gives the phones one URL. A hackathon crew with a React Native or Kotlin wallet gets a data layer in one file, and a team that moves a web dashboard to a phone puts its reads behind one route.

The phone sends a wallet address to GET /portfolio/<address>. The wallet on the phone still signs. The backend never sees a private key and sends nothing.

02

What it returns

One JSON object per request. The first three fields come from a single getMultipleAccounts call and the last from getSignaturesForAddress. When one of the two calls fails, its fields come back null with an error message, and the other half stays in the answer.

FieldWhere it comes fromExample
slotcontext.slot of the account readthe slot the balances were read at
sollamports of the wallet account divided by 1e9; a wallet with no account reads 01.482
tokensuiAmountString of each tracked token account; 0 when the account does not exist{"USDC":"25.5","wSOL":"0"}
recentthe five newest signatures with slot, block time and a failed flagfailed: true means the transaction landed and reverted

The token accounts are the wallet's associated token accounts for each tracked mint, derived from the wallet address, the token program and the mint. A wallet that never held a token has no such account, so the read returns null and the backend answers 0.

uiAmountString is a decimal string, so the phone shows the amount in any locale without float rounding.

03

The build

The backend is one file that needs @solana/kit and what Node 24 ships.

  1. Create one RPC client at start for https://services.carbium.sh with the key from CARBIUM_KEY in the x-api-key header, and reuse it for every request.
  2. Derive the associated token account of the wallet for each tracked mint. The code tracks USDC and wrapped SOL; add mints to one object.
  3. Call getMultipleAccounts with the wallet and the derived accounts, with encoding: "jsonParsed" so the token amount arrives decoded. Three pubkeys cost 30 cells.
  4. Call getSignaturesForAddress for the wallet with limit: 5, at the same time as the first call, so the phone waits for one round trip. Promise.allSettled settles the two apart, so one failing leaves the other's data in the answer.
  5. Keep each answer in memory for 5 seconds, keyed by address, and share the fetch in flight under the same key. A failed fetch, or an answer with an error field, is not kept. Ten pull-to-refresh taps in one window cost one refresh, and so do a thousand phones watching the same public wallet.

Run it with a wallet address as the argument and it prints that wallet's JSON and exits. Run it without one and it listens on 127.0.0.1:8787 (change it with PORT) and answers /portfolio/<address>. Put your TLS proxy in front.

main.ts
// BI0015 · Read-only mobile backend// https://carbium.sh/library/blockchainideas/read-only-mobile-backend// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport {  address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressEncoder, getProgramDerivedAddress,  isAddress, isSolanaError, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,} from "@solana/kit";import { createServer } from "node:http";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);// Tracked mints, all under the classic token program. Add yours here.const MINTS = { USDC: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", wSOL: "So11111111111111111111111111111111111111112" };const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const ATA_PROGRAM = address("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");const TTL_MS = 5000; // one refresh per address per 5 sconst cache = new Map<string, { at: number; body: unknown }>();const pending = new Map<string, Promise<unknown>>(); // fetches in flight, one per addressconst enc = getAddressEncoder();type Row = { lamports: bigint; data: { parsed?: { info?: { tokenAmount?: { uiAmountString?: string } } } } } | null;const why = (r: PromiseSettledResult<unknown>) => r.status === "rejected" ? String(r.reason instanceof Error ? r.reason.message : r.reason) : "";async function retry<T>(call: () => Promise<T>): Promise<T> {  try {    return await call();  } catch (e) {    if (!isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) || e.context.statusCode !== 429) throw e;    await new Promise((r) => setTimeout(r, (Number(e.context.headers.get("retry-after")) || 2) * 1000));    return call();  }}async function portfolio(owner: string) {  const wallet = address(owner);  const atas = await Promise.all(Object.values(MINTS).map(async (mint) => (await getProgramDerivedAddress({    programAddress: ATA_PROGRAM, seeds: [enc.encode(wallet), enc.encode(TOKEN_PROGRAM), enc.encode(address(mint))],  }))[0]));  // The two reads settle apart: one failing leaves the other half of the answer. A missing token account reads null.  const [read, sigs] = await Promise.allSettled([    retry(() => rpc.getMultipleAccounts([wallet, ...atas], { commitment: "confirmed", encoding: "jsonParsed" }).send()),    retry(() => rpc.getSignaturesForAddress(wallet, { commitment: "confirmed", limit: 5 }).send()),  ]);  if (read.status === "rejected" && sigs.status === "rejected") throw read.reason;  const rows = read.status === "fulfilled" ? (read.value.value as unknown as Row[]) : null;  return {    slot: read.status === "fulfilled" ? Number(read.value.context.slot) : null,    sol: rows && Number(rows[0]?.lamports ?? 0n) / 1e9,    tokens: rows && Object.fromEntries(Object.keys(MINTS).map((name, i) =>      [name, rows[i + 1]?.data.parsed?.info?.tokenAmount?.uiAmountString ?? "0"])),    recent: sigs.status === "fulfilled" ? sigs.value.map((s) => ({ signature: s.signature, slot: Number(s.slot), time: s.blockTime === null ? null : Number(s.blockTime), failed: s.err !== null })) : null,    error: [read, sigs].map(why).filter(Boolean).join("; ") || undefined,  };}async function cached(owner: string) {  const hit = cache.get(owner);  if (hit && Date.now() - hit.at < TTL_MS) return hit.body;  let p = pending.get(owner);  if (!p) pending.set(owner, p = portfolio(owner).then((body) => {    if (cache.size >= 10_000) cache.clear();    if (!body.error) cache.set(owner, { at: Date.now(), body });    return body;  }).finally(() => pending.delete(owner)));  return p;}const arg = process.argv[2];if (arg) {  portfolio(arg).then((p) => console.log(JSON.stringify(p, null, 2)), (e) => { console.error(String(e)); process.exit(1); });} else {  createServer(async (req, res) => {    const [, route, owner = ""] = new URL(req.url ?? "/", "http://localhost").pathname.split("/");    res.setHeader("content-type", "application/json");    if (route !== "portfolio" || !isAddress(owner)) return void res.writeHead(404).end("{}");    try {      res.end(JSON.stringify(await cached(owner)));    } catch (e) {      res.writeHead(502).end(JSON.stringify({ error: e instanceof Error ? e.message : String(e) }));    }  }).listen(Number(process.env.PORT ?? 8787), "127.0.0.1", () => console.log("listening on 127.0.0.1"));}

run: CARBIUM_KEY=<YOUR_KEY> node main.ts <WALLET_ADDRESS>

Both reads ask for confirmed, and the slot field shows the app what it got.

An address that fails validation gets a 404 before any call is made. When both calls fail, the answer is a 502 with the first error's message. The cache clears itself at 10,000 entries.

04

What it costs

Every refresh is two calls: getMultipleAccounts on three pubkeys at 10 cells each, so 30 cells, and getSignaturesForAddress at 50 cells. That is 80 cells. The cache holds an address to one refresh per 5 seconds, which is 0.2 refreshes a second however many phones ask.

Each call draws on its own class. The account read class gives 0.5, 15, 50 and 400 calls a second at 10 cells on Free, Dev, Business and Pro, so a 30-cell call takes three of those 10-cell shares and fits a third of that rate, and getSignaturesForAddress has its own rate. The last column counts the addresses the backend can refresh in one 5-second window, taking whichever class runs out first.

PlanCredits30-cell account reads per sgetSignaturesForAddress per sAddresses refreshed per 5 s
Free ($0)500K once, at sign-up0.170.24under 1
Dev ($20)10M per month51.26
Business ($250)50M per month16.710083
Pro ($500)200M per month133500666

Free fits a demo with gaps: one address at a 6-second window. For more addresses, move up a plan or split the activity list into a second route with a longer cache, which takes the 50-cell call off the balance screen. A staging copy on the same account shares the budget.

$The code retries a 429 once. A second 429 leaves that half of the answer null with an error field, and when both calls fail it becomes the 502.
05

What to add next

  • An activity route: /activity/<address> with a 30-second cache, so the balance route drops to 30 cells.
  • A push on change: hold a logsSubscribe mentions subscription for the wallet and tell the phone to refetch when a log arrives, because accountSubscribe stays silent for a plain SOL wallet. The wallet mention catches SOL moves and the wallet's own sends. A token transfer into an existing token account lists the two token accounts and the sender's authority and never the receiving wallet, so incoming USDC is missed unless you add one mentions subscription per tracked associated token account. Each subscription opens at 25 credits, then costs 20 credits per MiB sent, and Free carries 5 sockets. Delivery to the phone (APNs or FCM) is yours.
  • A price per token: the prices method answers on the same endpoint as JSON-RPC. Quote plans run from Free at 10 quotes/s to Elite at 500/s.
  • An access check: a session token from your own login in front of the route, so only your users spend your budget.
06

Where it ends

  • The backend returns the tokens on its list and does not discover what else a wallet holds, so a screen that lists every token needs an owner-wide token account lookup that the backend leaves out. A wallet can own several token accounts for one mint, and this read sees only the associated one.
  • Tracked mints must sit under the classic token program. A Token-2022 mint has its associated account derived with that program's address, so the seed in the code is wrong for it.
  • recent carries the signature, slot, time and a failed flag. The amount moved and the counterparty need getTransaction, 50 cells per row.
  • History is the 30-day address index at most. An empty page past that is the index's age limit and says nothing about the wallet's first transaction.
  • The backend signs and sends nothing. A send path needs sendTransaction, 20 cells without preflight and 70 with it, and the swap method returns one unsigned transaction for your software to sign.
  • Any public address is served to anyone who reaches the route. Add the access check before a launch.
07

When it goes wrong

what goes wrongwhat to do
Every request answers 502 with an HTTP error about the key.Carbium answers 401 unknown api key (UNKNOWN_KEY) at the door: attach the whole key. The code exits at start when CARBIUM_KEY is unset, so the running backend holds a value Carbium does not know. Replace it with the whole current key.
The backend answers 502 with a 429 inside.Both calls were over the account's rate twice in a row; if only one was, the answer is a 200 with that half null. Lengthen the cache window, split the activity route, or check what else shares the account, because limits are per account.
A token reads 0 for a wallet that holds it.Three causes. The mint is under Token-2022: derive the account with that mint's own token program. The mint is not on the tracked list: add it. Or the wallet holds it in a token account that is not its associated one: list the wallet's token accounts instead.
A request answers 404 with an empty object.The route checks the address before any call, so a typo, a stray space or any non-base58 text gets the 404. Check the path the app builds: /portfolio/<address>.
recent is empty for a wallet with history.The address index keeps up to 30 days. Show "no activity in 30 days" instead of an error.
The phone's balance lags a transaction it just sent.Reads use confirmed and the cache can hold a 5-second-old answer. Wait out the window, or add a small invalidate route or a ?fresh=1 bypass to the backend for the phone to call after it sends, and compare the slot field with the slot of the transaction.
08

Questions

Can the phone call Carbium directly?

It can, and then the key sits in the app and every install shares the account's one budget. The backend keeps the key on a server you control.

Why derive the token accounts instead of listing them?

One getMultipleAccounts call returns the wallet and every tracked token account together, at 10 cells per pubkey. The price is that the list of tokens is yours to maintain.

How does the phone get a fresh read after it sends a transaction?

As written, the backend answers from its 5-second cache, so the phone sees the same body until the window ends. A builder adds a small invalidate route or a ?fresh=1 bypass that skips the cached entry for that address, and the phone calls it right after the send. The slot field in the new answer tells the app whether the read came after its transaction.

Does this run on the Free plan?

For a demo, yes. Free fits a 30-cell getMultipleAccounts about 0.17 times a second, against the 0.2 a 5-second cache needs, so one address stays fresh at a 6-second window and has gaps at 5. Dev raises that to about 6 addresses per 5 seconds.

Can it tell the phone when a balance changes?

Not as written; a backend that adds the push holds a logsSubscribe mention of the wallet, which catches SOL moves and its own sends but misses tokens arriving in an existing token account, so that backend also subscribes to each tracked token account. Logs carry no balance, so the fresh read is what the user sees.