typestar

require and revert in Solidity

Guards with messages, or typed custom errors.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

// require guards with a message; custom errors revert cheaper.
contract CiderPress {
    error PressBusy(address holder);

    address public pressHolder;

    function book() external {
        require(msg.sender != address(0), "no ghost bookings");
        if (pressHolder != address(0)) {
            revert PressBusy(pressHolder);
        }
        pressHolder = msg.sender;
    }

    function release() external {
        require(msg.sender == pressHolder, "not the holder");
        pressHolder = address(0);
    }
}

How it works

  1. require(cond, "msg") reverts the whole call on failure.
  2. error PressBusy(address) declares a typed failure.
  3. revert PressBusy(holder) carries context back cheaply.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
498
Tokens
87
Three-star pace
60 tpm

At the three-star pace of 60 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 1 of 3 in Guards, step 8 of 28 in Language basics.

← Previous Next →