websocket.ts


Overview

The [websocket.ts](/projects/291/69055) file implements a robust **ConnectionHandler** class that manages individual WebSocket client connections within a real-time blockchain event subscription system. Its primary purpose is to handle client subscription requests, maintain connection health via heartbeats, and deliver blockchain transaction event updates to subscribed clients efficiently.

This file acts as the per-connection interface between external WebSocket clients and the centralized **Registry** that manages global subscription state. It supports topic-based subscriptions (currently only `'txs'` for transaction events) and integrates with other components including:

ConnectionHandler uses a ping/pong heartbeat mechanism to detect stale connections, and it cleanly manages subscription lifecycles to ensure accurate and efficient event delivery.


Detailed Breakdown

Interfaces and Types


Class: ConnectionHandler

Manages a single WebSocket connection, including subscription handling, message processing, heartbeat maintenance, and event publishing.

Properties

Property

Type

Description

`clientId`

`string`

Unique UUID identifier for this connection instance.

`websocket`

`WebSocket`

The underlying WebSocket connection object.

`registry`

`Registry`

Central subscription registry for managing subscriptions.

`client`

`WebsocketClient`

Client managing blockchain data feed subscriptions.

`prometheus`

`Prometheus`

Metrics collector for monitoring WebSocket connections.

`logger`

`Logger`

Logger scoped to this connection's namespace.

`routes`

`Record`

Maps topics to their subscription/unsubscription handlers.

`pingIntervalMs`

`number`

Interval in milliseconds for sending ping frames (default 10s).

`pingTimeout`

`NodeJS.Timeout \

undefined`

`subscriptionIds`

`Set`

Tracks active subscription IDs for this connection.

Constructor (private)

private constructor(
  websocket: WebSocket,
  registry: Registry,
  client: WebsocketClient,
  prometheus: Prometheus,
  logger: Logger
)

Static Method: start

static start(
  websocket: WebSocket,
  registry: Registry,
  client: WebsocketClient,
  prometheus: Prometheus,
  logger: Logger
): void
ConnectionHandler.start(ws, registryInstance, wsClient, prometheusInstance, loggerInstance);

Private Methods

heartbeat()

Maintains connection health by resetting the ping timeout whenever a pong frame is received.

sendError(message: string, subscriptionId: string): void

Sends a standardized error response to the client.

onMessage(event: WebSocket.MessageEvent): void

Processes incoming JSON messages from the client.

close(interval: NodeJS.Timeout): void

Handles cleanup on WebSocket closure or error.

handleSubscribeTxs(subscriptionId: string, data?: TxsTopicData): void

Handles subscription requests to the `'txs'` topic.

Example usage snippet:

handleSubscribeTxs('sub1', { topic: 'txs', addresses: ['addr1', 'addr2'] });

handleUnsubscribeTxs(subscriptionId: string, data?: TxsTopicData): void

Handles unsubscription requests from the `'txs'` topic.

publish(subscriptionId: string, address: string, data: unknown): void

Sends an event message to the client for a particular subscription.


Important Implementation Details


Interaction with Other System Components


Usage Example

import WebSocket from 'ws'
import { ConnectionHandler } from './websocket'
import { Registry } from './registry'
import { WebsocketClient } from '@shapeshiftoss/websocket'
import { Prometheus } from './prometheus'
import { Logger } from '@shapeshiftoss/logger'

// Assume these instances are initialized appropriately
const registry = new Registry(...)
const wsClient = new WebsocketClient(...)
const prometheus = new Prometheus(...)
const logger = new Logger({ namespace: ['app'] })

// WebSocket server connection handler
const wss = new WebSocket.Server({ port: 8080 })

wss.on('connection', (ws) => {
  ConnectionHandler.start(ws, registry, wsClient, prometheus, logger)
})

Mermaid Class Diagram

classDiagram
    class ConnectionHandler {
        +clientId: string
        -websocket: WebSocket
        -registry: Registry
        -client: WebsocketClient
        -prometheus: Prometheus
        -logger: Logger
        -routes: Record<Topics, Methods>
        -pingIntervalMs: number
        -pingTimeout?: NodeJS.Timeout
        -subscriptionIds: Set~string~
        +static start(websocket: WebSocket, registry: Registry, client: WebsocketClient, prometheus: Prometheus, logger: Logger): void
        -constructor(websocket: WebSocket, registry: Registry, client: WebsocketClient, prometheus: Prometheus, logger: Logger)
        -heartbeat(): void
        -sendError(message: string, subscriptionId: string): void
        -onMessage(event: WebSocket.MessageEvent): void
        -close(interval: NodeJS.Timeout): void
        -handleSubscribeTxs(subscriptionId: string, data?: TxsTopicData): void
        -handleUnsubscribeTxs(subscriptionId: string, data?: TxsTopicData): void
        +publish(subscriptionId: string, address: string, data: unknown): void
    }

Summary

The [websocket.ts](/projects/291/69055) file is a critical component enabling scalable, real-time blockchain event subscriptions over WebSocket connections. The **ConnectionHandler** class encapsulates all per-client connection logic, including message parsing, subscription lifecycle management, heartbeat monitoring, and event dispatching. It works closely with the centralized **Registry** and underlying **WebsocketClient** to ensure efficient and accurate delivery of transaction event updates to subscribed clients.

Its design emphasizes:

This organized approach ensures that clients receive timely, relevant blockchain data with minimal overhead and maximum reliability.


End of websocket.ts Documentation