services
Get a key

library / Integrations / Game engines / I0105

Unreal WebSocket account events

A small Node relay holds one Carbium WebSocket, subscribes to the accounts your game cares about, and writes one JSON line per change to a local port that an Unreal dedicated server reads and replicates to its clients.

By Carbium · Game engines · I0105 · updated 2026-11-23

01

A relay beside the game server

Chain watching belongs on the dedicated server. A game client runs on the player's machine, so a key packed into a build can be pulled out of it, and every connected player would open a subscription of their own on your account. The server process runs in your hosting, so the key stays there. Put a small relay next to it. The relay holds one WebSocket to Carbium, sends one accountSubscribe for each account the game cares about, and writes one JSON line per change to a TCP port on the same machine. The game server connects to that port and treats each line as a game event.

The split keeps TLS, subscription ids and reconnect handling out of engine code. C++ or Blueprint sees a plain socket and a line format you define, and the relay can be restarted or patched without rebuilding the game. The socket takes the key as `?api-key=` on the WebSocket URL, and the RPC reads the relay makes at startup carry it in the x-api-key header. Free carries 5 sockets per account. The relay uses one, however many game servers read from it.

02

The event line

Each line is one JSON object ended by a newline. Newline framing is easy to read from Unreal: collect bytes until \n, then hand the text to the JSON reader.

FieldValueUse
typeaccountLeaves room for other event kinds later.
accountBase58 addressWhich watched account changed.
slotDecimal numberOrdering. The relay drops any notification at or below the newest slot it has sent for that account.
lamportsString of digitsThe SOL balance of the account. A string, since JSON has no 64-bit integer.
amountString of digits, or nullThe token amount, read as a little-endian u64 at byte 64 of an SPL Token or Token-2022 token account. Null for any other account, a mint or a program's state account included.

Amounts travel as strings on purpose. Unreal's JSON reader turns every number into a double, and a double holds integers exactly only up to 2^53. A token with nine decimals passes that quickly. Read the string with the engine's 64-bit conversion, FCString::Strtoui64 for example, and keep the result in a uint64.

03

The program, end to end

With no argument, main.ts finds work for itself. It lists the newest signatures that mention the USDC mint, reads those transactions as jsonParsed, and collects up to six USDC token accounts they touched, so lines start arriving within seconds. Pass account addresses as arguments to watch your own: a player's token account, a prize vault, a state account owned by your program. Mainnet carries v1 transactions, so the reads send maxSupportedTransactionVersion: 1, and leaving it out or sending 0 answers -32015 for a v1 transaction. The signature list comes from an address index of up to 30 days that reaches below the validator's ledger, so getTransaction can answer null for a signature it lists. The program skips nulls and prints each failed read.

Install with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. CARBIUM_KEY is required. CARBIUM_RPC_URL and CARBIUM_WS_URL default to the Carbium endpoints. RELAY_PORT defaults to 8787, and the relay binds to 127.0.0.1 only.

