library / Integrations / I0041
Godot on-chain leaderboard
A Node job that holds your Carbium key, reads a token's newest transactions, adds up balances per wallet and prints the top ten as one JSON file, with the Godot 4 steps that load it into a leaderboard scene.
What a score is on chain
A leaderboard needs one number per player. On chain, the simplest source is a token your game mints as score points. Each player wallet holds a balance of that token, and the balance is the score. Anyone can read it, the game client cannot edit it, and a player who changes device keeps it by connecting the same wallet.
The job reads the token's recent activity, collects the balances it finds and prints the ten highest as JSON. USDC stands in for the score token in the code, so the run has live traffic to read. Pass your own mint as the first argument once the game has one.
A transaction that touches a token lists every token account it changed in postTokenBalances, with the owner wallet, the mint and the balance after the transaction. That one field carries the owner and the score together, so the job needs no account lookups and no address derivation.
A wallet can own several token accounts for one mint, and one transaction can list more than one of them, so the job adds those up per owner within a transaction. The same wallet can also show up in several of the ten transactions, and its older balance is out of date, so the job keeps the figure from the newest transaction that names it.
The relay and where the key stays
Godot's HTTPRequest node can call any URL, including the Carbium RPC endpoint. The trouble is the key. An exported Godot project ends up as a .pck file that players can unpack, and a key inside it, in a header or in a ?api-key= URL, can be read out. Limits are per account, so a copied key spends the same budget as everything else you run.
So the game never speaks JSON-RPC. A Node job holds the key in its environment, makes the reads and prints one small document. The game fetches that document from an ordinary web address. You can rotate the key at any time and the game build never changes.
Run the job from cron or a systemd timer and move its output to a folder your web server serves: node main.ts > next.json && mv next.json leaderboard.json. The job exits with status 1 when it read no balances, and the && then leaves the previous file in place.
The JSON and the GDScript side
| Field | Meaning |
|---|---|
| mint | The token the scores come from. |
| updated | The UTC time of the run. |
| scores | Up to ten rows, highest first. |
| rank | Position in the list, starting at 1. |
| owner | The wallet address that holds the balance. |
| score | The raw token amount, as a string. |
In Godot 4, add an HTTPRequest child to the leaderboard scene and connect its request_completed signal. Call request("https://your-host/leaderboard.json") from _ready. In the handler, check that response_code is 200, pass body.get_string_from_utf8() to JSON.parse_string, and loop over the scores array. Each element is a dictionary with rank, owner and score.
Scores are strings on purpose. Godot parses every JSON number as a 64-bit float, which loses digits above 2^53, and a raw amount of a token with 9 decimals gets there quickly. String.to_int() returns a 64-bit integer, so convert there, then divide by 10 to the power of the mint's decimals for display. Show the owner shortened to its first and last four characters, or look it up in your own table of player names.
If the request fails, keep drawing the list you already have and ask again on a timer. A web export loads the file under browser CORS rules, so the host that serves it must send the matching headers.
The job
Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. CARBIUM_KEY is required, and the file exits with a message without it. CARBIUM_RPC_URL is optional.
It asks getSignaturesForAddress for the mint's newest 10 signatures, then sends all ten getTransaction calls at once and settles each alone, so a failed read goes to stderr and the others still count. A call that returns null is skipped too. Neither call names a commitment, so kit sends confirmed.
The config of getTransaction carries maxSupportedTransactionVersion: 1. Mainnet carries v1 transactions, and a call without it, or with 0, answers -32015 for one of them.
// I0041 · Godot on-chain leaderboard// https://carbium.sh/library/integrate/godot-on-chain-leaderboard// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createDefaultRpcTransport, createSolanaRpcFromTransport, isAddress } from "@solana/kit";const key = process.env.CARBIUM_KEY;if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1);}// USDC stands in for the game's score token; pass your own mint as the first argument.const mint = process.argv[2] ?? "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";if (!isAddress(mint)) { console.error("The argument is not a mint address."); process.exit(1);}const rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key }, }),);const why = (e: unknown) => (e instanceof Error ? e.message : String(e));const timeout = () => ({ abortSignal: AbortSignal.timeout(10_000) });const sigs = await rpc .getSignaturesForAddress(mint, { limit: 10 }) .send(timeout()) .catch((e: unknown) => { console.error("signature list failed:", why(e)); return process.exit(1); });// Each transaction is read alone, so one failure does not sink the rest.const reads = await Promise.allSettled( sigs.map(({ signature }) => rpc.getTransaction(signature, { encoding: "json", maxSupportedTransactionVersion: 1 }).send(timeout()), ),);// Newest first: the first transaction that names an owner holds its latest balance.const latest = new Map<string, bigint>();reads.forEach((r, i) => { const tag = sigs[i].signature.slice(0, 8); if (r.status === "rejected") return void console.error(`${tag} failed: ${why(r.reason)}`); if (!r.value) return void console.error(`${tag} came back null`); const inTx = new Map<string, bigint>(); // one wallet can own several token accounts for (const b of r.value.meta?.postTokenBalances ?? []) { if (b.mint !== mint || !b.owner) continue; inTx.set(b.owner, (inTx.get(b.owner) ?? 0n) + BigInt(b.uiTokenAmount.amount)); } for (const [owner, amount] of inTx) if (!latest.has(owner)) latest.set(owner, amount);});if (latest.size === 0) { console.error("no balances read"); process.exit(1);}const top = [...latest].sort(([, a], [, b]) => (b > a ? 1 : b < a ? -1 : 0)).slice(0, 10);console.log( JSON.stringify( { mint, updated: new Date().toISOString(), scores: top.map(([owner, score], i) => ({ rank: i + 1, owner, score: score.toString() })), }, null, 1, ),);
run: node main.ts <mint>
Run it with node main.ts <mint>. With no argument it reads USDC. The JSON goes to stdout and every problem to stderr.
What a refresh costs
A run makes 11 calls: one getSignaturesForAddress and ten getTransaction. Each of the two methods costs 50 cells, so a run counts 550 cells. A class absorbs bursts up to 1,024 cells, so the ten reads can go out together. A refused run leaves the old file up and the timer's next run tries again.
The cost follows the refresh timer and the window, and never the player count. A timer that fires every minute makes 11 calls a minute whether ten players or ten thousand load the file. A wider window adds 50 cells for each extra transaction read.
Where it ends
- The window is the mint's newest 10 transactions. A holder who has not moved tokens recently is absent, so this is a recent-activity board. A full ranking needs the list of holders, which your game server has to keep itself, because getTokenLargestAccounts is not served and answers -32601.
- A plain Transfer between token accounts never names the mint, so it is missing from the window. A TransferChecked names the mint and shows up.
- An owner with two token accounts, where only one is touched in its newest transaction, reads low. The job sums only what the transaction lists.
- getSignaturesForAddress reaches back 30 days at most, because Carbium serves it from its own address index, and getTransaction can answer null for an older signature it lists. The job skips a null. With the newest 10 that is rare.
- The job reads balances and proves nothing about who plays. A player's wallet is tied to a game account by a sign-in step that you write.
- The board is as fresh as the timer. For a push, Carbium's WebSocket has logsSubscribe with a mention filter, and the relay could rerun the read when a log for the mint arrives.
- It never signs or sends. Minting score tokens stays with your own server code.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| A read logs -32015 and some transactions are missing from the board. | The getTransaction config lost maxSupportedTransactionVersion: 1. Put it back with the value 1, since a value of 0 fails the same way. |
| The log shows HTTP error (429) and the job exits with no balances read. | The account is over its rate for those methods. Run the job less often, or read a smaller window, and check that no other key on the account is using the budget. The previous file stays served. |
| The log shows signature list failed: HTTP error (401) and the job exits. | The key was refused as unknown. Check that CARBIUM_KEY holds the whole key and that the timer's environment passes it on. |
| The job lists a signature and its read logs null. | The signature is below the validator's ledger floor, where the address index still lists it. The job skips it. If every read is null, point the job at a mint with activity now. |
| JSON.parse_string returns null in Godot. | The body is empty or an error page. Write to a temporary file and move it into place only when the job succeeds, and check response_code before parsing. |
| A player's score in the scene is rounded or wrong in the last digits. | The value was read as a number somewhere. Keep score a string until String.to_int() converts it. |
Questions
Why not call Carbium from Godot directly?
The key would sit in the exported .pck file, where a player can read it, and it would spend your whole account's budget. The relay keeps it in one process you control.
Does it work with my game's own token?
Yes, pass the mint address as the first argument. postTokenBalances has the same fields for a token under the classic program and one under Token-2022.
How many players can load the board?
As many as your web host serves. Players read the static file, and Carbium sees only the 11 calls of each run.
Can the board update as scores change?
Poll the file from Godot on a timer for a simple version. For a push, have the relay subscribe to logs that mention the mint and rerun the read when one arrives.