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:
- Has Binance Lost $1.8 Billion In USDC? Is This The Next FTX? - Crypto Reporter [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Ethereum Killer: How Do Projects Outshine Others for Top Spot ... - Cryptopolitan [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Binance US to Delist HNT Token Ahead of Helium Migration to Solana - BSC NEWS [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Meta scraps NFTs on Instagram and Facebook: Nifty Newsletter, March 814 - Cointelegraph [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Core DAO Announces Strategic Partnership with OKX, Gets Tracked ... - BSC NEWS [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Top Five Decentralized Exchanges Built on Core Network - BSC NEWS [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Chainlyze.AI Empowers Investors with On-Chain Analysis - BSC NEWS [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Avorak AI (AVRK) Secures Massive $50,000 USD OTC Deal With Binance (BNB) Chain-Focused Institution - Crypto Mode [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- How To Add Tron [TRX] To Metamask? [What Goes & What Not] - Captain Altcoin [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Ebisu's Bay NFT Marketplace Announces Launch of Native Token ... - BSC NEWS [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Polygon Wallet Suite Will Go Live on zkEVM at Mainnet Beta Launch - BSC NEWS [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Dream Idols Trainee Voting Results Are In! - BSC NEWS [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Arbitrum Shatters Records: Hits $1 Billion in Daily Trading Volume ... - BSC NEWS [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Poolz & Euler Hit With Back-to-Back DeFi Exploits Totaling $2.3M - BeInCrypto [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- Uniswap's V3 Successfully Launched on The BNB Chain - Crypto Times [Last Updated On: March 16th, 2023] [Originally Added On: March 16th, 2023]
- How Can Blockchain Explorers Help Understand the Technology ... - Cryptopolitan [Last Updated On: March 20th, 2023] [Originally Added On: March 20th, 2023]
- Shiba Inu To Launch Native Blockchain, Avorak AI Looks To Partner With Cross-Chain Liquidity - Coinpedia Fintech News [Last Updated On: March 20th, 2023] [Originally Added On: March 20th, 2023]
- The Biggest Crypto Movers & Shakers of the Week - Securities.io [Last Updated On: March 20th, 2023] [Originally Added On: March 20th, 2023]
- XRP and Filecoin Begin To Explore AI Support From Top Players ... - Crypto Reporter [Last Updated On: March 20th, 2023] [Originally Added On: March 20th, 2023]
- Battle of the DEXes: Uniswap v3 Goes Live on BNB Chain - BSC NEWS [Last Updated On: March 20th, 2023] [Originally Added On: March 20th, 2023]
- Is The Future of Crypto Pancake Shaped? - BOSS Magazine [Last Updated On: April 4th, 2023] [Originally Added On: April 4th, 2023]
- Introducing KingKong DOGE: The Future of Meme Tokens - StreetInsider.com [Last Updated On: April 4th, 2023] [Originally Added On: April 4th, 2023]
- Uwerx (WERX), Fantom (FTM), and Binance Coin Ready to Explode ... - Cryptopolitan [Last Updated On: April 4th, 2023] [Originally Added On: April 4th, 2023]
- Cronos (CRO), Polkadot (DOT) and TMS Network (TMSN) Go Head ... - The Crypto Basic [Last Updated On: April 4th, 2023] [Originally Added On: April 4th, 2023]
- Value Locked in Defi Holds the Line at $50B, After Temporarily ... - Bitcoin News [Last Updated On: April 4th, 2023] [Originally Added On: April 4th, 2023]
- Top 5 Best Bet Altcoins To Watch This April - Coinpedia Fintech News [Last Updated On: April 4th, 2023] [Originally Added On: April 4th, 2023]
- Crypto Updates: Ethereum (ETH) and RenQ Finance (RENQ) are ... - Analytics Insight [Last Updated On: April 4th, 2023] [Originally Added On: April 4th, 2023]
- CZ tweeted that a $1B recovery fund would be moved into native crypto with transparency. Then Binance stuck it in a corporate wallet - Yahoo Finance [Last Updated On: April 4th, 2023] [Originally Added On: April 4th, 2023]
- What Coinbase's Layer 2 Says About Where We're Headed - Crypto News Flash [Last Updated On: April 4th, 2023] [Originally Added On: April 4th, 2023]
- Binance Resumes Deposits, Withdrawals After 5hrs Of BNB Network Issue - CoinGape [Last Updated On: April 4th, 2023] [Originally Added On: April 4th, 2023]
- Dexmart wallet is building on the core blockchain ecosystem - Benzinga [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Binance CEO CZ Offers Elon Crypto-Friendly Solution to Rid Twitter ... - BSC NEWS [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- FTX Token Sees Resurgence In Recent Weeks, Learn How Avorak AI Trade Algos Nailed Price Action - Coinpedia Fintech News [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Discover Venus Stars: A Revolutionary Ambassador Program Fueling Community Engagement And Growth For Venu - Benzinga [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Digital Asset Tech Provider Metaco's Partnership Boosts TMS ... - UseTheBitcoin [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Web3 Attacks Continue Into 2023, But Figures Better Than 2022 - BeInCrypto [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Floki Inu Can Break Out This Week - FLOKI Price Prediction - Inside Bitcoins [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- XRP Grabbing Investor's Eyeballs As The Leading Coin, Report | Bitcoinist.com - Bitcoinist [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- The Rise of the Bull Market: Why Big Eyes Coin, Binance Coin And ... - Atalayar [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Dogecoin (DOGE), Binance Coin (BNB), And Uwerx (WERX) Rally ... - Analytics Insight [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Dogecoin creator issues stark warning on crypto investing; Here's ... - Finbold - Finance in Bold [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Binance Coin (BNB) and RenQ Finance (RENQ) only two tokens that will make massive gains in 2023 - mid-day.com [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Exploring the powerhouses of Web3: A look at Solana, BNB Chain ... - Euro Weekly News [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- I questioned ChatGPT if BNB could defeat its competitors, the bot said - AMBCrypto News [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- PancakeSwap Voting To Make CAKE Deflationary, But Prices Are Free-falling - NewsBTC [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- RenQ Finance (RENQ) Set To Enter The Top 20 Tokens, Will ... - The Crypto Basic [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Binance Coin (BNB) and RenQ Finance (RENQ) are the two cryptos ... - Crypto News Flash [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Ripple's (XRP) Support Could be Short Term as Binance (BNB ... - Bitcoinist [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Shiba Inu (SHIB) investors fear more losses, shifting major investments towards this DeFi Token. | - Bitcoinist [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Access, Storage, and Personal Keys: BNB Smart Chain & BNB ... - Retail Technology Innovation Hub [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Arbitrum Overtakes Ethereum in Daily Transactions Once Again: Is ... - BSC NEWS [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- Binance Launches Wrapped-BETH on Binance Chain - BSC NEWS [Last Updated On: April 24th, 2023] [Originally Added On: April 24th, 2023]
- As BNB Chain logs high development activity, will the tides finally turn in its favor? - AMBCrypto News [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- Analyzing the current market trend for Avorak AI, Dogecoin, and Shiba Inu - ZyCrypto [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- I asked ChatGPT if BNB could emerge from the ashes, its answer was strange - AMBCrypto News [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- Lucky Block (LBLOCK) V1 Price Prediction - Blockchain Reporter [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- What is DeFi 2.0, and why is it considered the new trend in ... - The VR Soldier [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- Ankr Expands Focus to Avalanche and Fantom Ecosystems With ... - The Defiant - DeFi News [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- Sotheby's Metaverse Unveils On-Chain Secondary NFT Marketplace - EconomyWatch.com [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- Top 12 Bridges with Highest Liquidity in Q1 2023 - CryptoTvplus [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- Learn Campus, Groundbreaking Learn-to-Earn Project ... - GlobeNewswire [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- Solana (SOL) or Binance Smart Chain (BSC)? Experts Are ... - The Portugal News [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- LINK, AVAX, RenQ Finance: who is the best? - The Cryptonomist [Last Updated On: May 3rd, 2023] [Originally Added On: May 3rd, 2023]
- Polkadot vs RenQ Finance: Will RENQ Overtake DOT? | Mint - Mint [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- Unveiling The Crystal Ball: Apecoin And Dogettis Destiny In The ... - Tekedia [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- How to develop Pancakeswap-like exchange with pancakeswap ... - The Coin Republic [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- Will RenQ Finance (RENQ) repeat what Pepe (PEPE) did? Experts ... - Crypto News Flash [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- Why An Open Interoperable Metaverse Is Better For Everyone - Blockchain Magazine [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- New Jersey Bureau of Securities Joins other States in Effort to Stop ... - New Jersey Attorney General [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- Uwerx (WERX), Binance Coin, and Solana: The Top Crypto Price ... - The Coin Republic [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- Meme Coin Tokens Like Dogecoin (DOGE) and ApeCoin (APE ... - Blockzeit [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- BRC-20: Know Everything About This New Development By Bitcoin - CoinGape [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- Shiba Inu Admin Warns of Fake SHIB Tokens on Other Chains - The Crypto Basic [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- Cardano [ADA]: DJED spreads its wings, prepares for multi-chain takeoff - AMBCrypto News [Last Updated On: May 12th, 2023] [Originally Added On: May 12th, 2023]
- BRC-20 vs. ERC-20 Tokens: What's the Difference? - MUO - MakeUseOf [Last Updated On: May 17th, 2023] [Originally Added On: May 17th, 2023]
- Avalanche vs other blockchain platforms: Key differences and similiarities - Reader's Digest [Last Updated On: May 17th, 2023] [Originally Added On: May 17th, 2023]
- IoTeX community votes massively in favor of bridging its token... - Crypto Daily [Last Updated On: May 17th, 2023] [Originally Added On: May 17th, 2023]
- Coining It: Why Binance Coin, Solana, & PATWARS are the top ... - Euro Weekly News [Last Updated On: May 17th, 2023] [Originally Added On: May 17th, 2023]
- 5 Fundamental Technologies In Web3 And What They Mean - Net Newsledger [Last Updated On: May 17th, 2023] [Originally Added On: May 17th, 2023]
- Bring On The Bull Market - Love Hate Inu, Solana & Big Eyes Coin ... - The Coin Republic [Last Updated On: May 17th, 2023] [Originally Added On: May 17th, 2023]