Copyright © 2025-2026 Dankest, LLC

XChain SDK: WebSocket Client

The SDK includes a built-in WebSocket client for real-time event streaming from the xchain-explorer. It wraps the explorer’s WebSocket API with a developer-friendly interface including convenience methods, automatic reconnection with catch-up, and lifecycle hooks.

Quick Start

const { XChainSDK } = require('@dankest-llc/xchain-sdk');

// The WebSocket follows the explorer: https://explorer.xchain.io becomes
// wss://explorer.xchain.io/BTC/api/websocket. A bare host would dial ws://host:8080.
const sdk = new XChainSDK({
    network: 'bitcoin-mainnet',
    explorerUrl: 'https://explorer.xchain.io'
});

// Connect the WebSocket
await sdk.connectWs();

// Listen for new blocks
const unsub = sdk.onBlock((event) => {
    console.log('New block:', event.data.block_index);
});

// Stop listening
unsub();

Configuration

The WebSocket client is auto-created when explorerUrl or websocketUrl is configured. No separate initialization needed; it shares the explorer’s host and port by default.

Constructor Options

Option Type Default Description
websocketUrl string explorerUrl WebSocket server hostname (falls back to explorer URL)
websocketPort number explorerPort WebSocket server port (falls back to explorer port)

Environment Variables

Variable Description
WEBSOCKET_URL WebSocket server hostname
WEBSOCKET_PORT WebSocket server port

Resolution Priority

  1. Constructor websocketUrl / websocketPort
  2. Constructor explorerUrl / explorerPort
  3. Hub-discovered endpoints (via init())
  4. Environment variables WEBSOCKET_URL / WEBSOCKET_PORT
  5. Environment variables EXPLORER_URL / EXPLORER_PORT

Connection Management

// Connect (returns Promise, resolved on WELCOME)
const serverInfo = await sdk.connectWs();
console.log('Server version:', serverInfo.version);

// Check connection state
sdk.ws.isConnected(); // true

// Disconnect
sdk.disconnectWs();

sdk.stop() automatically disconnects the WebSocket.

Convenience Methods

Every convenience method returns an unsubscribe function. Call it to remove the handler and unsubscribe from the channel.

sdk.onBlock(callback)

Listen for new blocks.

const unsub = sdk.onBlock((event) => {
    console.log('Block', event.data.block_index, 'with', event.data.action_count, 'actions');
});

sdk.onAction(callback, opts?)

Listen for new actions with optional filters.

// All actions
sdk.onAction((event) => {
    console.log(event.data.action, event.data.action_index);
});

// Only specific types
sdk.onAction((event) => {
    console.log('Order event:', event.data.action_index);
}, { types: ['ORDER', 'ORDER_MATCH', 'ORDER_EXPIRE'] });

Options: { types?: string[], statuses?: string[], ticks?: string[] } (neither statuses nor ticks is supported on the actions stream: no action frame carries a status or a tick, so neither filter can ever reject an event. The SDK drops both rather than forward them, and a raw client that sends them gets them back under SUBSCRIBED ignored_filters. ticks is meaningful only as the token channel’s batch entity param.)

sdk.onAddress(address, callback, opts?)

Watch an address for all relevant events (actions, balance changes, order matches, COINPay obligations).

const unsub = sdk.onAddress('1abc...', (event) => {
    console.log(event.type, ':', event.data);
}, { snapshot: true });

Events delivered: NEW_ACTION, ADDRESS_UPDATE, MEMPOOL_ACTION, MEMPOOL_REMOVED, ORDER_MATCH, ORDER_EXPIRED, COINPAY_REQUIRED, COINPAY_FULFILLED, COINPAY_EXPIRED, SWAP_MATCH, SWAP_EXPIRED, DISPENSE, DISPENSER_CLOSED, DISPENSER_EXPIRED, BET, BET_EXPIRED, BET_CLOSED, ATTESTATION_REQUEST, ATTESTATION_RESPONSE, XCALL_COMPLETED, XCALL_EXPIRED

Options: { types?: string[], statuses?: string[], snapshot?: boolean } (statuses is not supported: never honored by the server; do not rely on it)

sdk.onMempoolAction(address, callback)

