[Ethereum] How to wait until transaction is confirmed web3.js

confirmationstransactionsweb3jsweb3js-v0.x

I am new to web3. I am trying to connect UI with web3. Metamask version is 6.0.1 and web3 version injected by (don't know who), but it is 0.20.3.
Following is my code to send ethers to a function of my contract which is inside using Oracalize as well,

var option = {from: accounts[0], to: contractAddress, value:4000000000000000};
        mycontract.update.sendTransaction(option, function(error,result){});

I want to run some other code on basis of confirmation of this transaction. What is the best way to wait until transaction is confirmed and then I can run some more code? Make sure, I am stuck with this version of web3 and I cannot use 1.0.0 version and so does the "send" function.

Best Answer

sendTransaction returns transactionHash in callback. If the transaction was a contract creation use web3.eth.getTransactionReceipt() to get the contract address, after the transaction was mined.

web3.eth.sendTransaction({data: code}, function(err, transactionHash) {
  if (!err)
    console.log(transactionHash);

  var receipt = web3.eth.getTransactionReceipt(transactionHash);
});

In order to wait until transaction is mined, you can use this module:

module.exports = function getTransactionReceiptMined(txHash, interval) {
    const self = this;
    const transactionReceiptAsync = function(resolve, reject) {
        self.getTransactionReceipt(txHash, (error, receipt) => {
            if (error) {
                reject(error);
            } else if (receipt == null) {
                setTimeout(
                    () => transactionReceiptAsync(resolve, reject),
                    interval ? interval : 500);
            } else {
                resolve(receipt);
            }
        });
    };

    if (Array.isArray(txHash)) {
        return Promise.all(txHash.map(
            oneTxHash => self.getTransactionReceiptMined(oneTxHash, interval)));
    } else if (typeof txHash === "string") {
        return new Promise(transactionReceiptAsync);
    } else {
        throw new Error("Invalid Type: " + txHash);
    }
};
Related Topic