Skill 2.1.4

Use modifiers, events and error handling

Key Concepts

A modifier wraps a function: modifier onlyOwner() { if (msg.sender != owner) revert NotOwner(); _; } runs its check, and the function body runs at _. Modifiers keep access checks consistent across functions.

An event such as event Transfer(address indexed from, address indexed to, uint256 value); is emitted with emit Transfer(a, b, v);. Events are written to the transaction receipt's logs, cost much less than storage and are read by off-chain applications; contracts cannot read them. Up to three parameters can be indexed for filtering.

Errors undo all state changes of the current call. require(condition, "message") validates inputs and conditions; revert CustomError(args) with a declared error is cheaper and carries structured data (and since Solidity 0.8.27, or 0.8.26 through the IR pipeline, require also accepts a custom error). assert checks internal invariants that should never fail and raises a Panic error. try/catch handles failures of external calls.