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

# Unity optimistic action confirm

A Node script that follows one transaction signature through processed, confirmed and finalized on a single WebSocket and prints the state change a Unity game server would push to its client, including a revert when the transaction fails.

## Where the wait goes

A player taps an action: open the chest, place the tile, spend the potion. A transaction sits behind that tap, and the game has to decide what to draw while the transaction travels. Most of the wait a player feels comes from the game loop. The common mistake is a loop that blocks on `finalized` before it draws anything, or one that polls on a fixed timer and adds the timer's own delay on top of the chain's.

Once a transaction sits in a block, your code cannot speed up the chain's finality. Since the Alpenglow switch on 2026-10-21 a slot is about 200 ms and `finalized` sits 0 to 1 slots behind `processed`, where it used to sit about 32 behind. With the levels this close, the useful work is on your side of the wire. [Commitment levels](https://carbium.sh/library/howsolana/solana-commitment-levels) explains what each level promises. These are the changes that matter for a game, in the order they pay off:

- Draw the result when the player taps and mark it pending. The screen never waits on the chain for the first frame.
- Get the transaction into an early block: build it on a fresh blockhash from `getLatestBlockhash`, set a compute unit limit sized to what it uses, and add a priority fee read from `getRecentPrioritizationFees`. A transaction that lands early reaches `finalized` early.
- Subscribe to the signature before the send leaves your server, so no notification can slip past between the send and the subscription.
- Replace timer polling with the push notification. A one-second poll adds up to a second of wait to a confirmation that already happened.
- Pick the level by what the action costs to undo. A cosmetic move can proceed at `confirmed`. Anything the player can sell, trade or ship waits for `finalized`.
- Treat an `err` in a notification as a revert of the optimistic draw, and keep the fee in mind: a failed transaction still paid it.

## Three states for the client

