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: Object
Call signature​
• new WsImplementation(url, protocols?): WebSocket
Parameters​
| Name | Type |
|---|---|
url | string | URL |
protocols? | string | string[] |
Returns​
WebSocket
Type declaration​
| Name | Type |
|---|---|
prototype | WebSocket |
CONNECTING | 0 |
OPEN | 1 |
CLOSING | 2 |
CLOSED | 3 |
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(blockIdentifier?): Promise<Subscription<BLOCK_HEADER>>
Subscribes to new block headers.
Parameters​
| Name | Type | Description |
|---|---|---|
blockIdentifier? | SubscriptionBlockIdentifier | The 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​
subscribeEvents​
â–¸ subscribeEvents(fromAddress?, keys?, blockIdentifier?): Promise<Subscription<EMITTED_EVENT>>
Subscribes to events matching a given filter.
Parameters​
| Name | Type | Description |
|---|---|---|
fromAddress? | BigNumberish | The contract address to filter by. |
keys? | string[][] | The event keys to filter by. |
blockIdentifier? | SubscriptionBlockIdentifier | The 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​
subscribeTransactionStatus​
â–¸ subscribeTransactionStatus(transactionHash, blockIdentifier?): Promise<Subscription<NEW_TXN_STATUS>>
Subscribes to status updates for a specific transaction.
Parameters​
| Name | Type | Description |
|---|---|---|
transactionHash | BigNumberish | The hash of the transaction to monitor. |
blockIdentifier? | SubscriptionBlockIdentifier | The 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​
subscribePendingTransaction​
â–¸ subscribePendingTransaction(transactionDetails?, senderAddress?): Promise<Subscription<string | TXN_WITH_HASH>>
Subscribes to pending transactions.
Parameters​
| Name | Type | Description |
|---|---|---|
transactionDetails? | boolean | If 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​
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