Skip to main content
New in v0.5.6 - Real-time balance tracking with WebSocket updates
Subscribe to real-time updates for all your token balances. Automatically fetches initial balances via REST API and keeps them synchronized with WebSocket events.

Return Values

AccountBalance[]
Array of user token balances, automatically updated in real-time. Merged from REST API initial data and WebSocket updates.
boolean
true while fetching initial balances from REST API, false once loaded
boolean
true when WebSocket subscription is active, false otherwise
Error | null
Error object if something went wrong during fetch or subscription, null otherwise
() => void
Function to clear the current error state
() => Promise<void>
Manually refresh balances from REST API (useful for force refresh after errors or manual updates)

Features

Hybrid Data Loading

  1. Initial Load: reads every page of balances via REST (getUserBalances()), which is paginated — a single page would leave assets past the first unreachable.
  2. WebSocket Subscription: subscribes to the balances channel after the initial load.
  3. Race Condition Prevention: the subscription only opens once the REST data is in, so an event cannot be overwritten by the response it raced.
  4. Subscribe-time Snapshot: the channel’s snapshot carries every balance, and the hook applies it to the list it already has — no second REST read.

Applying the snapshot

The snapshot is the complete balance set, which makes it different from a stream of updates in two ways:
  • Its totals and version are taken verbatim from the same durable spot row as REST.
  • A held asset the snapshot omits is zeroed rather than left showing a figure that is no longer true. The row itself stays, so a portfolio renders “0 WSEI” instead of losing the line. A held row carrying a real version is the exception: a versioned zero is an explicit tombstone, so omission cannot be read as “this went to zero” and the row is retained until a newer one arrives.
This matters most on reconnect: the resubscribe brings a fresh snapshot, and balances that moved while the socket was down are corrected from it without a REST round trip.

Real-time Updates

The hook listens to balance update events triggered by:
  • Deposits - Tokens deposited to the vault
  • Withdrawals - Tokens withdrawn from the vault
  • Order Locking - Balance locked when placing orders
  • Order Unlocking - Locked balance released when orders are cancelled or expire
  • Trades - Balance changes from order fills and fee deductions
  • Margin Transfers - Collateral moved into or out of a margin account
A versioned spot event replaces the whole spot row only when its version is higher. Equal or lower versions are idempotent. A collateral transfer that moves the spot wallet row is versioned like any other spot event. Margin collateral notifications — a parent to risk-bucket allocation, a margin-routed deposit — remain unversioned because they are not authoritative user_balances rows; the hook applies those notifications fail-open without changing the held spot version. Refresh margin-account state separately. updatedAt is never used to order rows.

Automatic Balance Updates

When a balance update event is received:
  • If the token already exists in state, the balance is updated with the new values
  • If a new token appears, the hook re-reads from REST — the wire payload carries no assetId, decimals or wrapped-native flag, so a new asset cannot be built from an event alone
  • Balance updates include both normalized (human-readable) and raw (wei) values
That background re-read merges rather than replaces. It runs with the subscription live, so its response is already potentially stale by the time it lands; it therefore adds only genuinely new assets and leaves every held row’s live values untouched. Wire state for an unknown asset is buffered until the read supplies its metadata, then replayed through the same version arbitration as an ordinary event or snapshot. The read is also coalesced — a burst of frames for one unknown asset costs a single read plus one trailing read, rather than one per frame — and it does not raise loading, which describes the initial load. The public refresh() re-reads the full set and applies the same version arbitration: a fetched row supersedes the held one unless the held row carries a newer version, and a held versioned row the fetch omits is retained rather than dropped. So it is a version-aware refresh, not a blind overwrite — an in-flight REST read cannot roll a balance back to a state the stream has already moved past.

Authentication Required

This hook requires an authenticated session. Log in with the useAuth hook (or sdk.login(...)) before using it.

Basic Usage

With Refresh Button

Filter Non-Zero Balances

Balance Summary with Charts

Real-time Balance Updates

Error Handling with Retry

Complete Dashboard Example

AccountBalance Type Structure

See Also