Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

more reliable websocket provider #12

Merged
merged 3 commits into from
Dec 5, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,32 +1,91 @@
import chalk from 'chalk'
import { ethers } from 'ethers'
import Web3WsProvider from 'web3-providers-ws'
import Configurator, { Context, Menu } from '../configurator'

// this provider code block comes in here
// https://github.com/ethers-io/ethers.js/issues/1053
const WEBSOCKET_PING_INTERVAL = 10000;
const WEBSOCKET_PONG_TIMEOUT = 5000;
const WEBSOCKET_RECONNECT_DELAY = 100;

const WebSocketProviderClass = (): new () => ethers.providers.WebSocketProvider => (class { } as never);

export class WebSocketProvider extends WebSocketProviderClass() {
private provider?: ethers.providers.WebSocketProvider;
private events: ethers.providers.WebSocketProvider['_events'] = [];
private requests: ethers.providers.WebSocketProvider['_requests'] = {};

private handler = {
get(target: WebSocketProvider, prop: string, receiver: unknown) {
const value = target.provider && Reflect.get(target.provider, prop, receiver);

return value instanceof Function ? value.bind(target.provider) : value;
},
};

constructor(private providerUrl) {
super();
this.create();

return new Proxy(this, this.handler);
}

private create() {
if (this.provider) {
this.events = [...this.events, ...this.provider._events];
this.requests = { ...this.requests, ...this.provider._requests };
}

const provider = new ethers.providers.WebSocketProvider(this.providerUrl, this.provider?.network?.chainId);
let pingInterval: NodeJS.Timer | undefined;
let pongTimeout: NodeJS.Timeout | undefined;

provider._websocket.on('open', () => {
pingInterval = setInterval(() => {
provider._websocket.ping();

pongTimeout = setTimeout(() => { provider._websocket.terminate(); }, WEBSOCKET_PONG_TIMEOUT);
}, WEBSOCKET_PING_INTERVAL);

let event;
while ((event = this.events.pop())) {
provider._events.push(event);
provider._startEvent(event);
}

for (const key in this.requests) {
provider._requests[key] = this.requests[key];
provider._websocket.send(this.requests[key].payload);
delete this.requests[key];
}
});

provider._websocket.on('pong', () => {
if (pongTimeout) clearTimeout(pongTimeout);
});

provider._websocket.on('close', (code: number) => {
provider._wsReady = false;

if (pingInterval) clearInterval(pingInterval);
if (pongTimeout) clearTimeout(pongTimeout);

if (code !== 1000) {
setTimeout(() => this.create(), WEBSOCKET_RECONNECT_DELAY);
}
});

this.provider = provider;
}
}

export default class ConnectWeb3 extends Configurator {
static code = Menu.CONNECT_WEB3

async run(context: Context): Promise<{ context: Context; next: number }> {
console.log(chalk.blue('Connecting to the Ethereum network'))
const provider = new ethers.providers.Web3Provider(
new (Web3WsProvider as any)(this.base.provider, {
reconnect: {
delay: 2000,
auto: true,
onTimeout: false
},
clientConfig: {
keepalive: true,
keepaliveInterval: 30000,
},
}))
async function waitConnection() {
return new Promise<void>(async res => {
if (await provider.ready) return res()
provider.on('connect', res)
})
}
await waitConnection()
console.log(chalk.blue('Connecting to the Ethereum network')
const provider = new WebSocketProvider(this.base.provider);

console.log(chalk.blue(`Connected via ${this.base.provider}`))
return {
context: { ...context, provider },
Expand Down