library / Blockchain ideas / BI0014
Public chain stats page
A small server that keeps one WebSocket open, polls a few cached reads, holds the newest sample in memory and serves it as a page and as JSON. The cost per plan and a runnable main.ts come with it.
Who uses it
The stats page is a small public-good repository: a team publishes it and others fork it and host their own copy. A fork sets its own CARBIUM_KEY, installs the one dependency with npm install @solana/[email protected], runs node main.ts and puts its reverse proxy in front of the server. It answers one question for visitors: is the chain healthy right now? A docs site wants the answer in its footer. A support page links to it when someone asks why a transaction looks stuck.
The page is a read-only server with one job. It listens to one slot stream, polls a few cached reads on a timer and keeps the newest sample in memory. A visitor reads that sample from your server. Carbium sees the same stream and the same calls whether ten people or ten thousand open the page, so usage follows the sample interval and ignores the audience.
The code is one file on @solana/kit and what Node 24 ships, so a fork has almost nothing to install.
What it shows
Each sample is one row of ten fields. The page shows the newest row, and /history.json returns the last 720.
| Field | Where it comes from | What it tells a visitor |
|---|---|---|
| at | the server clock when the sample is built | the time of the sample |
| processed, confirmed, finalized | getSlot, called three times with the commitment named | the newest slot at each level |
| finalizedBehind | processed minus finalized | how far finalized trails the newest slot |
| slotsPerSecond | slotNotification messages counted over the sample window | about 5 when a slot lasts about 200 ms |
| rootBehind | slot minus root, from the same notification | how far the root the node reports trails its newest slot |
| core | solana-core in the getVersion reply | the software version of the node that answers |
| health | getHealth | ok when the node says it is healthy, otherwise the error message the node returned |
| streamMiB | bytes of every WebSocket message | a check on the credit estimate |
finalizedBehind is the raw difference. The three reads go out together but land at slightly different moments, so on mainnet today the field takes values from -1 to 1 and often reads -1; before 2026-10-21 it read about 32. Treat it as a check that the three levels sit within a slot of each other. The page shows it as it came.
The build
The server is read-only: no key pair, nothing signed or sent.
- Read CARBIUM_KEY and exit with a message when it is unset. RPC goes to https://services.carbium.sh with the key in x-api-key, and the WebSocket to wss://services.carbium.sh with the key as ?api-key=. CARBIUM_RPC_URL and CARBIUM_WS_URL override the two.
- Open one WebSocket and send slotSubscribe. Count each slotNotification and keep its slot and root. A refused subscription is free and prints a message.
- Every 5 seconds call getSlot at processed, confirmed and finalized, plus getVersion and getHealth, in parallel on one RPC client.
- Build the row, with the slot rate for that window, push it onto a list capped at 720 rows (an hour at this gap) and print it.
- Serve / (the page), /stats.json (the newest row) and /history.json (the list) on 127.0.0.1, port 8787 unless PORT says otherwise.
// BI0014 · Public chain stats page// https://carbium.sh/library/blockchainideas/public-chain-stats-page// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createServer } from "node:http";import { createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);const WS_URL = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");WS_URL.searchParams.set("api-key", key);const PORT = Number(process.env.PORT ?? 8787);const SAMPLE_MS = 5000; // five cached reads per sample, 1 req/s on averageconst history: Record<string, unknown>[] = [];let slotsSeen = 0;let windowStart = Date.now();let latestSlot = 0;let latestRoot = 0;let bytes = 0;function connect(): void { const ws = new WebSocket(WS_URL); ws.onopen = () => ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "slotSubscribe" })); ws.onmessage = (ev) => { const text = String(ev.data); bytes += Buffer.byteLength(text); const msg = JSON.parse(text); if (msg.id === 1 && msg.error) console.error(`subscribe refused: ${msg.error.message}`); if (msg.method !== "slotNotification") return; slotsSeen++; latestSlot = msg.params.result.slot; latestRoot = msg.params.result.root; }; ws.onclose = () => setTimeout(connect, 2000); ws.onerror = () => ws.close();}// Every getSlot call names its commitment: kit fills in confirmed, the server's own default is finalized.const slotAt = (commitment: "processed" | "confirmed" | "finalized") => rpc.getSlot({ commitment }).send();const ok = <T>(r: PromiseSettledResult<T>): T | null => (r.status === "fulfilled" ? r.value : null);const num = (v: bigint | null): number | null => (v === null ? null : Number(v));const CALLS = ["processed", "confirmed", "finalized", "getVersion", "getHealth"];async function sample(): Promise<void> { const out = await Promise.allSettled([ slotAt("processed"), slotAt("confirmed"), slotAt("finalized"), rpc.getVersion().send(), rpc.getHealth().send().catch((e) => (e instanceof Error ? e.message : String(e))), ]); out.forEach((r, i) => r.status === "rejected" && console.error(`sample failed (${CALLS[i]}):`, r.reason instanceof Error ? r.reason.message : r.reason)); const [processed, confirmed, finalized, version, health] = [ok(out[0]), ok(out[1]), ok(out[2]), ok(out[3]), ok(out[4])]; const seconds = (Date.now() - windowStart) / 1000; const row = { at: new Date().toISOString(), core: version?.["solana-core"] ?? null, health, processed: num(processed), confirmed: num(confirmed), finalized: num(finalized), finalizedBehind: processed === null || finalized === null ? null : Number(processed - finalized), // raw: can read 0 or dip below it slotsPerSecond: Number((slotsSeen / seconds).toFixed(1)), rootBehind: latestSlot - latestRoot, streamMiB: Number((bytes / 2 ** 20).toFixed(3)), }; slotsSeen = 0; windowStart = Date.now(); history.push(row); if (history.length > 720) history.shift(); // an hour at 5 s console.log(JSON.stringify(row));}const PAGE = `<!doctype html><meta charset="utf-8"><title>Chain stats</title><pre id="o">loading</pre><script>const t=async()=>{o.textContent=JSON.stringify(await(await fetch("/stats.json")).json(),null,1)};t();setInterval(t,5000)</script>`;const server = createServer((req, res) => { const json = req.url === "/stats.json" ? history[history.length - 1] ?? null : req.url === "/history.json" ? history : undefined; res.setHeader("content-type", json === undefined ? "text/html" : "application/json"); res.end(json === undefined ? PAGE : JSON.stringify(json));});server.on("error", (e) => console.error("http server:", e.message));server.listen(PORT, "127.0.0.1", () => console.log(`stats page on http://127.0.0.1:${PORT}/`));connect();setInterval(sample, SAMPLE_MS);
run: CARBIUM_KEY=<YOUR_KEY> node main.ts
Every getSlot call names its commitment. @solana/kit 8.6.0 fills in confirmed when a call leaves it out, while the JSON-RPC server's own default is finalized, so an unnamed call can return a different slot on a different client. Each call is settled on its own with Promise.allSettled. A call that fails sets its field to null and prints its name with the error, and the row is still built from the rest. getHealth is the exception: an unhealthy node answers it with an error, which is caught into the health field as the node's message, so that call never leaves null and never prints sample failed. The RPC client is created once and reused, because a cold connect pays the full handshake. The WebSocket address is built with new URL and the key is added with searchParams.set, so an override with a trailing slash or a path still gives a valid address. The close handler reconnects and subscribes again. For the public, put your reverse proxy in front of the server and let that proxy set the cache header.
What it costs
The subscription is billed in credits: a slot subscription opens at 5 credits, then costs 20 credits per MiB sent. A reconnect opens a new one at 5 credits. The cached reads (getSlot, getVersion, getHealth) cost 1 cell each, and each plan allows them at its own rate.
A slot notification is small. Assume 140 bytes per notification and replace it with the measured figure from the streamMiB field. At 5 notifications a second that is about 2.4 MiB an hour, which is about 48 credits an hour and about 34,600 credits over 30 days.
| Plan | Credits | Cached reads per second | Stream share over 30 days |
|---|---|---|---|
| Free ($0) | 500K once, at sign-up | 5 | about 6.9% of the grant |
| Dev ($20) | 10M per month | 30 | about 0.35% of the month |
| Business ($250) | 50M per month | 100 | about 0.07% of the month |
| Pro ($500) | 200M per month | 500 | about 0.017% of the month |
The five calls in a sample average 1 req/s at the 5-second gap, under every ceiling, and they go out together. A class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger, so the five calls of a sample go through together on every plan. Limits are per account, so other tools on the same keys draw on the same budget. Free carries 5 sockets and the page uses one.
What to add next
- History that survives a restart: write each row with node:sqlite as it is built. The list in memory is empty after a restart.
- A chart: draw finalizedBehind and slotsPerSecond from /history.json with a few lines of canvas.
- A status badge: an SVG route that turns red when health is not ok or finalizedBehind passes a limit you choose. For a message when a number crosses a line, see Slack slot-lag alerts.
- Push instead of poll: send each row to the page with server-sent events.
- Transactions per block: mainnet blocks carry no vote transactions since Alpenglow, so a count from a block holds no votes, and counts from before 2026-10-21 included them and do not line up. Look up the cost of the block methods in the RPC docs first.
Where it ends
- The page shows slots, commitments and the version of the node that answers. There is no TPS, no validator count and no epoch panel. Check the cost of the methods behind those in the RPC docs before adding them.
- Every number is one endpoint's view of the chain. core is the version that endpoint reports and says nothing about the rest of the cluster.
- Samples are 5 seconds apart. A stall shorter than that shows only as a lower slotsPerSecond.
- History lives in memory, so a restart empties it.
- A call that fails leaves null in its field for that row, and the console names the call. getHealth is the exception: its error goes into health as the node's message. finalizedBehind is null when either of its two slots is missing.
- A top-holders panel is out: getTokenLargestAccounts is not served and answers -32601. For one token's balance, see SPL token balance.
- A recent-activity panel for one address uses getSignaturesForAddress, which reaches back 30 days at most. An empty page past that is the index's age limit and says nothing about the address's first transaction.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The process exits at once and asks for CARBIUM_KEY. | Set the variable to your Carbium key in the environment that starts the server. The code never prints the key, so keep your own logs free of it too. |
| subscribe refused prints and slotsPerSecond stays at 0. | Check the key and that the account is under its socket cap (Free carries 5). A refused subscription is free, and the polled fields keep updating meanwhile. |
| sample failed prints with a 429. | Carbium absorbs the burst of five calls, so look at the shared budget. Other tools on the account draw on it, because the limit is shared across its keys, and a Free key can also run over its network's shared budget. Stop what else is calling, then widen SAMPLE_MS. |
| finalizedBehind reads 0, goes negative, or sits a slot either way. | The three reads happen at slightly different moments, so two can be equal, out of order or a slot apart. Show the number as it is, or clamp it at 0 in the page. |
| sample failed mentions -32601 after you add a method. | -32601 is method not found: the method is misspelt or not served. Do not retry it. Check the name against the RPC docs. |
| The page shows null when you open it. | The first row is built 5 seconds after the start, and /stats.json answers null until then. The page refetches every 5 seconds, so the row appears within about 10 seconds with no reload. |
Questions
Does each visitor cost credits?
No. A visitor reads the newest sample from your server's memory. Carbium sees one stream and one set of reads per sample interval, however many people open the page.
What does rootBehind measure?
It is the newest slot minus the root, both taken from one slotNotification. The root is the slot the node treats as settled, so the field shows how far that point trails the newest slot. Both numbers come from the same message, so it does not go negative the way finalizedBehind can.
How often can it sample?
On Free keep the 5-second gap, since a 1-second gap averages 5 req/s, the whole Free rate for cached reads, which leaves nothing for other tools on the account. On Dev, which allows 30, the same 1-second gap uses one sixth of the rate.
Will this run on the Free plan?
Over 30 days the stream uses about 34,600 credits at the assumed message size, about 6.9% of the 500K grant. The five polled reads in each sample draw credits too, so the table column is the stream's share alone. The grant comes once at sign-up, and the streamMiB field shows the real stream total.
Why is `slotsPerSecond` about 5?
A slot is about 200 ms since the Alpenglow switch, which is 5 slots a second. A figure well under that can mean the cluster skipped slots, since a skipped slot sends no slotNotification, or that the stream dropped notifications or reconnected during the window.