Skip to content

Instantly share code, notes, and snippets.

@naps62
Created January 15, 2018 10:52
Show Gist options
  • Save naps62/e987323357fb7630871eb293e0308c36 to your computer and use it in GitHub Desktop.
Save naps62/e987323357fb7630871eb293e0308c36 to your computer and use it in GitHub Desktop.
waiting for a transaction to be mined in truffle tests
const toTxHash = (value) => {
if (typeof value === "string") {
// this is probably a tx hash already
return value;
} else if (typeof value.receipt === "object") {
// this is probably a tx object
return value.receipt.transactionHash;
} else {
throw "Unsupported tx type: " + value;
}
}
const mineTx = (promiseOrTx, interval) => {
return Promise.resolve(promiseOrTx)
.then(tx => {
const txHash = toTxHash(tx);
return new Promise((resolve, reject) => {
const getReceipt = () => {
web3.eth.getTransactionReceipt(txHash, (error, receipt) => {
if (error) {
reject(error);
} else if (receipt) {
resolve(receipt);
} else {
setTimeout(getReceipt, interval || 500);
}
})
}
getReceipt();
})
});
}
module.exports = mineTx;
@naps62
Copy link
Author

naps62 commented Jan 15, 2018

Sample usage:

const mineTx = require("./helpers/mineTx.js");

contract("MySmartContract", accounts => {
  it("waits for transactions to mine", async () => {
    // can receive a txHash
    let tx = await contract.makeATransaction({ from: accounts[0] });
    await mineTx(tx);

    // can also receive a tx object
    tx = await contract.makeATransaction.sendTransaction({from: accounts[0] });
    await mineTx(tx);

    // can also receive a promise to a txHash,
    // so the await can be safely removed from the contract call :)
    let tx = contract.makeATransaction({ from: accounts[0] });
    await mineTx(tx);
  });
});

@Westlad
Copy link

Westlad commented May 10, 2019

Hi, do you have any objection to me including this code in an open-source project please?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment