Web3.js How to keep Websocket subscriptions alive and reconnect on failures
Smart contracts are an essential part of the Ethereum ecosystem; Smart contracts emit so-called events when something meaningful happens within the smart contract that the smart contract wants to communicate to dApps and other smart contracts.
I want to share with you some ways for keeping the Websocket connection open while listening to smart contract events. Some smart contracts don’t emit events so often, therefore, you can configure your Infura Websocket to stay alive even though the smart contract is not constantly emitting events.
Setting Up Our Project
This tutorial makes use of Web3.js v1.x.x. Not all functionality might work with Web3.js v4.
Please create a new folder in which we can work on our project, then install web3js using npm.
npm install web3
Ensure you have your Infura account set up and have access to your endpoint URL. Feel free to read more about getting started with Infura.
At the top of our new Javascript file, we can add the following to import the web3js library that we just installed and connect to the Infura websockets endpoint:
const Web3 = require("web3");
const web3 = new Web3("wss://mainnet.infura.io/ws/v3/<API_KEY>");