websocket.ts


Overview

The [websocket.ts](/projects/291/69055) file defines a specialized WebSocket client class, `WebsocketClient`, designed to connect to a Blockbook indexer's real-time WebSocket API. This client enables subscribing to live blockchain events, specifically new blocks and new transactions related to specified addresses. It extends a base WebSocket client from the `@shapeshiftoss/websocket` package, adding custom handlers for processing incoming blockchain event data and managing subscriptions.

Key functionalities include:

This client is critical for applications needing low-latency, event-driven updates from blockchain indexers, such as wallets or blockchain explorers.


Classes and Types

Type Aliases

Interface: WebsocketArgs

interface WebsocketArgs extends Omit<Args, 'logger'> {
  transactionHandler: TransactionHandler | Array<TransactionHandler>
  blockHandler: BlockHandler | Array<BlockHandler>
}

Class: WebsocketClient

export class WebsocketClient extends BaseWebsocketClient

A specialized WebSocket client for Blockbook event subscriptions.

Properties

Property

Type

Description

`handleTransaction`

`TransactionHandler

TransactionHandler[]`

`handleBlock`

`BlockHandler

BlockHandler[]`

`addresses`

`string[]`

List of blockchain addresses to subscribe for transaction updates.

Constructor

constructor(_url: string, args: WebsocketArgs, opts?: Options)

**Behavior:**

Methods


protected onOpen(): void

Called when the WebSocket connection opens.

**Usage:**

// Automatically invoked internally on connection open

protected async onMessage(message: WebSocket.MessageEvent): Promise<void>

Handles incoming WebSocket messages.

**Parameters:**

**Return:**

**Usage Example:**

// Handlers are invoked automatically when new block or transaction events arrive

subscribeAddresses(addresses: string[]): void

Subscribes to transaction events for specified blockchain addresses.

**Parameters:**

**Usage Example:**

wsClient.subscribeAddresses(['bc1qaddress1...', 'bc1qaddress2...'])

private getAddressesSubscription(): Subscription

Constructs the subscription request object for address transaction events.

**Returns:**

{
  "jsonrpc": "2.0",
  "id": "newTx",
  "method": "subscribeAddresses",
  "params": {
    "addresses": [/* subscribed addresses */],
    "newBlockTxs": true
  }
}

This subscription ensures the client receives new transactions related to subscribed addresses, including transactions in newly mined blocks.


Important Implementation Details


Interaction with Other System Parts


Usage Example

import { WebsocketClient } from './websocket'
import { Tx, NewBlock } from './models'

async function handleTransaction(tx: Tx): Promise<void> {
  console.log('New transaction:', tx.txid)
  // process transaction
}

async function handleBlock(block: NewBlock): Promise<void> {
  console.log('New block height:', block.height)
  // process block
}

const wsClient = new WebsocketClient(
  'wss://blockbook.example.com',
  {
    transactionHandler: handleTransaction,
    blockHandler: [handleBlock], // single or array supported
    apiKey: 'your-api-key', // optional
  }
)

// Subscribe to addresses dynamically
wsClient.subscribeAddresses(['bc1qexampleaddress1...', 'bc1qexampleaddress2...'])

Visual Diagram

classDiagram
    class WebsocketClient {
        -handleTransaction: TransactionHandler | TransactionHandler[]
        -handleBlock: BlockHandler | BlockHandler[]
        -addresses: string[]
        +constructor(_url: string, args: WebsocketArgs, opts?: Options)
        +subscribeAddresses(addresses: string[]): void
        #onOpen(): void
        #onMessage(message: WebSocket.MessageEvent): Promise<void>
        -getAddressesSubscription(): Subscription
    }
    WebsocketClient --|> BaseWebsocketClient
    BaseWebsocketClient : +initialize()
    BaseWebsocketClient : +reset()

Summary

The [websocket.ts](/projects/291/69055) file provides a robust, extensible WebSocket client tailored for Blockbook's real-time blockchain event API. By extending a base client, it focuses on subscribing to new block and transaction events, supports multiple asynchronous handlers, and allows dynamic address subscriptions. This facilitates building reactive blockchain applications with real-time data feeds integrated cleanly into larger systems. The design leverages structured logging, JSON-RPC messaging, and strong typing to ensure reliability and maintainability.