Modifiers and require
Control flow in Solidity looks familiar: if, else, for and while work as in many languages. What is special is how a transaction fails. When a check fails, the whole transaction reverts and every state change it made is undone, so a function either completes fully or has no effect at all.
Three tools trigger a revert. require checks a condition and reverts with an optional message, and it is the right choice for validating inputs and permissions. revert stops execution and is handy inside if statements. assert checks things that should never be false, and a failed assert signals a bug in the contract.
A modifier wraps a function with reusable checks. The underscore marks where the original function body runs. Modifiers keep the permission rules in one place, so the functions stay short and the rules are easy to audit.
Modifiers can take parameters and can run code both before and after the underscore. Keep them small, because hidden logic inside a modifier is easy to overlook when reading a function.
A failed require returns the unused gas to the caller, but the gas already used is still spent. Put cheap checks first so that invalid calls fail early and cost less.
contract Owned { address public owner = msg.sender; bool public paused; uint256 public value; modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _; } modifier whenActive() { require(!paused, "Paused"); _; } modifier minValue(uint256 min) { require(value >= min, "Too low"); _; } function setOwner(address next) external onlyOwner { require(next != address(0), "Zero address"); owner = next; } function setPaused(bool p) external onlyOwner { paused = p; } function setValue(uint256 v) external onlyOwner whenActive { value = v; } function spend() external view whenActive minValue(10) returns (uint256) { return value; } }
Try it yourself
Add a modifier onlyAfter(uint256 time) that reverts if block.timestamp is earlier than time, and use it on a new function. Then add an assert somewhere and think about when it could fail.
Press Compile to check your code in the browser. Short fragments are wrapped in a contract automatically.