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.
Websocket Stream with Ethers.js
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment