solidity – Why Does Gas Usage Vary for Similar Functions Checking Condition and Setting Boolean?

bscgasmodifierssolidity

I am facing one issue when interacting with my smart contract. Just to add, I have deployed by smart contract in bsc testnet.

It has two similar functions- enableQuestion & disableQuestion, whose basic functionality is to change the Status of a question. The code is very similar for both, the one difference is that the disableQuestion function is calling one extra modifier 'inStatus'. But similar functionality of 'inStatus' is implemented in enableQuestion as well.

Now when trying to execute these two functions, here are the gas consumptions. The gas required for disableQuestion is insanely high!

enableQuestion -> 0.00069382 BNB
disableQuestion -> 0.285 BNB

Here is the snippet of the code.

modifier inStatus(uint256 _qid, Status _status) {
    require(
        mapQuestions[_qid].status == _status,
        "Operation not valid, invalid question status."
    );
    _;
}

function enableQuestion(uint256 _qid) public onlyOwner validQuestion(_qid) {
    require(
        (mapQuestions[_qid].status == Status.New || mapQuestions[_qid].status == Status.Closed),
        "Operation not valid, invalid question status."
    );
    mapQuestions[_qid].status = Status.Open;
}

function disableQuestion(uint256 _qid) public onlyOwner validQuestion(_qid) inStatus(_qid, Status.Open) {
    mapQuestions[_qid].status = Status.Closed;
}

Can someone please help me understand why this is happening? Also, how can I calculate gas required for each function call ?

UPDATE:

Just saw one more behaviour. The high fee is coming when the condition is failing.

So if I call disableQuestion(1) without calling enableQuestion, the gas is high.
But if I call enableQuestion(1), and then call disableQuestion(1), gas is normal.

Best Answer

I am new to smart contracts and blockchain but not to software engineering. Looking at your code would it best to have one function that accepts a boolean for the enable/disable state and then uses a deterministic state machine to only execute valid transitions?

Related Topic