library / Use cases / Gaming / UC0129
Player deposit balance sync
Sync on-chain deposits into in-game balances after the player signs once at login. A Node script reads SOL and USDC balances at finalized and tracks new deposit transactions by signature, with the polling and subscription cost per plan.
Sign once, then only read
A wallet signature proves control of a key at one moment. A dapp asks for it once at login, verifies it on the server, and issues its own session. Balances need no further signature, because they are public account data: your server reads them by address for as long as the session lasts, and the wallet prompt only comes back when the player moves funds.
That split turns the deposit job into a read job. The player signs a transfer in their own wallet to an address you control. Your side watches that address, decides when a deposit counts, and credits the in-game balance. The sync only reads: it signs and sends nothing. Payouts back to the player are a separate job with a separate key. Game state and player items covers how a game reads the rest of what it keeps on chain.
What the ledger holds
The sync keeps four things per player, in a small local database:
- SOL in lamports from getBalance, held as a bigint so large amounts never lose digits.
- The deposit token's total across every token account the wallet owns for that mint, because a wallet can own more than one.
- The newest signature already processed for each watched address, so the next run asks only for what came after it.
- A table keyed by signature, so a retried run cannot book the same transaction twice.
The balance tells you how much changed, and the signature list tells you which transactions did it. You need both. A difference alone cannot separate one large deposit from two small ones, or a deposit from a withdrawal in the same interval.
Token deposits add a wrinkle. A transfer into an existing token account lists the token accounts and the sender's authority, never the receiving wallet, so the wallet's own signature list misses it. The script watches the wallet and each of its token accounts.
The sync script
The script takes a wallet as its first argument. With none, it picks the fee payer of a recent USDC transaction so the run has something real to read. It makes its calls through one client built with your key against https://services.carbium.sh. Every call names finalized, because a credit the player can spend should not be able to roll back, and @solana/kit 8.6.0 would fill in confirmed for a call that left the level out. Finalized trails processed by 0 to 1 slots, so a deposit waits a slot at most before it counts.
// UC0129 · Player deposit balance sync// https://carbium.sh/library/usecase/player-deposit-balance-sync// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MIT// Read-only: sync a player's deposit balances and new deposit transactions into a local ledger.import { DatabaseSync } from "node:sqlite";import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } 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 rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const USDC = address("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");const commitment = "finalized" as const; // credit only what cannot roll back// With no argument, take the fee payer of a recent USDC transaction as the deposit wallet.async function pickWallet(): Promise<string> { const given = process.argv[2]; if (given) return given; for (const s of await rpc.getSignaturesForAddress(USDC, { limit: 5, commitment }).send()) { const tx = await rpc.getTransaction(s.signature, { encoding: "json", maxSupportedTransactionVersion: 1, commitment }).send(); const keys = (tx as unknown as { transaction?: { message?: { accountKeys?: string[] } } } | null)?.transaction?.message?.accountKeys; if (keys?.[0]) return keys[0]; } throw new Error("no recent USDC transaction found; pass a wallet address");}const wallet = await pickWallet();const db = new DatabaseSync("deposits.db");db.exec(`CREATE TABLE IF NOT EXISTS balance (asset TEXT PRIMARY KEY, amount TEXT); CREATE TABLE IF NOT EXISTS cursor (addr TEXT PRIMARY KEY, newest TEXT); CREATE TABLE IF NOT EXISTS seen (sig TEXT PRIMARY KEY, addr TEXT, slot INTEGER)`);const one = (sql: string, a: string) => db.prepare(sql).get(a) as Record<string, string> | undefined;const [sol, tok] = await Promise.allSettled([ rpc.getBalance(address(wallet), { commitment }).send(), rpc.getTokenAccountsByOwner(address(wallet), { mint: USDC }, { encoding: "jsonParsed", commitment }).send(),]);const show = (asset: string, amount: bigint) => { const old = one("SELECT amount FROM balance WHERE asset = ?", asset)?.amount; db.prepare("INSERT OR REPLACE INTO balance VALUES (?, ?)").run(asset, String(amount)); console.log(`${asset} ${amount}`, old === undefined ? "(first sync)" : `(${amount - BigInt(old)} since last sync)`);};console.log(`deposit wallet ${wallet}, reads at ${commitment}`);const watch: string[] = [wallet];if (sol.status === "fulfilled") show("SOL lamports", sol.value.value);else console.log("getBalance failed:", String(sol.reason));if (tok.status === "fulfilled") { let total = 0n; for (const t of tok.value.value) { watch.push(t.pubkey); const data = t.account.data as unknown as { parsed: { info: { tokenAmount: { amount: string } } } }; total += BigInt(data.parsed.info.tokenAmount.amount); } show("USDC base units", total);} else console.log("getTokenAccountsByOwner failed:", String(tok.reason));// A token transfer lists token accounts, not the owner, so page signatures for each one too.for (const addr of watch) { try { const cursor = one("SELECT newest FROM cursor WHERE addr = ?", addr)?.newest; const sigs = await rpc.getSignaturesForAddress(address(addr), { limit: 50, commitment, ...(cursor ? { until: signature(cursor) } : {}) }).send(); if (!sigs.length) { console.log(addr.slice(0, 8), "no new signatures"); continue; } let fresh = 0; db.exec("BEGIN"); // the seen rows and the cursor commit together for (const s of cursor ? sigs : []) { if (s.err !== null) continue; // a failed transaction moves no funds fresh += Number(db.prepare("INSERT OR IGNORE INTO seen VALUES (?, ?, ?)").run(s.signature, addr, Number(s.slot)).changes); } db.prepare("INSERT OR REPLACE INTO cursor VALUES (?, ?)").run(addr, sigs[0].signature); db.exec("COMMIT"); console.log(addr.slice(0, 8), cursor ? `${fresh} new transactions to attribute` : "baseline set"); } catch (e) { console.log(addr.slice(0, 8), "getSignaturesForAddress failed:", String(e)); }}
run: CARBIUM_KEY=$CARBIUM_KEY node main.ts <deposit-wallet>
The first run on an address stores a baseline: it records the balance and the newest signature and credits nothing. Each later run prints the change since the last sync and counts the successful transactions that arrived after the stored signature. Failed transactions are skipped, since they move no funds. Each read is settled on its own, so a failing getBalance prints its error while the token read and the signature pages still run.
The amount and the sender come from getTransaction. Pass maxSupportedTransactionVersion: 1 with an encoding, because mainnet carries v1 transactions and a call without it answers -32015 for one. The wallet picker in the script does this. A signature that the index lists can still return null from getTransaction when it is older than the validator's ledger, so treat null as unavailable and lean on the balance difference.
Staying current
Polling signatures for every logged-in player works for a few players and gets expensive as the count grows. A WebSocket tells you when to read instead. Open it at wss://services.carbium.sh with ?api-key= in the URL and keep one socket per game server: connections and subscriptions are capped per account by plan, and Free carries 5 sockets.
- logsSubscribe streams the logs of transactions that mention an address. For SOL deposits, mention the deposit wallet. For token deposits, mention the token account that receives them, since the owner wallet is not in the transaction.
- signatureSubscribe sends one confirmation and then ends. Use it when a player says they sent funds, so you can tell them as soon as that signature lands.
- accountSubscribe sends nothing for a plain SOL wallet. Use logsSubscribe mentions plus getBalance.
A mention subscription opens at 25 credits and then costs 20 credits per MiB sent. A signature subscription opens at 5. If every player deposits to one vault, one mention subscription covers all of them, and you read the transaction afterwards to see who sent it. If each player has a deposit address of their own, subscribe only while a deposit is pending and close the subscription after it lands.
What a sync costs
Each call has a charge in cells and a rate per plan, in requests per second.
| Call | Cells | Free | Dev | Business | Pro |
|---|---|---|---|---|---|
| getSignaturesForAddress | 50 | 0.24 | 1.2 | 100 | 500 |
| getTransaction | 50 | 0.24 | 1.2 | 5 | 25 |
Say each player has a wallet and one token account, polled every 10 seconds. That is two signature calls per cycle, or 0.2 calls per second per player. Dev's 1.2 covers 6 players and Business's 100 covers 500. Past that, read on a notification and keep the timer as a slow fallback. Credits meter RPC and WebSocket work, and unspent credits stay from month to month on the plans.
A reconciliation pass over many players reads their token accounts in one getMultipleAccounts call instead. A call of 100 pubkeys costs 1000 cells, or 1001 when the body is over 4 KiB. Below Pro a call takes at most 100 pubkeys, and Pro takes up to 300. Account reads run at 0.5, 15, 50 and 400 requests per second on Free, Dev, Business and Pro. A JSON-RPC call can also be a batch of up to 100 calls, which saves round trips. For the same idea on a front end, see React post-confirm balance refresh.
Where it ends
- A balance difference is not an attribution. The script counts transactions and leaves who sent what to your code: read the transaction with getTransaction for the sender, the amount and any memo.
- The script asks for 50 signatures per address per run. Past 50 new transactions between runs, the older ones are skipped when the cursor moves to the newest, so page with before down to the stored signature to catch every one.
- History stops at 30 days. The signature pages come from an address index that keeps up to 30 days, and an empty page past that shows the index's age limit; the address may still have older transactions. A ledger that must reach further has to be kept from its first day.
- The script reads one mint. Token-2022 transfer fees take a cut of what was sent and confidential transfers hide the amount, so read the mint's extensions before crediting a Token-2022 deposit.
- The balance read and the signature pages are separate calls at separate slots. A deposit that lands between them shows in one and not the other, and the next run closes the gap because the balance and the cursor both move forward.
- The script reads and never signs. Withdrawals, refunds and anything that spends from your vault belong to a signer you operate, kept apart from this reader.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| A deposit is credited twice after a crash between the credit and the cursor update. | Key the ledger on the signature and write the credit and the cursor in one SQLite transaction. A replay then meets INSERT OR IGNORE and books nothing. |
| A token deposit never appears in the wallet's signature list. | The transfer lists token accounts and not the receiving wallet. Page signatures for each token account the wallet owns, as the script does. |
| getTransaction returns null for a signature the list gave you. | The address index reaches below the validator's ledger floor, so an older signature can be listed and still not fetched. Treat null as unavailable and use the balance difference. |
| getTransaction answers -32015. | Add maxSupportedTransactionVersion: 1 and an encoding to the call. Without it a v1 transaction is refused. |
| Polling returns 429 once the player count grows. | Each signature poll costs 50 cells at a capped rate per plan. Move to logsSubscribe mentions, read on each notification, and honour the retry-after value. |
| A player's balance reads unchanged right after they deposit. | A deposit that is not finalized yet is absent from a finalized read. Show it as pending and read again after a moment, since finalized sits 0 to 1 slots behind processed. |
Questions
Does the player have to sign again to see their balance?
No. Balances are public account data, so your server reads them by address after the login signature. A signature is needed only when funds move.
Which commitment should credit a deposit?
Use finalized for anything the player can spend. The server defaults to finalized, and @solana/kit 8.6.0 fills in confirmed when a call leaves it out, so name the level on every call.
Can accountSubscribe watch a player's SOL balance?
No, it sends nothing for a plain SOL wallet. Subscribe to logs that mention the address and call getBalance on each notification.
How far back can the sync look on the first run?
Thirty days at most, from the address index. The script starts from a baseline anyway, so it credits only what arrives after its first run.