services
Get a key

library / Integrations / I0036

React post-confirm balance refresh

A Node script that holds the logic for a React balance refresh: it waits for a transaction signature to reach confirmed over WebSocket, falls back to polling, then reads the wallet balance pinned to the confirmation slot so the number is never stale.

By Carbium · Web frameworks · I0036 · updated 2026-11-22

01

Why the balance lags the click

After a wallet signs and sends a transaction, the page holds a signature and nothing else. The balance on screen is still the number read before the send. Two obvious fixes go wrong. A read right after the send returns the old value, because the transaction has not landed. A read on a timer works until the timer fires a moment early, and then the page shows the old value for a whole interval.

Order matters. Wait for the signature to reach a commitment level. Read the balance at that same level. Tell the node which slot the read has to include, so a node that is still catching up refuses to answer instead of returning the old number. Commitment levels explains the levels. This job uses confirmed. @solana/kit 8.6.0 fills in confirmed when a call leaves commitment out, and the script passes it on every call that takes one so the choice is visible.

finalized is the stricter choice. Since the Alpenglow switch on 2026-10-21 it sits 0 to 1 slots behind processed, and a slot is about 200 ms, so a page that wants it pays roughly one slot more than confirmed. A screen that only shows a number rarely needs it.

02

The sequence, step by step

  1. Open a WebSocket to wss://services.carbium.sh with the key as ?api-key= on the URL and send signatureSubscribe for the signature at confirmed.
  2. The one notification carries the slot where the signature confirmed and an err field, then the subscription ends. A non-null err means the transaction landed and failed. It still paid its fee, so the balance dropped by the fee, and the read in step 4 still runs at that slot.
  3. If the socket has said nothing after 3 seconds, start polling getSignatureStatuses once a second. Whichever path answers first wins and the other is dropped. Both paths return the slot together with err.
  4. Read getBalance at confirmed with minContextSlot set to the confirmation slot. A node behind that slot answers with an error, and the script tries up to 5 times, 400 ms apart.
CallCommitmentPurpose
signatureSubscribeconfirmedPush notice that the transaction landed
getSignatureStatusesstatus field confirmationStatusFallback when the push never arrives
getBalanceconfirmed plus minContextSlotThe number to show, never older than the confirmation
03

The script

Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. The script needs CARBIUM_KEY, and CARBIUM_RPC_URL and CARBIUM_WS_URL are optional overrides. Run it as node main.ts <wallet> <signature> to refresh the balance for a transaction you just sent.

With no arguments it finds a real case. It lists the newest signatures of a busy program, reads each transaction until one answers, and takes that transaction's fee payer as the wallet. A read that errors is logged and the loop moves on to the next signature. getTransaction is called with maxSupportedTransactionVersion: 1, because a v1 transaction answers -32015 when the field is absent or 0. It also answers null for some older signatures that the address index still lists, so the loop skips a null and tries the next one.

main.ts
// I0036 · React post-confirm balance refresh// https://carbium.sh/library/integrate/react-post-confirm-balance-refresh// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } 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 wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");wsUrl.searchParams.set("api-key", key);const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));const BUSY_PROGRAM = "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";type Seen = { via: string; slot: bigint; err: unknown };// No arguments: take the fee payer of one of the newest transactions of a busy program.async function sample(): Promise<[string, string]> {  const sigs = await rpc.getSignaturesForAddress(address(BUSY_PROGRAM), { limit: 10, commitment: "confirmed" }).send();  for (const s of sigs) {    if (s.err) continue;    const tx = await rpc      .getTransaction(s.signature, { commitment: "confirmed", encoding: "json", maxSupportedTransactionVersion: 1 })      .send()      .catch((e) => { console.error("getTransaction failed:", e instanceof Error ? e.message : e); return null; });    const payer = tx?.transaction.message.accountKeys[0]; // null for a signature below the ledger floor    if (payer) return [payer, s.signature];  }  throw new Error("no readable transaction among the newest 10");}function viaSocket(sig: string, ms: number): Promise<Seen> {  return new Promise((resolve, reject) => {    const ws = new WebSocket(wsUrl);    const timer = setTimeout(() => { ws.close(); reject(new Error("socket: no notification")); }, ms);    ws.onerror = () => { clearTimeout(timer); reject(new Error("socket error")); };    ws.onopen = () => ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "signatureSubscribe", params: [sig, { commitment: "confirmed" }] }));    ws.onmessage = (ev) => {      const m = JSON.parse(String(ev.data));      if (m.method !== "signatureNotification") return;      clearTimeout(timer);      ws.close();      resolve({ via: "socket", slot: BigInt(m.params.result.context.slot), err: m.params.result.value.err });    };  });}async function viaPoll(sig: string, ms: number, stop: AbortSignal): Promise<Seen> {  await sleep(3000); // the socket gets a head start  for (const end = Date.now() + ms; Date.now() < end && !stop.aborted; await sleep(1000)) {    const { value } = await rpc.getSignatureStatuses([signature(sig)], { searchTransactionHistory: true }).send();    const st = value[0];    if (st?.confirmationStatus === "confirmed" || st?.confirmationStatus === "finalized") return { via: "poll", slot: st.slot, err: st.err };  }  throw new Error("poll: not confirmed in time");}const [wallet, sig] = process.argv[2] && process.argv[3] ? [process.argv[2], process.argv[3]] : await sample();console.log(`wallet ${wallet}\nsignature ${sig}`);const stop = new AbortController();let seen: Seen;try {  seen = await Promise.any([viaSocket(sig, 15_000), viaPoll(sig, 12_000, stop.signal)]);} catch (e) {  console.error("not confirmed:", e instanceof AggregateError ? e.errors.map(String).join("; ") : String(e));  process.exit(1);}stop.abort();// A failed transaction still paid its fee, so the balance is read either way.if (seen.err) console.error(`transaction failed: ${JSON.stringify(seen.err)}`);let ok = false;for (let i = 1; i <= 5 && !ok; i++) {  try {    const r = await rpc.getBalance(address(wallet), { commitment: "confirmed", minContextSlot: seen.slot }).send();    console.log(`balance ${Number(r.value) / 1e9} SOL read at slot ${r.context.slot} (try ${i}); confirmed at slot ${seen.slot} via ${seen.via}`);    ok = true;  } catch (e) {    console.error(`balance read ${i} failed:`, e instanceof Error ? e.message : e);    await sleep(400);  }}process.exit(ok ? 0 : 1);

