press release
Published March 11, 2023
Using ethers.js to create WebSockets subscriptions to Ethereum and Binance smart chains is useful for developers for several reasons, including scalability and ease of integration.
Creating a WebSockets subscription to a blockchain network using NOWNodes is a common practice. Javascript libraries such as ether.js are popular frameworks for WebSocket development.
WebSockets subscriptions are similar to event listeners in Javascript. There are several reasons why event listeners are essential. This article walks through creating a simple BSC WebSocket and Ethereum WebSocket subscription to popular blockchain networks such as Ethereum and Binance Smart Chain.
Why Create a Javascript WebSockets Subscription
Javascript WebSockets subscriptions, either on the Ethereum blockchain or the Binance Smart Chain, are important for several reasons. Below are some of the reasons for developing a WebSockets subscription.
- Scalability
- real time update
- Reduced network load
- decentralized communication
- easier integration
- Compatibility with ethers.js
WebSocket is a communication protocol that enables real-time, two-way communication between a client (such as a web browser) and a server. It provides a persistent connection between client and server to send and receive real-time data.
Constant communication is often established through the Websockets API. The WebSockets API provides methods for opening and closing connections, sending and receiving data, and handling errors and events. WebSockets provide 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 that are integral to blockchain and web 3 development.
Platforms like NOWNodes offer an easier way to establish such connections, greatly reducing the need for technical development teams. Below is a step-by-step guide to importing the ethers.js library and developing a WebSockets subscription to the Ethereum blockchain network and Binance Smart Chain.
How to import the ethers.js library and create a WebSockets subscription
To use the Ethers.js library, you first need to learn how to install ethers. npm install ether Then you can import it using the code below.
const { ether } = require(“ether”);
After importing, create a provider instance that connects directly to your preferred blockchain network. In this case, either the Ethereum blockchain or the Binance Smart Chain. Below are the lines of code to create the necessary connections using NOWnodes.
const provider = new ethers.providers.WebSocketProvider(“‘wss://bsc.nownodes.io/wss/YOUR_API_KEY’);
It’s important to note that you should replace YOUR_API_KEY Use the actual NOWNodes API key you are developing.
Then create a contract instance with the following lines of code:
const contractAddress = “0x…”; // contract address to exchange
const abi = […] // Contract ABI
const contract = new ethers. Contract(contractAddress, abi, provider);
Next, we need to create a subscription to the events emitted by the contract. To do that, we need to implement the following lines of code:
contract.on(“event name”, (arg1, arg2, event) => {
console.log(“Event received:”, arg1, arg2);
});
Important matter:
- “EventName” should be replaced with the actual name of the event you plan to subscribe to.
- The actual names of the specific event arguments should replace the arguments “Arg1” and “Arg2”.
Below is the code for WebSockets connecting to the Binance Smart Chain blockchain network using the NOWNodes node provider.
const { ether } = require(‘ether’)
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”,
Chain ID: 56,
}))
let pingTimeout = null
let keepAliveInterval = null
provider._websocket.on(‘open’, () => {
console.log(‘Connection’)
keepAliveInterval = setInterval(() => {
console.log(‘Checking if connection is valid and sending ping’)
provider._websocket.ping()
// use WebSocket#terminate() to immediately destroy the connection,
// Instead of WebSocket#close() waiting for the close timer.
// delay must equal the interval the server delays
// Send a conservative assumption of latency in addition to the ping.
pingTimeout = setTimeout(() => {
provider._websocket.terminate()
}, EXPECTED_PONG_BACK)
}, KEEP_ALIVE_CHECK_INTERVAL)
}))
provider._websocket.on(‘close’, () => {
console.error(‘WebSocket connection closed’)
clearInterval(keepAliveInterval)
clearTimeout(ping timeout)
startConnection()
}))
provider._websocket.on(‘pong’, () => {
console.log(‘Receiving pong, connection is valid, clearing timeout’)
clearInterval(pingTimeout)
}))
provider.on(‘block’,(block)=>{
console.log(‘new block!’, block)
}))
}
startConnection()
Advanced features of ethers.js for creating Ethereum/BSC WebSockets
Ethers.js provides various advanced features for creating Ethereum WebSocket and BSC WebSocket subscriptions. Here are some examples:
can be used to filter events based on specific parameters. `ethers.utils` library. For example, to filter specific token transfer events, you can use the following code:
const filter = {
Address: contractAddress,
topic: [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 try to reconnect to the Ethereum node. You can also configure the number of reconnection attempts and the delay between attempts using WebSocketProvider options.
For example, to configure the WebSockets provider to retry up to 10 times every 5 seconds, you can use the following code:
const option = {
Reconnect: {
maximum number of attempts: 10,
Delay: 5000
}
};
const provider = new ethers.providers.WebSocketProvider(‘wss://bsc.nownodes.io/wss/YOUR_API_KEY’);
This code creates a reconnection object with provider options that specify the maximum number of attempts and the delay between attempts.
Providers allow you to send multiple requests to Ethereum nodes with a single batch.send() method. This reduces latency and improves performance. For example, to get the balances of multiple accounts in one batch, you can use the following code block.
const request = [
{ method: ‘eth_getBalance’, params: [‘0x123…’, ‘latest’] },
{ method: ‘eth_getBalance’, parameters: [‘0x456…’, ‘latest’] },
{ method: ‘eth_getBalance’, parameters: [‘0x789…’, ‘latest’] }
];
const results = await provider.send(‘eth_batch’, requests);
With the NOWNodes service you get:
- High uptime: NOWNodes offers SQS contracts with 99.95% uptime, ensuring your WebSocket connections are consistently available.
- Easy Integration: NOWNodes easily integrates with a wide variety of programming languages and frameworks, making it easy to incorporate WebSockets node providers into your applications.
- Security: NOWNodes stores a very limited range of data (only email addresses) and requests statistics done via API keys to ensure WebSockets connections are secure and protected from potential attacks. And confirm that it has.
- Scalability: NOWNodes provide a scalable infrastructure that can handle high demand volumes of traffic and are suitable for applications that require large amounts of real-time data.
NOWNodes has three paid plans: pro, business and enterprise. It also offers a free plan suitable for small projects.
Start: Free/ 100,000 requests per month + access to 1 API key and 5 nodes.
Professional: €20 / 1,000,000 requests per month + access to up to 3 API keys and all nodes work: €200 / 30,000,000 requests per month + access to up to 25 API keys and all nodes.
Companies: €500 / 100 million requests / month + up to 100 API keys and access to all nodes.
Conclusion
For several reasons, creating WebSockets on platforms such as NOWNodes is important to maintain high security levels, consistent uptime, and interoperability. Using the code snippet above, you can establish BSC WebSockets and Ethereum WebSockets using Ethers.js. The resulting WebSockets subscription guarantees real-time communication, enhanced security, and scalability to ensure the growth of your Web 3 project.
media contact
Company Name: NOW node
Email: I send a mail
Country: Estonia
Website: https://nownodes.io/