Jim
Jim

Reputation: 4172

Why Does My Ethereum ".on" Event Listener Stop Firing?

I have a node.js server where I am listening for an event that is emitted from a Solidity smart contract deployed on the Mumbai Polygon testnet.

First, I'm using the "web3-providers-ws" node package to create a provider, using keepalive and reconnection options:

let providerNetworkUrl;
let ccggContractAddress;

if (process.env.TESTNET === 'true') {

  console.log('using mumbai URLs')
  // on mumbai
  ccggContractAddress = process.env.CCGG_ADDRESS_MUMBAI_TESTNET;
  providerNetworkUrl = 'wss://polygon-mumbai.g.alchemy.com/v2/';
} else {
  // on polygon mainnet
  ccggContractAddress = process.env.CCGG_ADDRESS_POLYGON_MAINNET;
  providerNetworkUrl = 'wss://polygon-mumbai.g.alchemy.com/v2/';
}

const connectionUrl = providerNetworkUrl + process.env.alchemyApiKey;
console.log('connectionUrl: ', connectionUrl)

// Enable auto reconnection
const options = {

  clientConfig: {
    // Useful to keep a connection alive
    keepalive: true,
    keepaliveInterval: 20 * 60 * 60 * 1000 // keep alive for 20 min
  },

  // Enable auto reconnection
  reconnect: {
    auto: true,
    delay: 1000, // ms
    maxAttempts: 10,
    onTimeout: false
  }
};

let provider = new ethers.providers.WebSocketProvider(
  new Web3WsProvider(connectionUrl, options))

provider.on('end', (e) => {
  console.log('provider ended: ' + e);
})

provider.on('error', (e) => {
  console.log('provider errored: ' + e);
})

Then I'm using ethers.js to connect to the smart contract.

const wallet = new ethers.Wallet(process.env.PRIVATE_WALLET_KEY, provider)
console.log('my address (wallet): ', wallet.address)

const signer = wallet.connect(provider)

const ccggContract = new ethers.Contract(
  ccggContractAddress,
  ccggAbi,
  signer
)

Then finally I set up the listener for the "GuessSubmitted" event.

ccggContract.on('GuessSubmitted', async (guess, sender, betSize) => {

  console.log('GuessSubmitted')

})

The strange thing is that it all works great when I first start it up. The node server hears the events, logs "GuessSubmitted", and handles the event.

However, after a few hours, or overnight, I then go to play the game, the events are dispatched in Solidity, but the node server doesn't hear anything!!! what??

After looking at some other posts on the internet I even set up this ping function to keep the websocket connection alive, and I'm invoking it every 15 min:

async function ping() {

  const now = new Date();

  try {
    console.log('Sending a ping! ' + now.toUTCString());
    const blockNum = await provider.send('eth_blockNumber');
    console.log('Got blocknum: ', blockNum);
  }
  catch (err) {
    console.log('PING ERROR')
    console.log(err)
  }

}

// ping every 15 min
setInterval(ping, 1000 * 60 * 15);

console.log('provider created.')

The strange thing is that the connection doesn't seem to actually drop. I never see any "provider errored" or "provider ended" in the logs.

The logs look like this, with the ping going through fine every 15 min while never hearing any "GuessSubmitted" events anymore!! 😢

I thought the issue could be with my eth connection provider, but I've tried now with Alchemy, Infura, and GetBlock!! This "stops hearing events" issue happens with all three so I am wondering what could possibly be the problem, if it is some underlying bug in the ethereum platform or if I am making some mistake in the code...

Thanks!

Upvotes: 4

Views: 3084

Answers (2)

Charly El
Charly El

Reputation: 29

Seems you are correctly setting up the WebSocketProvider and handling the events emitted by the smart contract.try This:

Check the event emission, Verify the contract address,Check for error messages,Test with a different environment: Try running the code on a local Ethereum testnet (e.g., Ganache) to see if the issue persists.Check any new versions of the web3-providers-ws package, ethers.js,

Test with a GetBlock again, sure it Will Work

Upvotes: -1

kaliatech
kaliatech

Reputation: 17867

If you look at the web3.js project issues, there are number of reports about disconnect/close/reconnect not working as expected:

There is no one solution, afaict. A rewrite is in progress with intent to solve some of the issues:

Upvotes: 0

Related Questions