javascripttypescriptweb3jsmetamask

Unable to catch, when a user cancels MetaMask transaction


Here is my code example:

const userAccount = '0x...';

// Call the contract method helloWorld()
const transaction = this.contract.methods
  .helloWrold('some parameter 1', 'some parameter 2')
  .send({ from: userAccount });

// Handle errors from the transaction
transaction.on('error', (error: any) => {
  console.error('Transaction error:', error);
});

// Handle success
transaction.on('receipt', (receipt: any) => {
  console.log('Transaction success:', receipt);
});

When the send() method is executed then MetaMask's popup appears. And the problem is, if a user cancels the transaction by pressing cancel in that popup.

My error handler is not executed. I have tried to use different events, I have tried to use try...catch block, but that doesn't seems to work with an async functions.

Is there any solution on this?

All I can see - that is the error in the console, that comes from MetaMask, that the user has denied to sign the transaction.


Solution

  • Finally, I have caught the error, using this code:

    window.ethereum
      .request({
        method: 'eth_sendTransaction',
        params: [
          {
            from: wallet,
            gas: '0x2dc6c0',
            gasPrice: '0x2540be400',
            to: this.contract.options.address,
            data: this.contract.methods
              .deploy('Hello World', this.generateSalt())
              .encodeABI(),
          },
        ],
      })
      .then((transactionHash: any) => {
        console.log('Transaction hash:', transactionHash);
      })
      .catch((error: any) => {
        if (error.code === 4001) {
          console.log('User denied transaction signature.');
          // Handle the case where the user denies the transaction signature
        } else {
          console.error('Another Error:', error);
          // Handle other errors
        }
      });