Created
April 24, 2023 15:57
-
-
Save SZharkov/3535d3eaf2dcc4d93447621adea3e2e9 to your computer and use it in GitHub Desktop.
Revisions
-
SZharkov revised this gist
Apr 24, 2023 . 1 changed file with 0 additions and 2 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -24,8 +24,6 @@ class WebsocketStream { }, WebsocketStream.EXPECTED_PONG_BACK); }, WebsocketStream.KEEP_ALIVE_CHECK_INTERVAL); this.providerWss.on("block", async (blockNum) => { console.log(blockNum); }); -
SZharkov created this gist
Apr 24, 2023 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,62 @@ 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); const currentBlock = await this.providerWss.getBlockNumber(); 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(); } }