Watch an address for UNCONFIRMED (pre-validation) transactions only: MEMPOOL_ACTION when the decoder first sees one, MEMPOOL_REMOVED when it leaves the mempool. Shares onAddress’s subscription (same channel, same { address } params), so watching both confirmed and unconfirmed events for one address costs a single explorer subscription slot, not two.

sdk.onMempoolAction('1abc...', (event) => {
    console.log(event.type, ':', event.data.tx_hash);
});

MEMPOOL_REMOVED cannot distinguish “confirmed” from “evicted”; reconcile against the confirmed NEW_ACTION feed rather than treating a removal as a result. first_seen is unix SECONDS and may be null.

sdk.onToken(tick, callback)

Watch a token for supply/holder changes. Sends a snapshot on subscribe.

sdk.onToken('PEPE', (event) => {
    console.log('PEPE supply:', event.data.supply, 'holders:', event.data.holders);
});

sdk.onMarket(tick1, tick2, callback)

Watch a market pair for price/volume changes. Sends a snapshot on subscribe.

sdk.onMarket('PEPE', 'BTC', (event) => {
    console.log('PEPE/BTC price:', event.data.last_price);
});

sdk.onDispenser(actionIndex, callback)

Watch a dispenser for triggers, status changes, and expiration. Sends a snapshot on subscribe.

sdk.onDispenser(12345, (event) => {
    console.log(event.type, 'remaining:', event.data.give_remaining);
});

Events delivered: DISPENSER_UPDATE, DISPENSE, DISPENSER_CLOSED, DISPENSER_EXPIRED

The three lifecycle events (DISPENSE, DISPENSER_CLOSED, DISPENSER_EXPIRED) carry data.dispenser_action_index = the dispenser you subscribed to, the same way the bet feed carries data.feed_action_index. On a DISPENSE event data.action_index is that individual dispense’s own index, not the dispenser’s, so a page following more than one dispenser correlates on dispenser_action_index. DISPENSER_UPDATE and the subscribe snapshot carry no dispenser_action_index at all: on those frames data.action_index already IS the dispenser you subscribed to.

sdk.onBetFeed(feedActionIndex, callback)

Watch one betting market by its feed ACTION_INDEX: bets placed, the deadline latch, resolution, cancellation, and expiry. Sends a snapshot on subscribe.

sdk.onBetFeed(1234, (event) => {
    if (event.type === 'BET' && event.data.action_format === 2) { /* a stake was placed */ }
    if (event.type === 'BET' && event.data.action_format === 3) { /* the market paid out */ }
    if (event.type === 'BET_CLOSED') { /* deadline latch: stop accepting stakes */ }
    if (event.type === 'BET_EXPIRED') { /* refund pass: every stake refunded */ }
});

Events delivered: BET (branch on data.action_format: 0 create, 1 cancel, 2 stake placed, 3 payout decision), BET_EXPIRED, BET_CLOSED. Every event is keyed on the MARKET via data.feed_action_index, not on the individual bet’s own action_index.

sdk.onXcall(callId, callback)

Watch one cross-chain call by its 64-character hex call_id for its terminal phases. Sends a snapshot on subscribe. The id is lower-cased before it is sent, because the explorer normalizes case at subscribe time.

sdk.onXcall('a1b2c3...', (event) => {
    console.log(event.type, ':', event.data.call_id);
});

Events delivered: XCALL_COMPLETED, XCALL_EXPIRED.

sdk.onAttestation(callback)

Watch the global attestation stream: both request and response phases of oracle attestation traffic. No entity key and no snapshot; it is a stream, not an entity with current state.

sdk.onAttestation((event) => {
    console.log(event.type, ':', event.data);
});

Events delivered: ATTESTATION_REQUEST, ATTESTATION_RESPONSE.

sdk.onCoinpayRequired(address, callback)

Shortcut for watching an address for COINPAY_REQUIRED events only. Ideal for trading bots that need to auto-fulfill COINPay obligations.

sdk.onCoinpayRequired('1BotAddr...', (event) => {
    const { payer_address, payee_address, coin_amount, expiration } = event.data;
    console.log('COINPay needed:', coin_amount, 'BTC to', payee_address);
    console.log('Deadline:', new Date(expiration * 1000));
    // Construct and broadcast COINPAY transaction...
});