The script opens one [WebSocket](https://carbium.sh/docs/websocket) and sends three `signatureSubscribe` calls for the same signature, one each at `processed`, `confirmed` and `finalized`. Each subscription sends a single notification and ends. The script turns every notification into the message a game server would forward to its Unity client.

| Level | Client state | What the game does |
|---|---|---|
| `processed` | `show-pending` | Keep the optimistic draw, add a small pending marker |
| `confirmed` | `mark-confirmed` | Clear the marker, allow reversible follow-up actions |
| `finalized` | `mark-final` | Allow trades, rewards and anything hard to undo |
| any level, `err` set | `revert` | Undo the draw and tell the player the action failed |

The three notifications can arrive close together or in an unexpected order, and one of them can arrive with the next on the same read of the socket. The state machine on the client therefore only moves forward: a `mark-confirmed` that arrives after a `mark-final` changes nothing. A `revert` always wins: a transaction that failed carries its `err` at every level, so no later state can undo it.

## The tracker

Install the one dependency with `npm install @solana/kit@8.6.0` and set `"type": "module"` in `package.json`. Node 24 strips the types on load. The script needs `CARBIUM_KEY`, and `CARBIUM_RPC_URL` and `CARBIUM_WS_URL` are optional overrides. Run `node main.ts <signature>` to follow a signature your own flow just sent.

With no argument the script takes the newest signature of a busy program with `getSignaturesForAddress`, a 50-cell call. That signature has usually landed already, so all three notifications arrive together and the printed timings show the tiers close to each other. Use a signature you have just sent to see the real gaps. While the socket runs, the script reads `getSignatureStatuses` once as a cross-check, and each of the two reads is settled on its own so one failing does not hide the other.

`main.ts` (run: `node main.ts`)

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

import { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";

const key = process.env.CARBIUM_KEY;
if (!key) {
  console.error("Set CARBIUM_KEY.");
  process.exit(1);
}
const rpc = createSolanaRpcFromTransport(
  createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": key } }),
);
const wsUrl = new URL(process.env.CARBIUM_WS_URL ?? "wss://services.carbium.sh");
wsUrl.searchParams.set("api-key", key);
const BUSY_PROGRAM = "JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4";
const LEVELS = ["processed", "confirmed", "finalized"] as const;
const STATE: Record<string, string> = { processed: "show-pending", confirmed: "mark-confirmed", finalized: "mark-final" };

// No argument: the newest signature of a busy program (it has usually landed already).
async function newest(): Promise<string> {
  const sigs = await rpc.getSignaturesForAddress(address(BUSY_PROGRAM), { limit: 1, commitment: "confirmed" }).send();
  if (!sigs[0]) throw new Error("no signature found");
  return sigs[0].signature;
}

// One socket, three subscriptions; each notification becomes the message a game server would push to Unity.
function track(sig: string, ms: number): Promise<void> {
  return new Promise((resolve) => {
    const t0 = Date.now();
    const ws = new WebSocket(wsUrl);
    const level = new Map<number, string>();
    const done = (why: string) => {
      clearTimeout(timer);
      ws.close();
      console.log(JSON.stringify({ end: why }));
      resolve();
    };
    const timer = setTimeout(() => done("timeout"), ms);
    ws.onerror = () => done("socket error");
    ws.onopen = () =>
      LEVELS.forEach((c, i) =>
        ws.send(JSON.stringify({ jsonrpc: "2.0", id: i + 1, method: "signatureSubscribe", params: [sig, { commitment: c }] })),
      );
    ws.onmessage = (ev) => {
      const m = JSON.parse(String(ev.data));
      if (m.error) console.error("subscribe failed:", JSON.stringify(m.error));
      if (typeof m.result === "number" && m.id) level.set(m.result, LEVELS[m.id - 1]);
      if (m.method !== "signatureNotification") return;
      const c = level.get(m.params.subscription) ?? "unknown";
      const { context, value } = m.params.result;
      const state = value.err ? "revert" : (STATE[c] ?? c);
      console.log(JSON.stringify({ state, level: c, slot: context.slot, ms: Date.now() - t0, err: value.err }));
      if (value.err) done("reverted");
      else if (c === "finalized") done("final");
    };
  });
}

const sig = process.argv[2] ?? (await newest().catch((e) => { console.error("sample failed:", String(e)); process.exit(1); }));
console.log(`signature ${sig}`);
const [socket, status] = await Promise.allSettled([
  track(sig, 20_000),
  rpc.getSignatureStatuses([signature(sig)], { searchTransactionHistory: true }).send(),
]);
if (socket.status === "rejected") console.error("socket path failed:", String(socket.reason));
if (status.status === "rejected") console.error("status read failed:", String(status.reason));
else console.log(`status read: ${status.value.value[0]?.confirmationStatus ?? "unknown"} at context slot ${status.value.context.slot}`);
```

## Wiring it into Unity

Keep this logic on your own game server and let Unity talk to that server. The server signs through your wallet flow, subscribes, sends, and pushes the three states to the client over whatever channel the game already uses: a WebSocket, a long-poll or a message in the next state sync. The Unity client holds a small dictionary from action id to state and redraws on each change.

A key placed in a player build, WebGL or native, ships to everyone who downloads the game. The server keeps the [key](https://carbium.sh/docs/auth) and the client never sees it. [Unity player wallets](https://carbium.sh/library/integrate/unity-player-wallets) covers where the signature comes from in the first place.

On the client, store the state next to the action id and the slot of the last notification. When the server reconnects after a drop, it asks `getSignatureStatuses` for every action still pending and replays the state it finds, so a socket that closed in the middle of a round costs one read per pending action and no stuck marker.

## What it costs against your limits

A `signatureSubscribe` opens at 5 credits and then costs 20 credits per MiB sent, and one notification is a few hundred bytes. A refused subscription costs nothing. Three subscriptions per action is 15 credits to open. Your plan caps sockets per account, and Free carries 5, so a game server holds one socket for all players and adds subscriptions to it, never one socket per player.

After a reconnect, one `getSignatureStatuses` call takes the pending signatures as one array, and a [JSON-RPC batch](https://carbium.sh/docs/rpc) carries up to 100 calls when the list runs longer, so a server that restarts with many pending actions never sends one request per action.

## Where it ends

- It reads and never signs or sends. The signature comes from your own wallet flow.
- It shows when each level arrived at your server. The player's own network adds to every number, and the script cannot measure the last hop to the Unity client.
- A signature that never lands, because its blockhash expired, sends no notification at all. Only the timeout in the script ends the wait, and the client has to decide when to give up and offer a retry.
- `processed` can still be undone. A slot notified there can end up skipped when its fork is dropped, so never hand out something irreversible at that level.
- The no-argument run follows a signature that has already landed. It proves the plumbing, not the gaps between levels.

## When it goes wrong

| What goes wrong | What to do |
|---|---|
| The script prints `socket error` or nothing comes back and the run ends with `timeout`. | Check that `CARBIUM_KEY` holds the whole key and reaches the socket as `?api-key=`. An [unknown key](https://carbium.sh/docs/errors) gets 401 at the door. A Free account past its 5 sockets is refused too, so close the sockets you opened. |
| The Unity client shows `mark-confirmed` and then goes back to `show-pending`. | States arrived out of order and the client applied the older one. Keep a rank per state and ignore any message ranked lower than the one shown, except `revert`. |
| A `mark-final` arrives, and later the action turns out to have failed. | The client acted on an `err` it did not read. Check `err` on every notification and send `revert` first, since a failed transaction still lands and still shows all three levels. |
| Every notification arrives at once and the timings look like zero. | The signature had already landed when the subscription opened. Run the script against a signature you just sent, or subscribe before the send leaves the server. |
| `getSignaturesForAddress` lists a signature and the status read prints `unknown`. | The listing comes from a 30-day [address index](https://carbium.sh/docs/migrate) that reaches below the ledger the node holds, so an older signature can have no status left to read. Follow the newest signatures, as the no-argument run does. |

## Questions

### Why subscribe at all three levels instead of only the one I need?

The three subscriptions give the client the pending, confirmed and final states from a single socket without a poll. Each costs 5 credits to open, so the extra two are small next to the wait they remove.

### Should the game grant rewards at confirmed?

Only when the reward can be taken back. For anything a player can sell or trade, wait for `finalized`, which now sits 0 to 1 slots behind `processed`, so the wait is short.

### Does a failed transaction still send all three notifications?

Yes. A transaction that lands and fails reaches each level with a non-null `err`, and it still paid its fee. The script prints a `revert` at the first one and ends there.

### Can one socket carry the subscriptions for every player?

Yes. Each `signatureSubscribe` is its own subscription on the same connection and ends after its one notification, so the socket stays open for the next action. Free carries 5 sockets per account, which is another reason to share one.

## Related

- [Solana commitment levels](https://carbium.sh/library/howsolana/solana-commitment-levels) (How to use Solana, HS0003)
- [Unity player wallets](https://carbium.sh/library/integrate/unity-player-wallets) (Integrations, I0014)
- [carbium.sh/docs/websocket](https://carbium.sh/docs/websocket)
- [carbium.sh/docs/rpc](https://carbium.sh/docs/rpc)
- [carbium.sh/docs/limits](https://carbium.sh/docs/limits)
- [carbium.sh/docs/auth](https://carbium.sh/docs/auth)
- [carbium.sh/docs/errors](https://carbium.sh/docs/errors)
- [carbium.sh/docs/migrate](https://carbium.sh/docs/migrate)
