Skip to main content
Version: 7.5.1

Class: WebSocketChannel

Manages a WebSocket connection to a Starknet node for receiving real-time updates. This class handles subscriptions, automatic reconnection, and request queueing.

Example

const channel = new WebSocketChannel({ nodeUrl: 'YOUR_NODE_URL' });
await channel.waitForConnection();

const sub = await channel.subscribeNewHeads();
sub.on((data) => {
console.log('New Block:', data);
});

// ... later
await sub.unsubscribe();
channel.disconnect();

Constructors​

constructor​

• new WebSocketChannel(options): WebSocketChannel

Creates an instance of WebSocketChannel.

Parameters​

NameTypeDescription
optionsWebSocketOptionsThe options for configuring the channel.

Returns​

WebSocketChannel

Defined in​

src/channel/ws/ws_0_8.ts:170

Properties​

nodeUrl​

• nodeUrl: string

The URL of the WebSocket RPC Node.

Example

'wss://starknet-sepolia.public.blastapi.io/rpc/v0_8';

Defined in​

src/channel/ws/ws_0_8.ts:114


websocket​

• websocket: WebSocket

The underlying WebSocket instance.

Defined in​

src/channel/ws/ws_0_8.ts:119


WsImplementation​

• Private WsImplementation: Object

Call signature​

• new WsImplementation(url, protocols?): WebSocket

Parameters​
NameType
urlstring | URL
protocols?string | string[]
Returns​

WebSocket

Type declaration​

NameType
prototypeWebSocket
CONNECTING0
OPEN1
CLOSING2
CLOSED3

Defined in​

src/channel/ws/ws_0_8.ts:122


activeSubscriptions​

• Private activeSubscriptions: Map<string, Subscription<any>>

Defined in​

src/channel/ws/ws_0_8.ts:125


maxBufferSize​

• Private Readonly maxBufferSize: number

Defined in​

src/channel/ws/ws_0_8.ts:127


autoReconnect​

• Private Readonly autoReconnect: boolean

Defined in​

src/channel/ws/ws_0_8.ts:129


reconnectOptions​

• Private Readonly reconnectOptions: Required<ReconnectOptions>

Defined in​

src/channel/ws/ws_0_8.ts:131


requestTimeout​

• Private Readonly requestTimeout: number

Defined in​

src/channel/ws/ws_0_8.ts:133


isReconnecting​

• Private isReconnecting: boolean = false

Defined in​

src/channel/ws/ws_0_8.ts:135


reconnectAttempts​

• Private reconnectAttempts: number = 0

Defined in​

src/channel/ws/ws_0_8.ts:137


userInitiatedClose​

• Private userInitiatedClose: boolean = false

Defined in​

src/channel/ws/ws_0_8.ts:139


reconnectTimeoutId​

• Private reconnectTimeoutId: null | Timeout = null

Defined in​

src/channel/ws/ws_0_8.ts:141


requestQueue​

• Private requestQueue: { method: string ; params?: object ; resolve: (value: any) => void ; reject: (reason?: any) => void }[] = []

Defined in​

src/channel/ws/ws_0_8.ts:143


events​

• Private events: EventEmitter<WebSocketChannelEvents>

Defined in​

src/channel/ws/ws_0_8.ts:150


closeListener​

• Private closeListener: (ev: CloseEvent) => void

Type declaration​

â–¸ (ev): void

Parameters​
NameType
evCloseEvent
Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:154


messageListener​

• Private messageListener: (event: MessageEvent<any>) => void

Type declaration​

â–¸ (event): void

Parameters​
NameType
eventMessageEvent<any>
Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:156


sendId​

• Private sendId: number = 0

JSON RPC latest sent message ID. The receiving message is expected to contain the same ID.

Defined in​

src/channel/ws/ws_0_8.ts:164

Methods​

openListener​

â–¸ openListener(ev): void

Parameters​

