---
id: I0014
title: "Unity player wallets"
url: https://carbium.sh/library/integrate/unity-player-wallets
collection: Integrations
category: Game engines
revision: 1
updated: 2026-11-22
author: Carbium
code: MIT (LICENSE in the zip); text: all rights reserved, Carbium Corporation
---

# Unity player wallets

A Node file that holds your Carbium key and answers a Unity client's wallet request with the player's SOL and game-token balance, read in one call and cached for 5 seconds, plus how the C# side fetches and parses it.

## What the server returns

A game that shows a player's wallet needs two numbers on its loading screen: the SOL balance and the balance of the game's own token. This server gives a Unity client both through one HTTP call. It is one Node file whose only dependency is `@solana/kit`, and it holds your Carbium key so the game build never carries it.

`GET /wallet/<address>` answers with JSON in this shape.

| Field | Meaning |
|---|---|
| owner | The wallet address that was asked for. |
| slot | The slot both accounts were read at, as a string. |
| lamports | The SOL balance in lamports, as a string. A wallet that has never been funded reads "0". |
| token | The raw amount of the game token in the player's associated token account, as a string. "0" when the account does not exist, null when `GAME_MINT` is unset. |
| at | The UTC time the snapshot was taken. |

A string that is not an address gets 400 before any call is made, so a typo costs no credits. When Carbium answers 429 the server answers 503 and passes on the `retry-after` value. Any other failure gets 502 and a log line that names the cause. Each snapshot is cached for 5 seconds per address (`CACHE_MS`), so a screen that asks again within 5 seconds of a finished read gets the cached snapshot.

## The Unity side

A Unity build is a folder of files the player owns, and a key inside it can be read out. Calling Carbium from the game would put the key there, in a header or in a `?api-key=` URL alike. Keeping it on the server keeps it out of every build, and you can change it without shipping an update.

In C#, call `UnityWebRequest.Get` on your server's `/wallet/<address>` URL from a coroutine, check the result, and parse `request.downloadHandler.text` with `JsonUtility.FromJson` into a class with string fields `owner`, `slot`, `lamports`, `token` and `at`. Convert the two amounts with `ulong.Parse`. The server sends them as strings because many JSON parsers lose digits above 2^53, and a raw token amount passes that quickly when the mint has 9 decimals.

Show `lamports` divided by 1,000,000,000 as SOL, and `token` divided by 10 to the power of your mint's decimals. The decimals belong to the mint your game created, and the server never reads them. On a 503, wait the `retry-after` seconds before asking again and keep showing the last balance meanwhile. Mobile builds refuse plain HTTP by default, so put the server behind HTTPS. A WebGL build runs under browser CORS rules, so set `ALLOW_ORIGIN` to the origin that serves your game.

## The Solana side: two accounts, one read

The server talks to Carbium's [RPC endpoint](https://carbium.sh/docs#endpoints) at `https://services.carbium.sh`. `createDefaultRpcTransport` sets the key header once.

The wallet and the token account come back from one `getMultipleAccounts` call with base64 encoding. The token account address is derived on the machine, so it needs no lookup call. The associated token account of an owner and a mint is a program derived address under the associated token program, from three seeds: the owner, the token program and the mint. `getProgramDerivedAddress` works it out locally. This file uses the classic token program. A mint created under Token-2022 uses that program's address as the seed, and this file does not cover it.

A token account holds its amount as a little-endian u64 at byte 64 of its data, so `readBigUInt64LE(64)` on the decoded bytes gives the raw amount. A null entry means the account does not exist: an unfunded wallet, or a player with no associated token account for the mint. Both read as 0.

The call passes commitment `confirmed`. If a balance gates a purchase, switch it to `finalized`. Both accounts in one call share one slot, and the response reports it.

## The server

Install the dependency with `npm install @solana/kit@8.6.0` 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. `GAME_MINT`, `PORT`, `CACHE_MS`, `ALLOW_ORIGIN` and `CARBIUM_RPC_URL` are optional.

`main.ts` (run: `node main.ts <wallet-address>`)

