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?

2 Answers 2

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.

1
  • 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, 2020 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
            }
        }
    
    }
2
  • 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 3, 2022 at 4: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. Oct 9, 2022 at 9:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.