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:
- Breaking News: Cosmos ($ATOM) Enables Inter-Blockchain Communication; Connects with Ethereum ($ETH), Binance Smart Chain ($BSC), and Terra ($LUNA) -... - February 7th, 2025 [February 7th, 2025]
- Ethereum News: Ethereum (ETH)bPrice Targets $3.7K Amid Growing Smart Money Confidence and On-chain Strength - Binance - November 24th, 2024 [November 24th, 2024]
- Pattieswap/PattiePad Announces Last Stage Pre-sale of $PATTIE Token on Binance Smart Chain - GlobeNewswire - November 17th, 2024 [November 17th, 2024]
- A beginners guide to the BNB Chain: The evolution of the Binance Smart Chain - Cointelegraph - November 14th, 2024 [November 14th, 2024]
- BABY PEPE; Meet the Largest Pepe Token on the Binance Smart Chain Network! - Binance - October 12th, 2024 [October 12th, 2024]
- IAMDOG Expands to Binance Smart Chain: Bringing Meme Culture, Transparent Rewards, and an Engaging Gaming Experience to Millions - Benzinga - October 7th, 2024 [October 7th, 2024]
- Binance Smart Chain Expands with AI Deal, Why This is Great for FET and RCOF - Live Bitcoin News - September 6th, 2024 [September 6th, 2024]
- Binance to Temporarily Suspend Deposits and Withdrawals on BNB Smart Chain Soon: Heres Why - CryptoPotato - September 6th, 2024 [September 6th, 2024]
- Binance Integrates DeXe (DEXE) on BNB Smart Chain, Opens Deposits and Withdrawals - Blockchain.News - June 18th, 2024 [June 18th, 2024]
- DeFi Exchange 1Inch Expands to Binance Smart Chain Citing ETH Gas Fees - Yahoo News UK - June 18th, 2024 [June 18th, 2024]
- WUSD Stablecoin Expands Reach with Integration on Binance Smart Chain and Solana - PR Newswire - June 18th, 2024 [June 18th, 2024]
- Memereum Surpasses 21 Million Tokens Sold in Presale, Pioneers Blockchain-Based Insurance on Binance Smart ... - CryptoPotato - June 12th, 2024 [June 12th, 2024]
- Exploring the rise of Binance Coin: factors behind its surging value and future prospects - The National - The National - June 12th, 2024 [June 12th, 2024]
- Binance Coin (BNB) Surges Over 6%, Hits All-Time High Amid Network Growth - NullTX - June 12th, 2024 [June 12th, 2024]
- Tupan Launches the New Binance Smart Chain TCT - GlobeNewswire - March 9th, 2024 [March 9th, 2024]
- ChatGPT picks 3 low-fee 'Ethereum killers' to buy as ETH gas fees ... - Finbold - Finance in Bold - November 19th, 2023 [November 19th, 2023]
- Title: Unveiling Polkastream: The Evolution of Web 3.0 Entertainment - Medium - November 19th, 2023 [November 19th, 2023]
- PEPE and FLOKI Meet a New Rival: Investor Attraction to ... - BeInCrypto - November 17th, 2023 [November 17th, 2023]
- Why So Many Crypto Games Are Switching ChainsOr Calling it Quits - Decrypt - November 14th, 2023 [November 14th, 2023]
- USDV stablecoin backed by tokenized treasuries launches - crypto.news - November 14th, 2023 [November 14th, 2023]
- What Fueled Polygon's (MATIC) 10% Price Increase? - Investing.com India - November 14th, 2023 [November 14th, 2023]
- SEC and Binance Agree on Protective Order in the Ongoing Legal ... - BSC NEWS - November 14th, 2023 [November 14th, 2023]
- Ethereum vs. Binance Smart Chain: Where to Make More Money - Medium - October 26th, 2023 [October 26th, 2023]
- What Are Trust Wallet Airdrops and How to Claim One? - Latest Cryptocurrency Prices & Articles - October 26th, 2023 [October 26th, 2023]
- Binance Statistics 2023 (Data on Usage, Revenue, and More) - The Tech Report - October 26th, 2023 [October 26th, 2023]
- 10 Cryptocurrencies That Could Explode in 2024 - Analytics Insight - October 26th, 2023 [October 26th, 2023]
- The Rise of Automated Crypto Trading: Strategies and Success Stories - TechiExpert.com - October 26th, 2023 [October 26th, 2023]
- The Best Crypto to Buy Now - Tekedia - October 26th, 2023 [October 26th, 2023]
- Crypto hacks: The Story - The Cryptonomist - October 15th, 2023 [October 15th, 2023]
- Taurus taps Bank of America and SAP veterans to head European ... - Tekedia - October 15th, 2023 [October 15th, 2023]
- Why Are Whales Flooding Everlodge (ELDG)? Bitcoin Cash (BCH ... - The Crypto Basic - October 15th, 2023 [October 15th, 2023]
- Ankr teams up with XDC Network to launch RPC Integration - crypto.news - October 15th, 2023 [October 15th, 2023]
- Binance froze cryptocurrency accounts associated with Hamas amid ... - Tekedia - October 15th, 2023 [October 15th, 2023]
- TangibleDAO Plans Recovery After USDR Stablecoin Crashes - BeInCrypto - October 15th, 2023 [October 15th, 2023]
- The Environmental Impact of Proof-of-Stake Blockchains: A ... - Tribune Online - October 15th, 2023 [October 15th, 2023]
- Binance Coin Hovers Above $200: BNB Smart Chain Users Rise 40% - Watcher Guru - September 11th, 2023 [September 11th, 2023]
- Binance's indecision to freeze BNB wallets drew controversy in this ... - Cointelegraph - September 11th, 2023 [September 11th, 2023]
- 3 Coins Set To Dominate the Market in 2023 Ethereum (ETH ... - Finbold - Finance in Bold - September 11th, 2023 [September 11th, 2023]
- While Bitcoin Battles Inside Price Channel, Traders Are Buying This ... - Captain Altcoin - September 11th, 2023 [September 11th, 2023]
- Binance Airdrop $3 million BNB to Morocco Earthquake Victims - Watcher Guru - September 11th, 2023 [September 11th, 2023]
- ETH Price Prediction: Uncertain Short-Term Outlook, But These ... - Captain Altcoin - September 11th, 2023 [September 11th, 2023]
- BNB Shows Promising Signs As opBNB Launches, Pomerdoge ... - The Crypto Basic - September 11th, 2023 [September 11th, 2023]
- B2BinPay v17 - Breaking down the latest major platform update - Cointelegraph - September 11th, 2023 [September 11th, 2023]
- 4 Reasons The Bitcoin Price Could Hit $50,000 This Winter ... - Finbold - Finance in Bold - September 11th, 2023 [September 11th, 2023]
- Cronos (CRO) Price Insight - With Growing Utility, Can CRO Reach ... - Inside Bitcoins - September 11th, 2023 [September 11th, 2023]
- How to Bridge to Tron - Watcher Guru - August 13th, 2023 [August 13th, 2023]
- Could the SEC Lawsuit End Binance for Good? Analysts Weigh In - Live Bitcoin News - August 13th, 2023 [August 13th, 2023]
- BNB Chain hard fork to improve security and compatibility with EVM ... - Cointelegraph - August 13th, 2023 [August 13th, 2023]
- How To Get Free 10 BNB with PancakeSwap Full Tutorial 2023 - Medium - August 13th, 2023 [August 13th, 2023]
- How to find BEP-20 wallet address on Trust Wallet & Metamask ... - Cryptopolitan - August 13th, 2023 [August 13th, 2023]
- Curved Finance Receives $5 Million FromBinance - cryptonewsbytes.com - August 13th, 2023 [August 13th, 2023]
- Early activity on Coinbase's Base chain shows promising signs - Blockworks - August 13th, 2023 [August 13th, 2023]
- Solana TVL Soars: Outperforms Ethereum, BSC, and Avalanche ... - Crypto News Flash - August 13th, 2023 [August 13th, 2023]
- Developing Automated Market Making on PancakeSwap: Tools ... - Rebellion Research - August 13th, 2023 [August 13th, 2023]
- Visa Unveils Experimental Solution to Abstract Away Gas Fees ... - Tekedia - August 13th, 2023 [August 13th, 2023]
- Shiba Inu Price Prediction: SHIB's Meteoric Rise; A Meme from the ... - Inside Bitcoins - August 13th, 2023 [August 13th, 2023]
- Exploring DeFi Protocols And Ecosystems: Unveiling The ... - Blockchain Magazine - August 13th, 2023 [August 13th, 2023]
- Altcoin Daily and Raoul Pal Anticipate Alt Season: BNB, AVAX, and ... - Tekedia - August 13th, 2023 [August 13th, 2023]
- The Galactic Meme Coin Making Waves in the Binance Smart Chain - Digital Journal - July 26th, 2023 [July 26th, 2023]
- Top 3 Binance Coins in Q3-2023. - Altcoin Buzz - July 26th, 2023 [July 26th, 2023]
- Binance: Fight The Urge To Buy The Dip (BNB-USD) - Seeking Alpha - July 26th, 2023 [July 26th, 2023]
- The 5 Forces Propelling The Continued Growth Of Ethereum - Blockzeit - July 26th, 2023 [July 26th, 2023]
- Seize the Day: Could Chancer Be the Best New Crypto of 2023? - The Coin Republic - July 26th, 2023 [July 26th, 2023]
- Unraveling the Craze: The Furry Spectacle of Hamster Racing in the ... - Blockzeit - July 26th, 2023 [July 26th, 2023]
- The Future of Crypto Exchanges Centralized DEX Interfaces - Techopedia - July 26th, 2023 [July 26th, 2023]
- 12 Best Blockchain Protocols To Know - Techopedia - July 17th, 2023 [July 17th, 2023]
- Binance Coin: Fueling the Worlds Largest Crypto Exchange - Business News This Week - July 17th, 2023 [July 17th, 2023]
- As the Theta Network Price Rises More Upside Could be Limited - BanklessTimes - July 17th, 2023 [July 17th, 2023]
- Discover Emerging Opportunities With BNB Chain And Uwerx(WERX) - The Portugal News - July 17th, 2023 [July 17th, 2023]
- Benefits of Wrapped Crypto that You Need to Check Out ... - Cryptopolitan - July 17th, 2023 [July 17th, 2023]
- 3 Cryptos to Catapult You into the Millionaires' Club - InvestorPlace - July 17th, 2023 [July 17th, 2023]
- 5 Meme Coins That Are Dominating Crypto Social Media Activity in ... - Analytics Insight - July 17th, 2023 [July 17th, 2023]
- CertiK Completes Comprehensive Security Audit of Automated ... - GlobeNewswire - July 17th, 2023 [July 17th, 2023]
- Parsiq: Real-Time Blockchain Monitoring and Automation - Tech Critter - July 17th, 2023 [July 17th, 2023]
- The Top 10 Blockchain-Based Storage Platforms - MUO - MakeUseOf - July 17th, 2023 [July 17th, 2023]
- Exploring The Best Altcoins For The Next Bull Run: Cardano ... - Tekedia - July 17th, 2023 [July 17th, 2023]
- An Introduction to Binance Smart Contracts for Token Holders - Net Newsledger - June 22nd, 2023 [June 22nd, 2023]
- Palmswap Secures Partnership with Gotbit for the Palmswap ... - GlobeNewswire - June 22nd, 2023 [June 22nd, 2023]
- Exciting Adventure Awaits as My Neighbor Alice Unveils Alpha ... - Finbold - Finance in Bold - June 22nd, 2023 [June 22nd, 2023]
- Among Blockchains Supporting NFTs, Here's Why Ethereum Will ... - Inside Bitcoins - June 22nd, 2023 [June 22nd, 2023]