```ts
// I0014 · Unity player wallets
// https://carbium.sh/library/integrate/unity-player-wallets
// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.
// SPDX-License-Identifier: MIT

import {
  address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressEncoder, getProgramDerivedAddress,
  isAddress, isSolanaError, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR, type Address,
} from "@solana/kit";
import { createServer } from "node:http";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY to your Carbium API key.");
  process.exit(1);
}
const mint = process.env.GAME_MINT ? address(process.env.GAME_MINT) : null; // the game's token, classic token program
const cacheMs = Number(process.env.CACHE_MS ?? 5_000);
const port = Number(process.env.PORT ?? 8787);

// One client for the life of the process: connections stay warm.
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({
    url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh",
    headers: { "x-api-key": key },
  }),
);

const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
const ATA_PROGRAM = address("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
const enc = getAddressEncoder();

type Snapshot = { owner: string; slot: string; lamports: string; token: string | null; at: string };
const cache = new Map<string, { until: number; snap: Snapshot }>();

async function snapshot(owner: Address): Promise<Snapshot> {
  const hit = cache.get(owner);
  if (hit && hit.until > Date.now()) return hit.snap;
  const keys = [owner];
  if (mint) {
    // The associated token account is a derived address: no lookup call needed.
    const [ata] = await getProgramDerivedAddress({
      programAddress: ATA_PROGRAM,
      seeds: [enc.encode(owner), enc.encode(TOKEN_PROGRAM), enc.encode(mint)],
    });
    keys.push(ata);
  }
  const { context, value } = await rpc
    .getMultipleAccounts(keys, { commitment: "confirmed", encoding: "base64" })
    .send({ abortSignal: AbortSignal.timeout(5_000) });
  const raw = value[1] ? Buffer.from(value[1].data[0], "base64") : null;
  const snap: Snapshot = {
    owner,
    slot: context.slot.toString(),
    lamports: (value[0]?.lamports ?? 0n).toString(),
    // A token account keeps its u64 amount at byte 64; no account reads as 0.
    token: !mint ? null : raw && raw.length >= 72 ? raw.readBigUInt64LE(64).toString() : "0",
    at: new Date().toISOString(),
  };
  if (cache.size > 10_000) cache.clear();
  cache.set(owner, { until: Date.now() + cacheMs, snap });
  return snap;
}

const why = (e: unknown) =>
  isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) ? `HTTP error (${e.context.statusCode})` : e instanceof Error ? e.message : String(e);

const server = createServer(async (req, res) => {
  const [, route, owner] = new URL(req.url ?? "/", "http://game").pathname.split("/");
  const send = (status: number, body: unknown, headers: Record<string, string> = {}) => {
    const cors = process.env.ALLOW_ORIGIN ? { "access-control-allow-origin": process.env.ALLOW_ORIGIN } : {};
    res.writeHead(status, { "content-type": "application/json", ...cors, ...headers });
    res.end(JSON.stringify(body));
  };
  if (route !== "wallet" || !owner || !isAddress(owner)) return send(400, { error: "use /wallet/<address>" });
  try {
    send(200, await snapshot(owner));
  } catch (e) {
    console.error("read failed:", why(e));
    if (isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) && e.context.statusCode === 429) {
      return send(503, { error: "busy" }, { "retry-after": e.context.headers.get("retry-after") ?? "1" });
    }
    send(502, { error: "upstream read failed" });
  }
});

const first = process.argv[2];
if (first) {
  if (!isAddress(first)) {
    console.error("The argument is not an address.");
    process.exit(1);
  }
  console.log(JSON.stringify(await snapshot(first))); // one read as a check, before serving
}
server.listen(port, () => console.log(`serving /wallet/<address> on port ${port}`));
```

## Run it and check it

Start it with `node main.ts <wallet-address>`. The address is optional. When given, the file prints one snapshot of that wallet before it starts serving, which proves the key and the mint work without a Unity client. Then ask for a snapshot the way the game will, with `curl http://localhost:8787/wallet/<address>`, and compare `lamports` with a block explorer.

Run it under a supervisor such as a systemd unit, with the key in the unit's environment and never in the repository. Put your game's session check in front of the `/wallet` route before it faces players. The file does not authenticate callers.

## What it costs against your limits

