2

Suppose I have a non-constant function which changes a state variable under some condition.

In other words, the function may sometimes change this variable and sometimes leave it as is.

Will I pay any gas fee to the miner when the function doesn't change the variable?

I wrote a small Truffle test which shows the gas cost when the function doesn't change the variable:

File MyContract.sol:

pragma solidity 0.4.24;

contract MyContract {
    uint private x;

    constructor(uint _x) public {
        x = _x;
    }

    function set() external {
        if (x >= 42)
            x += 42;
    }

    function get() external view returns (uint) {
        return x;
    }
}

File MyContract.js:

contract("MyContractTest", function(accounts) {
    it("set", async function() {
        let myContract = await artifacts.require("MyContract.sol").new(41);
        let estimateGas = await myContract.set.estimateGas();
        console.log(estimateGas);
    });
    it("get", async function() {
        let myContract = await artifacts.require("MyContract.sol").new(41);
        let estimateGas = await myContract.get.estimateGas();
        console.log(estimateGas);
    });
});

The Printout:

Contract: MyContractTest set: 21647
Contract: MyContractTest get: 21656

I then realized that estimateGas runs under the assumption that the tested function is called from the on-chain (i.e., by some other contract) and not from the off-chain, because the gas cost of the constant function get was also larger than 0.

So as in the title of my question:

Will I pay any fee to the miner if I call function set and it doesn't change variable x?

Thank you!

CLARIFICATION:

My question is about the gas cost of a non-constant function (can it be zero in some cases). The question suggested as a duplicate is about the gas cost of a constant function (can it be larger than zero in some cases). So these are essentially two different questions.

3

Yes.

The non-constant (not pure, view or constant) would be invoked by a transaction to be potentially state-changing. A transaction is mined and confirmed by all full nodes to find out what it does. Even if it does nothing as a result of conditional branching, the sender pays for the gas consumed forming network consensus.

In more detail: https://blog.b9lab.com/calls-vs-transactions-in-ethereum-smart-contracts-62d6b17d0bc2

Hope it helps.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.