library / Blockchain ideas / Games / BI0148
Chain clock drift meter
Block time is an estimate the network agrees on, so it cannot seed a fair draw. This job reads the chain clock with getSlot and getBlockTime, prints how far it runs from your wall clock, and gives rounds a timing base they can check.
Who uses it
A team that runs timed rounds needs to see how the chain clock moves before it writes a deadline. A round that closes on block time expects a set number of seconds per slot. When the clock runs ahead or behind the wall clock, a countdown on the player's screen and the program disagree about when a round ended.
The second reader is a team that wants a random draw from the chain. A common idea is to hash the block time and use the result as a seed. Reading the drift does not make that idea safe. The game does not control block time, and anyone reading the chain sees the same value the moment the block lands.
For a draw, use a commit-reveal scheme or a verifiable random source, and keep block time for deadlines. For turning a slot into a calendar date, the slot to timestamp conversion covers the arithmetic. The meter below sizes the grace window that a deadline needs.
What it shows
Each sample prints one line. The table lists what each number is and where it comes from.
| Value | Where it comes from | Example |
|---|---|---|
| Head slot | getSlot at confirmed commitment | a slot number that rises about five times a second |
| Block time | getBlockTime on the newest slot that has one | Unix seconds, whole numbers |
| Drift | block time minus the wall clock, read after the calls return | -1.0 s when the chain reads one second behind |
| Slots per second | slot change over the wall time between two samples | about 5 |
| Chain seconds per wall second | block time change over the same wall time | about 1.00 |
Block time counts whole seconds, so a five-second gap moves the ratio in steps of 0.2. Read the ratio over several minutes before you treat it as a trend.
A slot with no block time is normal, because a skipped slot never gets a block. The code steps back up to ten slots and prints the slot it used, so the gap shows in the output.
The build
The program is one file that uses @solana/kit and the global fetch of Node 24. It reads the chain and writes nothing: no key pair, no signing, no transaction sent.
- Create one client for https://services.carbium.sh and send the key in the x-api-key header. Connections stay open for 600 s, so the one client is reused for every call.
- Read the head slot with getSlot at confirmed commitment. The call names the commitment, so it does not wait on the client default.
- Walk back from the head until getBlockTime returns a time.
- Read the wall clock after both answers come back, then keep the pair.
- Wait five seconds, sample again, and print the drift and the two rates between the samples.
// BI0148 · Chain clock drift meter// https://carbium.sh/library/blockchainideas/chain-clock-drift-meter// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createDefaultRpcTransport, createSolanaRpcFromTransport, type Slot } from "@solana/kit";const token = process.env.CARBIUM_KEY;if (token === undefined || token === "") { console.error("CARBIUM_KEY is missing. Export it, then start the meter again."); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": token }, }),);const rounds = Math.max(1, Number(process.argv[2] ?? 3));const gapMs = 5000;const maxSkips = 10n;const sleep = (ms: number) => new Promise<void>((done) => setTimeout(done, ms));// Walk down from the head; the first slot with a recorded block time wins.async function stampFrom(head: bigint): Promise<{ slot: bigint; time: bigint }> { for (let offset = 0n; offset < maxSkips; offset++) { const probe = head - offset; const seconds = await rpc.getBlockTime(probe as Slot).send(); if (seconds !== null) return { slot: probe, time: seconds }; } throw new Error(`no block time within ${maxSkips} slots of ${head}`);}let previous: { slot: bigint; time: bigint; at: number } | undefined;for (let i = 0; i < rounds; i++) { if (i > 0) await sleep(gapMs); try { const head = BigInt(await rpc.getSlot({ commitment: "confirmed" }).send()); const { slot, time } = await stampFrom(head); const at = Date.now(); const drift = Number(time) - at / 1000; let line = `head ${head} block ${slot} time ${time} drift ${drift.toFixed(1)} s`; if (previous) { const secs = (at - previous.at) / 1000; const slotRate = Number(slot - previous.slot) / secs; const chainRate = Number(time - previous.time) / secs; line += ` | slots/s ${slotRate.toFixed(2)} chain s per wall s ${chainRate.toFixed(2)}`; } console.log(line); previous = { slot, time, at }; } catch (failure) { console.error("sample failed:", failure instanceof Error ? failure.message : failure); }}
run: CARBIUM_KEY=<YOUR_KEY> node main.ts 3
The program takes three samples by default, about ten seconds, and exits. Pass a count as the first argument to watch for longer. A skipped slot adds a few calls for the walk back, and the limits page explains how bursts are counted.
What it costs
Each sample is two reads, so a meter at five-second gaps makes 720 samples an hour. getSlot is one of the cheap cached reads and costs one cell each. The table gives the per-second rate of those reads on each plan, with the monthly credits.
| Plan | Price | Cheap cached reads per second | Credits |
|---|---|---|---|
| Free | $0 | 5 | 500K once, at sign-up |
| Dev | $20 | 30 | 10M per month |
| Business | $250 | 100 | 50M per month |
| Pro | $500 | 500 | 200M per month |
Credits meter RPC work, and unspent credits stay. An account's keys share one budget, so a meter on a shared key draws on the same budget as the team's other tools. On Free, one meter at five-second gaps stays under the 5 req/s rate, except when a skipped run adds calls for the walk back. Check the credit count against the plan's monthly figure before you leave a meter running for a month.
Where it ends
- Block time is in whole seconds and is an estimate. The meter gives a clock reading to the second, not a time you can enforce to the second.
- It is not a random source. A value that every reader sees before the next move can be predicted, so no draw should rest on it.
- Since the Alpenglow switch on mainnet, a slot is about 200 ms and finalized sits 0 to 1 slot behind processed. The meter reads the head at confirmed, so the clock it shows is the recent one the cluster has agreed on, not a finalized clock.
- A skipped slot is walked back at most ten slots. A longer run of skips fails that sample, and the meter prints the error and keeps going.
- Three samples are a snapshot. A drift trend needs minutes of samples and a saved log of the output.
- The meter reads the chain only. It does not sign, send or check any wallet.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The drift sits at a steady few seconds from the first sample. | Check the host clock first. A wall clock off by seconds shows up as drift the chain did not cause, so sync the host clock before you trust the chain's reading. |
| Every sample fails with no block time within 10 slots. | The head is stalled or the run of skipped slots is longer than the walk back. Run it again later, and check that the head number moves between two runs. |
| The meter answers 429. | Wait a few seconds and run it again. A call over its rate waits once and is served if its cells refill within a second; past that it gets 429 with a retry-after hint. The account's keys share the budget, so stop other tools on the same key while you watch. |
| The slots-per-second and ratio columns print wild values. | Two samples are too close together. Block time has whole seconds, so keep the gap at five seconds or more. |
| The program exits with a message about the key. | Set CARBIUM_KEY in the environment for the run. The code reads it from there and never prints it. |
Questions
Can I use the block timestamp as a random seed?
Not for a draw that someone could win. Block time is an estimate the network agrees on, so every reader sees the same value, and a seed built from it can be predicted. Use commit-reveal or a verifiable random source for the draw, and keep block time for deadlines.
Do I need my own RPC node to read the chain clock?
No. Both reads go to services.carbium.sh over HTTPS with one key, and the one client is reused across samples.
How does the drift number help a game?
It sizes the grace window. When the chain clock reads a few seconds behind your wall clock, a deadline shown to players should allow for that gap, so nobody loses a round to the difference.
Why does the meter read at confirmed and not finalized?
The head reading only needs to be recent and agreed by most of the cluster, and the code names the commitment so the call does not depend on a default. A clock reading does not need the wait a payment needs.