Ethereum Solidity - Does require() use any gas?
Asked Answered
O

3

15

Google has failed to give me an concrete answer, does using the require() function in Solidity use up any gas? Even if the statement in the function is evaluated as true?

Oulu answered 3/1, 2018 at 12:49 Comment(0)
R
16

I'm not quite sure if you're asking if the OPCODE itself consumes gas or if gas is consumed if the statement evaluates to true.

If you're asking about the OPCODE itself, I agree with you that the answer is unclear. I don't see the REVERT OPCODE (which is what require() is compiled to) in the (now very deprecated) Google OPCODE gas usage spreadsheet or in the yellowpaper (Appendix G).

Running a test in Remix, it looks like it does consume a very small amount of gas. Simply adding a require(true) call at the top of this method increased gas usage by 23.

contract GasUsage {
    uint val;

    function someFunc() public returns (bool) {
        require(true);

        delete val;
    }
}

Execution cost when included:5230

Execution cost when commented out: 5207


If you're asking about gas consumption up until the require statement, then the answer is yes. As of the Byzantium release, all gas consumed up to the point of a require statement is consumed, but any remaining gas is returned. Prior to Byzantium, require() and assert() were identical and all gas would be consumed.

From the Solidity docs:

Internally, Solidity performs a revert operation (instruction 0xfd) for a require-style exception and executes an invalid operation (instruction 0xfe) to throw an assert-style exception. In both cases, this causes the EVM to revert all changes made to the state...Note that assert-style exceptions consume all gas available to the call, while require-style exceptions will not consume any gas starting from the Metropolis release.

Rump answered 3/1, 2018 at 21:4 Comment(0)
A
2

require does not use gas in case of failure but uses if it is evaluated true. In case of failure, the state is reverted and "UNUSED" gas is returned. However, it does not return already consumed gas.

function test() public view {
    // some function logic;
    require(condition,"")
}

In this case if require fails, the gas that used to execute "some function logic" will not be reverted. That is why require is used at the beginning of the function.

Arrogance answered 20/8, 2022 at 2:23 Comment(0)
H
1

Complementing the previous answer, nowadays it is already possible to check the REVERT OPCODE in https://www.evm.codes/ and the minimum gas is 0.

Halfandhalf answered 21/7, 2022 at 1:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.