class WebsocketStream { static EXPECTED_PONG_BACK = 10000; static KEEP_ALIVE_CHECK_INTERVAL = 5000; pingTimeout = null; keepAliveInterval = null; provider; providerWss; constructor() { this.provider = new ethers.providers.JsonRpcProvider( CONFIG.rpc_arb_http ); this.providerWss = new ethers.providers.WebSocketProvider( CONFIG.rpc_eth_wss ); } async init() { this.providerWss._websocket.on("open", async () => { this.keepAliveInterval = setInterval(() => { this.providerWss._websocket.ping(); this.pingTimeout = setTimeout(() => { this.providerWss._websocket.terminate(); }, WebsocketStream.EXPECTED_PONG_BACK); }, WebsocketStream.KEEP_ALIVE_CHECK_INTERVAL); this.providerWss.on("block", async (blockNum) => { console.log(blockNum); }); }); this.providerWss._websocket.on("close", (code) => { console.log( `Connection lost with code ${code}! Attempting reconnect in 1s...` ); this.restart(); }); this.providerWss._websocket.on("pong", () => { // console.log(`Connection is alive`); clearInterval(this.pingTimeout); }); this.providerWss._websocket.on("error", () => { console.error(`Unable to connect. Reconnect...`); this.restart(); }); } destroy() { this.providerWss._websocket.terminate(); clearInterval(this.keepAliveInterval); clearTimeout(this.pingTimeout); } restart() { this.destroy(); new WebsocketStream().init(); } }