Best Website-BuildersBest Website-Builders
    What's Hot

    How to Use DALL·E 2 and Craiyon to Generate AI Art

    March 20, 2023

    Weiss Asset Management LP will reduce its holding in Juniper II Corp. (NYSE:JUN).

    March 20, 2023

    Spotify: Bollywood songs removed from music app

    March 20, 2023
    Facebook Twitter Instagram
    Facebook Twitter Instagram
    Best Website-BuildersBest Website-Builders
    • Home
    • CSS

      Weiss Asset Management LP will reduce its holding in Juniper II Corp. (NYSE:JUN).

      March 20, 2023

      8 semantic HTML tags to make your website accessible, clean and modern

      March 20, 2023

      CSS Entertainment (CSSE) and Allen Media Group join Redbox as partners

      March 20, 2023

      European Bank Bonds, Stocks Fall After Surprise AT1 Wipeout of CS

      March 20, 2023

      UK banks hit as CS AT1 bond writedown sparks turmoil

      March 20, 2023
    • Joomla

      Web Hosting: 8 Elements Every Entrepreneur Should Look For

      March 20, 2023

      VS Code Extension for In-Browser Development, WapuuGotchi Gamification Plugin & More – WP Tavern

      March 20, 2023

      How Superior Web Hosting Support Can Drive Business Success

      March 17, 2023

      PANDACU Studio Website Development Cooperation First Page Sage SEO Dsign Chicago adstargets Cardinal Digital Agency

      March 16, 2023

      Bluehost Review: Best Solution for Your Web Hosting Needs? – WISH-TV | Indianapolis News | Indiana Weather

      March 15, 2023
    • PHP

      Christina Ricci said she was nearly sued for a sex scene

      March 20, 2023

      Gen Z adults pay rent with credit cards

      March 20, 2023

      Adam Sandler Wins Mark Twain Award for American Humor

      March 20, 2023

      Sarah Snook was told the ‘inheritance’ was over

      March 20, 2023

      Anna Marie Tendler responds to Taylor Swift backlash

      March 20, 2023
    • UX

      The UX Behind #TheUnlock at Riot Games: Part 1 | by Cheryl Platz | Riot Games UX Design | Mar, 2023

      March 20, 2023

      Assistive technology – improve the user experience for people with disabilities

      March 20, 2023

      Furman fosters talent development and launches Center for Innovative Leadership

      March 20, 2023

      Is coding bootcamp worth it?

      March 20, 2023

      Twitter now auto-replies to press emails with poop emoji: NPR

      March 20, 2023
    • Web Builders
      1. Web Design
      2. View All

      What Comes First in Website Development — Design or Copy?

      February 2, 2023

      Modern Campus Honors Best Higher Education Websites of 2022

      February 2, 2023

      Premier SEO Consultant in Las Vegas, Nevada with Unparalleled Customer Service

      February 2, 2023

      Can Religious Freedom Be Saved? This group is racing the clock to teach America’s first freedom

      February 2, 2023

      How i Create New Google Account

      February 7, 2023

      CWT powers tools for meeting and event planners

      January 31, 2023

      Best Website Builder – Website Builders

      January 24, 2023

      Is There A Market For Rap-Themed Slot Games? – Rap Review

      January 19, 2023
    • WordPress

      Hitachi Energy confirms data breach after being hit by Clop ransomware

      March 20, 2023

      Don’t keep your guests waiting on poor Wi-Fi. Offer Aruba Instant On.

      March 20, 2023

      iPhone 15 Pro leak suggests it may make controversial button changes

      March 20, 2023

      Intel seems to have canceled the most interesting CPU hybrid ever

      March 20, 2023

      Using a fake Samsung SSD can make upgrading your PC or PS5 difficult

      March 20, 2023
    • Realtoz
      • Our Other Sites
    • More News
    Best Website-BuildersBest Website-Builders
    Home » How to create JavaScript WebSockets subscriptions to Ethereum and Binance Smart Chain via ethers.js?
    JavaScript

    How to create JavaScript WebSockets subscriptions to Ethereum and Binance Smart Chain via ethers.js?

    websitebuildersnowBy websitebuildersnowMarch 11, 2023No Comments6 Mins Read
    Facebook Twitter LinkedIn Telegram Pinterest Tumblr Reddit WhatsApp Email
    Share
    Facebook Twitter LinkedIn Pinterest Email


    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/



    Source link

    Share this:

    • Tweet
    • Email
    • Pocket
    • Mastodon
    • WhatsApp
    • Telegram
    • Share on Tumblr
    • Print
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Telegram Email
    Previous ArticleHomeless children: Living with trauma, tears and tiredness
    Next Article Franklin McClure said the Tennessee lieutenant governor sent him a DM
    websitebuildersnow
    • Website

    Related Posts

    TypeScript 5 – Smaller, Simpler, Faster

    March 20, 2023

    JavaScript Libraries Enable Developers to Add AI Capabilities to the Web

    March 20, 2023

    Who is EMRO | 2nd High-Level Interregional Conference on Refugee and Migrant Health | News

    March 19, 2023
    Add A Comment

    Leave a Reply Cancel reply

    Top Posts

    Subscribe to Updates

    Get the latest sports news from SportsSite about soccer, football and tennis.

    Advertisement
    Demo

    This website provides information about CSS and other things. Keep Supporting Us With the Latest News and we Will Provide the Best Of Our To Makes You Updated All Around The World News. Keep Sporting US.

    Facebook Twitter Instagram Pinterest YouTube
    Top Insights

    How to Use DALL·E 2 and Craiyon to Generate AI Art

    March 20, 2023

    Weiss Asset Management LP will reduce its holding in Juniper II Corp. (NYSE:JUN).

    March 20, 2023

    Spotify: Bollywood songs removed from music app

    March 20, 2023
    Get Informed

    Subscribe to Updates

    Get the latest creative news from FooBar about art, design and business.

    © 2023 bestwebsite-builders. Designed by bestwebsite-builders.
    • Home
    • About us
    • Contact us
    • DMCA
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.