This version (v0.7) has not been published to npm yet.
Skip to content

Realtime ​

Realtime delivers to the app what the gateway publishes over WebSocket: balance, notifications and, in the product packages, markets and orders. It lives in a separate entry, @getenginex/sdk/realtime, so that those who do not use WebSocket do not pay for its bytes.

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

const realtime = createRealtime(enginex) // always the same instance for the same client
const off = realtime.subscribe(coreTopics.balance(), (update, meta) => {
  console.log(update.available, meta.kind) // 'event' (or 'snapshot'/'delta' in sequenced mode)
})
realtime.onResync(coreTopics.balance(), () => reloadBalance()) // reload the baseline over HTTP
realtime.onStatus((status) => showBanner(status))
off() // cancels only this subscription

Topics ​

A topic is a typed descriptor, created by a factory: coreTopics.balance() and coreTopics.notification() in the core; predictionsTopics in @getenginex/sdk-predictions. The message arrives validated and in camelCase, in the client's validation mode (strict discards a message outside the schema; warn delivers it recovered field by field and warns through onValidationIssue; see Response validation). An error thrown in the handler does not affect the SDK.

Lazy connection ​

Nothing connects when you create realtime. The connection opens on the first subscribe, is a single one for all the client's topics and closes about 1 s after the last off(). client.dispose() closes the connection and, after it, subscribe throws CONFIGURATION_ERROR.

The URL comes from the client's wsUrl option; without it, from baseUrl (http→ws, https→wss, plus /ws) and, without baseUrl, from the page's origin. The SDK appends the access token in ?token= (renewed before connecting if it is expired); the token never appears in hooks, warnings or errors.

ts
createEnginexClient({ baseUrl: 'https://api.operador.com', wsUrl: 'wss://ws.operador.com/ws' })

Status ​

realtime.status() and realtime.onStatus(listener) report the connection state:

StatusMeaning
connectingFirst connection in progress.
openConnected.
reconnectingDropped; trying again with exponential backoff and jitter (1 s up to 30 s), with no limit.
closedNo subscribers, after dispose(), or the gateway refused the private topics (below).
unavailableNo WebSocket available or no URL: subscribe becomes a no-op and never throws because of it.

closed due to refusal applies to all topics

After a repeated unauthorized on a private topic (see Private topics), the connection is closed for all topics, including the public ones (market, orderbook...): no handler receives anything more until the session gets a new access token (a new login or a refresh) or the user changes. hooks.onError receives UNAUTHENTICATED: it is time to ask for login again.

Reconnection and onResync ​

After a drop, the SDK reconnects, resubscribes to all topics and fires onResync once per active topic. The gateway does not resend what was lost during the drop: use onResync to reload the baseline over HTTP (e.g. wallet.getBalance()) and only then continue applying messages. Live balance shows the complete pattern.

ts
// one topic: pass the same descriptor as subscribe (on a private one, it applies to the session's user)
const off = realtime.onResync(coreTopics.balance(), () => reloadBalance())

// all topics: the listener receives the full topic, e.g. 'market:m-1'
realtime.onResync((topic) => console.log('reload', topic))

Treat the descriptor (Topic) as opaque: create it with the factory (coreTopics.balance(), predictionsTopics.orderbook({ marketId })) and pass it to subscribe/onResync, without reading its fields.

onResync also fires in sequenced mode (below) when a requested snapshot does not arrive within 10 s. A connection with no response to a ping (every 30 s, with a 10 s tolerance) is considered dead and reconnected.

If the gateway responds with an error to a subscribe for another reason (e.g. rate_limited, a message limit), hooks.onError receives the error (RESOURCE_EXHAUSTED for rate_limited) and the SDK resends that subscribe on its own, on the same connection, with the same backoff (1 s, 2 s, 4 s... per topic).

Private topics ​

balance and notification belong to the user themselves: the descriptor takes no id and realtime uses the session's sub (balance:<sub>). Without a session, subscribe throws UNAUTHENTICATED. When the session's user changes (logout, login to another account), realtime reconnects with the new token and discards the previous user's private subscriptions: their handler never receives a message from the next user. React to the change with enginex.session.subscribe and subscribe again. A token refresh does not reconnect.

