websocket.ts


Overview

The [websocket.ts](/projects/291/69087) file defines a specialized WebSocket client class (`WebsocketClient`) tailored for subscribing to Solana blockchain transaction logs and processing them in real time. It extends a base WebSocket client from an external library to facilitate subscription management by addresses, handle incoming blockchain event messages, and delegate transaction data to user-defined asynchronous handlers.

This file's core functionality is to:

The class is designed with scalability and flexibility in mind, supporting multiple transaction handlers and multiple address subscriptions concurrently.


Class: WebsocketClient

A Solana blockchain-specific WebSocket client extending the generic `BaseWebsocketClient` for subscribing to logs notifications filtered by addresses. It manages subscription lifecycle and handles incoming messages to process transaction logs.

Declaration

class WebsocketClient extends BaseWebsocketClient

Constructor

constructor(_url: string, args: WebsocketArgs, opts?: Options)
const wsClient = new WebsocketClient('wss://solana-rpc.example.com', {
  apiKey: 'your-api-key',
  transactionHandler: async (tx) => {
    console.log('Received transaction:', tx.signature);
  }
});

Properties

Property

Type

Description

`handleTransaction`

`TransactionHandler

TransactionHandler[]`

`addresses`

`string[]`

List of addresses currently subscribed to.

`subscriptionIds`

`number[]`

List of active subscription IDs returned from the server.

`currentId`

`number`

Incremental ID used for tracking subscription requests.


Methods

protected onOpen(): void


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


subscribeAddresses(addresses: string[]): void

wsClient.subscribeAddresses(['Address1', 'Address2']);

private unsubscribe(subscriptionId: number): void


Types and Interfaces

TransactionHandler

type TransactionHandler = (data: Logs) => Promise<void>

WebsocketArgs

interface WebsocketArgs extends Omit<Args, 'logger'> {
  transactionHandler: TransactionHandler | TransactionHandler[]
}

Important Implementation Details


Interactions with Other System Components


Usage Example

import { WebsocketClient } from './websocket'
import { Logs } from '@solana/web3.js'

async function processTransaction(tx: Logs): Promise<void> {
  console.log('Tx signature:', tx.signature)
  // Add custom processing logic here...
}

const ws = new WebsocketClient('wss://api.mainnet-beta.solana.com', {
  apiKey: process.env.SOLANA_API_KEY,
  transactionHandler: processTransaction,
})

// Subscribe to logs for multiple addresses
ws.subscribeAddresses([
  '4Nd1mLkZQ7zbmfK9hQ7aMT1p5H1yM7Wj7f4p7x1LJ4Vq',
  'FhtGmnP4CJc7v1L2x2v7vKKKxW5vE5V2Wz4t5hRJcbkV',
])

Mermaid Class Diagram

classDiagram
    class WebsocketClient {
        -handleTransaction: TransactionHandler | TransactionHandler[]
        -addresses: string[]
        -subscriptionIds: number[]
        -currentId: number
        +constructor(_url: string, args: WebsocketArgs, opts?: Options)
        +subscribeAddresses(addresses: string[]): void
        #onOpen(): void
        #onMessage(message: WebSocket.MessageEvent): Promise<void>
        -unsubscribe(subscriptionId: number): void
    }
    WebsocketClient --|> BaseWebsocketClient

Summary

The [websocket.ts](/projects/291/69087) file delivers a specialized WebSocket client implementation for the Solana blockchain, enabling precise, address-based subscription to transaction logs. It efficiently manages subscription lifecycles, validates incoming data, and delegates transaction processing to customizable asynchronous handlers. It integrates seamlessly with the broader system by extending a generic WebSocket client base, using structured logging, and adhering to Solana's RPC specifications, making it a key component for real-time blockchain event-driven applications.