library / Integrations / I0010
React Native getBalance fix
A Node relay that holds your Carbium key and answers a React Native app's balance reads, with the checks that tell a TypeError in the app from a failing RPC call. The app calls it with plain fetch and gets lamports and slot back.
What the error says
The message has two parts. The text up to the first colon, failed to get balance of account <address>, was written by the code that caught the error: your app, or a library around getBalance (with @solana/web3.js that is Connection.getBalance). The text after the colon is the original error turned into a string.
TypeError is the part that matters. A server that refuses or fails a JSON-RPC call answers with a numeric code and a message. A TypeError is thrown by JavaScript itself, inside the phone's runtime, so the step that failed ran on the device. React Native's fetch also rejects with TypeError: Network request failed when the network fails, and that wording is the network case; Cannot convert undefined value to object is not. It is how Hermes, React Native's default engine, words the fault when Object.keys or Object.entries receives undefined. Node words the same fault as Cannot convert undefined or null to object.
So an object the code expected is missing, such as a response body or an options object, and nothing in the message points at the node or the key. A new key or another endpoint will not clear it.
- Read the stack under the message. The first frame in your own code or in node_modules names the function that received undefined.
- Run the relay below with an address argument. If its startup check prints a balance, the key, the endpoint and the address are fine and the fault is in the app's runtime.
- Compare what the app builds around the call with what the relay does: one URL, one header, one commitment. A custom fetch, an options object read from storage, or a value read from process.env is the first suspect, since a React Native bundle has no process.env values unless your build inlines them.
- Take the JavaScript RPC client out of the phone and ask the relay with fetch.
The Carbium side: one key, one header
Carbium's RPC endpoint is https://services.carbium.sh. The relay sends the key in the x-api-key header, because URLs get written to logs and crash reports.
Keep the key off the phone. Anything bundled into an app can be pulled out of the installed package, and limits are per account, so a copied key draws on the same budget as your own traffic. The relay holds the key and the app holds only the relay's address.
The app side: plain fetch
In the app, call fetch on the relay's /balance/<address> and read the JSON. lamports and slot arrive as strings, because a lamport count can pass what a JavaScript number holds exactly. One SOL is 1,000,000,000 lamports, and Number(lamports) / 1e9 is fine for display.
fetch ships with React Native, so this path needs no polyfill, no Buffer and no Solana package on the device.
| Status | When | Body |
|---|---|---|
| 200 | Carbium answered. | address, lamports and slot, all strings. |
| 400 | The string has the shape of an address but does not decode to one. | error |
| 404 | Any other path or method. | error |
| 429 | Carbium rate-limited the call. | error, and the retry-after header when Carbium sent one. |
| 502 | Any other failure between the relay and Carbium, a timeout after 5 seconds included. | error |
A balance changes only when a transaction touches the account. For a screen that must update, accountSubscribe stays silent for a plain SOL wallet, so use logsSubscribe with a mention of the address and read the balance again when a log arrives. Run that from a server over the WebSocket, with one subscription per wallet, and push the result to the phone.
The relay
Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. CARBIUM_KEY is required and the file exits with a message when it is unset. CARBIUM_RPC_URL, HOST (default 127.0.0.1) and PORT (default 8787) are optional. An address as the first argument turns on a startup check.
// I0010 · React Native getBalance fix// https://carbium.sh/library/integrate/react-native-getbalance-fix// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createServer } from "node:http";import { createDefaultRpcTransport, createSolanaRpcFromTransport, isAddress, isSolanaError, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR,} from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium key."); process.exit(1);}const host = process.env.HOST ?? "127.0.0.1";const port = Number(process.env.PORT ?? 8787);// One client for the life of the process, so connections stay warm.const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);type Reply = { status: number; body: Record<string, string>; retryAfter?: string };async function balance(address: string): Promise<Reply> { if (!isAddress(address)) return { status: 400, body: { error: "not a Solana address" } }; try { const { context, value } = await rpc .getBalance(address, { commitment: "confirmed" }) .send({ abortSignal: AbortSignal.timeout(5_000) }); // Strings, because a lamport count can pass what a JS number holds exactly. return { status: 200, body: { address, lamports: value.toString(), slot: context.slot.toString() } }; } catch (e) { if (isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR)) { const code = e.context.statusCode; const retryAfter = e.context.headers.get("retry-after") ?? undefined; return { status: code === 429 ? 429 : 502, body: { error: `Carbium answered HTTP ${code}` }, retryAfter }; } return { status: 502, body: { error: e instanceof Error ? e.message : "call failed" } }; }}// Startup check: read one address, and refuse to serve when that read fails.const probe = process.argv[2];if (probe) { const r = await balance(probe); console.log("startup check", r.status, JSON.stringify(r.body)); if (r.status !== 200) process.exit(1);}const server = createServer(async (req, res) => { const address = /^\/balance\/([1-9A-HJ-NP-Za-km-z]{32,44})$/.exec((req.url ?? "").split("?")[0] ?? "")?.[1]; const r: Reply = req.method === "GET" && address ? await balance(address) : { status: 404, body: { error: "GET /balance/<address>" } }; res.writeHead(r.status, { "content-type": "application/json", ...(r.retryAfter ? { "retry-after": r.retryAfter } : {}) }); res.end(JSON.stringify(r.body));});server.listen(port, host, () => console.log(`relay listening on ${host}:${port}`));
run: node main.ts
Run it and test from the app's side
Start it with node main.ts <address>. The startup check reads that address once, prints the status, lamports and slot, and exits with code 1 when the status is not 200, so a wrong key stops the process before it serves. Without an address the check is skipped.
Then run curl http://127.0.0.1:8787/balance/<address> on the same machine. It returns the JSON the app will read. If curl works and the app still throws the same TypeError, the relay is cleared and the fault sits in the app's own code, before or after the fetch. The first stack frame names it.
Where it ends
- It does not name the line in your app that fails. It splits the fault into the app's runtime or the endpoint, and gives you a call that needs no Solana library on the phone.
- It reads SOL balances and nothing else. Token balances live on token accounts; see SPL token balance. It signs and sends nothing.
- It has no login, no cache and no per-user limit. Every app request becomes one Carbium call, so the app's refresh rate counts against the account budget that all keys share.
- When Carbium answers 429 with a retry hint, the relay passes the 429 on, and the app decides how long to back off.
- A read is one balance at one moment at confirmed. It gives no history.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The app still throws Cannot convert undefined value to object while curl against the relay returns a balance. | The fault is in the app's code. Read the first stack frame under the message, then log the value that function receives, such as the parsed JSON or an options object, just before the call. |
| The relay answers 502 with Carbium answered HTTP and a status other than 429. | Check that CARBIUM_KEY holds the key itself and that nothing else sets CARBIUM_RPC_URL. |
| The app shows an empty or stale balance and the relay answers 429. | Carbium refused the call. Read the retry-after header the relay passes on, wait that long and retry once. Lower the app's refresh rate, since every key on the account draws on one budget. |
| The process exits at start with startup check 502 and a message. | The message names the cause: a timeout after 5 seconds, a wrong CARBIUM_RPC_URL, or an HTTP error status. Fix it and restart. The relay does not serve until the check passes. |
| curl works on the server but the phone cannot reach the relay. | The relay listens on 127.0.0.1 by default. Set HOST, or put a reverse proxy with TLS in front, and add your own session check. |
| The app shows a balance 1,000,000,000 times too large. | The app is displaying lamports as SOL. Divide by 1e9 for display. |
Questions
Can the app call Carbium directly instead?
It can, with the key in x-api-key or on the URL. The key then ships inside the app, and a copied key spends your account's budget. The relay keeps it on a server you control.
Can the app keep `@solana/web3.js` and only change its RPC URL?
Pointed at Carbium directly, yes, with the key shipped in the app as described above. Pointed at the relay, no: the relay answers only GET /balance/<address>, not JSON-RPC, so a Connection gets a 404. Use fetch for the relay.
Does a key in the URL work too?
Yes, Carbium takes ?api-key= on the URL. A header keeps the key out of logs, which is why the relay uses one.