sdk.onOrderMatch(address, callback, opts?)

Shortcut for watching an address for ORDER_MATCH events. To react only to coinpay-required matches, check event.data.status inside the callback: statuses filtering is not supported by the server.

// All order matches
sdk.onOrderMatch('1abc...', (event) => {
    console.log('Order matched:', event.data.action_index);
});

// Only coinpay-required matches (filter client-side; the server does not honor a statuses option)
sdk.onOrderMatch('1abc...', (event) => {
    if (event.data.status !== 'pending_coinpay') return;
    console.log('Needs COINPay:', event.data.action_index);
});

sdk.onNetworkStats(callback)

Listen for network statistics updates (emitted with each new block).

sdk.onNetworkStats((event) => {
    console.log('Block height:', event.data.block_height);
});

Low-Level API

For advanced use cases, access the WebSocket client directly via sdk.ws.

const ws = sdk.ws;

// Subscribe with full control (statuses is not a supported filter; the server ignores it)
await ws.subscribe(['address'], {
    address: '1abc...',
    types: ['ORDER_MATCH', 'COINPAY_REQUIRED'],
    snapshot: true,
    since_action_index: 45000
});

// Register event handlers
ws.on('ORDER_MATCH', (msg) => { /* ... */ });
ws.once('COINPAY_REQUIRED', (msg) => { /* fires once then auto-removes */ });

// List active subscriptions
const list = await ws.listSubscriptions();
console.log(list.data.subscriptions);

// Unsubscribe
ws.unsubscribe(['address'], { address: '1abc...' });

// Follow one betting market: bets placed, the deadline latch, resolution,
// cancellation, expiry. A parimutuel payout is only ever a projection until the
// market resolves, so a market page needs the pools to stay current.
await ws.subscribeBetFeed(1234);

// Create, cancel, place and resolve all arrive as ONE event type, because BET is
// one action name carrying four formats. `data.action_format` is what tells them
// apart: 0 create, 1 cancel, 2 a stake placed, 3 the payout decision.
ws.on('BET', (msg) => {
    if (msg.data.action_format === 2) { /* recompute projected payouts */ }
    if (msg.data.action_format === 3) { /* the market paid out */ }
});

// The deadline latch closes betting. It has no transaction behind it (the node
// writes it in an end-of-block pass), so it arrives under its own type with
// tx_hash null and synthetic true.
ws.on('BET_CLOSED', (msg) => { /* stop accepting stakes; msg.data.block_index */ });

// The refund pass, when a market is never resolved inside its refund window.
ws.on('BET_EXPIRED', (msg) => { /* every stake refunded */ });

ws.unsubscribeBetFeed(1234);

Every event on this channel is keyed on the MARKET, not on the action that caused it: data.feed_action_index is the feed you subscribed to, so a page following one market receives stakes placed by strangers on it and nothing from any other.

Reconnection and Catch-Up

The client automatically reconnects on disconnect with exponential backoff. On reconnect, it replays every subscription. Those that carry actions (actions and address), and those naming blocks, carry since_action_index set to the last action index received before the disconnect; the WELCOME of the new connection does not move that cursor. The explorer runs one catch-up per connection, so the client sends these one at a time, each after the previous one’s CATCH_UP_COMPLETE, and continues a replay the server truncated at its row cap from where it stopped. A blocks subscription replays nothing (the explorer never replays NEW_BLOCK); its CATCH_UP_COMPLETE names NEW_BLOCK in not_replayed, which the client emits as a not_replayed event.

Every frame the client sends is paced under the explorer’s per-connection message rate (limits.max_message_rate from WELCOME, 10 per second before it arrives), so a reconnect with many subscriptions goes out over a few hundred milliseconds instead of in one burst. A subscribe or catch-up the explorer still drops with RATE_LIMITED is sent again after one drain interval, up to five times. The messageRate constructor option sets the rate assumed before WELCOME.

A REORG frame (the chain was rolled back below rows already delivered) lowers the cursor to just below its first_invalid_action_index, and is dispatched to ws.on('REORG', ...) handlers like any frame: drop what you hold at or above that index, then apply the replacement frames that follow. See REORG.

