services
Get a key

library / Blockchain ideas / BI0009

Live chain-state game

A game whose world is a set of mainnet accounts. One slot subscription sets the tick, one finalized read sets the state, and each change becomes a game event. Runnable code and the cost per plan are included.

By Carbium · Games · BI0009 · updated 2026-11-22

01

Who uses it

Two groups want this loop. The first builds a game whose rules live in an on-chain program: a board, a creature or a plot of land, each one an account the program owns. Players send moves as transactions, and every screen needs to show the result. The second adds a spectator layer to a game that already exists, such as a live scoreboard, a stream overlay or a map that lights up when a tile changes.

A hackathon crew can start before any program exists. Run the file with no arguments and it watches the Clock sysvar, which changes every slot, so a front end has a moving world to draw. Add a token mint or your game's accounts when you have them.

02

What the game sees

Slots set the turn length. Since the Alpenglow switch on mainnet (2026-10-21) a slot is about 200 ms, so a tick of 25 slots is about 5 seconds, a pace a player can follow. The file computes the tick as Math.floor(slot / 25), so a restart or a second copy of the server lands on the same tick with no counter to save.

Accounts set the world. Each tick the file reads every watched account in one getMultipleAccounts call, hashes the data and compares lamports and hash with the previous tick. A difference is a move, and a client reacts to four events.

EventWhenWhat a client does
startfirst read of an accountdraws the initial board
MOVElamports or data hash differs from the last readanimates the change and adds one to that account's move count
tickevery new block of 25 slotsrefreshes the scoreboard
missingthe account does not exist at that slotshows an empty cell

The read asks for finalized by name, because @solana/kit 8.6.0 fills in confirmed when a call leaves commitment out. Finalized sits 0 to 1 slots behind processed, so a game that cannot take back a turn can show it without making players wait. Pick one level and use it for the whole board.

03

The build

  1. Open one WebSocket to wss://services.carbium.sh with the key as ?api-key=. The key can also travel as the subprotocol api-key.<YOUR_KEY>.
  2. Send slotSubscribe. The reply carries the subscription id, or an error if the subscription is refused (a refusal is free).
  3. On each slotNotification, derive the tick. When it is higher than the last one, run one turn.
  4. A turn calls getMultipleAccounts on https://services.carbium.sh with the key in x-api-key, at finalized, base64 encoded.
  5. Compare each account with the last read, print a MOVE for every change and update the move counts.
  6. On a 429 the turn is skipped and the next tick reads again. The comparison runs against the last successful read, so a skipped turn shows up as one larger change.

Pass addresses as arguments: node main.ts <ADDRESS> <ADDRESS>.

main.ts
// BI0009 · Live chain-state game// https://carbium.sh/library/blockchainideas/live-chain-state-game// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, isSolanaError, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR } from "@solana/kit";import { createHash } from "node:crypto";const key = process.env.CARBIUM_KEY;if (!key) {  console.error("Set CARBIUM_KEY to your Carbium API key.");  process.exit(1);}// The Clock sysvar changes every slot, so it shows the loop working; pass your game's accounts as arguments.const CLOCK = "SysvarC1ock11111111111111111111111111111111";const board = (process.argv.length > 2 ? process.argv.slice(2) : [CLOCK]).map((a) => address(a));const TICK_SLOTS = Number(process.env.TICK_SLOTS ?? 25); // about 5 s at 200 ms a slotconst WS_URL = `${process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh"}/?api-key=${key}`;const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",    headers: { "x-api-key": key },  }),);const last = new Map<string, string>();const moves = new Map<string, number>();let lastTick = -1;let busy = false;async function turn(tick: number): Promise<void> {  if (busy) return;  busy = true;  try {    // finalized by name: kit would fill in confirmed, and a game turn should not roll back.    const res = await rpc.getMultipleAccounts(board, { commitment: "finalized", encoding: "base64" }).send();    const slot = res.context.slot;    res.value.forEach((acc, i) => {      const id = board[i];      const now = acc        ? `lamports ${acc.lamports} data ${createHash("sha256").update(acc.data[0], "base64").digest("hex").slice(0, 8)}`        : "missing";      const before = last.get(id);      last.set(id, now);      if (before === undefined) console.log(`start slot ${slot} ${id.slice(0, 8)} ${now}`);      else if (before !== now) {        moves.set(id, (moves.get(id) ?? 0) + 1);        console.log(`MOVE  slot ${slot} ${id.slice(0, 8)} ${before} -> ${now}`);      }    });    const score = Object.fromEntries([...moves].map(([k, v]) => [k.slice(0, 8), v]));    console.log(`tick ${tick} slot ${slot} moves ${JSON.stringify(score)}`);  } catch (e) {    if (isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) && e.context.statusCode === 429) {      console.log(`tick ${tick} skipped: rate limited, retry-after ${e.context.headers.get("retry-after") ?? "?"} s`);    } else console.error("read failed:", e instanceof Error ? e.message : e);  } finally {    busy = false;  }}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 msg = JSON.parse(String(ev.data));    if (msg.id === 1) {      console.log(msg.error ? `subscribe refused: ${msg.error.message}` : `subscribed, id ${msg.result}`);      return;    }    if (msg.method !== "slotNotification") return;    const tick = Math.floor(msg.params.result.slot / TICK_SLOTS);    if (tick > lastTick) {      lastTick = tick;      void turn(tick);    }  };  ws.onclose = () => setTimeout(connect, 2000);  ws.onerror = () => ws.close();}connect();

