9

In ethers.js is there any way I can check whether a hash is mined and confirmed so that I know it is not reverted and valid?

Louis
  • 1,155
  • 5
  • 17
  • 29

2 Answers2

8

In order to know whether a transaction (transactionHash) has been mined and confirmed, the following steps are required:

  1. Get the transaction receipt
  2. Check whether the transaction has been included in a block i.e. the blockNumber is not null

Below is the code snippet for achieving this:

const isTransactionMined = async(transactionHash) => {
    const txReceipt = await provider.getTransactionReceipt(transactionHash);
    if (txReceipt && txReceipt.blockNumber) {
        return txReceipt;
    }
}

In this way you can check whether the transaction has been mined.

balajipachai
  • 937
  • 5
  • 12
  • 2
    Close, but no banana. This does not take into account that txReceipt itself may be null. I just ran a version of this solution and ended up with Cannot read property 'blockNumber' of null. – Cliff Hall Apr 15 '20 at 22:24
2

Now its:

    const txnCheck = async (txnHash) => {
    const provider = new ethers.providers.Web3Provider(ethereum);
    signer = provider.getSigner();
    let txn_test = await provider.getTransaction(txnHash);
    if (txn_test) {
        if (txn_test.blockNumber) {
            console.log("txn_test: ");
            console.log(txn_test);
            return txn_test
        }
    }

}

  • Doesn't fully answer the question -- how would you know if the transaction failed for some reason, or just hadn't completed yet? – GGizmos Oct 03 '22 at 04:20
  • 2
    Another way would be to scan the transaction receipt, and look for any events which are emitted only when a transaction succeeds. Thus, if such a topic is present in the events array of the transaction receipt, then the transaction has succeeded. This assumes an event is emitted though. – Abhik Banerjee Oct 09 '22 at 09:23