Search code examples
ethereumtruffle

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 transaction doesn't change funds
  • I explicitly set the transaction gasPrice to 1

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!


Solution

  • startingBalance and endBalance are BigNumber objects. Change your test to

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