Catch-up events have catch_up: true in the envelope. After each replay, a CATCH_UP_COMPLETE event is emitted.

ws.on('CATCH_UP_COMPLETE', (msg) => {
    console.log('Caught up:', msg.data.events_replayed, 'events replayed');
});

When a catch-up is refused (for example CATCH_UP_TOO_OLD, when the cursor is further behind than the explorer’s catch-up depth limit, or CATCH_UP_REORGED, when a rollback while the client was away replaced rows at or below its cursor) or goes unanswered for 30 seconds, the client emits resync_required and moves on to the next subscription. The missed actions were not replayed, so backfill them over REST:

ws.on('resync_required', (msg) => {
    // msg.data: { code, message, channels, since_action_index }, plus
    // fork_block_index and first_invalid_action_index for CATCH_UP_REORGED
    reloadFromRest(msg.data.channels, msg.data.since_action_index);
});

When the replay comes from an explorer whose indexed tip is behind the chain, its CATCH_UP_COMPLETE carries stale: true and the client emits stale_replay. Every row it replayed is real, and the cursor still moves to the last one, but the replay ends at that tip rather than at the chain’s. Later rows arrive live once the explorer catches up, so treat the event as a “you are behind” signal, not a gap to backfill:

ws.on('stale_replay', (msg) => {
    // msg.data: { channels, since_action_index, latest_action_index }
    showBehindBanner(msg.data.latest_action_index);
});
sequenceDiagram
    participant Client
    participant Server

    Note over Client,Server: connection is lost
    Client->>Client: reconnect with exponential backoff
    Client->>Server: reconnect

    Server-->>Client: WELCOME, current tip (cursor unchanged)
    Client->>Server: replay first action subscription, since_action_index = last received index
    Server-->>Client: catch-up events, catch_up true
    Server-->>Client: CATCH_UP_COMPLETE, events_replayed
    Client->>Server: replay next action subscription, same since_action_index
    Server-->>Client: catch-up events, then CATCH_UP_COMPLETE

Reconnection uses the same retry configuration as the explorer/encoder clients:

Setting Default
Max attempts 10
Base delay 1,000 ms
Max delay 30,000 ms
Backoff factor 2x

Configure via the retry constructor option:

new XChainSDK({
    network: 'bitcoin-mainnet',
    explorerUrl: 'https://explorer.xchain.io',
    retry: { maxRetries: 20, baseDelay: 500, maxDelay: 60000 }
});

Lifecycle Hooks

The WebSocket client supports five hooks, configured via the hooks constructor option:

Hook Fires When
onWsConnect WebSocket connection established
onWsDisconnect WebSocket connection closed
onWsMessage Any message received from server
onWsReconnect Before a reconnection attempt
onWsSchemaMismatch The server’s frame carries a newer schema_version than this SDK build understands (fires once per connection; parsing continues)
const sdk = new XChainSDK({
    network: 'bitcoin-mainnet',
    explorerUrl: 'https://explorer.xchain.io',
    hooks: {
        onWsConnect:    (info) => console.log('WS connected:', info.url),
        onWsDisconnect: (info) => console.log('WS disconnected:', info.code),
        onWsMessage:    (msg)  => console.log('WS event:', msg.type),
        onWsReconnect:  (info) => console.log('WS reconnecting, attempt', info.attempt)
    }
});

Error Handling

WebSocket errors throw SDKExplorerError (same class as REST API errors):

const { SDKExplorerError } = require('@dankest-llc/xchain-sdk');

try {
    await sdk.connectWs();
} catch (e) {
    if (e instanceof SDKExplorerError) {
        console.log('WS error:', e.code, e.message);
    }
}
Error Code Cause
WS_CONNECTION_FAILED Could not connect to WebSocket server
WS_CONNECTION_CLOSED Connection closed before response received
WS_TIMEOUT No response for a request within timeout
WEBSOCKET_NOT_CONFIGURED Called a WS method without configuring WebSocket URL

Server-side errors (e.g., SUBSCRIPTION_LIMIT) are returned as rejected Promises from subscribe(). A RATE_LIMITED refusal is sent again under the same id up to five times first, and rejects the Promise only after that.

Edit this page on GitHub ↗