From 5bf29191b334507b5430854976269b4ba9675604 Mon Sep 17 00:00:00 2001 From: Shuhui Luo <107524008+shuhuiluo@users.noreply.github.com> Date: Mon, 9 Sep 2024 12:56:27 -0400 Subject: [PATCH] feat(contract): Introduce `CustomRevert` library for efficient reverts (#1010) Adds a new `CustomRevert` library to streamline and optimize custom error handling by using efficient assembly code. --- .../src/utils/libraries/CustomRevert.sol | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 contracts/src/utils/libraries/CustomRevert.sol diff --git a/contracts/src/utils/libraries/CustomRevert.sol b/contracts/src/utils/libraries/CustomRevert.sol new file mode 100644 index 0000000000..09f3f455f3 --- /dev/null +++ b/contracts/src/utils/libraries/CustomRevert.sol @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: MIT +pragma solidity ^0.8.0; + +/// @title Library for reverting with custom errors efficiently +/// @notice Contains functions for reverting with custom errors with different argument types efficiently +/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with +/// `CustomError.selector.revertWith()` +/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately +library CustomRevert { + /// @dev Reverts with the selector of a custom error in the scratch space + function revertWith(bytes4 selector) internal pure { + assembly ("memory-safe") { + mstore(0, selector) + revert(0, 0x04) + } + } + + /// @dev Reverts with a custom error with a uint256 argument in the scratch space + function revertWith(bytes4 selector, uint256 value) internal pure { + assembly ("memory-safe") { + mstore(0, selector) + mstore(0x04, value) + revert(0, 0x24) + } + } + + /// @dev Reverts with a custom error with an address argument in the scratch space + function revertWith(bytes4 selector, address addr) internal pure { + assembly ("memory-safe") { + mstore(0, selector) + mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff)) + revert(0, 0x24) + } + } +}