Errors (require & revert)

  • An error will undo all changes made to the state during a transaction.

  • You can throw an error by calling require, revert or assert.

Great article explaining how Solidity reverts, custom errors, and try/catch work:

https://www.rareskills.io/post/try-catch-solidity

require

  • Used to validate inputs and conditions before execution.

// Used in both test contracts and main contracts
require(success, "Call failed"); 

revert

  • Similar to require, revert is useful when the condition to check is complex.

  • So put it at the end of a longer logic statement making it easier to read.

// This error definition is needed in the main contract and the test contract
error FundMe__RefundFailed();

// In main contract
if (!callSuccess) revert FundMe__RefundFailed();

// In test contract
// Expects the next line to revert with the specified error
vm.expectRevert(FundMe__RefundFailed.selector);
testHelper.fundMeRefund();
  • The .selector property retrieves the unique identifier (selector) of the FundMe__RefundFailed error.

  • In the case of errors (and events), the selector is derived from the error's name and its parameters.

assert

Gas Saving

Example

Last updated