5

Trying to understand what are the use cases for a "require" statement and when would it be better to revert using an error:

For example

require(msg.sender == owner);

Or

if (msg.sender != owner) revert FunctionRestrictedToOnlyOwner();

I intentionally omitted any string explanation since I understand those are expansive.

2 Answers 2

6

Like you mentioned, both can be used. The gas consumed by both are the same too. (calculations using forge suggests its 17 units, but not very sure about this).

require(condition) under the hood uses revert, so essentially they are the same and it's just a matter of style and usability.

You can use require() for guard functions. And in complex if-else conditions, you can use revert().

1
  • 1
    Thank you, I'm too new to upvote your response (not enough reputation), but I appreciate it very much. Commented Jan 20, 2022 at 10:08
5

The docs mention that require and assert are convenience functions that can be used to check for conditions and throw an exception if the condition is not met (see https://docs.soliditylang.org/en/v0.8.11/control-structures.html#panic-via-assert-and-error-via-require).

It is important to understand what happens when you use a custom error. The name of the error is used to calculate a 4 bytes identifier (similar how it is done for functions). If the custom error has parameters these will be also encoded in the data in the same way as it is done when encoding function parameters.

In most cases custom errors are therefore cheaper and allow better handling of error parameters.

1
  • 1
    Thank you, I'm too new to upvote your response (not enough reputation), but I appreciate it very much. As a developer, which method would be more readable to you? Commented Jan 20, 2022 at 10:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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