I'm working on an Ethereum project using Web3.js 4.4.0. My application successfully subscribes to new block headers using a WebSocket connection. However, after a period of time (ranging from 4 hours to a day), the subscription stops receiving any events without throwing any errors. Restarting the application temporarily resolves this issue.
Code Sample:
'use strict';
const { Web3 } = require("web3");
// HTTP Provider
const httpProvider = new Web3.providers.HttpProvider(process.env.HTTP_URL);
const web3 = new Web3(httpProvider);
// WebSocket Provider
const wsProvider = new Web3.providers.WebsocketProvider(process.env.WEBSOCKET_URL);
const web3Ws = new Web3(wsProvider);
(async () => {
const blockSubscription = await web3Ws.eth.subscribe('newBlockHeaders');
blockSubscription.on("data", async (BlockHeaders) => {
const blockNumber = Number(BlockHeaders.number)
console.log('Received block number => ', blockNumber)
let block = await web3.eth.getBlock(blockNumber, true);
console.log("block transactions length : ", block.transactions?.length);
});
blockSubscription.on("error", error => {
console.error('Web3 on-error event: ', error);
});
})().catch(e => console.error(e));
The subscription works initially but stops after a few hours. I suspect this might be related to the WebSocket connection. I have attempted to add custom connection options for reconnection and timeout handling, but in Web3.js 4.4.0, the constructors for HttpProvider and WebsocketProvider seem to only accept {url: string, net?: Socket} as parameters.
Questions:
- How can I resolve the issue where the WebSocket subscription stops receiving events after several hours?
- Is there a way to correctly set custom WebSocket options in Web3.js 4.4.0?
- Are there any workarounds or specific methods to pass these options or to ensure the WebSocket connection remains active?
Environment:
- Node.js Version: v16.20.2 Geth Version:
- Geth/v1.12.2-stable-bed84606/linux-amd64/go1.20.7
- Web3.js Version: 4.4.0