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:
Establishing and managing a WebSocket connection to the Blockbook server.
Automatic subscription to new block notifications upon connection.
Dynamic subscription to address-specific transaction events.
Dispatching incoming messages to user-defined asynchronous handler functions.
Handling multiple handlers for both transaction and block events.
Robust error handling and session reset logic on receiving events.
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
TransactionHandler
type TransactionHandler = (data: Tx) => Promise<void>An asynchronous function type that handles incoming transaction data (
Tx).BlockHandler
type BlockHandler = (data: NewBlock) => Promise<void>An asynchronous function type that handles incoming new block data (
NewBlock).
Interface: WebsocketArgs
interface WebsocketArgs extends Omit<Args, 'logger'> {
transactionHandler: TransactionHandler | Array<TransactionHandler>
blockHandler: BlockHandler | Array<BlockHandler>
}
Extends the base
Argstype (from@shapeshiftoss/websocket) excluding theloggerproperty.Adds:
transactionHandler: A single or array of transaction handler functions.blockHandler: A single or array of block handler functions.
Used to configure the
WebsocketClient, specifying how to process incoming blockchain events.
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)
_url: Base WebSocket URL of the Blockbook server (e.g.,
"wss://blockbook.example.com").args: Object containing:
transactionHandler: One or more async functions to handle transactions.blockHandler: One or more async functions to handle new blocks.Optional
apiKey(inherited fromArgs) appended to URL if provided.
opts: Optional configuration options for the base WebSocket client.
**Behavior:**
Constructs the full URL including API key if present.
Passes a scoped logger and options to the base client constructor.
Assigns handlers.
Calls
super.initialize()to start the WebSocket connection.
Methods
protected onOpen(): void
Called when the WebSocket connection opens.
Sends a JSON-RPC subscription request to
subscribeNewBlockto receive new block events.If addresses have been subscribed, sends subscription for those addresses' transactions.
**Usage:**
// Automatically invoked internally on connection open
protected async onMessage(message: WebSocket.MessageEvent): Promise<void>
Handles incoming WebSocket messages.
Parses the JSON message.
If message contains data:
If
idis"newBlock"and data contains ahashproperty:Calls
super.reset()to reset connection state.Invokes one or multiple block handlers with the new block data.
If
idis"newTx"and data containstx:Calls
super.reset().Invokes one or multiple transaction handlers with the new transaction data.
Logs errors if message parsing or handling fails.
**Parameters:**
message: The incoming WebSocket message event.
**Return:**
Promise<void>resolves after message processing.
**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.
Updates the internal
addresseslist.Sends a JSON-RPC subscription request for those addresses.
Logs debug message if subscription fails.
**Parameters:**
addresses: Array of blockchain address strings to subscribe to.
**Usage Example:**
wsClient.subscribeAddresses(['bc1qaddress1...', 'bc1qaddress2...'])
private getAddressesSubscription(): Subscription
Constructs the subscription request object for address transaction events.
**Returns:**
Subscriptionobject formatted as:
{
"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
Multiple Handlers Support: The class supports registering either a single function or an array of handler functions for both transactions and blocks. When multiple handlers are provided, each is invoked asynchronously on event reception.
Session Reset Logic: On receiving either a new block or transaction event,
super.reset()is called. This is likely a method in the base class that handles resetting connection state or internal timers to maintain a healthy WebSocket session.Dynamic Address Subscription: Addresses can be updated at runtime using
subscribeAddresses(). This does not require reconnecting the WebSocket client; instead, a new subscription message is sent over the open socket.Logging: Uses a scoped logger configured with namespace
['unchained', 'blockbook', 'websocket']and respects environment variableLOG_LEVEL. Errors and debug info during message parsing and subscription attempts are logged.JSON-RPC 2.0 Protocol: The client communicates with Blockbook over WebSocket using JSON-RPC 2.0 message format, including method calls like
subscribeNewBlockandsubscribeAddressesidentified by IDs"newBlock"and"newTx"respectively.
Interaction with Other System Parts
Base WebSocket Client (
@shapeshiftoss/websocket):
This class extends a generic WebSocket client that provides foundational connection management, logging, and reconnection capabilities.Blockchain Event Models:
TypesTxandNewBlockrepresent the normalized blockchain transaction and block event data structures. They are imported from local modules and define the shape of the data passed to handlers.Logger (
@shapeshiftoss/logger):
Provides structured logging to trace connection lifecycle, incoming event details, and errors.Application Layer:
Client code instantiates thisWebsocketClientto receive real-time blockchain updates and react accordingly, e.g., updating UI, triggering notifications, or processing transactions.Blockbook Indexer Backend:
The WebSocket connects to a Blockbook server endpoint, which streams blockchain events as they occur on the network.
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()
The diagram shows
WebsocketClientextendingBaseWebsocketClient.The class has private properties for handlers and subscribed addresses.
Key public methods include the constructor and
subscribeAddresses.Protected lifecycle hooks
onOpenandonMessageare implemented to manage connection and messages.
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.