1

I am trying to compute the gas usage of an empty (i.e., the most basic) fallback function.

My on-chain code (compiled via Truffle 4.1.15):

pragma solidity 0.4.25;

contract MyContract {
    function() external payable {}
}

My off-chain code (executed via Truffle 4.1.15 and Ganache 6.2.5):

contract("MyContract", function(accounts) {
    it("Test", async function() {
        const myContract    = await artifacts.require("MyContract").new();
        const balanceBefore = await web3.eth.getBalance(accounts[0]);
        const response      = await web3.eth.sendTransaction({from: accounts[0], to: myContract.address, value: 1000000});
        const balanceAfter  = await web3.eth.getBalance(accounts[0]);
        const gasUsed       = balanceBefore.minus(balanceAfter).div(web3.eth.gasPrice);
        console.log("gasUsed =", gasUsed.toFixed());
    });
});

The result I get is gasUsed = 21018.00005.

I've made sure that web3.eth.gasPrice doesn't change throughout the execution (it remains 20000000000, as configured in my ganache-cli command line).

So what exactly am I missing here?

Thank you!

7
  • This done in remix using JavaScript VM produces an integer as it should (21018). – Jaime Feb 26 '19 at 10:34
  • @Jaime: Yet, it doesn't explain what is wrong in my process of computing the gas usage. – goodvibration Feb 26 '19 at 10:38
  • You seem to be having numerical issues and this is unrelated to ethereum or the smart contract. Just out of curiosity you could try dividing your numbers (balanceBefore, balance after and gassPrice) by 1000000 before calculating gasUsed – Jaime Feb 26 '19 at 10:47
  • @Jaime: I disagree on your statement that this is unrelated to ethereum or the smart contract, since this is how one can compute the total gas usage of a given transaction. Again - unless I have something wrong in my computation process, which you haven't been able to point out as of yet (so until then, I don't think that it can be regarded as a purely "numerical issue"). Thank you. – goodvibration Feb 26 '19 at 10:50
  • You said "this is how one can compute the total gas usage of a given transaction", but the gas used is in the receipt of the transaction so you do not have to calculate it like this. Also, this is a numerical issue. I did this using the javaScript VM and then again in python, I got the expected results. This is not related to ethereum. – Jaime Feb 26 '19 at 11:02

Your Answer

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

Browse other questions tagged or ask your own question.