---
url: https://game-engine-io.github.io/enginex-frontend-sdk/flows/live-balance.md
---
# Live balance

The demo above runs the real SDK (`createEnginexClient`, `createRealtime`) with `fetch: createMockFetch(...)` and
`webSocket: createMockRealtime().webSocket` from [`@getenginex/sdk/testing`](/guide/testing): no call
goes out to the network. The balance baseline comes from `wallet.getBalance()` and each `balance_update`
adjusts the screen without polling; the buttons play the role of the gateway (they publish the message
with `emit`). **Drop the connection** loses a credit on purpose: on reconnect, `onResync` reloads the
balance over HTTP and the screen matches again. The **Topic rejected** scenario shows the gateway
answering `unauthorized` to the private topic (status `closed` and `UNAUTHENTICATED`). The **Under the
hood** panel shows the connection status, the WebSocket URL with the `token` masked and the last message
as the handler received it.

`coreTopics.balance()` announces every change in the player's balance (confirmed deposit, bet,
withdrawal) without polling. It requires login: the topic is the session user's. The concepts
(connection, status, `onResync`) are in [Realtime](/concepts/realtime).

```ts
import { createRealtime, coreTopics } from '@getenginex/sdk/realtime'

const realtime = createRealtime(enginex)

async function loadBalance() {
  const balance = await enginex.wallet.getBalance()
  render(balance.realBalance)
}

await loadBalance() // initial balance, over HTTP
let off = realtime.subscribe(coreTopics.balance(), (update) => {
  render(update.available) // already in minor units (cents), like the rest of the SDK
})
// after a drop, reload over HTTP: same descriptor as subscribe, no text comparison
const offResync = realtime.onResync(coreTopics.balance(), () => void loadBalance())

// when leaving the screen
off()
offResync()
```

## What arrives

```ts
interface BalanceUpdate {
  available: number // available balance after the change
  change: number // delta (negative on a debit)
  changeType: string // 'credit', 'debit', 'reserve', 'release'
  description?: string
  updatedAt: string
}
```

## Why `reserved`, `bonus` and `total` do not arrive

The gateway defines these fields in `balance_update`, but the producer only fills `available`, `change`,
`changeType`, `description` and `updatedAt`: the others always arrive as `0`. Exposing them would lead
to showing a zeroed bonus or total. That is why the SDK omits them: for the full balance (real, bonus,
pending withdrawals), use `wallet.getBalance()`, on the initial load and in `onResync`.

## Message loss

The production gateway does not number messages, so an update lost in a drop cannot be detected.
`onResync` (reloading over HTTP) is what guarantees the right screen after reconnecting. In
single-tenant mode the balance snapshot has a different format and the SDK ignores it; the baseline still
comes from `wallet.getBalance()`.

## Switching users

The topic belongs to the user who was logged in when subscribing. On logout, or on login to another
account, the subscription is discarded: subscribe again for the new user.

```ts
let userId = enginex.session.get().userId
enginex.session.subscribe((session) => {
  if (session.userId === userId) return // a token refresh does not need a new subscription
  userId = session.userId
  off()
  if (session.status === 'authenticated') off = realtime.subscribe(coreTopics.balance(), render)
})
```

## Testing

```ts
import { createMockRealtime } from '@getenginex/sdk/testing'

const mock = createMockRealtime()
const enginex = createEnginexClient({ /* ... */ webSocket: mock.webSocket })
// ... subscribe, wait for the connection to open
mock.emit('balance:mock-user-1', 'balance_update', {
  available: 5_000,
  change: 5_000,
  change_type: 'credit',
  updated_at: new Date().toISOString(),
})
mock.drop() // reconnects and fires onResync
```
