[Ethereum] How to detect if the user cancels a transaction in Metamask

metamaskweb3js

I want to detect if the user has clicked a button that will make metamask popup asking them to submit, but then rejects the transaction. I have something like the following:

Contract.deployed().then(function (contractInstance) {
        contractInstance.function({ from: web3.eth.accounts[0]}).then(function (error, result) {

            if (!error) {
                console.log('ok')
            } else {
                if (error.message.includes("User denied")) {
                    alert("You rejected the transaction on Metamask!")
                } else {
                    alert(error)
                }
            }

        })
    })

This doesn't work as intended. How should this be done? The error printed if the user rejects the transaction is:

Uncaught (in promise) Error: Error: MetaMask Tx Signature: User denied
transaction signature.

So presumably this should be simple by checking if that's the error message.

Best Answer

I was looking for a solution for this too. I am using truffle and looked up their documentation. http://truffleframework.com/docs/getting_started/contracts

Contract.deployed().then(function(contractInstance){ 
  contractInstance.function({from: web3.eth.accounts[0]}).then(function(result){             
      alert('transaction success')}).catch(function(e){ 
      console.log('error')                                          
})
Related Topic