1

I would like to understand a part of the Ownable() contract of the OpenZeppelin Solidity library:

modifier onlyOwner() {
   require(isOwner());
   _;
}

The last line of this modifier consists only of an underscore. Can anybody please explain to me or refer what the underscore does?

I checked other questions involving modifiers but could only find out that an underscore-command is an existential part of a modifier.

oleracea
  • 25
  • 5

1 Answers1

3

It's used to specify when the instructions in the modifier will be executed

If the instructions goes before _;, then the code in the modifier will be executed before the function is executed.

modifier onlyOwner() {
   require(isOwner());
   _;
}

On the opposite, if the modifier is after _;, then the instructions in the modifier will be executed after the function is executed.

modifier onlyOwner() {
   _;
   require(isOwner());
}

Source: https://www.educative.io/answers/what-is-in-solidity

  • 2
    technically correct but you should not implement the second example. because you will be paying gas to execute the code before `require`, so if the `require` fails, the used gas cost won't be reverted. – Yilmaz Aug 20 '22 at 03:41
  • 1
    Correct, probably using `require` in the example is not the best use case as it should always come before executing anything, but when people need to execute something after the function finish executing that might make sense, can't think of an example for this on the top of my head now – Yoseph Kurnia Soenggoro Aug 23 '22 at 16:13