I don't want to get a "golden shovel" reward or something but that question doesn't seem to be very old. I managed to successfully implement automatic reconnect thus I wanted to share the code:
First I created a separate function getProvider
:
function getProvider() {
const { WebsocketProvider } = Web3.providers;
const provider = new WebsocketProvider(WEB3_WEBSOCKET_PROVIDER_URL);
return new Promise((resolve) => {
provider.on('connect', () => {
logger.info('Web3 WS connected.');
return resolve(provider);
});
provider.on('error', () => resolve());
});
}
Then I have a function listen
that attaches to blockchain in order to listen for events that I'm interested in:
async function listen(repositories, wallet) {
const provider = await getProvider();
if (!provider) {
logger.info('Web3 WS unavailable. Reconnecting...');
setTimeout(() => listen(repositories, wallet), 5000);
return;
}
const web3 = new Web3(provider);
provider.on('error', (e) => {
logger.error(`Web3 WS encountered an error: ${e}.`);
listen(repositories, wallet);
});
provider.on('end', () => {
logger.error('Web3 WS disconnected. Reconnecting...');
listen(repositories, wallet);
});
const contractsConnector = contractsConnectorFactory(web3);
const contracts = await contractsConnector.connectAll();
const listeners = listenersFactory(repositories, contracts, wallet);
listeners.attachAll();
}
This way whenever the connection closes I make sure that I won't miss any events that were thrown in the meantime. Hope that helps anyone that will have problems with that.