`getMultipleAccounts` charges 10 cells per pubkey, so a snapshot with a game token counts 20 cells and a SOL-only one counts 10. It is an account read, which Free allows at 0.5 req/s, Dev at 15, Business at 50 and Pro at 400. [Limits](https://carbium.sh/docs#limits) are per account, so every key on the account shares one budget.

The cache keeps one player's screen from multiplying calls: at 5 seconds, one player costs at most 12 snapshots a minute however often the game asks. Different players do not share a cache entry, so size the plan for the players online at once.

## Where it ends

- It only reads. Signing and sending a transaction stay in the player's own wallet app, and this file holds no private key.
- Anyone who can reach the server can ask about any address and spend your budget on it. The session check in front of it is yours to write.
- It reads one mint under the classic token program. Token-2022 mints, other mints and a full list of what a wallet holds need more code than this file has.
- Amounts come in raw units. The mint's decimals and any token names or icons are for your game to supply.
- A snapshot is a poll. A balance that changes shows up after the cache expires. For a push, Carbium's [WebSocket](https://carbium.sh/docs#websocket) has `logsSubscribe` with a mention filter, and `accountSubscribe` stays silent for a plain SOL wallet, so pair the logs with a balance read. A subscription like that opens at 25 credits, then costs 20 credits per MiB sent. Subscriptions are capped per account as well as sockets, and Free carries 5 sockets, so one server socket can carry each online player's logs subscription up to the plan's subscription cap, which fits where one socket per player would not.
- A player's transaction history is a different call. `getSignaturesForAddress` costs 50 cells and reaches back 30 days at most, because Carbium serves it from its own address index. An empty page past that means the index ends there, and the wallet may hold older transactions. This file does not call it.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| curl or the game gets 400 with `use /wallet/<address>`. | The path holds something that is not a base58 public key: a trailing newline, a wallet name, or an empty string from a player who has not connected a wallet. Trim the value and send the public key only. |
| The game gets 503 with a `retry-after` header and the server log shows `read failed: HTTP error (429)`. | The account is over its account-read rate. Raise `CACHE_MS`, wait the `retry-after` seconds, and check that no other key on the same account is using the budget. |
| The game gets 502 and the log shows `read failed: HTTP error (401)`. | The key was refused. Check that `CARBIUM_KEY` holds the key itself and that the supervisor passes it on. |
| `token` reads "0" for a player who holds the token. | Either `GAME_MINT` is wrong, or the mint belongs to Token-2022, or the player holds it in a token account that is not the associated one. This file reads only the associated account under the classic token program. |
| The server exits at start with `Set CARBIUM_KEY to your Carbium API key.` | The variable did not reach the process. Add it to the supervisor's environment file and restart. |
| A WebGL build shows a CORS error in the browser console and no balance. | Set `ALLOW_ORIGIN` to the exact origin that serves the game, with scheme and port, and restart the server. |

## Questions

### Why not call Carbium from Unity directly?

The key would ship in the build, where a player can read it, and it would count against your whole account's budget. Carbium takes the key in a header or in the URL, and either one would sit in the build.

### Can the game get a push when a balance changes?

Yes, from the server over Carbium's WebSocket. Subscribe to logs that mention the wallet and read the balance when one arrives, then relay it to the client over your own channel. The server here polls instead.

### How many players can one account serve?

Count snapshots per second at peak, multiply by the 20 cells a snapshot with a game token counts, and compare with your plan's account-read rate at 10 cells a request. The 5 second cache caps each player at 12 snapshots a minute.

### Does it list the NFTs or other tokens a player owns?

No. It reads the SOL balance and one mint. A full inventory is a separate job.

## Related

- [SPL token balance](https://carbium.sh/library/howsolana/spl-token-balance) (How to use Solana, HS0001)
- [RPC rate-limit alerts](https://carbium.sh/library/usecase/rpc-rate-limit-alerts) (Use cases, UC0001)
- [carbium.sh/docs#endpoints](https://carbium.sh/docs#endpoints)
- [carbium.sh/docs#auth](https://carbium.sh/docs#auth)
- [carbium.sh/docs#rpc](https://carbium.sh/docs#rpc)
- [carbium.sh/docs#limits](https://carbium.sh/docs#limits)
- [carbium.sh/docs#websocket](https://carbium.sh/docs#websocket)
