[Ethereum] Web3 – How to determine when a transaction has been mined

solidityweb3js

I am executing a transfer() function in a solidity contract, and want to know when the transaction is finished. I can get the transaction receipt immediately if the transaction is executed properly, but want a simple way of knowing when it's been mined. This is what I've tried (a bit messy):

deployedContract.transfer(transfer_to, transfer_value, { from:web3.eth.accounts[0], gas: 200000 }, function (error, result) {
      if (!error) {
        console.log(result + ' is the TxHash')
        var test = web3.eth.getTransactionReceipt(result, function (error, result2) {
          if (!error) {
            if (!result2) {
              console.log('waiting for transaction to be mined....')
              console.log(result + ' is still the TxHash')
            } else {
              console.log('transaction done')
            }
          } else {
            console.error(error)
          }
        })
      } else {
        console.error(error)
      }
    })

This will get to the console.log('waiting for transaction to be mined....') part but even after the transaction is definitely mined, won't get to the console.log('transaction done').

If it's relevant, when deploying a new contract I could easily see when the transaction was complete as follows – but doing the same thing isn't working for me for seeing if functions executed on a contract have completed:

let deployedContract = contract.new({ from:web3.eth.accounts[0], data:bytecode, gas: 1300000 }, function (error, result) {
        if (!error) {
          if (!deployedContract.address) {
            // transaction hasn't been mined yet
          } else {
            // transaction has been mined
          }
        } else { console.error(error) }
      })

Best Answer

If you are using the latest version of web3.js, you can use the following piece of code:

deployedContract.methods.transfer(transfer_to, transfer_value,).send({from: web3.eth.accounts[0], gas: 200000})
    on('transactionHash', function(hash){
        console.log("transactionHash: "+transactionHash);
    })
    .on('confirmation', function(1, receipt){
        console.log("Transaction confirmed");
    })
    .on('error', console.error);

PS: I have not tested this personally but as per the documentation this should work fine.

Related Topic