1

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.

  • Here is a coding example from the official documentation. Check the one under using the event emitter. It allows you to wait for the hash, then for the receipt, then for each one of 24 confirmation events. Please note that this is relevant for web3.js v1.x, but it should be pretty similar to that of web3.js v0.x. – goodvibration Feb 18 at 10:42
  • @goodvibration I would prefer using this approach but im stuck with web3.js v0.x. because I have no idea who is injecting this version, do u know how can I use web3.js v1.x, so I can straightaway use the above mentioned method. Thank you – Fariha Abbasi Feb 18 at 13:00
1

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);
    }
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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