main.ts
// I0105 · Unreal WebSocket account events// https://carbium.sh/library/integrate/unreal-websocket-account-events// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport } from "@solana/kit";import { createServer, type AddressInfo, type Socket } from "node:net";const apiKey = process.env.CARBIUM_KEY ?? "";if (!apiKey) {  console.error("Set CARBIUM_KEY, then run: node main.ts [account ...]");  process.exit(1);}const USDC = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v";const rpc = createSolanaRpcFromTransport(  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey } }),);// The game server connects here and reads one JSON object per line.const clients = new Set<Socket>();const relay = createServer((c) => {  clients.add(c);  c.on("error", () => c.destroy());  c.on("close", () => clients.delete(c));});relay.listen(Number(process.env.RELAY_PORT ?? 8787), "127.0.0.1", () => console.error("relay listening on port", (relay.address() as AddressInfo).port));const emit = (event: object) => {  const line = JSON.stringify(event) + "\n";  process.stdout.write(line);  for (const c of clients) c.writableLength > 1_000_000 ? c.destroy() : c.write(line); // a reader far behind is cut off};// A token account (165 bytes, or longer with account type 2 at byte 165 under Token-2022) keeps its amount as a little-endian u64 at byte 64.const amountOf = (owner: string, b64: string) => {  const raw = Buffer.from(b64, "base64");  return ["TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA", "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"].includes(owner) && (raw.length === 165 || raw[165] === 2) ? String(raw.readBigUInt64LE(64)) : null;};// USDC token accounts touched by the newest USDC transactions.async function findAccounts(): Promise<string[]> {  const sigs = await rpc.getSignaturesForAddress(address(USDC), { limit: 6 }).send();  const txs = await Promise.allSettled(    sigs.filter((s) => !s.err).map((s) => rpc.getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }).send()),  );  const found = new Set<string>();  for (const r of txs) {    if (r.status === "rejected") {      console.error("getTransaction failed:", r.reason instanceof Error ? r.reason.message : r.reason);      continue;    }    const tx = r.value as any; // null when the ledger no longer holds an older signature    for (const b of tx?.meta?.postTokenBalances ?? []) {      if (b.mint !== USDC) continue;      const k = tx.transaction.message.accountKeys[b.accountIndex];      found.add(typeof k === "string" ? k : k.pubkey);    }  }  return [...found].slice(0, 6);}async function main() {  const accounts = process.argv.length > 2 ? process.argv.slice(2) : await findAccounts();  if (accounts.length === 0) throw new Error("no accounts to watch; pass account addresses");  console.error("watching", accounts.join(" "));  const subs = new Map<number, string>(); // subscription id -> account  const newest = new Map<string, number>(); // account -> newest slot sent  const url = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");  url.searchParams.set("api-key", apiKey);  const ws = new WebSocket(url);  ws.onopen = () =>    accounts.forEach((a, i) =>      ws.send(JSON.stringify({ jsonrpc: "2.0", id: i, method: "accountSubscribe", params: [a, { encoding: "base64", commitment: "confirmed" }] })),    );  ws.onmessage = (ev) => {    const m = JSON.parse(String(ev.data));    if (m.error) return void console.error("accountSubscribe refused:", m.error.message);    if (typeof m.result === "number") return void subs.set(m.result, accounts[m.id]);    if (m.method !== "accountNotification") return;    const account = subs.get(m.params.subscription);    const { context, value } = m.params.result;    if (!account || context.slot <= (newest.get(account) ?? 0)) return;    newest.set(account, context.slot);    emit({ type: "account", account, slot: context.slot, lamports: String(value.lamports), amount: amountOf(value.owner, value.data[0]) });  };  ws.onerror = () => console.error("socket error");  ws.onclose = () => {    console.error("socket closed");    process.exit(1); // a supervisor restarts the relay  };}main().catch((e) => {  console.error(e instanceof Error ? e.message : e);  process.exit(1);});

run: node main.ts

Every line also prints on stdout, so you can run the relay before any engine code exists and watch what the game would receive. Diagnostics go to stderr. When the Carbium socket closes, the process exits with code 1. Run it under a supervisor such as a systemd unit or a container restart policy, and let the game server reconnect to the port.

04

Reading it in Unreal

In C++, add the Sockets and Networking modules, create a client socket through ISocketSubsystem, connect to 127.0.0.1 and the relay port, and call Recv from a worker thread built on FRunnable. Split the bytes on newlines, parse each line with FJsonSerializer, and hand the result to the game thread with AsyncTask(ENamedThreads::GameThread, ...) before touching an actor or any other UObject.

A game instance subsystem is a good owner for that thread. It exposes a multicast delegate such as OnAccountEvent(Account, Slot, Amount), and gameplay code binds to the delegate and never sees the socket. If the connection drops, the thread waits a second and connects again. The relay keeps no backlog, so after a reconnect the subsystem reads the current state once, through your inventory loader or a getAccountInfo call, before it trusts later events. Unreal NFT inventory loader covers the load that comes first.

