How to Create javascript WebSockets Subscriptions to Ethereum and Binance Smart Chain through ethers.js? – Benzinga

Creating a WebSockets subscription to Ethereum and Binance Smart Chain using ethers.js can be useful for developers for several reasons, including scalability and easier integration.

Using NOWNodes to create WebSockets subscriptions to blockchain networks is a common practice. Javascript libraries such as ether.js have been a popular framework for WebSockets development.

Enter your email and you'll also get Benzinga's ultimate morning update AND a free $30 gift card and more!

WebSockets subscription is similar to an Event Listener in Javascript. There are several reasons why an Event Listener is essential. This article illustrates creating simple BSC WebSocket and Ethereum websocket subscriptions to popular Blockchain networks like Ethereum and Binance Smart Chain.

Why create a Javascript WebSockets subscription

Javascript WebSockets subscription is either the Ethereum blockchain or the Binance Smart Chain is important for several reasons. Below are some of the reasons to develop a WebSockets subscription.

WebSockets are communication protocols that enable real-time, two-way communication between a client (such as a web browser) and a server. It provides a persistent connection between the client and server, sending and receiving real-time data.

Constant communication is often established through Websockets API. The WebSockets API provides methods for opening and closing connections, sending and receiving data, and handling errors and events. WebSockets offer a powerful and flexible way to enable real-time communication between client-side and server-side applications. They have become essential for building modern web applications crucial for blockchain and web 3 development.

Platforms like NOWNodes provide more straightforward ways to establish such connections, making it much easier to alleviate the need for a technical developer team. Below is a step-by-step guide on importing the ethers.js library and developing WebSockets subscription to the Ethereum blockchain network and Binance Smart Chain.

How to import ethers.js library and create WebSockets subscription

To use the Ethers.js library, first of all, you need to learn how to install ethers. npm install ethers Then you can import it using the code below.

const { ethers } = require("ethers");

After importing, you create a provider instance directly connecting to the preferred blockchain network. In this case, either the Ethereum blockchain or the Binance Smart Chain. Below is the line of code to create the required connection using NOWnodes.

const provider = new ethers.providers.WebSocketProvider("'wss://bsc.nownodes.io/wss/YOUR_API_KEY');

It is important to note that you'll be required to replace YOUR_API_KEY with your actual NOWNodes API key in development.

Subsequently, create a contract instance using the below line of code.

const contractAddress = "0x..."; // The contract address you want to interact with

const abi = [...] // The ABI of the contract

const contract = new ethers.Contract(contractAddress, abi, provider);

Next, you should create a subscription to an event emitted by the contract. To do so, you'll need to implement the code line below.

contract.on("EventName", (arg1, arg2, event) => {

console.log("Event received:", arg1, arg2);

});

Important Notes:

Below is the code for WebSockets that connect to the Binance Smart Chain blockchain network using the NOWNodes node provider.

const { ethers } = require('ethers')

const url = 'wss://bsc.nownodes.io/wss/YOUR_API_KEY'

const EXPECTED_PONG_BACK = 15000

const KEEP_ALIVE_CHECK_INTERVAL = 7500

const startConnection = async () => {

const provider = new ethers.providers.WebSocketProvider(url, {

name: 'binance',

chainId: 56,

})

let pingTimeout = null

let keepAliveInterval = null

provider._websocket.on('open', () => {

console.log('Connect')

keepAliveInterval = setInterval(() => {

console.log('Checking if the connection is alive, sending a ping')

provider._websocket.ping()

// Use WebSocket#terminate(), which immediately destroys the connection,

// instead of WebSocket#close(), which waits for the close timer.

// Delay should be equal to the interval at which your server

// sends out pings plus a conservative assumption of the latency.

pingTimeout = setTimeout(() => {

provider._websocket.terminate()

}, EXPECTED_PONG_BACK)

}, KEEP_ALIVE_CHECK_INTERVAL)

})

provider._websocket.on('close', () => {

console.error('The websocket connection was closed')

clearInterval(keepAliveInterval)

clearTimeout(pingTimeout)

startConnection()

})

provider._websocket.on('pong', () => {

console.log('Received pong, so connection is alive, clearing the timeout')

clearInterval(pingTimeout)

})

provider.on('block',(block)=>{

console.log('New block!', block)

})

}

startConnection()

Some advanced features of ethers.js for creating Ethereum/BSC WebSockets

Ethers.js provides a variety of advanced features for creating Ethereum WebSocket and BSC websocket subscriptions. Here are a few examples:

You can filter events based on specific parameters using the `ethers.utils` library. For example, to filter for a specific token transfer event, you could use the following code:

const filter = {

address: contractAddress,

topics: [ethers.utils.id('Transfer(address,address,uint256)')],

fromBlock: 'latest'

};

const logs = await provider.getLogs(filter);

If the WebSockets connection is lost, Ethers.js will automatically attempt to reconnect to the Ethereum node. You can also configure the number of reconnection attempts and the delay between attempts using the WebSocketProvider options.

For instance, to configure the WebSockets provider to retry every 5 seconds for up to 10 times, you could use the code below:

const options = {

reconnect: {

maxAttempts: 10,

delay: 5000

}

};

const provider = new ethers.providers.WebSocketProvider('wss://bsc.nownodes.io/wss/YOUR_API_KEY');

This code creates a reconnect object in the provider options that specifies the maximum number of attempts and the delay between attempts.

Using the provider, you can send multiple requests to an Ethereum node in a single batch.send() method. This can help reduce latency and improve performance. For instance, to retrieve the balances of multiple accounts in a single batch, you could use the following block of code:

const requests = [

{ method: 'eth_getBalance', params: ['0x123...', 'latest'] },

{ method: 'eth_getBalance', params: ['0x456...', 'latest'] },

{ method: 'eth_getBalance', params: ['0x789...', 'latest'] }

];

const results = await provider.send('eth_batch', requests);

What you get with NOWNodes service:

NOWNodes offers three paid plans, pro, business, and enterprise. It also provides a FREE plan suitable for small projects.

Start: FREE/ 100,000 requests per month + 1 API key and access to 5 nodes.

Pro: 20 / 1,000,000 requests per month + up to 3 API keys and access to all nodes Business: 200 / 30,000,000 requests per month + up to 25 API keys and access to all nodes.

Enterprise: 500 / 100,000,000 requests per month + up to 100 API keys and access to all nodes.

Conclusion

For several reasons, creating WebSockets with platforms such as NOWNodes can be important for maintaining high-security levels, constant uptime, and interoperability. Using the code snippet above, you can establish BSC WebSocket and Ethereum WebSocket using Ethers.js. The resulting WebSockets subscription would ensure Real-time communication, enhanced security, and scalability to ensure the growth of Web 3 projects.

Media Contact Company Name: NOWNodesEmail: Send EmailCountry: EstoniaWebsite: https://nownodes.io/

See the original post here:

How to Create javascript WebSockets Subscriptions to Ethereum and Binance Smart Chain through ethers.js? - Benzinga

Related Posts

Comments are closed.