The gateway validates the token only when opening the connection and silently downgrades an invalid token to anonymous. If it responds unauthorized on a private topic with an active session, the SDK renews the token and tries one more time; if it repeats, the status becomes closed (for all topics, including the public ones) and hooks.onError receives UNAUTHENTICATED. There is never a reconnection loop. If the renewal itself fails (network, gateway down), the extra attempt is not spent: the SDK tries again with the backoff growing up to 30 s, and returns to normal when a private topic is accepted.

Multi-tenant mode without sequencing ​

In production the gateway runs multi-tenant: simple messages (meta.kind === 'event'), with no sequence number and no snapshot. A lost message is not detectable; that is why the baseline is always reloaded over HTTP on onResync and when subscribing. In single-tenant environments (WS_SEQUENCED), snapshot, delta and heartbeat arrive with seq: the SDK detects a gap (seq greater than the last + 1), requests snapshot_request, discards the deltas until the snapshot and discards duplicates. If the snapshot does not arrive within 10 s, onResync fires and the next delta becomes the new baseline of the sequence. The handler receives the same format in both modes, with meta.kind and meta.seq.

The balance snapshot is not delivered

In sequenced mode the balance: snapshot is the raw protobuf of GetBalance, in a different format from balance_update. coreTopics.balance() ignores that snapshot (no validation warning and without reaching the handler); the deltas proceed normally. Load the initial balance with wallet.getBalance().

Without an available WebSocket ​

Realtime uses globalThis.WebSocket or the client's webSocket option. Node 22+ has a global WebSocket, so on a modern Node server realtime does not become unavailable. Without any WebSocket (older runtimes, or nothing passed in webSocket), the status is unavailable and subscribe returns a no-op. Even so, create realtime and subscribe only in the browser (e.g. inside a useEffect): a connection opened during server rendering makes no sense, and off() needs to run on unmount.

tsx
useEffect(() => {
  const realtime = createRealtime(enginex)
  const off = realtime.subscribe(coreTopics.balance(), (update) => setBalance(update.available))
  return off
}, [])

Outside the browser: the Origin ​

The gateway resolves the connection's tenant from the Origin header, which the browser sends on its own and a Node client does not. That is why, on a server or script, neither Node's global WebSocket nor the ws package work when passed directly: the connection is refused before opening and the status stays at reconnecting. Pass in webSocket a constructor that adds the operator site's Origin (realtime only calls new webSocket(url)):

ts
// Node 22+: the global WebSocket (undici) accepts `{ headers }` as the second argument.
type NodeWebSocket = new (url: string, init: { headers: Record<string, string> }) => WebSocket

class OriginWebSocket extends (globalThis.WebSocket as unknown as NodeWebSocket) {
  constructor(url: string) {
    super(url, { headers: { Origin: 'https://casino.operador.com' } })
  }
}

createEnginexClient({ baseUrl, webSocket: OriginWebSocket })

With the ws package (or another implementation), the pattern is the same:

ts
import WebSocket from 'ws'

class OriginWebSocket extends WebSocket {
  constructor(url: string) {
    super(url, { origin: 'https://casino.operador.com' })
  }
}

createEnginexClient({ baseUrl, webSocket: OriginWebSocket })

In React and Vue ​

The adapters wrap this API in hooks (@getenginex/sdk-react, also re-exported by @getenginex/sdk-next) and composables (@getenginex/sdk-vue) with the same names:

tsx
import { coreTopics } from '@getenginex/sdk/realtime'
import { useRealtime, useRealtimeStatus, useRealtimeSync } from '@getenginex/sdk-react'

export function RealtimeBridge() {
  useRealtimeSync() // balance and notifications kept fresh in the TanStack cache, resync included
  const status = useRealtimeStatus()
  useRealtime(coreTopics.notification(), (notification) => toast(notification.title))
  return status === 'reconnecting' ? <Banner>Reconnecting...</Banner> : null
}
  • useRealtime(topic, handler) subscribes while the component is mounted and unsubscribes when it unmounts; a private topic waits for a user in the session and resubscribes on user switch.
  • useRealtimeStatus() returns the connection status, without opening the connection.
  • useRealtimeSync() is the ready-made version of the onResync pattern above for TanStack Query: it invalidates the balance query on every balance_update, the notifications queries on every notification, and the wallet and notifications queries after a reconnection. Product topics (e.g. predictionsTopics.orderbook) go in its topics option, with the keys each one feeds.

Details and the Vue form in React and Vue.

Testing ​

createMockRealtime() from @getenginex/sdk/testing provides a fake WebSocket, with controls to send messages, drop the connection and simulate refused topics. See Testing.