Run this on the dedicated server only. Clients hear about a change the way they hear about anything else in Unreal, through replication: the server sets a replicated property on the owning actor, a PlayerState for instance, and the engine sends it down the connections that already exist. No client needs to know that a chain is involved.

05

What watching costs

An accountSubscribe costs 25 credits to open, then 20 credits per MiB sent to the relay. Six watched accounts open for 150 credits. The charge falls once per account on the relay's socket, so ten game servers reading the relay change nothing. A refused subscription costs nothing, and an accountSubscribe that never notified is refunded when it closes. Credits and rates are per account, and its keys share one budget.

The traffic charge follows how often your accounts are written. A prize vault that changes a few times a minute costs little. A busy USDC account, like the ones the program picks for its demo run, can notify every slot, often with the same amount as the line before, so the game should compare values before it acts. Choose accounts the game acts on and skip the ones that only look interesting.

06

Where it ends

  • A plain SOL wallet sends nothing on accountSubscribe, so a player's SOL balance never arrives this way. Follow logsSubscribe with a mention and re-read getBalance after each line. Token accounts and program-owned accounts notify normally.
  • The relay holds no history. Changes written while it was down, or while the game server was disconnected, are gone, and the first read after a reconnect has to establish the current state.
  • The watch list is fixed when the relay starts. A new player's token account means a new subscription, which counts against your plan's cap. Your own backend picks the list and restarts the relay to change it, and a game client never picks an address.
  • Events arrive at confirmed. For a reward that is expensive to take back, change commitment in the subscribe call to finalized and keep the rest.
  • The port has no authentication. It binds to loopback, and it should stay there. A relay on another machine needs a private network and a firewall rule.
  • A change is a chain event. Anything the game needs every frame, such as a health bar or a position, stays in the game's own state, and the chain value gets copied in when an event arrives.
07

When it goes wrong

what goes wrongwhat to do
The relay exits at once with Set CARBIUM_KEY.Export CARBIUM_KEY in the environment of the process that starts the relay. A supervisor does not inherit your shell, so put it in the unit's environment file.
The log shows accountSubscribe refused: followed by a message.Read the message. Your plan caps sockets and subscriptions per account, so watch fewer accounts or raise the plan. A refused subscription costs nothing, and the others stay open.
The relay exits with an HTTP 401 error while it looks for accounts, or, run with account arguments, prints socket error and socket closed within a second and no line ever prints.An unknown key gets a 401 before the handshake ends. Check that CARBIUM_KEY holds the whole key and that CARBIUM_WS_URL, if you set it, is wss://services.carbium.sh.
getTransaction failed with -32015 while the relay looks for accounts.The transaction is a v1 transaction and the call left maxSupportedTransactionVersion out or set it to 0. Pass 1 in the config object.
The relay lists accounts and stays silent for minutes.The accounts are quiet, or one is a plain SOL wallet, which sends nothing on accountSubscribe. Watch a token account that changes, or run without arguments to see the demo accounts.
The Unreal side fails to parse some lines and the errors stop on their own.TCP delivers bytes in arbitrary chunks, so one Recv can end in the middle of a line. Keep a buffer, cut only at \n, and parse complete lines.
08

Questions

Why not open the WebSocket from the game client?

The key would ship inside every build and any player could read it. Each client would also take a socket from the account's cap, and Free carries 5.

Can I skip the relay and use Unreal's WebSockets module on the server?

Yes, on a trusted dedicated server the module can connect to the wss URL and send the same accountSubscribe messages. You then carry subscription ids, the key and reconnect logic inside engine code. The relay keeps that in one small file.

Do clients need to read anything from the relay?

No. The server applies the event to game state and replicates it, so clients get it through the connection they already hold.

How many accounts can one relay watch?

As many subscriptions as your plan allows per account. The relay needs one socket in all, and each watched account opens one subscription on it.