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.