Ben Yu
Ben Yu

Reputation: 13

Why is (startingBalance - endBalance) > (gasUsed * gasPrice) for an Ethereum transaction?

I'm trying to write javascript tests in truffle framework to verify eth balance change after a transaction that moves funds.

I want to rule out the gas expense so that I can assert the balance change by an exact amount.

The following is how I'm trying to determine the amount of eth spent on gas:

let startingBalance = await web3.eth.getBalance(me);
let tx = await contract.method.sendTransaction({from: me, gasPrice: 1});
let endBalance = await web3.eth.getBalance(me);
let receipt = await web3.eth.getTransactionReceipt(tx);
await (startingBalance - endBalance).should.be.equal(receipt.gasUsed);

My reasoning is that, since:

the receipt.gasUsed should be equal to the balance change.

But running against testrpc, the test complained that the balance decremented slightly more than gasUsed * gasPrice, by about 2000.

Is there other factors that could contribute to eth balance change?

Thanks!

Upvotes: 1

Views: 332

Answers (2)

Adam Kipnis
Adam Kipnis

Reputation: 10971

startingBalance and endBalance are BigNumber objects. Change your test to

await (startingBalance.minus(endBalance)).should.be.equal(receipt.gasUsed);

Upvotes: 1

gaiazov
gaiazov

Reputation: 1960

I would not trust testrpc. Try running your code on testnet

Upvotes: 0

Related Questions