OpenZeppelin/openzeppelin-contracts

Optimize Gas Usage by Replacing require Statements with Custom Errors in Solidity

ArshilHapani opened this issue · 1 comments

🧐 Motivation
Using require statements for error handling is currently common across OpenZeppelin Contracts. However, with the EVM’s gas optimizations in mind, replacing require with custom errors in Solidity could lead to more efficient gas usage. This change can be particularly impactful in contracts with multiple conditions, where gas savings would accumulate over numerous transactions.

📝 Details
Switching from require statements to custom error definitions in OpenZeppelin Contracts can help optimize gas efficiency. Custom errors reduce gas costs because they don’t carry the same overhead as error strings in require statements. By standardizing custom errors for common validations, OpenZeppelin Contracts can maintain functionality while enhancing performance.

  • Proposed Changes:

    • Define custom errors for recurring validations (e.g., UnauthorizedAccess, InvalidInput).
    • Replace instances of require(condition, "Error message") with custom error definitions, such as:
      error InvalidInput();
      if (!condition) revert InvalidInput();
  • Implementation Benefits:

    • Reduces gas consumption, especially in high-frequency transactions.
    • Promotes best practices for Solidity error handling.

Assignment: Feel free to assign this to me for implementation in OpenZeppelin contracts.

Hi,

This was implemented since #2839 was closed. Closing too