library / Integrations / I0064
Hono server-sent account events
A Hono server holds one Carbium WebSocket subscription per account and streams a snapshot, then every change, to any number of browsers as server-sent events, with the slot as the event id and the API key kept on the server.
One socket up, many streams down
A browser cannot hold your API key. Anything in its JavaScript is readable by whoever opens the page, so the key stays on your Hono server and the browser talks to your server only. The server opens one WebSocket to Carbium, sends one accountSubscribe per account you want to show, and keeps the newest state of each account in memory. Every browser that wants an account gets a server-sent event stream from your route, fed from that memory and from the notifications as they arrive.
That shape fixes the cost on both sides. Carbium sees one socket and one subscription per account, however many pages are open. Your server holds many small HTTP responses. The socket takes the key as ?api-key= on the WebSocket URL, and RPC reads carry it in the x-api-key header. Free carries 5 sockets per account, and this design needs one.
The route itself is short. In Hono, streamSSE from hono/streaming hands you a stream whose writeSSE takes event, id and data. The handler writes the account's current state as the first frame, adds the stream to a hub that the WebSocket handler calls on every notification, and removes it in stream.onAbort when the browser leaves. The page side is a plain EventSource on the route's path, with one listener for snapshot and one for change.
Snapshot, then changes
An account subscription sends changes. It does not send what the account holds right now, so a client that only listens shows nothing until the next write, and for a quiet account that can be a long wait. The contract has two parts: a snapshot read with getAccountInfo, then every change after it.
The order matters. Read first and subscribe second, and a write between the two is lost. Subscribe first and read second, and the read can finish after a notification that already carried newer state. Both the read and the notification name a slot in context.slot, so the program subscribes, reads, holds any notification that arrives meanwhile, and drops each one whose slot is at or below the snapshot's. What survives is a sequence with no gap and no repeat. Both run at confirmed, which @solana/kit fills in for the read.
Keep the last frame of each account in the hub. A browser that connects gets its snapshot from that memory and costs no RPC call. A getAccountInfo is an account read of 10 cells, and Free allows those at 0.5 req/s, so one read per page load would stall as soon as a few visitors arrive together.
The SSE frame and its id
A server-sent event is a few lines of text ended by a blank line. The program prints them, and your Hono route writes the same three fields.
| Field | Value | Used for |
|---|---|---|
| event | snapshot or change | The page registers one listener per name. |
| id | The slot, as decimal digits | The browser stores the last one and sends it back as Last-Event-ID on reconnect. |
| data | JSON with account, lamports and amount | What the page draws. |
EventSource reconnects by itself after a dropped connection and sends the last id it saw in a Last-Event-ID header. Your route reads it with c.req.header("Last-Event-ID"). A slot is ordered and the same on every server instance, so the route can compare it with the hub's newest slot: when the hub is not ahead, it sends nothing and waits for the next change, and when it is ahead, it sends one fresh snapshot. A frame the page already drew is never repeated, and a late frame from another instance is easy to refuse by comparing ids.
lamports is the SOL balance as a string of digits, because JSON has no 64-bit integer. amount is the token amount, read as a little-endian u64 at byte 64 of the account data, which is where an SPL token account keeps it (Token account layout decoder shows the rest). A token transfer changes amount and leaves lamports where they were, and the account still notifies.
The program, end to end
main.ts is the hub and one client in a single file, without Hono, so you can see the frames before you write the route. With no argument it finds a busy account itself. It lists the newest signatures that mention the USDC mint, reads those transactions as jsonParsed with maxSupportedTransactionVersion: 1, and picks the USDC token account that holds the most after its transaction. Mainnet carries v1 transactions, and a lower value answers -32015. The signature list comes from an address index of up to 30 days, so a signature can list while getTransaction answers null for it. The program takes the newest five and skips the nulls. Pass an address as the first argument to follow another account.
Install 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 CARBIUM_RPC_URL and CARBIUM_WS_URL default to the Carbium endpoints.
// I0064 · Hono server-sent account events// https://carbium.sh/library/integrate/hono-server-sent-account-events// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY, then run: node main.ts [account]"); process.exit(1);}const apiKey: string = key;const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey } }),);// One SSE frame. The id is the slot, so a client can order frames and drop stale ones.const frame = (event: string, slot: bigint, data: object) => console.log(`event: ${event}\nid: ${slot}\ndata: ${JSON.stringify(data)}\n`);// An SPL token account keeps its amount as a little-endian u64 at byte 64.const amountOf = (b64: string) => { const raw = Buffer.from(b64, "base64"); return raw.length >= 72 ? String(raw.readBigUInt64LE(64)) : null;};// The USDC token account holding the most after one of the newest USDC transactions.async function findBusyAccount(): Promise<string> { const sigs = await rpc.getSignaturesForAddress(address(USDC), { limit: 5 }).send(); const txs = await Promise.allSettled( sigs.filter((s) => !s.err).map((s) => rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()), ); let best: { account: string; amount: bigint } | undefined; for (const r of txs) { if (r.status === "rejected") { console.error("getTransaction failed:", r.reason instanceof Error ? r.reason.message : r.reason); continue; } const tx = r.value as any; // null when the ledger no longer holds an older signature for (const b of tx?.meta?.postTokenBalances ?? []) { if (b.mint !== USDC) continue; const k = tx.transaction.message.accountKeys[b.accountIndex]; const amount = BigInt(b.uiTokenAmount.amount); if (!best || amount > best.amount) best = { account: typeof k === "string" ? k : k.pubkey, amount }; } } if (!best) throw new Error("no USDC token account found; pass an account address"); return best.account;}async function main() { const account = process.argv[2] ?? (await findBusyAccount()); console.error("following", account); let last: bigint | undefined; const held: any[] = []; // notifications that arrive before the snapshot is in const change = (r: any) => { const slot = BigInt(r.context.slot); if (last !== undefined && slot <= last) return void console.error(`dropped stale frame at slot ${slot}`); last = slot; frame("change", slot, { account, lamports: String(r.value.lamports), amount: amountOf(r.value.data[0]) }); }; const snapshot = async () => { const { context, value } = await rpc.getAccountInfo(address(account), { encoding: "base64" }).send(); if (!value) throw new Error("account not found"); last = context.slot; frame("snapshot", context.slot, { account, lamports: String(value.lamports), amount: amountOf(value.data[0]) }); held.splice(0).forEach(change); }; const url = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh"); url.searchParams.set("api-key", apiKey); const ws = new WebSocket(url); ws.onopen = () => ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "accountSubscribe", params: [account, { encoding: "base64", commitment: "confirmed" }] })); ws.onmessage = (ev) => { const m = JSON.parse(String(ev.data)); if (m.error) console.error("accountSubscribe refused:", m.error.message); else if (m.method === "accountNotification") (last === undefined ? held : { push: change }).push(m.params.result); else if (m.result != null) snapshot().catch((e) => { console.error(e instanceof Error ? e.message : e); process.exit(1); }); }; ws.onerror = () => console.error("socket error"); ws.onclose = () => console.error("socket closed"); setTimeout(() => { ws.close(); process.exit(0); }, 20_000);}main().catch((e) => { console.error(e instanceof Error ? e.message : e); process.exit(1);});
run: node main.ts
It runs for about 20 seconds. First comes the snapshot frame, then a change frame each time the account is written. A notification whose slot is not above the last printed one goes to stderr as a stale drop. To move this into Hono, replace frame with a writeSSE call on every connected stream and replace the argument with a list your server fixes. A browser should never choose the address: each new one opens a subscription you pay for.
What opening costs
A WebSocket subscription costs credits to open by its filter weight, then 20 credits per MiB sent to you.
| Weight | Opens at | Filters |
|---|---|---|
| Light | 5 credits | slot, root, signature |
| Middle | 25 credits | account, logs with mentions, slot updates |
| Heavy | 200 credits | program, all logs, blocks, a transaction firehose |
accountSubscribe sits in the middle row. The charge is once per account on your one socket, so ten browsers or ten thousand leave it unchanged. The per-MiB charge applies to what Carbium sends your server and never to what your server sends browsers. A refused subscription costs nothing, and an accountSubscribe that never notified is refunded when it closes. Credits and rates are per account, and its keys share one budget.
Where it ends
- A plain SOL wallet sends nothing on accountSubscribe. Used as the subject, the page gets its snapshot and then silence. For a wallet, follow logsSubscribe with a mention and re-read getBalance; Wallet watch list at scale covers that route.
- The hub keeps the latest state per account and no history. A browser that was away through three changes receives the newest state in a single frame.
- The program ends when the socket closes. A long-running server has to reconnect, subscribe again and take a fresh snapshot, as in WebSocket keepalive and reconnect.
- Each Hono instance opens its own socket and holds its own memory. Slots are the same everywhere, so ids compare across instances, but every instance counts against the socket cap.
- Frames come at confirmed. If the page must never show a value that a dropped fork could take back, run the subscription and the read at finalized.
- Some proxies buffer a response or close an idle one. Send a comment line such as : ping on a timer, and check that your proxy passes the stream through.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The snapshot frame prints and no change frame ever follows. | The subject is a plain SOL wallet or an account nobody writes. A SOL wallet sends nothing on accountSubscribe. Pass an account that changes, such as a busy token account, or let the program find one. |
| The log shows accountSubscribe refused: followed by a message. | Read the message. Your plan caps sockets and subscriptions per account, so follow fewer accounts or raise the plan. A refused subscription costs nothing, and the others stay open. |
| The socket reports an error at once and no snapshot appears. | An unknown key gets a 401 before the handshake finishes. Check that CARBIUM_KEY holds the whole key and that CARBIUM_WS_URL, if set, is wss://services.carbium.sh. |
| getTransaction answers -32015 while looking for an account. | The transaction is a v1 transaction and the call left maxSupportedTransactionVersion out or set it to 0. Pass 1 in the config object. |
| The program stops with no USDC token account found. | All five newest signatures read back null or failed. Run it again a moment later, or pass an account address as the argument. |
| A snapshot read fails with HTTP 429 when several pages open together. | Each page is triggering its own read. Serve the snapshot from the hub's last frame, and let only the first subscription of an account call getAccountInfo. |
Questions
Why not open the WebSocket from the browser?
The key would travel to every visitor. Each page would also take a socket from the account's cap, and Free carries 5.
Why is the slot the event id?
It is ordered, it is the same on every server instance, and a notification already carries it. A page or a route can compare two ids and drop the older frame.
Do I have to use Hono?
No. main.ts uses no framework, and any server that can write event, id and data lines to an open response does the same job. Hono's streamSSE is one short way to write them.
Does EventSource reconnect on its own?
Yes. It waits a short delay, which the server can set with a retry: field, and sends the last id it saw in Last-Event-ID. Your route decides whether a new snapshot is needed.