library / Integrations / I0042
Unreal NFT inventory loader
A Node file that holds your Carbium key and answers an Unreal client's inventory request with the NFT items a wallet holds, each with name, symbol, uri and verified collection, plus the Unreal HTTP and Json calls that fetch and parse it.
What the server returns
Players carry owned items into a match, so the game must learn what a wallet holds and get enough detail per item to pick its in-game counterpart. The packaged build makes one HTTP call to this server and receives that list. The server is main.ts, which Node runs directly and whose only dependency is @solana/kit. Your Carbium key sits in its environment.
Ask for GET /inventory/<address> and the body is JSON shaped like this.
| Field | Meaning |
|---|---|
| owner | The wallet address from the request path. |
| slot | The slot of the token account read, as a string. |
| nfts | One object per item with mint, name, symbol, uri, collection and verified. An item with no collection has collection set to null. |
| unread | The count of NFT-shaped holdings that never became an item: no metadata account, one that would not parse, or a read that failed. |
Send anything except an address and you get 400, with no upstream call made. When the read fails, the reply is 502 with the cause in the body, and that failure is dropped from the cache. Good answers are kept 10 seconds per address (CACHE_MS), so a lobby screen asking twice within a second triggers a single read.
The Unreal side
In your module's Build.cs, list HTTP and Json under PublicDependencyModuleNames. The C++ then builds the request with FHttpModule::Get().CreateRequest(), sets GET and the URL of your server's /inventory/<address>, binds OnProcessRequestComplete and calls ProcessRequest(). Inside the callback, test bWasSuccessful and the response code first. Next, feed Response->GetContentAsString() to FJsonSerializer::Deserialize along with a reader from TJsonReaderFactory. The parsed object gives you GetArrayField("nfts"), and every element has string fields mint, name, symbol and uri. In a Blueprint-only project, a JSON plugin that wraps the same calls does the job.
Key game logic on collection or mint. A name proves nothing, since anyone can mint an item titled Iron Sword. A Data Table indexed by collection address fits well: each row describes one item class and what it does in your game. Skip any item whose verified is false, because true means the collection's authority signed the link.
A packaged game is a set of files on the player's disk, and anything inside them can be extracted, a Carbium key included. For that reason the Unreal build only ever learns this server's address. Rotating the key then means restarting the server, with no game patch. Call the server from a dedicated server or from your own backend too, since a client can say anything about itself. Console and mobile builds expect HTTPS, so terminate TLS in front of the server.
The uri field points at off-chain JSON with the image link and attributes. The server never fetches it. Pull art through your content pipeline or your own cache, so a slow image host never holds up the inventory.
How an inventory is read
The inventory takes two reads. First, getTokenAccountsByOwner with the classic token program and jsonParsed encoding returns each token account the wallet owns, with mint, amount and decimals. Holdings with 0 decimals and an amount of 1 look like NFTs, so the filter keeps them and discards fungible tokens. Only the first MAX_ITEMS of those (100 by default) move on to the second read.
For the second read, each mint has a metadata account whose address is derived under the Token Metadata program from the seeds metadata, the program address and the mint. getProgramDerivedAddress computes it locally, and a single getMultipleAccounts call fetches up to 100 of them. Inside the account sit a fixed header, then name, symbol and uri as length-prefixed strings padded with zero bytes, then seller fee, creators and flags, then the edition nonce and token standard, and an optional collection with its verified flag and key after them. The parser steps through these in order and trims the padding. Any account it cannot parse adds to unread.
A collection NFT is a mint with its own metadata account. If you set GAME_COLLECTION to that mint, only items whose collection equals it and is verified come back. Leave it unset and every NFT-shaped item in the wallet is returned with collection and verified, so the game can sort them.
Both calls read at confirmed commitment, and a purchase check that must be final can switch both to finalized. The two reads are separate calls and may land in different slots. The response reports the slot of the first.
The server
Run npm install @solana/[email protected], and put "type": "module" in package.json. Node 24 strips the types as it loads. CARBIUM_KEY is required: without it the file prints a message and exits. GAME_COLLECTION, MAX_ITEMS, CACHE_MS and PORT are optional, and so is CARBIUM_RPC_URL, which defaults to the Carbium RPC endpoint.
// I0042 · Unreal NFT inventory loader// https://carbium.sh/library/integrate/unreal-nft-inventory-loader// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, getAddressDecoder, getAddressEncoder, getProgramDerivedAddress, getUtf8Encoder, 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 collection = process.env.GAME_COLLECTION ? address(process.env.GAME_COLLECTION) : null; // keep one verified collectionconst cacheMs = Number(process.env.CACHE_MS ?? 10_000);const maxItems = Number(process.env.MAX_ITEMS ?? 100); // one metadata call per 100 itemsconst rpc = createSolanaRpcFromTransport( createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),);const TOKEN_PROGRAM = address("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");const METADATA_PROGRAM = address("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");const enc = getAddressEncoder(), dec = getAddressDecoder(), utf8 = getUtf8Encoder();const why = (e: unknown) => isSolanaError(e, SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR) ? `HTTP error (${e.context.statusCode})` : e instanceof Error ? e.message : String(e);// Metaplex metadata account: a fixed header, then length-prefixed strings and optional fields.function parseMetadata(b: Buffer) { try { let o = 65; // key (1), update authority (32), mint (32) const str = () => { const n = b.readUInt32LE(o), s = b.toString("utf8", o + 4, o + 4 + n); o += 4 + n; return s.replace(/\0+$/, ""); }; const name = str(), symbol = str(), uri = str(); o += 2; // seller fee basis points if (b[o++]) o += 4 + b.readUInt32LE(o) * 34; // creators o += 2; // primary sale happened, is mutable if (b[o++]) o += 1; // edition nonce if (b[o++]) o += 1; // token standard const col = b[o++] ? { verified: b[o] === 1, key: dec.decode(b.subarray(o + 1, o + 33)) } : null; return { name, symbol, uri, collection: col?.key ?? null, verified: col?.verified ?? false }; } catch { return null; }}async function inventory(owner: Address) { const held = await rpc .getTokenAccountsByOwner(owner, { programId: TOKEN_PROGRAM }, { commitment: "confirmed", encoding: "jsonParsed" }).send(); type Info = { mint: Address; tokenAmount: { amount: string; decimals: number } }; const mints = held.value .map((a) => (a.account.data as unknown as { parsed: { info: Info } }).parsed.info) .filter((i) => i.tokenAmount.decimals === 0 && i.tokenAmount.amount === "1") // NFT-shaped: one unit, no decimals .slice(0, maxItems).map((i) => i.mint); const pdas = await Promise.all(mints.map(async (m) => (await getProgramDerivedAddress({ programAddress: METADATA_PROGRAM, seeds: [utf8.encode("metadata"), enc.encode(METADATA_PROGRAM), enc.encode(m)], }))[0])); const nfts: unknown[] = []; let unread = 0; for (let i = 0; i < pdas.length; i += 100) { try { const r = await rpc.getMultipleAccounts(pdas.slice(i, i + 100), { commitment: "confirmed", encoding: "base64" }).send(); r.value.forEach((acc, j) => { const meta = acc && parseMetadata(Buffer.from(acc.data[0], "base64")); if (!meta) unread++; else if (!collection || (meta.verified && meta.collection === collection)) nfts.push({ mint: mints[i + j], ...meta }); }); } catch (e) { unread += Math.min(100, pdas.length - i); console.error("metadata read failed:", why(e)); } } return { owner, slot: held.context.slot.toString(), nfts, unread };}const cache = new Map<string, { until: number; inv: Promise<unknown> }>();const server = createServer(async (req, res) => { const [, route, owner] = new URL(req.url ?? "/", "http://game").pathname.split("/"); const send = (status: number, body: unknown) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(body)); }; if (route !== "inventory" || !owner || !isAddress(owner)) return send(400, { error: "use /inventory/<address>" }); let hit = cache.get(owner); if (!hit || hit.until < Date.now()) { if (cache.size > 5_000) cache.clear(); cache.set(owner, (hit = { until: Date.now() + cacheMs, inv: inventory(owner) })); hit.inv.catch(() => cache.delete(owner)); // a failed read is not kept } try { send(200, await hit.inv); } catch (e) { console.error("read failed:", why(e)); send(502, { error: why(e) }); }});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 inventory(first))); // one read as a check, before serving}server.listen(Number(process.env.PORT ?? 8788), () => console.log(`serving /inventory/<address> on port ${(server.address() as { port: number }).port}`));
run: node main.ts <wallet-address>
Launch it as node main.ts <wallet-address>. Given an address, the file prints one inventory before serving, which exercises the key and the parser without any Unreal build. After that, query it the way the game will with curl http://localhost:8788/inventory/<address> and compare the mints against a block explorer. For production, run it under a supervisor such as a systemd unit with the key in the unit's environment, never in your repository, and check your game's session in front of the route.
What it costs against your limits
One inventory means a single getTokenAccountsByOwner call plus one getMultipleAccounts call per 100 items. The heavy case is a wallet full of airdropped tokens, since the first response grows with every token account. In getMultipleAccounts, each pubkey costs 10 cells, so a full chunk of 100 costs 1001 cells, because its request body passes 4 KiB. That still fits inside the 1,024 cells a rate class absorbs as a burst. Account reads run at 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro. A full chunk costs as much as 100 single account reads. Only Pro takes 300 pubkeys in one call. Below Pro the burst ceiling caps a call at 100, which is the most this file ever sends.
The account owns the budget, so all its keys draw on one allowance. Only a 429 on the owner call becomes a 502 carrying HTTP error (429). A rate-limited metadata chunk is counted in unread and the reply is a 200 that stays cached for CACHE_MS, so the game re-asks after that window.
With a 10 second cache, a given wallet costs at most 6 inventories a minute however often the game asks. Entries are per wallet, so budget for how many load together: 50 players with full wallets entering a lobby at once means 50 chunks of 1001 cells, which is 50,050 cells. Business refills 500 cells a second and Pro 4,000, about four full chunks, so no plan refills that in a second. Stagger the lobby loads or lower MAX_ITEMS, whatever your plan.
Where it ends
- It only reads. It holds no private key and signs nothing, and it cannot show that the person at the keyboard owns the wallet they named. For that, the player signs a message in their wallet app and your backend checks the signature.
- It reads the classic token program. Token-2022 holdings are not listed, and neither is anything past the first MAX_ITEMS NFT-shaped holdings of a wallet.
- A token that a wallet has delegated or frozen still counts as held, so a game that treats escrowed items differently needs its own check.
- Metadata can change. While an item is mutable, its authority can edit the name and uri, and the server reports what the account says now.
- The inventory is a poll. To learn of a purchase as it lands, open a server socket, subscribe to logs that mention the wallet, and re-read on each notification.
- Who held an item last month is a history question. getSignaturesForAddress reaches back 30 days at most, because Carbium serves it from its own address index, and this file does not call it.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| curl or the game gets 400 with use /inventory/<address>. | The path segment is not a base58 address. Typical causes are a trailing newline, a wallet nickname, or an empty string from a player who has no linked wallet. Trim it and send only the address. |
| The game gets 502 and the body reads HTTP error (429). | The owner read went over its rate. Raise CACHE_MS, retry after a short delay, and look at whether another key on the same account is spending the budget. |
| The game gets 502 and the body reads HTTP error (401). | Carbium does not know the key. Confirm CARBIUM_KEY holds the whole key and that your supervisor passes it through. The key goes in the x-api-key header, or as ?api-key= on the URL. |
| nfts comes back empty for a player who holds items. | Compare GAME_COLLECTION with the item's collection, which must match and be verified. Also confirm the mint belongs to the classic token program, and that the wallet does not hold more than MAX_ITEMS NFT-shaped tokens listed before it. |
| unread is above 0. | Some holding with 0 decimals and an amount of 1 has no readable metadata account, or one chunk of the metadata read failed, as a rate-limited chunk does under your limits. A failed read shows in the server log as metadata read failed, and the game can re-ask after the cache window. |
| The server exits at start with Set CARBIUM_KEY to your Carbium API key. | The variable never reached the process. Put it in the supervisor's environment file and restart. |
Questions
Why not call Carbium straight from the Unreal client?
The key would ship inside the packaged game where any player can extract it, and each player's traffic would draw on your account's budget directly. This server keeps the key in one place under your control.
Does this prove a player owns the wallet?
No. It lists what an address holds, and anyone can type any address. Have the player sign a message from their wallet and verify the signature on your backend before granting items.
How do item art and stats get into the game?
Fetch the item's uri, which points at off-chain JSON with the image link and attributes, and cache what you need. For stats, map collection or mint to a Data Table row in your own project.
How does the game notice a new purchase quickly?
Poll the endpoint once the purchase flow ends, or have the server subscribe to logs that mention the wallet and re-read when one arrives. The 10 second cache applies either way, so lower CACHE_MS if you need it sooner.