library / Integrations / I0003
Svelte wallet button
A Node module watches one wallet over Carbium's WebSocket, re-reads the SOL balance on each transaction, and exposes it as a Svelte store. A SvelteKit route streams it to a wallet button that connects through the Wallet Standard.
What the button does
A wallet button has three jobs: connect to a browser wallet, show the connected address, and show its SOL balance as it changes. The connection comes from the Wallet Standard, which the common Solana browser wallets implement. The balance comes from Carbium, read with @solana/kit 8.6.0. The part a Svelte app needs help with is a balance that updates when a transaction touches the wallet.
- A server module, main.ts below, reads the balance over RPC and watches the wallet over a WebSocket. It exposes a Svelte store: subscribe(run) calls run with the current value and again on each change. A SvelteKit route turns that store into a server-sent event stream.
- The browser opens that stream with EventSource and never sees the key. A small client store wraps the stream, and the button component reads it as $balance.
The Solana side: one balance, kept current
Carbium's RPC and WebSocket endpoints are https://services.carbium.sh and wss://services.carbium.sh. The module reads the two base URLs from CARBIUM_RPC_URL and CARBIUM_WS_URL, with those values as the defaults, and sends the key on each call the way each transport expects.
A plain SOL wallet gives accountSubscribe nothing to say, so the store subscribes with logsSubscribe and a mentions filter, and each notification triggers one getBalance read. That is the combination Carbium's WebSocket service recommends for this case. The notification carries no balance, only the news that a transaction touched the address. Failed transactions mention the wallet too, so now and then a read returns the same number as the last one.
Both calls run at confirmed commitment, which the module sets by hand on the getBalance read and on the subscription. The notification and the read are still two calls, so the number on screen is the balance at the slot of the read, and the store carries that slot next to it.
A busy address would start a burst of reads from a burst of notifications. The store runs one read at a time and, if more notifications land meanwhile, runs one more when the first returns. When the socket drops, it reconnects with a growing delay of up to 30 seconds and reads again once it is back, because a change during the gap sent no notification. Every read goes through one client built at start.
The store
Install with npm install @solana/[email protected], set "type": "module" in package.json, and use Node 24, which strips the types on load. CARBIUM_KEY is required, and the file exits with a message when it is unset. Everything down to the closing brace of balanceStore is the module you copy into your SvelteKit server code. In a server module, swap process.exit(1) for a thrown error, because exiting on import stops the whole SvelteKit server. The last lines are a command-line demo to delete there.
// I0003 · Svelte wallet button// https://carbium.sh/library/integrate/svelte-wallet-button// 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."); 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);type Balance = { lamports: bigint; slot: bigint };const sol = (l: bigint) => `${l / 1_000_000_000n}.${(l % 1_000_000_000n).toString().padStart(9, "0").slice(0, 4)} SOL`;const report = (e: unknown) => console.error("balance read failed:", e instanceof Error ? e.message : e);// A Svelte store: subscribe(run) calls run now and on every change, and returns the unsubscribe function.export function balanceStore(owner: string) { const who = address(owner); const subs = new Set<(b: Balance | null) => void>(); let value: Balance | null = null; let ws: WebSocket | undefined; let retry = 0; let busy = false; let dirty = false; // One read in flight at a time; a notification that lands meanwhile asks for one more. const read = () => { if (busy) { dirty = true; return; } busy = true; rpc.getBalance(who, { commitment: "confirmed" }).send().then((r) => { value = { lamports: r.value, slot: r.context.slot }; subs.forEach((run) => run(value)); }, report).finally(() => { busy = false; if (dirty) { dirty = false; read(); } }); }; const open = () => { const s = (ws = new WebSocket(wsUrl)); s.onopen = () => { if (retry) read(); // catch up on what the gap hid retry = 0; s.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "logsSubscribe", params: [{ mentions: [who] }, { commitment: "confirmed" }] })); }; s.onmessage = (e) => { const m = JSON.parse(String(e.data)); if (m.error) console.error("subscribe refused:", m.error.code, m.error.message); else if (m.method === "logsNotification") read(); }; s.onerror = () => console.error("socket error"); s.onclose = () => { if (ws === s && subs.size) setTimeout(() => ws === s && subs.size && open(), Math.min(30_000, 1000 * 2 ** retry++)); }; }; return { subscribe(run: (b: Balance | null) => void) { subs.add(run); run(value); if (subs.size === 1) { read(); open(); } return () => { subs.delete(run); if (!subs.size) { const s = ws; ws = undefined; s?.close(); } }; }, };}const owner = process.argv[2];if (owner) { const short = `${owner.slice(0, 4)}..${owner.slice(-4)}`; balanceStore(owner).subscribe((b) => { if (b) console.log(`${short} ${sol(b.lamports)} at slot ${b.slot}`); });} else { console.error("Usage: node main.ts <wallet address>");}
run: node main.ts <wallet address>
Run it with an address that transactions touch every few seconds, for example 96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5, a public tip account that a steady stream of transactions pays into. It prints the balance with the slot of the read, then prints again after each transaction that mentions the address, so within the first seconds you see lines that a logsNotification triggered. Stop it with Ctrl-C.
The Svelte side: route, store, button
Save the copied module as src/lib/server/balance.ts. The route in src/routes/balance/[address]/+server.ts starts with import { balanceStore } from "$lib/server/balance". Its GET handler checks the path parameter with address() from Kit and returns a Response whose body is a ReadableStream with the header content-type: text/event-stream. In its start, it subscribes to the store for that address and writes data: plus the JSON of { lamports, slot } and a blank line on every value. The store calls run(null) straight away, before the first read returns, so skip null before you read lamports and slot, or the bigint-to-string step throws on the first value. Convert both bigints to strings, because JSON.stringify throws on a bigint. In its cancel, it calls the unsubscribe function. Keep a Map from address to store on the server and count the clients per address, so a hundred open tabs on one wallet share one socket, and drop the entry at zero.
On the client, readable(null, (set) => { const es = new EventSource(url); es.onmessage = (e) => set(JSON.parse(e.data)); return () => es.close(); }) gives a store that opens the stream when the first component subscribes and closes it after the last one leaves. EventSource reconnects by itself when the connection drops.
The button calls getWallets() from @wallet-standard/app, lists the wallets that support standard:connect and whose chains include solana:mainnet, so wallets for other chains stay out of the list, and on click calls its connect(). It returns the accounts, and accounts[0].address is a base58 string. Keep it in $state, build the client store from it, and render the short address with $balance beside it. A second click calls standard:disconnect where the wallet has it and clears the state, which closes the stream. Lamports become SOL by dividing by 1,000,000,000, as sol() in the module does with bigint arithmetic, truncated to four decimals.
What it uses against your limits
| Piece | What it uses | Carbium limit that applies |
|---|---|---|
| Balance read | One getBalance per burst of notifications, plus one on start and one on each reconnect. | The account's request rate, shared by all its keys. |
| Watch | One logs-mentions subscription on one socket for each watched address. | Opens at 25 credits, then 20 credits per MiB sent. Sockets are capped per account by tier, and Free carries 5. |
A subscription that is refused costs nothing. If a read fails, the store logs it and tries again on the next notification.
Where it ends
- It shows SOL only. A token balance needs token account reads, which SPL token balance covers.
- It signs and sends nothing. The connect call yields an address, and a transaction goes through the wallet's own signing methods, which this store leaves alone.
- The route needs a server runtime, because EventSource needs a response that stays open. A fully static build of SvelteKit cannot host it.
- The address comes from the browser, so the route takes a visitor's word for which wallet is theirs. Each address sent costs you a socket, and Free has 5. Cap the addresses per client and in total, or the allowance is gone at once.
- One address holds one socket. A page that watches many wallets needs several subscriptions on one shared socket, which this store does not do.
- A change that no transaction caused would not be announced. The re-read after a reconnect and the next notification catch it up.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The log shows balance read failed and the button never gets a number. | The key is wrong in the server's environment. RPC calls take it in the x-api-key header. The route runs on the server, so read the key from the server's environment and never from a PUBLIC_ variable, which SvelteKit ships to the browser. |
| The balance shows once and then stops updating, and the log shows subscribe refused with a code and a message. | The store reads the balance once at start whether or not the subscription works, so that first number appears and no notification follows. The log prints the error code and message the server returned, so read them. If the message points at a limit, remember that Free carries 5 sockets. Free the socket of an address nobody watches, or move to a plan with more sockets. The refused attempt is free. |
| The log repeats socket error and the store keeps retrying. | The WebSocket handshake fails. Check that CARBIUM_WS_URL is a wss:// URL and that the key is valid. The module sets ?api-key= itself and overwrites any api-key already in that URL. |
| The log shows new balances, but the page does not update. | A proxy in front of the app is buffering the stream. Send cache-control: no-cache and, behind nginx, x-accel-buffering: no on the response, and check that the route returns the stream without waiting for it to end. |
| The route throws Do not know how to serialize a BigInt. | lamports and slot are bigints. Convert both with toString() before JSON.stringify, and parse them back to bigint in the client only if you need arithmetic. The same error on the very first value means the route did not skip the initial null. |
| The log fills with failed reads on a busy wallet, and the balance trails. | The account is over its rate limit. The store already runs one read at a time. Lower the other traffic or move to a plan with a higher rate. |
Questions
Why not `accountSubscribe` on the wallet?
For a plain SOL wallet Carbium's accountSubscribe stays silent. Logs that mention the wallet plus a getBalance read give you the same news.
Can the browser call Carbium directly?
Keep the calls on the server. RPC calls carry the key in the x-api-key header and the socket takes it as ?api-key= in the URL, so a key placed in browser code ships to every visitor.
Does Kit connect the wallet?
No. @solana/kit has no connect call, so the Wallet Standard does the connecting and Kit does the balance read. The two meet at the address string.
Does the store work in Svelte 4?
The store contract is the same in Svelte 4 and 5. The component code differs: Svelte 4 uses on:click where Svelte 5 uses onclick, and Svelte 4 keeps the address in a plain let where Svelte 5 uses $state.