0

My smart contract has several events to listen for, and my dapp normally interacts with the contract through a wrap provided by the contract Web3.js abstraction.

It would be nice for me to logically split the events related to the network connection (which are in fact common for all of the contract events) and ones tied up with specific events, so I could implement it in the following way:

myContract.currentProvider
  .on('connected', onConnected)
  .on('close', onClose)
  .on('error', onConnectionError);

myContract.events.foo()
  .on('data', onData)
  .on('error', onFooError);

The issue with this approach is if a connection error appears, both onConnectionError and onFooError will be reported on it (and perhaps there are onBooError, and so on).

How can I prevent this behavior and set up an error connection handler in one single place?

Actually, my question would be annihilated if there is an assurance that the error of a smart contract event is always no more than a replica of the connection error. In this case it would be just possible not to use a special handler like onFooError. However I have not found this point enlightened in the docs.

1 Answer 1

0

If the connection failed you wont be able to read on the socket on the next step.

Note that depending on the setup, I have seen cases where an event would get triggered multiple time and increase over event. This is because the previous event that got triggered was still listening but the app create a new one each time. So if you get to 3, 4, 5 after that might be your case.

Now what you should try is to listen for a event only after the connection is established.

myContract.currentProvider
  .on('connected', () => {
      myContract.events.foo()
      .on('data', onData)
      .on('error', onFooError);
    
  })
  .on('close', onClose)
  .on('error', onConnectionError);

This might not work as his but it's giving you the idea.

On close and on error will no longer trigger a send error. You only listen for event once the user is connected.

1
  • In this case if the connection is lost (after it has been successfully established previously), both onConnectionError and onFooError would be reported on the same error yet again. I wonder what are the kinds of errors onFooError may get except those related to connection? In the other words, is it possible just to leave onFooError out as long as we have onConnectionError set up? Oct 29, 2021 at 9:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.