Skip to main content

Custom Errors For Better Gas Efficiency

Description

Using custom errors instead of revert strings can significantly reduce gas costs, especially when deploying contracts. Prior to Solidity v0.8.4, revert strings were the only way to provide more information to users about why an operation failed. However, revert strings are expensive, and it is difficult to use dynamic information in them. Custom errors, on the other hand, were introduced in Solidity v0.8.4 and provide a gas-efficient way to explain why an operation failed.

Example Code

Consider the following code snippet from a smart contract:

require(balance >= amount, "Insufficient balance.");

Instead of using the revert string "Insufficient balance.", a custom error could be defined and used like this:

error InsufficientBalance(uint256 balance, uint256 amount);

...

require(balance >= amount, InsufficientBalance(balance, amount));

Recommendation

It is recommended to use custom errors instead of revert strings to reduce gas costs, especially during contract deployment. Custom errors can be defined using the error keyword and can include dynamic information.