Lesson 4 of 4 Solidity Language Fundamentals

Modifiers, Events and Errors

Modifiers keep checks consistent, events communicate with off-chain applications, and errors stop invalid operations safely. This lesson explains each, including custom errors and the difference between require, revert and assert.

Learning outcomes

After completing this lesson, you will be able to:

  • Explain how modifiers wrap function bodies.
  • Describe how events and indexed parameters are recorded.
  • Distinguish require, revert with custom errors and assert.
  • Explain how try/catch handles failures of external calls.

Modifiers

A modifier is reusable code that runs before, and optionally after, the body of the functions it is applied to. The special statement _; marks where the function body runs. Modifiers can take arguments, such as onlyRole(MINTER_ROLE), and several can be applied to one function, running in the order listed.

modifier whenOpen() {
    if (block.timestamp >= deadline) revert CampaignClosed();
    _;
}

function contribute() external payable whenOpen {
    contributions[msg.sender] += msg.value;
}

Modifiers make access control visible in the function signature. Keep them to simple checks; modifiers that make external calls or change state are harder to reason about.

Put in order

Modifier execution order

Exam skills 2.1.4

Arrange what runs when a function with two modifiers is called.

Log in to try this activity Interactive activities are free with an account.

Events

An event writes a log entry into the transaction receipt. Events are the cheapest way to record data that only off-chain applications need, and they are how front ends, indexers and web3.js subscriptions learn what happened. Contracts cannot read events.

event Transfer(address indexed from, address indexed to, uint256 value);
emit Transfer(msg.sender, to, amount);

Up to three parameters can be indexed. Indexed parameters are stored as topics, which nodes can filter efficiently ("all transfers to this address"); the first topic is the hash of the event signature. Non-indexed parameters are ABI-encoded in the log's data.

The following diagram shows how an event's parameters become topics and data.

How an event becomes a log entry. For event Transfer(address indexed from, address indexed to, uint256 value), topic 0 is the Keccak-256 hash of the event signature, and each indexed parameter becomes a further topic, up to three. Nodes can filter logs by topics efficiently. Non-indexed parameters, here value, are ABI-encoded in the log's data. Contracts cannot read events.
Indexed parameters are topics; the rest is data.
Select all that apply

Designing an event

Exam skills 2.1.4

Check what is true about indexing and reading event parameters.

Log in to try this activity Interactive activities are free with an account.

Reverting with require, revert and custom errors

A revert stops execution and undoes every state change made in the current call, returning error data to the caller. The sender still pays for the gas used up to that point. The following comparison shows the ways to raise errors.

require(cond, "msg")
PurposeValidate inputs and conditions
Error dataError(string)
GasHigher: stores and returns the string
When it failsBad input or state
revert CustomError(args)
PurposeValidate with structured, cheaper errors
Error dataThe custom error's selector and arguments
GasLower
When it failsBad input or state
assert(cond)
PurposeCheck invariants that should never fail
Error dataPanic(uint256) code 0x01
GasLow
When it failsA bug in the contract

Custom errors are declared with error InsufficientBalance(uint256 available, uint256 required); and raised with revert InsufficientBalance(bal, amount);. Since Solidity 0.8.27 (0.8.26 when compiling through the IR pipeline), require(cond, InsufficientBalance(bal, amount)) is also allowed. The compiler also raises panics automatically, for example for arithmetic overflow (code 0x11), division by zero (0x12) and out-of-bounds array access (0x32).

Sort into groups

Which error does the caller see?

Exam skills 2.1.4

Decide which kind of error data each failure returns to the caller.

Log in to try this activity Interactive activities are free with an account.

Handling errors from other contracts

When a contract calls another through an interface and the callee reverts, the revert bubbles up and the caller reverts too. try/catch lets the caller handle the failure instead.

try oracle.latestPrice() returns (uint256 price) {
    lastPrice = price;
} catch {
    emit OracleFailed();   // keep the old price
}
True or false

try and catch

Exam skills 2.1.4

Check how a contract can handle a failure in a contract it calls.

Log in to try this activity Interactive activities are free with an account.
Worked example

Choosing the error mechanism

A withdrawal function must reject amounts larger than the caller's balance, and the developer also wants to check that the contract's total of balances never exceeds its ether. Which mechanism fits each?

The balance check validates user input, so use a custom error: if (amount > balances[msg.sender]) revert InsufficientBalance(balances[msg.sender], amount);. It is cheap and tells the front end exactly what went wrong. The total-versus-ether check is an invariant that only a bug could break, so assert expresses it; fuzz and invariant tests can then try to make it fail.

Worked example

Designing an event

A marketplace front end must list all sales of a given NFT collection and all purchases by a given buyer. The contract emits event Sale(address collection, uint256 tokenId, address buyer, uint256 price);. What should change?

Index the fields the front end filters by: event Sale(address indexed collection, uint256 indexed tokenId, address indexed buyer, uint256 price);. Nodes can then return matching logs directly with eth_getLogs topic filters. price stays non-indexed; it is displayed, not filtered, and the three-index limit is already reached.

Check yourself

Why are custom errors preferred to revert strings?

Show answer

They are cheaper, because the contract stores and returns a four-byte selector and encoded arguments instead of a string, and they carry structured data, such as the available and required balance, that applications can decode.

Exam Tips

Remember for the exam

  • Modifiers run checks around function bodies at the _; placeholder.
  • Events are cheap logs for off-chain readers; up to three parameters can be indexed.
  • A revert undoes the call's state changes; gas used is still paid.
  • Custom errors are cheaper than revert strings; assert is for invariants and raises a Panic.