Game state and player items
Read a player's items and your game's state accounts in one Solana call, at one slot, with a cost you can work out in advance. Includes a Node script that snapshots both and reports what changed since the last run.
What a game reads from the chain
An on-chain game keeps two kinds of data that a client needs. Game state is whatever your program stores in its own accounts: a match, a season, a loot table, a player profile. Player items are token balances. Each item is a mint, and a player's stack of it sits in a token account owned by that player's wallet. An NFT item is a mint with a supply of 1, so the same read shows a balance of 1.
To the node these are all accounts, so both come back from one method, getMultipleAccounts. How many accounts one screen needs, and how often you refresh them, decides what the game costs to run.
Writes need a signature. Minting, crafting and transferring an item are transactions that a wallet or your server signs, and the script below signs and sends nothing.
One call, one slot
`getMultipleAccounts` takes up to 300 pubkeys (100 below Pro) and charges 10 cells per pubkey. It answers with a context slot and every account as read at that slot, so a profile account and the item balances next to it agree with each other. Separate calls can straddle a slot, and then a screen shows an item that the state says was already spent.
Name the commitment on every call. The JSON-RPC server defaults to finalized, while @solana/kit 8.6.0 fills in confirmed when a call leaves it out, so code written with kit reads at confirmed unless you set it. The script sets confirmed in the call, which keeps the choice visible in the code. Compare slots only when they come from the same response, never across separate reads.
Budget for a lobby
Work the cost out before the first playtest. Each pubkey costs 10 cells, and a call whose request body is over 4 KiB adds one cell. The Cells column includes both.
| Screen | Pubkeys | Calls | Cells |
|---|---|---|---|
| One player: 3 state accounts and 20 items | 23 | 1 | 230 |
| A lobby of 8 players, 20 items each | 160 | 2 | 1601 |
| A leaderboard page of 100 players, 20 items each | 2000 | 20 | 20020 |
The 20 calls of the last row fit in one POST, because a JSON-RPC call can be a single call or a batch of up to 100. Batching cuts round trips and leaves the cells unchanged. Account reads are capped at 0.5, 15, 50 and 400 requests per second on Free, Dev, Business and Pro, and the plans run $0 with 500K credits once, $20 with 10M, $250 with 50M and $500 with 200M per month.
- Read the state accounts that the whole lobby shares once per refresh on your server, and send the result to every player.
- Read item balances only for players on screen, and page leaderboards at 100 players.
- Refresh on a change signal and use a timer only as the fallback.
For one balance in isolation see SPL token balance. When a refresh loop starts hitting 429, RPC rate-limit alerts covers what to watch.
A snapshot script
The script reads PLAYER, a comma-separated ITEM_MINTS, a comma-separated STATE_ACCOUNTS for your game's own accounts, and an optional GAME_DB file for the comparison. It builds one client with your key and sends every call to https://services.carbium.sh through it. For each item it derives the player's associated token account, puts the state accounts and the item accounts into one getMultipleAccounts call at confirmed, and prints the context slot.
// UC0010 · Game state and player items// https://carbium.sh/library/usecase/game-state-and-player-items// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: one consistent snapshot of a player's items and a game's state accounts.import { DatabaseSync } from "node:sqlite";import { createHash } from "node:crypto";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressEncoder, getProgramDerivedAddress } 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 url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const list = (name: string) => (process.env[name] ?? "").split(",").filter(Boolean);const player = process.env.PLAYER, mints = list("ITEM_MINTS"), states = list("STATE_ACCOUNTS");if (!player || !mints.length) { console.error("Set PLAYER (wallet) and ITEM_MINTS (comma-separated item mints)."); process.exit(1); }if (states.length + mints.length > 100) { console.error("getMultipleAccounts takes up to 100 pubkeys below Pro."); process.exit(1); }const owner = address(player);const TOKEN = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const ATA_PROGRAM = address("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");const enc = getAddressEncoder();const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const ataOf = async (mint: string) => (await getProgramDerivedAddress({ programAddress: ATA_PROGRAM, seeds: [enc.encode(owner), enc.encode(TOKEN), enc.encode(address(mint))] }))[0];// One call, one slot: state and items are read at the same point in the chain, at confirmed.const keys = [...states.map((s) => address(s)), ...(await Promise.all(mints.map(ataOf)))];const { context, value } = await rpc.getMultipleAccounts(keys, { encoding: "base64", commitment: "confirmed" }).send();console.log(`read ${keys.length} accounts at slot ${context.slot}`);const db = new DatabaseSync(process.env.GAME_DB ?? ":memory:");db.exec("CREATE TABLE IF NOT EXISTS seen (k TEXT PRIMARY KEY, v TEXT)");const prev = db.prepare("SELECT v FROM seen WHERE k = ?");const save = db.prepare("INSERT OR REPLACE INTO seen VALUES (?, ?)");const note = (label: string, k: string, v: string) => { const old = (prev.get(k) as { v: string } | undefined)?.v; save.run(k, v); console.log(label, v, old === undefined ? "(new)" : old === v ? "(unchanged)" : `(was ${old})`);};const bytes = (i: number) => { const a = value[i]; return a ? Buffer.from(a.data[0], "base64") : null; };states.forEach((s, i) => { const b = bytes(i); note(`state ${s.slice(0, 8)}`, s, b ? `${b.length}B ${createHash("sha256").update(b).digest("hex").slice(0, 12)}` : "missing");});mints.forEach((m, j) => { const b = bytes(states.length + j); // A token account keeps its balance as a u64 at bytes 64..72, in base units. note(`item ${m.slice(0, 8)}`, `${player}/${m}`, String(b && b.length >= 72 ? b.readBigUInt64LE(64) : 0n));});
run: CARBIUM_KEY=$CARBIUM_KEY PLAYER=<wallet> ITEM_MINTS=<mint1>,<mint2> STATE_ACCOUNTS=<state1> GAME_DB=game.db node main.ts
A token account holds the balance as an unsigned 64-bit integer at bytes 64 to 72. The script keeps it as a bigint in base units. An item minted with 0 decimals is a whole count. For any other, divide by the mint's decimals only when you display it.
Each line ends in (new), (unchanged) or (was N). State accounts are fingerprinted by their length and the first 12 hex characters of a SHA-256 of their data, so any changed byte shows. With GAME_DB set to a file, the next run compares against the last one. Without it the database lives in memory and every line reads (new). A missing account prints missing for state and 0 for an item, because an account that does not exist yet and a zero balance look the same to this script.
Change signals
A timer re-reads accounts that did not change. A WebSocket on wss://services.carbium.sh with ?api-key= in the URL tells you when to read. Open one socket per game server: connection and subscription counts are capped per account by tier, and Free carries 5 sockets.
- logsSubscribe streams transaction logs, all or by mention. A mention of your game program's address gives one notification per transaction that touches it. On each one, re-read the snapshot for the players involved.
- signatureSubscribe sends one confirmation for a signature and then ends. Use it to tell a player that the transaction they just signed landed.
- accountSubscribe sends account state on change, for accounts the stream carries. A plain SOL wallet stays silent, so for a SOL balance use logsSubscribe mentions plus getBalance.
A subscription opens at 5, 25 or 200 credits by filter weight and then costs 20 credits per MiB sent; a refused one is free. A signature filter sits in the lightest weight, an account or logs-mention filter in the middle, and a program or all-logs filter in the heaviest. The gRPC stream at https://services.carbium.sh:9443, with the key in the x-token header, opens on Dev, Business and Pro; Free is off.
Recent item history
To show a player what happened to an item, page getSignaturesForAddress for their token account at 50 cells a call, then read the transactions you need with getTransaction at 50 cells each. The pages come 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. For a permanent audit trail, write your own events table from the log notifications as they arrive.
Where it ends
- The script reads the mints you name. It does not discover what else a wallet holds, so keep the item list in your own catalog.
- Eight methods are not served and answer -32601, among them getProgramAccountsV2 and getTokenLargestAccounts. -32601 means method not found, so do not retry it. Rarity counts, leaderboards and the list of all players come from your own index, filled from the log notifications.
- The derivation uses the classic Token program. Items minted under Token-2022 use another program id in the derivation and read as 0 here.
- The script shows amounts only. Frozen or delegated flags, and the name and art of an item from its metadata account, are decoded in your own code.
- One call is consistent at one slot. Two calls are not, and state can move between them.
- History stops at 30 days.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The screen shows an item that the state says was already spent. | Read the state accounts and the item accounts in the same getMultipleAccounts call and compare the context slot of that one response. |
| Every item reads 0 for a player who owns it. | Check the owner program of the mint. Token-2022 items need that program id in the derivation. A token account made outside the associated-address rule is not found by derivation, so pass its address in STATE_ACCOUNTS. An account passed that way prints a length and hash fingerprint where an item line would show a balance. |
| A lobby refresh returns 429. | Each pubkey costs 10 cells. Refresh once per snapshot on the server and share the result, honour the retry-after value, and keep the refresh rate under your plan's account-read limit. |
| A call with more than 100 pubkeys is refused below Pro, and more than 300 on Pro. | Split the list into chunks of 100 and send the chunks as one JSON-RPC batch of up to 100 calls. |
| A reward is granted from a confirmed read and the player disputes it. | Read at finalized before value leaves the game. |
| A call that answered -32601 is retried in a loop. | Treat -32601 as final. Fix the method name or drop a method that is not served. |
Questions
Can one call return game state and player items together?
Yes. Both are accounts, so put your state accounts and the player's item token accounts in one getMultipleAccounts call. The response carries one context slot for all of them.
Which commitment should a game use?
The server defaults to finalized, and @solana/kit 8.6.0 fills in confirmed when a call leaves it out, so set it on purpose. Confirmed suits what a player sees, and finalized suits a reward or a withdrawal.
Do I need a subscription for each player?
No. Subscribe once per game server to logs that mention your program, and re-read the snapshot for the players in each notification. Free carries 5 sockets, and each subscription has its own credit cost.
Can I list every player of my game from the chain?
Not with getProgramAccountsV2, which is not served and answers -32601. Build the player list in your own index from the log notifications, and read each player's accounts by address.