Skip to main content

Class: WebSocketProvider

A JSON-RPC provider that communicates over WebSocket instead of HTTP.

Supports all the same methods as JsonRpcProvider (getBalance, getBlock, etc.) plus real-time subscriptions via eth_subscribe / eth_unsubscribe.

example

const provider = new WebSocketProvider('wss://eth-mainnet.g.alchemy.com/v2/YOUR_KEY');

// Standard JSON-RPC methods work the same as JsonRpcProvider
const block = await provider.getBlock('latest');

// Real-time subscriptions
const subId = await provider.subscribe('newHeads');
provider.on('block', (blockHeader) => {
console.log('New block:', blockHeader.number);
});

// Clean up
await provider.unsubscribe(subId);
provider.destroy();

Hierarchy

  • BaseProvider

    WebSocketProvider

Constructors

constructor

new WebSocketProvider(wsUrl)

Parameters

NameTypeDescription
wsUrlstringWebSocket URL to connect to (e.g. wss://eth-mainnet.g.alchemy.com/v2/...)

Overrides

BaseProvider.constructor

Defined in

providers/WebSocketProvider.ts:70

Properties

_destroyed

Private _destroyed: boolean = false

Defined in

providers/WebSocketProvider.ts:60


_eventListeners

Private _eventListeners: Map<string, Set<Function>>

Defined in

providers/WebSocketProvider.ts:58


_maxReconnectAttempts

Private _maxReconnectAttempts: number = 3

Defined in

providers/WebSocketProvider.ts:62


_pendingRequests

Private _pendingRequests: Map<number, PendingRequest>

Defined in

providers/WebSocketProvider.ts:56


_ready

Private _ready: Promise<void>

Defined in

providers/WebSocketProvider.ts:63


_readyReject

Private _readyReject: (err: any) => void

Type declaration

▸ (err): void

Parameters
NameType
errany
Returns

void

Defined in

providers/WebSocketProvider.ts:65


_readyResolve

Private _readyResolve: () => void

Type declaration

▸ (): void

Returns

void

Defined in

providers/WebSocketProvider.ts:64


_reconnectAttempts

Private _reconnectAttempts: number = 0

Defined in

providers/WebSocketProvider.ts:61


_requestId

Private _requestId: number = 0

Defined in

providers/WebSocketProvider.ts:55


_subscriptionIdToEvent

Private _subscriptionIdToEvent: Map<string, string>

Defined in

providers/WebSocketProvider.ts:59


_subscriptions

Private _subscriptions: Map<string, Set<Function>>

Defined in

providers/WebSocketProvider.ts:57


_ws

Private _ws: null | WebSocket = null

Defined in

providers/WebSocketProvider.ts:53


_wsUrl

Private _wsUrl: string

Defined in

providers/WebSocketProvider.ts:54

Accessors

ready

get ready(): Promise<void>

Returns a promise that resolves when the WebSocket connection is open and ready.

Returns

Promise<void>

Defined in

providers/WebSocketProvider.ts:370

Methods

_attemptReconnect

Private _attemptReconnect(): void

Returns

void

Defined in

providers/WebSocketProvider.ts:173


_connect

Private _connect(): void

Returns

void

Defined in

providers/WebSocketProvider.ts:84


_createReadyPromise

Private _createReadyPromise(): Promise<void>

Returns

Promise<void>

Defined in

providers/WebSocketProvider.ts:77


_sendRequest

Private _sendRequest(body): Promise<any>

Send a raw JSON-RPC request over the WebSocket and wait for the response.

Parameters

NameTypeDescription
bodyRecord<string, unknown>JSON-RPC request body. The id field is overwritten with an auto-incrementing counter.

Returns

Promise<any>

the result field from the JSON-RPC response

Defined in

providers/WebSocketProvider.ts:201


call

call(transaction, blockTag?): Promise<string>

Returns the result of adding a transaction to the blockchain without actually adding that transaction to the blockchain. Does not require any ether as gas.

example

await provider.call({ to: "0x6b175474e89094c44da98b954eedeac495271d0f", data: "0x70a082310000000000000000000000006E0d01A76C3Cf4288372a29124A26D4353EE51BE" });
// '0x0000000000000000000000000000000000000000000000000858898f93629000'

Parameters

NameTypeDefault valueDescription
transactionTransactionRequestundefinedthe transaction object to, in theory, execute. Doesn't actually get added to the blockchain.
blockTagBlockTag'latest'the block to execute this transaction on

Returns

Promise<string>

the result of executing the transaction on the specified block

Inherited from

BaseProvider.call

Defined in

providers/BaseProvider.ts:572


destroy

destroy(): void

Close the WebSocket connection cleanly and prevent reconnection. After calling destroy(), this provider instance cannot be reused.

Returns

void

Defined in

providers/WebSocketProvider.ts:349


estimateGas

estimateGas(transaction): Promise<bigint>

Returns an estimate of the amount of gas that would be required to submit transaction to the network. An estimate may not be accurate since there could be another transaction on the network that was not accounted for.

example

await provider.estimateGas({
// Wrapped ETH address
to: "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
data: "0xd0e30db0",
value: etherToWei('1.0').toHexString(),
});
// 27938n

Parameters

NameTypeDescription
transactionTransactionRequestthe transaction to check the estimated gas cost for

Returns

Promise<bigint>

the estimated amount of gas charged for submitting the specified transaction to the blockchain

Inherited from

BaseProvider.estimateGas

Defined in

providers/BaseProvider.ts:451


getBalance

getBalance(address, blockTag?): Promise<bigint>

Returns the balance of the account in wei.

example

 await provider.getBalance('0x7cB57B5A97eAbe94205C07890BE4c1aD31E486A8');
// 28798127851528138

Parameters

NameTypeDefault valueDescription
addressstringundefinedthe address to check the balance of
blockTagBlockTag'latest'the block to check the specified address' balance on

Returns

Promise<bigint>

the balance of the network's native token for the specified address on the specified block

Inherited from

BaseProvider.getBalance

Defined in

providers/BaseProvider.ts:394


getBlock

getBlock(timeFrame?, returnTransactionObjects?): Promise<BlockResponse>

Gets information about a certain block, optionally with full transaction objects.

example

await provider.getBlock(14879862);
// {
// baseFeePerGas: 39095728776n,
// difficulty: 14321294455359973n,
// extraData: "0x486976656f6e2073672d6865617679",
// gasLimit: 29970620n,
// gasUsed: 20951384n,
// hash: "0x563b458ec3c4f87393b53f70bdddc0058497109b784d8cacd9247ddf267049ab",
// logsBloom:
// "0x9f38794fe80b521794df6efad8b0d2e9582f9ec3959a3f9384bda0fa371cfa5fac5af9d515c6bdf1ec325f5b5f7ebdd6a3a9fae17b38a86d4dc4b0971afc68d8086640550f4c156e6f923f4a1bb94fb0bed6cdcc474c5c64bfeff7a4a906f72b9a7b94004ee58efc53d63ac66961acd3a431b2d896cc9fd75f6072960bced45f770587caf130f57504decfcb63c6ca8fbc5bdbd749edd5a99a7375d2b81872289adb775fb3c928259f4be39c6d3f4d5b6217822979bb88c1f1fb62429b1b6d41cf4e3f77f9e1db3f5723108f1e5b1255dd734ad8cdb11e7ea22487c788e67c83777b6f395e504ca59c64f52245ee6de3804cf809e5caa4f0ea6a9aa9eb6ed801",
// miner: "0x1aD91ee08f21bE3dE0BA2ba6918E714dA6B45836",
// mixHash: "0x73cc9419bfb89c9d41c3a8c34ce56b5ebe468bdcf870258d2e77262275d580ec",
// nonce: "0x976f3f5d596ffb08",
// number: 14879862,
// parentHash: "0x95986ae14a71face8d9a6a379edd875b2e8bc73e4de0d9d460e7752bddb0f579",
// receiptsRoot: "0x8e6ba2fd9bee602b653dae6e3132f16538c2c5df24f1df8c000392053f73defa",
// sha3Uncles: "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
// size: 134483n,
// stateRoot: "0xbf2bb67bd1c741f3d00904b8451d7c2cf4e3a2726f5a5884792ede2074747b85",
// timestamp: 1654016186n,
// totalDifficulty: 50478104614257705213748n,
// transactions: [
// "0xb3326a9149809603a2c28545e50e4f7d16e194bf5ee9764e0544603854c4a8d2",
// "0x8b42095f8d335404a4896b2817b8e5e3d86a5a87cb434a8eec295d5280a7f48e",
// "0x882f78fcb73f0f7ad0700bb0424a8b4beb366aaa93b88a3562c49a8d0ce4dcff",
// ...
// ],
// transactionsRoot: "0x5934902f3dcc263ec34f24318179bf6301f53f4834685792066026f3a4849d72",
// uncles: [],
// }

Parameters

NameTypeDefault valueDescription
timeFrameBlockTag'latest'The number, hash, or text-based description ('latest', 'earliest', or 'pending') of the block to collect information on.
returnTransactionObjectsbooleanfalseWhether to also return data about the transactions on the block.

Returns

Promise<BlockResponse>

A BlockResponse object with information about the specified block

Inherited from

BaseProvider.getBlock

Defined in

providers/BaseProvider.ts:337


getBlockNumber

getBlockNumber(): Promise<number>

Gets the number of the most recently mined block on the network the provider is connected to.

example

await provider.getBlockNumber();
// 1053312

Returns

Promise<number>

the number of the most recently mined block

Inherited from

BaseProvider.getBlockNumber

Defined in

providers/BaseProvider.ts:125


getCode

getCode(address, blockTag?): Promise<string>

Gets the code of a contract on a specified block.

example

await jsonRpcProvider().getCode('0xaC6095720221C79C6E7C638d260A2eFBC5D8d880', 'latest');
// '0x608060405234801561001057600080fd5b506004361061...'

Parameters

NameTypeDefault valueDescription
addressstringundefinedthe contract address to get the contract code from
blockTagBlockTag'latest'the block height to search for the contract code from. Contract code can change, so this allows for checking a specific block

Returns

Promise<string>

the contract creation code for the specified address at the specified block height

Inherited from

BaseProvider.getCode

Defined in

providers/BaseProvider.ts:420


getFeeData

getFeeData(): Promise<FeeData>

Returns the current recommended FeeData to use in a transaction. For an EIP-1559 transaction, the maxFeePerGas and maxPriorityFeePerGas should be used. For legacy transactions and networks which do not support EIP-1559, the gasPrice should be used.Returns an estimate of the amount of gas that would be required to submit transaction to the network.

example

await provider.getFeeData();
// {
// gasPrice: 14184772639n,
// lastBaseFeePerGas: 14038523098n,
// maxFeePerGas: 29577046196n,
// maxPriorityFeePerGas: 1500000000n
// }

Returns

Promise<FeeData>

an object with gas estimates for the network currently

Inherited from

BaseProvider.getFeeData

Defined in

providers/BaseProvider.ts:478


getGasPrice

getGasPrice(): Promise<bigint>

Gives an estimate of the current gas price in wei.

example

await provider.getGasPrice();
// 52493941856

Returns

Promise<bigint>

an estimate of the current gas price in wei

Inherited from

BaseProvider.getGasPrice

Defined in

providers/BaseProvider.ts:372


getLogs

getLogs(filter): Promise<Log[]>

Returns transaction receipt event logs that match a specified filter. May return [] if parameters are too broad, even if logs exist.

example

provider.getLogs({
address: "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
topics: [
"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
"0x00000000000000000000000021b8065d10f73ee2e260e5b47d3344d3ced7596e",
],
fromBlock: 14825027,
toBlock: 14825039,
});

[
{
address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
blockHash: '0x8e0dfac2f704851960f866c8708b3bef2f66c0fee0329cf25ff0261b264ca6bc',
blockNumber: 14825029,
data: '0x000000000000000000000000000000000000000000000000005f862ee352a38a',
logIndex: 384,
removed: false,
topics: [
'0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef',
'0x00000000000000000000000021b8065d10f73ee2e260e5b47d3344d3ced7596e',
'0x00000000000000000000000068b3465833fb72a70ecdf485e0e4c7bd8665fc45'
],
transactionHash: '0xbd49031be16f8fd1775f4e0fe79b408ffd8ae9c65b2827ee47e3238e3f51f4c0',
transactionIndex: 226
}
]

Parameters

NameTypeDescription
filterFilter | FilterByBlockHashparameters to filter the logs by

Returns

Promise<Log[]>

an array of logs matching the specified filter

Inherited from

BaseProvider.getLogs

Defined in

providers/BaseProvider.ts:540


getNetwork

getNetwork(): Promise<Network>

Gets information (name, chainId, and ensAddress when applicable) about the network the provider is connected to.

example

jsonRpcProvider('https://free-eth-node.com/api/eth').getNetwork();
// { chainId: 1, name: 'eth', ensAddress: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e' }

example

jsonRpcProvider('https://free-eth-node.com/api/MATIC').getNetwork();
// { chainId: 137, name: 'MATIC', ensAddress: null }

Returns

Promise<Network>

information about the network this provider is currently connected to

Inherited from

BaseProvider.getNetwork

Defined in

providers/BaseProvider.ts:98


getTransaction

getTransaction(transactionHash): Promise<TransactionResponse>

Gets information about a specified transaction, even if it hasn't been mined yet.

example

await provider.getTransaction('0x9014ae6ef92464338355a79e5150e542ff9a83e2323318b21f40d6a3e65b4789');
// {
// accessList: [],
// blockHash: "0x876810a013dbcd140f6fd6048c1dc33abbb901f1f96b394c2fa63aef3cb40b5d",
// blockNumber: 14578286,
// chainId: 1,
// from: "0xdfD9dE5f6FA60BD70636c0900752E93a6144AEd4",
// gas: 112163n,
// gasPrice: 48592426858n,
// hash: "0x9014ae6ef92464338355a79e5150e542ff9a83e2323318b21f40d6a3e65b4789",
// input: "0x83259f17000000000000000000000000000000000000000000...",
// maxFeePerGas: 67681261618n,
// maxPriorityFeePerGas: 1500000000n,
// nonce: 129n,
// r: "0x59a7c15b12c18cd68d6c440963d959bff3e73831ffc938e75ecad07f7ee43fbc",
// s: "0x1ebaf05f0d9273b16c2a7748b150a79d22533a8cd74552611cbe620fee3dcf1c",
// to: "0x39B72d136ba3e4ceF35F48CD09587ffaB754DD8B",
// transactionIndex: 29,
// type: 2,
// v: 0,
// value: 0n,
// confirmations: 298140,
// }

Parameters

NameTypeDescription
transactionHashstringthe hash of the transaction to get information about

Returns

Promise<TransactionResponse>

information about the specified transaction

Inherited from

BaseProvider.getTransaction

Defined in

providers/BaseProvider.ts:167


getTransactionCount

getTransactionCount(address, blockTag?): Promise<number>

Returns the number of sent transactions by an address, from genesis (or as far back as a provider looks) up to specified block.

example

await provider.getTransactionCount('0x71660c4005ba85c37ccec55d0c4493e66fe775d3');
// 1060000

example

await provider.getTransactionCount('0x71660c4005ba85c37ccec55d0c4493e66fe775d3', 'latest');
// 1060000

example

await provider.getTransactionCount('0x71660c4005ba85c37ccec55d0c4493e66fe775d3', 14649390);
// 1053312

Parameters

NameTypeDefault valueDescription
addressstringundefinedthe address to count number of sent transactions
blockTagBlockTag'latest'the block to count transactions up to, inclusive

Returns

Promise<number>

the number of transactions sent by the specified address

Inherited from

BaseProvider.getTransactionCount

Defined in

providers/BaseProvider.ts:283


getTransactionReceipt

getTransactionReceipt(transactionHash): Promise<TransactionReceipt>

Gives information about a transaction that has already been mined. Includes additional information beyond what's provided by getTransaction.

example

await provider.getTransactionReceipt('0x9014ae6ef92464338355a79e5150e542ff9a83e2323318b21f40d6a3e65b4789');
// {
// blockHash: "0x876810a013dbcd140f6fd6048c1dc33abbb901f1f96b394c2fa63aef3cb40b5d",
// blockNumber: 14578286,
// contractAddress: null,
// cumulativeGasUsed: 3067973n,
// effectiveGasPrice: 48592426858n,
// from: "0xdfD9dE5f6FA60BD70636c0900752E93a6144AEd4",
// gasUsed: 112163n,
// logs: [
// {
// address: "0x0eDF9bc41Bbc1354c70e2107F80C42caE7FBBcA8",
// blockHash: "0x876810a013dbcd140f6fd6048c1dc33abbb901f1f96b394c2fa63aef3cb40b5d",
// blockNumber: 14578286,
// data: "0x0000000000000000000000000000000000000000000003a12ec797b5484968c1",
// logIndex: 42,
// topics: [
// "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",
// "0x00000000000000000000000039b72d136ba3e4cef35f48cd09587ffab754dd8b",
// "0x000000000000000000000000dfd9de5f6fa60bd70636c0900752e93a6144aed4",
// ],
// transactionHash: "0x9014ae6ef92464338355a79e5150e542ff9a83e2323318b21f40d6a3e65b4789",
// transactionIndex: 29,
// },
// {
// address: "0x39B72d136ba3e4ceF35F48CD09587ffaB754DD8B",
// blockHash: "0x876810a013dbcd140f6fd6048c1dc33abbb901f1f96b394c2fa63aef3cb40b5d",
// blockNumber: 14578286,
// data: "0x0000000000000000000000000000000000000000000003a12ec797b5484968c1",
// logIndex: 43,
// topics: [
// "0x34fcbac0073d7c3d388e51312faf357774904998eeb8fca628b9e6f65ee1cbf7",
// "0x000000000000000000000000dfd9de5f6fa60bd70636c0900752e93a6144aed4",
// "0x0000000000000000000000000000000000000000000000000000000000000003",
// ],
// transactionHash: "0x9014ae6ef92464338355a79e5150e542ff9a83e2323318b21f40d6a3e65b4789",
// transactionIndex: 29,
// },
// ],
// logsBloom: "0x00000000000000000000000000000...",
// status: 1,
// to: "0x39B72d136ba3e4ceF35F48CD09587ffaB754DD8B",
// transactionHash: "0x9014ae6ef92464338355a79e5150e542ff9a83e2323318b21f40d6a3e65b4789",
// transactionIndex: 29,
// type: 2,
// byzantium: true,
// confirmations: 298171,
// }

Parameters

NameTypeDescription
transactionHashstringthe hash of the transaction to get information about

Returns

Promise<TransactionReceipt>

information about the specified transaction that has already been mined

Inherited from

BaseProvider.getTransactionReceipt

Defined in

providers/BaseProvider.ts:243


off

off(event, callback?): WebSocketProvider

Remove an event listener. If no callback is provided, removes all listeners for that event.

Parameters

NameTypeDescription
eventstringThe event name or subscription ID
callback?FunctionThe specific callback to remove, or omit to remove all

Returns

WebSocketProvider

Defined in

providers/WebSocketProvider.ts:330


on

on(event, callback): WebSocketProvider

Register an event listener for subscription events.

Event names correspond to subscription types:

  • 'block'newHeads subscription notifications
  • 'pending'newPendingTransactions subscription notifications
  • 'logs'logs subscription notifications
  • Any subscription ID → direct subscription callbacks

Parameters

NameTypeDescription
eventstringThe event name or subscription ID
callbackFunctionThe function to call when the event fires

Returns

WebSocketProvider

Defined in

providers/WebSocketProvider.ts:316


resolveName

resolveName(name): Promise<null | string>

Resolves an ENS name to an Ethereum address.

Performs the full ENS resolution process:

  1. Computes the namehash of the ENS name
  2. Queries the ENS Registry for the resolver contract
  3. Queries the resolver for the address

example

await provider.resolveName('vitalik.eth');
// '0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045'

example

await provider.resolveName('thisshouldnotexist12345.eth');
// null

Parameters

NameTypeDescription
namestringthe ENS name to resolve (e.g. 'vitalik.eth')

Returns

Promise<null | string>

the Ethereum address the name resolves to, or null if not found

Inherited from

BaseProvider.resolveName

Defined in

providers/BaseProvider.ts:629


subscribe

subscribe(type, params?): Promise<string>

Subscribe to real-time Ethereum events via eth_subscribe.

example

const subId = await provider.subscribe('newHeads');

example

const subId = await provider.subscribe('logs', {
address: '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2',
topics: ['0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef'],
});

Parameters

NameTypeDescription
typeSubscriptionTypeThe subscription type: 'newHeads', 'logs', or 'newPendingTransactions'
params?objectOptional parameters (e.g. filter object for 'logs')

Returns

Promise<string>

The subscription ID returned by the node

Defined in

providers/WebSocketProvider.ts:254


unsubscribe

unsubscribe(subscriptionId): Promise<boolean>

Unsubscribe from a previously created subscription.

Parameters

NameTypeDescription
subscriptionIdstringThe subscription ID to cancel (returned by subscribe)

Returns

Promise<boolean>

true if successfully unsubscribed, false otherwise

Defined in

providers/WebSocketProvider.ts:290