library / Integrations / Mobile and desktop / I0144
React Native WebSocket resume
A React Native app can subscribe to Carbium's programSubscribe and signatureSubscribe without the readyState 0 crash by holding each subscription until the socket opens and resending it after every reconnect. The code runs the same logic against Carbium.
Why the send throws
A WebSocket object exists from the moment it is constructed, but it accepts a send only after the handshake finishes. Until then readyState is 0 (CONNECTING), and the call throws the message in the query. React Native gives the app the same browser WebSocket API, so the rule holds on a phone too.
The crash comes and goes because it depends on timing. A screen that subscribes right after it mounts wins that race on a quick connection and loses it on a slow one. A retry after a drop hits the same race, since the new socket starts at 0 and any code that reuses the old subscribe call sends too early.
A socket that is closing moves to 2 (CLOSING), and then to 3 (CLOSED), where a send fails in the same way. Phones close sockets often: the operating system suspends a backgrounded app, and the connection dies without a message until the app reads the close event or tries to send.
Keep subscriptions in a registry
Treat the socket as a pipe that comes and goes, and keep the list of subscriptions apart from it. Each subscribe call stores its method, its parameters and its handler under a request id the app picks. The call sends at once when the socket is open. When it is not, the entry waits, and the open handler sends every stored request.
| readyState | Name | What the code does |
|---|---|---|
| 0 | CONNECTING | Stores the subscription and sends nothing; the open handler sends it. |
| 1 | OPEN | Sends the subscribe request at once. |
| 2 | CLOSING | Sends nothing; the close handler schedules a reconnect. |
| 3 | CLOSED | Sends nothing; the reconnect opens a new socket and sends again. |
A close clears the server's subscription ids, because they belong to the old socket. The next open sends each stored request again under the same request id, and the code maps the new id from the reply. A notification names its subscription in params.subscription, which is how the right handler runs after a reconnect.
What Carbium expects on the socket
The WebSocket endpoint is wss://services.carbium.sh. The key travels as the api-key query parameter, as the auth page describes, and the code adds it with URL.searchParams so the value is encoded. The RPC client sends the key in the x-api-key header instead, against https://services.carbium.sh. Nothing in the file prints the URL.
Limits are per account, and the plan caps the sockets and subscriptions a key may hold. A Free key carries 5 sockets. Each subscription costs 5, 25 or 200 credits to open, by filter weight: slot, root and signature subscriptions sit in the 5 tier, account, logs mention and slot update subscriptions in the 25 tier, and program subscriptions in the 200 tier. So programSubscribe is the expensive call here, while signatureSubscribe is cheap and ends after one confirmation.
A subscription the server refuses costs nothing. The code logs the refusal and drops the request instead of retrying it in a loop.
The resumable subscriber
The file opens one socket, keeps one registry, and holds two subscriptions. It reads CARBIUM_KEY and the two optional endpoint variables, takes the program address from the first argument, and finds that program's newest signature with getSignaturesForAddress before it subscribes to that signature. Both subscriptions ask for confirmed explicitly. Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json.
// I0144 · React Native WebSocket resume// https://carbium.sh/library/integrate/react-native-websocket-resume// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const envKey = process.env.CARBIUM_KEY;if (!envKey) { console.error("Set CARBIUM_KEY to your Carbium key."); process.exit(1); }const apiKey: string = envKey;const program = process.argv[2];if (!program) { console.error("Usage: node main.ts <program address>"); process.exit(1); }const rpcUrl = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const wsBase = process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh";const OPEN = 1;type Sub = { method: string; params: unknown[]; onMsg: (value: unknown) => void; sid?: number };type Msg = { id?: number; result?: unknown; error?: { message?: string }; params?: { subscription: number; result: unknown } };const subs = new Map<number, Sub>(); // our request id -> spec, kept across reconnectsconst bySid = new Map<number, Sub>(); // server subscription id -> spec, rebuilt on each socketlet nextId = 1;let closing = false;let ws: WebSocket;function connect(): Promise<void> { return new Promise((resolve, reject) => { const url = new URL(wsBase); url.searchParams.set("api-key", apiKey); const socket = new WebSocket(url); ws = socket; socket.onopen = () => { subs.forEach((s, id) => socket.send(JSON.stringify({ jsonrpc: "2.0", id, method: s.method, params: s.params }))); resolve(); }; socket.onmessage = (ev) => dispatch(String(ev.data)); socket.onerror = () => reject(new Error("WebSocket could not open")); socket.onclose = () => { bySid.clear(); if (!closing) setTimeout(() => connect().catch(() => undefined), 2_000); }; });}function dispatch(raw: string): void { const msg = JSON.parse(raw) as Msg; if (msg.id !== undefined) { const s = subs.get(msg.id); if (!s) return; if (msg.error) { console.error(`subscription ${msg.id} refused: ${msg.error.message ?? "unknown error"}`); subs.delete(msg.id); } else if (typeof msg.result === "number") { s.sid = msg.result; bySid.set(msg.result, s); } return; } if (msg.params) bySid.get(msg.params.subscription)?.onMsg(msg.params.result);}function subscribe(method: string, params: unknown[], onMsg: (value: unknown) => void): number { const id = nextId++; subs.set(id, { method, params, onMsg }); if (ws.readyState === OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", id, method, params })); return id;}function end(id: number): void { const s = subs.get(id); if (!s) return; if (s.sid !== undefined) { if (ws.readyState === OPEN) ws.send(JSON.stringify({ jsonrpc: "2.0", id: 0, method: s.method.replace("Subscribe", "Unsubscribe"), params: [s.sid] })); bySid.delete(s.sid); } subs.delete(id);}async function main(): Promise<void> { await connect(); const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url: rpcUrl, headers: { "x-api-key": apiKey } })); const [latest] = await rpc.getSignaturesForAddress(address(program), { limit: 1 }).send(); let notes = 0; let confirmed = false; const progSub = subscribe("programSubscribe", [program, { encoding: "base64", commitment: "confirmed" }], () => { notes++; }); const sigSub = latest ? subscribe("signatureSubscribe", [latest.signature, { commitment: "confirmed" }], () => { confirmed = true; end(sigSub); }) : 0; await new Promise<void>((done) => setTimeout(done, 8_000)); end(progSub); closing = true; ws.close(); console.log(`programSubscribe on ${program}: ${notes} notifications in 8 s`); console.log(latest ? `signature ${latest.signature} confirmed: ${confirmed ? "yes" : "not within 8 s"}` : "no recent signature found");}main().catch((err: unknown) => { console.error("run failed:", err instanceof Error ? err.message : String(err)); process.exit(1); });
run: node main.ts
Run it
Export CARBIUM_KEY and run the file with the Token program address, TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA. The run opens the socket, subscribes to the program and to the newest signature the program lists, and prints a count of program notifications after 8 seconds. The socket stays up for the whole run, so the output shows the subscribe path working and says nothing about a reconnect.
The signature line reads confirmed: yes when the confirmation arrives inside the window. When it reads not within 8 s, the subscription was accepted and the notification did not come in that window, so run it again.
What it costs against your limits
One run opens one socket, one program subscription at 200 credits and one signature subscription at 5 credits, plus 20 credits per MiB the server sends. The Token program is busy, so the notification count is large on a run, and the byte total is what the credits track. The single signature lookup costs 50 cells.
In an app, open the socket once per session and keep every subscription on it. Cache the newest signature for a few seconds instead of calling getSignaturesForAddress on each mount.
Where it ends
- The run covers the subscribe and unsubscribe paths on a socket that stays open. The reconnect branch runs only after a real close, so test it by closing the socket from the code and checking that the handler resumes.
- The reconnect waits a fixed 2 seconds. During a long outage the app tries every 2 seconds, so add a backoff before shipping.
- The registry lives in memory. A killed app loses its subscriptions and must subscribe again from its own state on the next start.
- A subscription reports what happens after it opens. It does not replay what the socket missed while it was down, so read the account or the signature state once with a plain RPC call after a reconnect.
- signatureSubscribe sends one confirmation and then ends. Read the err field in the result to learn whether that transaction failed.
- A plain SOL wallet gets nothing from accountSubscribe. Use logsSubscribe mentions with getBalance instead.
- The keepalive and reconnect notes cover the connection side in more depth.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| WebSocket is not open: readyState 0 (CONNECTING) on the first subscribe after a screen mounts. | Send only through the registry. A direct send call belongs in the open handler or behind a readyState check of 1. |
| The same error with readyState 2 or 3 after the phone sleeps or the app comes back from the background. | Check that the close handler runs and schedules a reconnect. A retry that reuses the old socket object sends into a dead connection, so the reconnect must open a new WebSocket. |
| A log line subscription 1 refused with a message about the plan or the key. | Confirm CARBIUM_KEY holds the whole key. A Free key carries 5 sockets, so close any socket the app left open from an earlier session. |
| The subscription opens but the program handler never runs. | A program that changes no accounts in the window sends nothing. Pick a program that changes its accounts, or use logsSubscribe when transaction logs are what you need. |
| A 429 with a retry-after hint on the signature lookup. | Cache the newest signature for a few seconds and wait the number of seconds the hint gives before the next lookup. |
Questions
Why not skip the send when the socket is not open?
Skipping it drops the subscription, so the screen never gets its notifications. The registry holds the request until the socket opens and then sends it once.
Does the run prove the reconnect works?
No. The socket stays open for the 8 seconds, so only the subscribe and unsubscribe paths run. Close the socket from a test, then check that the handler keeps receiving after the next open.
Can this go into a React Native app as it is?
The functions use the WebSocket API that React Native provides, so they port across once the process.env lines read from your own config. Keep the key in secure storage and keep the URL out of logs, because the key sits in its query string.
How many sockets should one app open?
One per session is enough, with each subscription on that socket. Each subscription still costs its own credits, so drop the ones a screen no longer shows.