Published on

Working with Success and Error Events in Drizzle

Authors

One of the key things that happen when contract methods execute on the Ethereum chain is that they fire off events. How you listen to these events and work with them is not immediately obvious with Drizzle.

Today after plenty of trial and error we came up with the following which works both when the contract executes successfully and when it fails to execute properly:

try {
  drizzle.contracts.MyContract.methods
    .nameOfContractMethod(param1Value, param2Value)
    .send()
    .on('error', (error) => {
      this.handleMyContractError(error)
    })
    .on('transactionHash', (transactionHash) => {
      this.handleMyContractSuccess(transactionHash)
    })
} catch (error) {
  this.handleMyContractError(error)
}

In the above, I have Drizzle managing a contract called MyContract which has a method called nameOfContractMethod I want to hit. The key element in the above is that I am using send instead of cacheSend where errors thrown for cacheSend for some reason are not caught in on("error", ...) and not in catch (error) either.

Another thing to note about the above is that the .on("error",...) does not seem to catch any errors (none of the errors we have tested with anyway). The catch portion always seems to catch errors but we left the .on("error",...) portion to ensure we catch all errors (just in case the catch does not catch all of them).

If you are using this React you will need to bind this for the above handler methods in your component's constructor as below:

import React from "react";
...

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    ...
    this.handleMyContractError = this.handleMyContractError.bind(this);
    this.handleMyContractSuccess = this.handleMyContractSuccess.bind(this);
    ...
  }
...
}
export default MyComponent;