NameType
evEvent

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:152


errorListener​

â–¸ errorListener(ev): void

Parameters​

NameType
evEvent

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:158


idResolver​

â–¸ idResolver(id?): number

Parameters​

NameType
id?number

Returns​

number

Defined in​

src/channel/ws/ws_0_8.ts:189


send​

â–¸ send(method, params?, id?): number

Sends a JSON-RPC request over the WebSocket connection without waiting for a response. This is a low-level method. Prefer sendReceive for most use cases.

Parameters​

NameTypeDescription
methodstringThe RPC method name.
params?objectThe parameters for the RPC method.
id?numberA specific request ID. If not provided, an auto-incrementing ID is used.

Returns​

number

The ID of the sent request.

Throws

If the WebSocket is not connected.

Defined in​

src/channel/ws/ws_0_8.ts:206


sendReceive​

â–¸ sendReceive<T>(method, params?): Promise<T>

Sends a JSON-RPC request and returns a Promise that resolves with the result. This method abstracts the request/response cycle over WebSockets. If the connection is lost, it will queue the request and send it upon reconnection.

Type parameters​

NameTypeDescription
TanyThe expected type of the result.

Parameters​

NameTypeDescription
methodstringThe RPC method name.
params?objectThe parameters for the RPC method.

Returns​

Promise<T>

A Promise that resolves with the RPC response result.

Throws

If the request does not receive a response within the configured requestTimeout.

Throws

If the WebSocket is not connected and auto-reconnect is disabled.

Defined in​

src/channel/ws/ws_0_8.ts:235


isConnected​

â–¸ isConnected(): boolean

Checks if the WebSocket connection is currently open.

Returns​

boolean

true if the connection is open, false otherwise.

Defined in​

src/channel/ws/ws_0_8.ts:310


waitForConnection​

â–¸ waitForConnection(): Promise<number>

Returns a Promise that resolves when the WebSocket connection is open. Can be used to block execution until the connection is established.

Returns​

Promise<number>

A Promise that resolves with the WebSocket's readyState when connected.

Example

const channel = new WebSocketChannel({ nodeUrl: '...' });
await channel.waitForConnection();
console.log('Connected!');

Defined in​

src/channel/ws/ws_0_8.ts:325


disconnect​

â–¸ disconnect(code?, reason?): void

Closes the WebSocket connection. This method is user-initiated and will prevent automatic reconnection for this closure.

Parameters​

NameTypeDescription
code?numberThe WebSocket connection close code.
reason?stringThe WebSocket connection close reason.

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:346


waitForDisconnection​

â–¸ waitForDisconnection(): Promise<number | Event>

Returns a Promise that resolves when the WebSocket connection is closed.

Returns​

Promise<number | Event>

A Promise that resolves with the WebSocket's readyState or a CloseEvent when disconnected.

Defined in​

src/channel/ws/ws_0_8.ts:359


unsubscribe​

â–¸ unsubscribe(subscriptionId): Promise<boolean>

Unsubscribes from a Starknet subscription. It is recommended to use the unsubscribe() method on the Subscription object instead.

Parameters​

NameTypeDescription
subscriptionIdstringThe ID of the subscription to unsubscribe from.

Returns​

Promise<boolean>

A Promise that resolves with true if the unsubscription was successful.

Defined in​

src/channel/ws/ws_0_8.ts:379


waitForUnsubscription​

â–¸ waitForUnsubscription(targetId): Promise<void>

Returns a Promise that resolves when a specific subscription is successfully unsubscribed.

Parameters​

NameTypeDescription
targetIdstringThe ID of the subscription to wait for.

Returns​

Promise<void>

Example

await channel.waitForUnsubscription(mySubscription.id);
console.log('Successfully unsubscribed.');

Defined in​

src/channel/ws/ws_0_8.ts:399


reconnect​

â–¸ reconnect(): void

