Below is from a truffle test cases in javascript, where I was trying to add the gas cost to an account balance to confirm the sum of transaction, where the sum should be equal to the previous balance.
But I couldn't get it to work!
The rcpt.cumulativeGasUsed, web3.eth.gasPrice, getBalance(accounts[1]) are all correct, but the arithmetic is not, some fromWei, toWei kung-fu needed?
What am I doing wrong here?
return instance.bailOut({ from: accounts[1] }).then(function (resp) {
var rcpt = web3.eth.getTransactionReceipt(resp.tx);
console.log("Sum: " + ((rcpt.cumulativeGasUsed * web3.eth.gasPrice) + web3.eth.getBalance(accounts[1]).toString(10)));
});
After a lot of experiments, it looks like the below method works fine, but couldn't explain the logic of transaction cost! Any idea is most welcome.
Anyways unit test is passing now!!!
return contractInstance.withdraw({ value: web3.toWei(1, "ether"), gas: 1000000 }).then(function () {
var contractAddressBalance = web3.fromWei(web3.eth.getBalance(contractAddress).toString(10));
console.log("contractAddress balance after withdraw: " + contractAddressBalance);
return contractInstance.bailOut({ from: accounts[1] }).then(function (resp) {
var rcpt = web3.eth.getTransactionReceipt(resp.tx);
console.log("cumulativeGasUsed: " + rcpt.cumulativeGasUsed);
console.log("gasPrice: " + web3.eth.gasPrice);
var transactionCost = (rcpt.cumulativeGasUsed / 10000000); // How come this works???
console.log("transactionCost: " + transactionCost);
console.log("Account[1] balance after withdraw: " + web3.eth.getBalance(accounts[1]));
contractWalletAfter = web3.fromWei(web3.eth.getBalance(accounts[1]).add(web3.fromWei(rcpt.cumulativeGasUsed)));
assert.equal(((contractWalletAfter.minus(contractWalletBefore)).add(transactionCost)).valueOf(), 6, "6 wasn't in the contract wallet");
});
});
gasUsed * gasPrice + value
. If the contracts make a transfer to the sender that will change the final balance.rcpt.cumulativeGasUsed * web3.eth.gasPrice
to get the transaction cost. But it didn't work! If you have a console open, you can quickly verify the same with the Metacoin in a truffle test case. Looks like some truffle test magic???