Require vs Revert – When to Use Require vs Custom Revert Errors in Smart Contracts

custom-errorsrequirerevert-opcode

This applies only to solidity ^0.8 and onward.

Let's say I have a function like this:

function withdraw() external {
  (bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
  // Now we should check the function succeeded
}

I could check this with:

require(success, "Transfer failed");

or

// At the top of the code
error TransferFailed();
.
.
.
if(!success){ revert TransferFailed();}

Where does it make sense to use require vs a custom error and revert? It seems you'll just need to check the gas costs, and that's it.

Best Answer

Custom errors are more gas efficient than using require with a string explanation. So ideally you'd always use this over require.

Related Topic