Manually initiates a reconnection attempt. This creates a new WebSocket instance and re-establishes listeners.

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:415


_processRequestQueue​

â–¸ _processRequestQueue(): void

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:425


_restoreSubscriptions​

â–¸ _restoreSubscriptions(): Promise<void>

Returns​

Promise<void>

Defined in​

src/channel/ws/ws_0_8.ts:433


_startReconnect​

â–¸ _startReconnect(): void

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:453


onCloseProxy​

â–¸ onCloseProxy(ev): void

Parameters​

NameType
evCloseEvent

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:495


onMessageProxy​

â–¸ onMessageProxy(event): void

Parameters​

NameType
eventMessageEvent<any>

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:507


subscribeNewHeads​

â–¸ subscribeNewHeads(blockIdentifier?): Promise<Subscription<BLOCK_HEADER>>

Subscribes to new block headers.

Parameters​

NameTypeDescription
blockIdentifier?SubscriptionBlockIdentifierThe block to start receiving notifications from. Defaults to 'latest'.

Returns​

Promise<Subscription<BLOCK_HEADER>>

A Promise that resolves with a Subscription object for new block headers.

Defined in​

src/channel/ws/ws_0_8.ts:546


subscribeEvents​

â–¸ subscribeEvents(fromAddress?, keys?, blockIdentifier?): Promise<Subscription<EMITTED_EVENT>>

Subscribes to events matching a given filter.

Parameters​

NameTypeDescription
fromAddress?BigNumberishThe contract address to filter by.
keys?string[][]The event keys to filter by.
blockIdentifier?SubscriptionBlockIdentifierThe block to start receiving notifications from. Defaults to 'latest'.

Returns​

Promise<Subscription<EMITTED_EVENT>>

A Promise that resolves with a Subscription object for the specified events.

Defined in​

src/channel/ws/ws_0_8.ts:566


subscribeTransactionStatus​

â–¸ subscribeTransactionStatus(transactionHash, blockIdentifier?): Promise<Subscription<NEW_TXN_STATUS>>

Subscribes to status updates for a specific transaction.

Parameters​

NameTypeDescription
transactionHashBigNumberishThe hash of the transaction to monitor.
blockIdentifier?SubscriptionBlockIdentifierThe block context. Not typically required.

Returns​

Promise<Subscription<NEW_TXN_STATUS>>

A Promise that resolves with a Subscription object for the transaction's status.

Defined in​

src/channel/ws/ws_0_8.ts:589


subscribePendingTransaction​

â–¸ subscribePendingTransaction(transactionDetails?, senderAddress?): Promise<Subscription<string | TXN_WITH_HASH>>

Subscribes to pending transactions.

Parameters​

NameTypeDescription
transactionDetails?booleanIf true, the full transaction details are included. Defaults to false (hash only).
senderAddress?BigNumberish[]An array of sender addresses to filter by.

Returns​

Promise<Subscription<string | TXN_WITH_HASH>>

A Promise that resolves with a Subscription object for pending transactions.

Defined in​

src/channel/ws/ws_0_8.ts:610


removeSubscription​

â–¸ removeSubscription(id): void

Internal method to remove subscription from active map.

Parameters​

NameType
idstring

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:629


on​

â–¸ on<K>(event, listener): void

Adds a listener for a given event.

Type parameters​

NameType
Kextends keyof WebSocketChannelEvents

Parameters​

NameTypeDescription
eventKThe event name.
listener(data: WebSocketChannelEvents[K]) => voidThe listener function to add.

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:638


off​

â–¸ off<K>(event, listener): void

Removes a listener for a given event.

Type parameters​

NameType
Kextends keyof WebSocketChannelEvents

Parameters​

NameTypeDescription
eventKThe event name.
listener(data: WebSocketChannelEvents[K]) => voidThe listener function to remove.

Returns​

void

Defined in​

src/channel/ws/ws_0_8.ts:650