Require vs Assert vs Revert in Solidity: Key Differences and Usage
require checks conditions on inputs or external calls and refunds unused gas on failure, assert checks for internal errors and uses all gas on failure, while revert explicitly stops execution and refunds gas with a custom error message.Quick Comparison
Here is a quick table comparing require, assert, and revert in Solidity based on key factors.
| Factor | require | assert | revert |
|---|---|---|---|
| Purpose | Validate inputs and external calls | Check for internal errors | Explicitly stop execution with error |
| Gas Refund | Refunds unused gas | Consumes all gas | Refunds unused gas |
| Use Case | User input validation | Detect bugs and invariants | Custom error handling |
| Error Message | Supports custom messages | No custom messages | Supports custom messages |
| When to Use | Check conditions before execution | Check for impossible states | Replace require for complex logic |
Key Differences
require is used to validate conditions like user inputs or external contract calls. If the condition fails, it stops execution, reverts state changes, and refunds unused gas. It also allows a custom error message to explain the failure.
assert is meant for checking internal errors or invariants that should never fail if the contract is correct. When an assert fails, it consumes all remaining gas and signals a serious bug. It does not support custom error messages.
revert explicitly stops execution and reverts state changes like require, but it is more flexible. It is often used for complex error handling or to replace require when multiple conditions or detailed error messages are needed. It also refunds unused gas.
Code Comparison
pragma solidity ^0.8.0; contract Example { function checkRequire(uint x) public pure returns (string memory) { require(x > 10, "x must be greater than 10"); return "Passed require check"; } }
Revert Equivalent
pragma solidity ^0.8.0; contract Example { function checkRevert(uint x) public pure returns (string memory) { if (x <= 10) { revert("x must be greater than 10"); } return "Passed revert check"; } }
When to Use Which
Choose require when you want to validate user inputs or external calls and want to provide clear error messages with gas refund. Use assert to check for conditions that should never fail, like internal bugs or invariants, since it uses all gas on failure signaling a critical error. Use revert when you need flexible error handling with custom messages, especially for complex logic or multiple checks where require might be less clear.
Key Takeaways
require is for input validation and refunds unused gas on failure.assert checks for internal errors and consumes all gas if it fails.revert explicitly stops execution with custom errors and refunds gas.require for user errors, assert for bugs, and revert for complex error handling.