run: CARBIUM_KEY=<YOUR_KEY> node main.ts

A busy flag keeps two reads from overlapping, and the RPC client is created once and reused. The close handler reconnects and subscribes again. TICK_SLOTS sets another turn length.

04

What it costs

The slot subscription opens at 5 credits, the lightest class, then costs 20 credits per MiB sent. The account read costs 10 cells per pubkey, and getMultipleAccounts takes up to 300 pubkeys (100 below Pro).

Slot notifications arrive about 5 times a second. At an assumed 100 bytes each that is about 1.7 MiB an hour, or about 40 credits for the first hour, which no plan notices. Measure the real size before you budget.

At one tick every 5 seconds the file makes 0.2 calls a second, 720 an hour. Each plan has a ceiling for a one-pubkey account read.

PlanCreditsOne-pubkey read ceiling
Free ($0)500K once, at sign-up0.5 req/s
Dev ($20)10M per month15 req/s
Business ($250)50M per month50 req/s
Pro ($500)200M per month400 req/s

Each added pubkey adds 10 cells to the call, so a board of 30 accounts is a 300 cell call. Check a large board against your plan, and lengthen TICK_SLOTS if the door pushes back.

Limits are per account, so other tools on the same keys share the budget. Free carries 5 sockets and the game server uses one. Put your own server between Carbium and the players' browsers: one socket and one read loop then feed any number of screens.

05

What to add next

  • A browser view: serve the board and the last 100 events from a small HTTP server and push them with server-sent events.
  • Move confirmations: when a player sends a move, signatureSubscribe on its signature sends one confirmation and ends, so the client can show pending, then done. Sending costs 20 cells without preflight and 70 with it.
  • Player balances: accountSubscribe stays silent for a plain SOL wallet, so track one with logsSubscribe mentions plus getBalance. For token rewards see SPL token balance.
  • A bigger board: the gRPC stream at https://services.carbium.sh:9443 opens on Dev, Business and Pro, and Free is off. For feed health, see Slack slot-lag alerts.
06

Where it ends

  • The file samples once per tick. An account that changes twice inside a tick shows one MOVE with the final values.
  • A hash says data changed and nothing about what it means. To show a creature's health, decode the account with your program's layout.
  • Nothing here signs or sends. Players' wallets send moves, and fairness is your program's job; the file shows what the chain holds.
  • getSignaturesForAddress on a state account lists past moves for a restart backfill, from Carbium's own address index, which keeps up to 30 days. An empty page past that is the index's age limit and says nothing about the account's first transaction.
07

When it goes wrong

what goes wrongwhat to do
The subscribe reply is an error, or the socket closes straight away.Check CARBIUM_KEY and that the account is under its socket cap (Free carries 5). A refused subscription is free, so a refused retry costs nothing.
Only start lines print and no MOVE follows.Your accounts may be quiet. Run with no arguments: the Clock sysvar changes every slot, so a MOVE should print each tick. If it does, the loop works and the addresses are the question.
Ticks are skipped with a 429.Read the retry-after seconds the file prints, then lengthen TICK_SLOTS or watch fewer accounts. The limit is shared across the account's keys, so check what else is calling.
An account that should be idle prints a MOVE every tick.The hash covers the whole account, including any timestamp or counter your program writes on each instruction. Hash only the bytes that matter.
getMultipleAccounts fails on a large board.The call takes up to 300 pubkeys (100 below Pro). Split the board into several calls, and remember each pubkey costs 10 cells.
A wallet shows a move before the board does.The board reads finalized, which sits 0 to 1 slots behind processed. The MOVE line carries the slot of the read, so compare it with the slot of the transaction. A larger gap usually means the wallet is showing its own pending state.
08

Questions

Do I need my own node to read game state?

No. The slot stream arrives on wss://services.carbium.sh and the account read on https://services.carbium.sh, with one key for both.

Why take the tick from the slot instead of a timer?

A timer drifts from the chain and starts at zero after a restart. A tick computed from the slot number is the same on every server and every restart, so two copies of your server agree on which turn it is.

Can accountSubscribe push the board instead of a read each tick?

For accounts the stream carries, yes. Polling fits this game because one batched read covers the whole board with one cost and one code path, and a plain SOL wallet stays silent on accountSubscribe anyway.

Will it run on the Free plan?

For a small board, yes. One socket fits within Free's 5, the slot stream is about 40 credits an hour at 100 bytes a notification, and a one-pubkey read every 5 seconds is 0.2 req/s against a 0.5 req/s ceiling.