Order of evaluation for Solidity modifiers

Posted on Thu 13 October 2022 in tech

Solidity modifiers are evaluated from left to right. It makes sense to order modifiers in order of those that are most likely to fail to those that are least likely to fail. It is also a good idea to order them from most primitive to most expensive. And prerequisite conditions should be considered from left to right. For example, if the requireSecond modifier depends on the FIRST state being correct then requireFirst should appear to the left of requireSecond.

Consider a contract ModOrder with state FIRST and SECOND:

    uint256 private constant FIRST = 1;
    uint256 private constant SECOND = 2;

If there are two modifiers that can not succeed:

    modifier requireNotFirst() {
        require(FIRST == FIRST - 1, "Not first");
        _;
    }

    modifier requireNotSecond() {
        require(SECOND == FIRST, "Not second");
        _;
    }

Then a function that requires both NotFirst and NotSecond in that order should revert with Not First.

    function notFirstNotSecond() public pure requireNotFirst requireNotSecond {
        revert("all good");
    }

Here is a complete example with a test: