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
| Name | Type | Description |
|---|---|---|
options | WebSocketOptions | The options for configuring the channel. |
Returns
Defined in
Properties
nodeUrl
• nodeUrl: string
The URL of the WebSocket RPC Node.
Example
'wss://starknet-sepolia.public.blastapi.io/rpc/v0_8'
Defined in
websocket
• websocket: WebSocket
The underlying WebSocket instance.
Defined in
WsImplementation
• Private WsImplementation: WebSocketModule
Defined in
activeSubscriptions
• Private activeSubscriptions: Map<string, Subscription<any>>
Defined in
maxBufferSize
• Private Readonly maxBufferSize: number
Defined in
autoReconnect
• Private Readonly autoReconnect: boolean
Defined in
reconnectOptions
• Private Readonly reconnectOptions: Required<ReconnectOptions>
Defined in
requestTimeout
• Private Readonly requestTimeout: number
Defined in
isReconnecting
• Private isReconnecting: boolean = false
Defined in
reconnectAttempts
• Private reconnectAttempts: number = 0
Defined in
userInitiatedClose
• Private userInitiatedClose: boolean = false
Defined in
reconnectTimeoutId
• Private reconnectTimeoutId: null | Timeout = null
Defined in
requestQueue
• Private requestQueue: { method: string ; params?: object ; resolve: (value: any) => void ; reject: (reason?: any) => void }[] = []
Defined in
events
• Private events: EventEmitter<WebSocketChannelEvents>
Defined in
closeListener
• Private closeListener: (ev: CloseEvent) => void
Type declaration
▸ (ev): void
Parameters
| Name | Type |
|---|---|
ev | CloseEvent |
Returns
void
Defined in
messageListener
• Private messageListener: (event: MessageEvent<any>) => void
Type declaration
▸ (event): void
Parameters
| Name | Type |
|---|---|
event | MessageEvent<any> |
Returns
void
Defined in
sendId
• Private sendId: number = 0
JSON RPC latest sent message ID. The receiving message is expected to contain the same ID.
Defined in
Methods
openListener
▸ openListener(ev): void
Parameters
| Name | Type |
|---|---|
ev | Event |
Returns
void
Defined in
errorListener
▸ errorListener(ev): void
Parameters
| Name | Type |
|---|---|
ev | Event |
Returns
void
Defined in
idResolver
▸ idResolver(id?): number
Parameters
| Name | Type |
|---|---|
id? | number |
Returns
number
Defined in
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
| Name | Type | Description |
|---|---|---|
method | string | The RPC method name. |
params? | object | The parameters for the RPC method. |
id? | number | A 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
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
| Name | Type | Description |
|---|---|---|
T | any | The expected type of the result. |
Parameters
| Name | Type | Description |
|---|---|---|
method | string | The RPC method name. |
params? | object | The 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
isConnected
▸ isConnected(): boolean
Checks if the WebSocket connection is currently open.
Returns
boolean
true if the connection is open, false otherwise.
Defined in
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
disconnect
▸ disconnect(code?, reason?): void
Closes the WebSocket connection. This method is user-initiated and will prevent automatic reconnection for this closure.
Parameters
| Name | Type | Description |
|---|---|---|
code? | number | The WebSocket connection close code. |
reason? | string | The WebSocket connection close reason. |
Returns
void
Defined in
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
unsubscribe
▸ unsubscribe(subscriptionId): Promise<boolean>
Unsubscribes from a Starknet subscription.
It is recommended to use the unsubscribe() method on the Subscription object instead.
Parameters
| Name | Type | Description |
|---|---|---|
subscriptionId | string | The ID of the subscription to unsubscribe from. |
Returns
Promise<boolean>
A Promise that resolves with true if the unsubscription was successful.
Defined in
waitForUnsubscription
▸ waitForUnsubscription(targetId): Promise<void>
Returns a Promise that resolves when a specific subscription is successfully unsubscribed.
Parameters
| Name | Type | Description |
|---|---|---|
targetId | string | The ID of the subscription to wait for. |
Returns
Promise<void>
Example
await channel.waitForUnsubscription(mySubscription.id);
console.log('Successfully unsubscribed.');
Defined in
reconnect
▸ reconnect(): void
Manually initiates a reconnection attempt. This creates a new WebSocket instance and re-establishes listeners.
Returns
void
Defined in
_processRequestQueue
▸ _processRequestQueue(): void
Returns
void
Defined in
_restoreSubscriptions
▸ _restoreSubscriptions(): Promise<void>
Returns
Promise<void>
Defined in
_startReconnect
▸ _startReconnect(): void
Returns
void
Defined in
onCloseProxy
▸ onCloseProxy(ev): void
Parameters
| Name | Type |
|---|---|
ev | CloseEvent |
Returns
void
Defined in
onMessageProxy
▸ onMessageProxy(event): void
Parameters
| Name | Type |
|---|---|
event | MessageEvent<any> |
Returns
void
Defined in
subscribeNewHeads
▸ subscribeNewHeads(params?): Promise<SubscriptionNewHeadsEvent>
Subscribes to new block headers.
Parameters
| Name | Type | Description |
|---|---|---|
params | SubscribeNewHeadsParams | The parameters for the subscription. |
Returns
Promise<SubscriptionNewHeadsEvent>
A Promise that resolves with a Subscription object for new block headers.
Defined in
subscribeEvents
▸ subscribeEvents(params?): Promise<SubscriptionStarknetEventsEvent>
Subscribes to events matching a given filter.
Parameters
| Name | Type | Description |
|---|---|---|
params | SubscribeEventsParams | The parameters for the subscription. |
Returns
Promise<SubscriptionStarknetEventsEvent>
A Promise that resolves with a Subscription object for the specified events.
Defined in
subscribeTransactionStatus
▸ subscribeTransactionStatus(params): Promise<SubscriptionTransactionStatusEvent>
Subscribes to status updates for a specific transaction.
Parameters
| Name | Type | Description |
|---|---|---|
params | SubscribeTransactionStatusParams | The parameters for the subscription. |
Returns
Promise<SubscriptionTransactionStatusEvent>
A Promise that resolves with a Subscription object for the transaction's status.
Defined in
subscribeNewTransactionReceipts
▸ subscribeNewTransactionReceipts(params?): Promise<SubscriptionNewTransactionReceiptsEvent>
Subscribes to new transaction receipts.
Parameters
| Name | Type | Description |
|---|---|---|
params | SubscribeNewTransactionReceiptsParams | The parameters for the subscription. |
Returns
Promise<SubscriptionNewTransactionReceiptsEvent>
A Promise that resolves with a Subscription object for new transaction receipts.
Defined in
subscribeNewTransactions
▸ subscribeNewTransactions(params?): Promise<SubscriptionNewTransactionEvent>
Subscribes to new transactions.
Parameters
| Name | Type | Description |
|---|---|---|
params | SubscribeNewTransactionsParams | The parameters for the subscription. |
Returns
Promise<SubscriptionNewTransactionEvent>
A Promise that resolves with a Subscription object for new transactions.
Defined in
removeSubscription
▸ removeSubscription(id): void
Internal method to remove subscription from active map.
Parameters
| Name | Type |
|---|---|
id | string |
Returns
void
Defined in
on
▸ on<K>(event, listener): void
Adds a listener for a given event.
Type parameters
| Name | Type |
|---|---|
K | extends keyof WebSocketChannelEvents |
Parameters
| Name | Type | Description |
|---|---|---|
event | K | The event name. |
listener | (data: WebSocketChannelEvents[K]) => void | The listener function to add. |
Returns
void
Defined in
off
▸ off<K>(event, listener): void
Removes a listener for a given event.
Type parameters
| Name | Type |
|---|---|
K | extends keyof WebSocketChannelEvents |
Parameters
| Name | Type | Description |
|---|---|---|
event | K | The event name. |
listener | (data: WebSocketChannelEvents[K]) => void | The listener function to remove. |
Returns
void