typestar

Custom errors in Solidity

Typed context, cheaper than revert strings.

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

// Custom errors carry typed context and cost less than strings.
contract PlotAssigner {
    error PlotTaken(uint256 plot, address holder);
    error OverLimit(uint256 requested, uint256 max);

    uint256 public constant MAX_PER_MEMBER = 2;
    mapping(uint256 => address) public holder;
    mapping(address => uint256) public held;

    function claim(uint256 plot) external {
        if (holder[plot] != address(0)) {
            revert PlotTaken(plot, holder[plot]);
        }
        if (held[msg.sender] >= MAX_PER_MEMBER) {
            revert OverLimit(held[msg.sender] + 1, MAX_PER_MEMBER);
        }
        holder[plot] = msg.sender;
        held[msg.sender] += 1;
    }
}

How it works

  1. Two errors carry the plot, the holder, and the limits.
  2. revert PlotTaken(plot, holder[plot]) names the conflict.
  3. Constants like MAX_PER_MEMBER document the policy.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
640
Tokens
132
Three-star pace
55 tpm

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

Type this snippet

Step 3 of 3 in Guards, step 10 of 28 in Language basics.

← Previous Next →

Custom errors in other languages