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
require(cond, "msg")reverts the whole call on failure.error PressBusy(address)declares a typed failure.revert PressBusy(holder)carries context back cheaply.
Keywords and builtins used here
addresscontractexternalfunctionifpublicrequire
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.
Step 1 of 3 in Guards, step 8 of 28 in Language basics.