Skip to content

Instantly share code, notes, and snippets.

@SZharkov
Created April 24, 2023 15:57
Show Gist options
  • Save SZharkov/3535d3eaf2dcc4d93447621adea3e2e9 to your computer and use it in GitHub Desktop.
Save SZharkov/3535d3eaf2dcc4d93447621adea3e2e9 to your computer and use it in GitHub Desktop.

Revisions

  1. SZharkov revised this gist Apr 24, 2023. 1 changed file with 0 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions index.js
    Original file line number Diff line number Diff line change
    @@ -24,8 +24,6 @@ class WebsocketStream {
    }, WebsocketStream.EXPECTED_PONG_BACK);
    }, WebsocketStream.KEEP_ALIVE_CHECK_INTERVAL);

    const currentBlock = await this.providerWss.getBlockNumber();

    this.providerWss.on("block", async (blockNum) => {
    console.log(blockNum);
    });
  2. SZharkov created this gist Apr 24, 2023.
    62 changes: 62 additions & 0 deletions index.js
    Original 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();
    }
    }