TExcelTAD
Home › Solidity › Modifiers

Modifiers

A function modifier packages a check (or other code) that should run around a function's body. Instead of repeating require(msg.sender == owner, "not owner"); in ten functions, you write it once as a modifier and attach it by name.

solidity
modifier onlyOwner() {
    require(msg.sender == owner, "not owner");
    _;                      // the function body is inserted here
}

function withdraw() external onlyOwner { … }

The special statement _; marks where the body of the function goes. Code before _ runs first, code after it runs when the body has finished.

onlyOwner

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Config {
    address public owner;
    uint256 public fee = 10;

    constructor() {
        owner = msg.sender;
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "not owner");
        _;
    }

    function setFee(uint256 newFee) external onlyOwner {
        fee = newFee;
    }
}

// A helper contract that plays a second user.
contract Stranger {
    function trySetFee(Config c, uint256 value) external {
        c.setFee(value);
    }
}

contract Main {
    function main() external {
        Config config = new Config();          // Main is the owner
        config.setFee(25);
        console.log("fee set by owner:", config.fee());

        Stranger mallory = new Stranger();
        mallory.trySetFee(config, 0);          // reverts inside setFee
    }
}
fee set by owner: 25
main() failed: reverted with reason: not owner

The Stranger contract stands in for a second user: when it calls setFee, msg.sender is the stranger's address, not the owner's, so the modifier stops the call. You'll use this "helper contract as user" trick throughout the course.

Modifiers with parameters

Modifiers can take arguments, often the function's own parameters:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Sale {
    uint256 public opensAt;
    uint256 public sold;

    constructor(uint256 opensAt_) {
        opensAt = opensAt_;
    }

    modifier after_(uint256 time) {
        require(block.timestamp >= time, "too early");
        _;
    }

    modifier between(uint256 value, uint256 min, uint256 max) {
        require(value >= min && value <= max, "quantity out of range");
        _;
    }

    function buy(uint256 qty) external after_(opensAt) between(qty, 1, 5) {
        sold += qty;
    }
}

contract Main {
    function main() external {
        Sale openSale = new Sale(block.timestamp - 1 hours);
        openSale.buy(3);
        console.log("sold:", openSale.sold());

        Sale laterSale = new Sale(block.timestamp + 1 days);
        try laterSale.buy(1) {
            console.log("bought early?!");
        } catch Error(string memory reason) {
            console.log("later sale:", reason);
        }

        openSale.buy(9);    // too many
    }
}
sold: 3
later sale: too early
main() failed: reverted with reason: quantity out of range

Several modifiers run in the order they are listed, each wrapping the next. The try … catch statement used here catches a failed external call so the rest of main() continues; it has its own lesson later.

Code after _

Code after _; runs after the function body. A classic use is a reentrancy lock, which sets a flag before the body and clears it afterwards:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Main {
    bool private locked;
    uint256 public depth;

    modifier noReentry() {
        require(!locked, "no reentry");
        locked = true;
        console.log("lock taken");
        _;
        locked = false;
        console.log("lock released");
    }

    function protectedWork() public noReentry {
        depth += 1;
        console.log("doing work, depth", depth);
    }

    function main() external {
        protectedWork();
        protectedWork();
    }
}
lock taken
doing work, depth 1
lock released
lock taken
doing work, depth 2
lock released

The Reentrancy lesson shows why this lock matters when a function sends ether.

Things to know

  • If a function returns early, the code after _ in its modifiers still runs.
  • _ may appear more than once (the body would run several times), but that is almost never what you want.
  • Modifiers can be inherited and overridden (virtual / override), like functions.
  • Keep modifiers to checks. Heavy logic hidden inside a modifier makes code hard to read and audit; a modifier that calls an internal function (modifier onlyOwner() { _checkOwner(); _; }) also produces smaller bytecode when it is used often.

Test yourself

What does _; mean inside a modifier?

  1. Ignore the return value
  2. Insert the body of the modified function here
  3. End the transaction
  4. A placeholder for the modifier's arguments

With function f() external a b { … }, in which order do the checks run?

  1. b, then a
  2. a, then b
  3. In parallel
  4. Only the last modifier runs

Why does the course deploy small helper contracts like Stranger?

  1. To save gas
  2. To simulate other users, since each contract has its own address and becomes msg.sender when it calls
  3. Because Main cannot call functions
  4. To create new blocks