run: node main.ts

04

Moving it into a React component

The body of viaSocket, viaPoll and the balance loop becomes one async function that takes a signature and returns the slot and the lamports. A wallet adapter hands the page the signature when sendTransaction resolves. A useEffect keyed on that signature calls the function and stores { lamports, slot } in state. Keep the slot the balance was read at next to the balance, and let a later answer with a lower slot never replace a newer one. The cleanup function closes the socket and sets a cancelled flag, so an answer that arrives after the component unmounts changes nothing.

Keep the Carbium key on your server. A key shipped in a browser bundle belongs to everyone who opens the page. Put a small route on your own backend that either proxies the JSON-RPC call with the key attached or opens the socket itself and passes the single notification to the page. The page then never sees the key, and you can add your own per-user limit in front of it.

Show a pending state between the send and the confirmation. When err comes back non-null, show the failure and still refresh the balance at the notified slot, because the fee was taken even though the transfer did not happen. React Strict Mode mounts effects twice in development, so a dev build opens two subscriptions per send. That is harmless, and the cleanup closes the first one.

05

What it costs against your limits

A signatureSubscribe opens at 5 credits and then costs 20 credits per MiB sent. One notification is a few hundred bytes. A refused subscription costs nothing. Your plan caps sockets per account, and Free carries 5, so a page that sends often should hold one socket and add one subscription per pending signature instead of one socket per send.

The retry loop in the script pauses 400 ms between balance reads. The discovery path in the script is for the demo only. getSignaturesForAddress and getTransaction cost 50 cells each, and ten transaction reads are 500 cells, inside the 1,024-cell burst.

06

Where it ends

  • It reads and never signs or sends. The signature comes from your own wallet flow.
  • It shows SOL only. A token balance needs getTokenAccountBalance on the token account, and a wallet can own more than one token account for the same mint, so a token screen has to pick or add them up.
  • It refreshes after your own transaction. A transfer someone else sends to the wallet triggers nothing: accountSubscribe sends nothing for a plain SOL wallet, and the route for that is logsSubscribe mentions plus getBalance, and multi-wallet watching goes further.
  • confirmed is enough to repaint a number. For money you hand goods against, wait for finalized before you ship.
  • The 5 tries cover a node that is a slot or two behind. A node that stays behind for seconds ends in an error line and no balance.
07

When it goes wrong

what goes wrongwhat to do
The balance printed after confirmation is still the old number.The read ran without minContextSlot, or on a different commitment than the confirmation. Pass the slot from the notification and read at confirmed, as the script does.
getTransaction answers -32015 while the script looks for a wallet.The transaction is a v1 transaction and the call left maxSupportedTransactionVersion out. Set it to 1.
The socket closes with no notification, and the balance line ends via poll.A Free account past its 5 sockets is refused, so close the sockets you opened. The poll path takes over after 3 seconds.
The script prints not confirmed: ... 401 and exits with no balance.Check that CARBIUM_KEY holds the whole key and that it reaches the socket on the URL as ?api-key=. An unknown key gets 401 at the door.
Every getBalance try fails with a minimum context slot error and the script exits with no balance.The node that answers is further behind the confirmation slot than the 5 tries, 400 ms apart, can cover. Run the script again, or raise the try count or the pause in the loop. Keep minContextSlot in place, because dropping it returns the old number.
getTransaction returns null for a signature that getSignaturesForAddress listed.The listing comes from a 30-day address index that reaches below the ledger the node holds. Skip a null and take the next signature, and run the script on the newest ones.
08

Questions

Why not subscribe to the wallet account and refresh on every change?

accountSubscribe sends account state for streamed accounts and sends nothing for a plain SOL wallet. The signature route covers your own transactions, and logsSubscribe mentions plus a getBalance call cover the rest.

What happens when the transaction never lands because its blockhash expired?

No notification arrives and the status poll never sees confirmed. The socket path gives up after 15 seconds, the script prints not confirmed and exits with code 1, and no balance read runs. In a component, keep the send's lastValidBlockHeight and mark the send failed, with a retry, only once getBlockHeight at confirmed has passed it, because until then the transaction can still land and a second send could pay twice.

Can one socket carry several signatures?

Yes. Each signatureSubscribe is its own subscription on the same connection, opens at 5 credits and ends after its one notification, so the socket stays open for the next send.

How does this change for a token balance?

Swap the getBalance call for getTokenAccountBalance on the token account. That is an account read at 10 cells.