Errors: require, revert, assert
Smart contracts handle errors by reverting: the current call stops, every state change it made is undone, and an error message (or error data) is returned to the caller. There is no partially finished transaction. Solidity gives you three tools for triggering a revert.
| Statement | Use it for | Error data |
|---|---|---|
require(cond, "msg") |
validating inputs, permissions, state | Error(string) with your message |
revert("msg") / revert CustomError(...) |
failing from inside complex logic | your message or custom error |
assert(cond) |
checking invariants that should never be false | Panic(0x01) |
require
require is the gatekeeper at the top of a function: if the condition is false, the call reverts with your message.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Ticketing {
uint256 public sold;
uint256 public constant CAPACITY = 3;
function buy(uint256 qty) external {
require(qty > 0, "quantity must be positive");
require(sold + qty <= CAPACITY, "not enough tickets left");
sold += qty;
}
}
contract Main {
function main() external {
Ticketing t = new Ticketing();
t.buy(2);
console.log("sold:", t.sold());
t.buy(2); // only 1 left
console.log("not reached");
}
}sold: 2
main() failed: reverted with reason: not enough tickets left
revert
revert("message") fails unconditionally. It's handy when the failing condition is found deep inside an if chain:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
function grade(uint256 score) public pure returns (string memory) {
if (score > 100) {
revert("score must be 0..100");
}
if (score >= 90) return "A";
if (score >= 75) return "B";
if (score >= 50) return "C";
return "F";
}
function main() external pure {
console.log("95 ->", grade(95));
console.log("60 ->", grade(60));
console.log("120 ->", grade(120));
}
}95 -> A
60 -> C
main() failed: reverted with reason: score must be 0..100
Reverts undo everything
A revert rolls back all state changes in the call, including changes made before the failing line and changes in other contracts called along the way:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Bank {
mapping(address => uint256) public balance;
function credit(address who, uint256 amount) external {
balance[who] += amount;
}
function creditThenFail(address who, uint256 amount) external {
balance[who] += amount; // happens...
require(amount < 100, "amount too large"); // ...then is undone
}
}
contract Main {
function main() external {
Bank bank = new Bank();
address alice = address(0xA11CE);
bank.credit(alice, 50);
// a low-level call returns false instead of bubbling the revert up
(bool ok, ) = address(bank).call(abi.encodeCall(Bank.creditThenFail, (alice, 500)));
console.log("call succeeded?", ok);
console.log("alice balance :", bank.balance(alice));
}
}call succeeded? false
alice balance : 50
The balance is still 50: the += 500 was rolled back. (The failed call's gas is still paid, though.)
assert and panics
assert is for conditions that can only be false if your code has a bug. A failing assert produces a Panic error. The compiler inserts similar panic checks automatically:
| Panic code | Cause |
|---|---|
0x01 |
assert(false) |
0x11 |
arithmetic overflow or underflow |
0x12 |
division or modulo by zero |
0x21 |
invalid enum conversion |
0x31 |
pop() on an empty array |
0x32 |
array index out of bounds |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "hardhat/console.sol";
contract Main {
uint256 public totalSupply;
uint256 public aliceBalance;
uint256 public bobBalance;
function mint(uint256 a, uint256 b) internal {
aliceBalance += a;
bobBalance += b;
totalSupply += a + b;
// invariant: the sum of balances equals the total supply
assert(aliceBalance + bobBalance == totalSupply);
}
function main() external {
mint(10, 5);
console.log("supply:", totalSupply);
totalSupply += 1; // simulate a bug elsewhere
mint(1, 1);
}
}supply: 15
main() failed: panic 0x01 (assert(false))
Tip: If users can trigger an error by sending bad input, use
requireor a custom error. If only a bug could trigger it, useassert. Tools for formal verification and fuzzing look for reachableassertfailures.
Gas when reverting
A revert refunds the unused gas to the caller, but the gas already consumed is gone. Checking conditions early, before expensive work, keeps failed transactions cheap.
Test yourself
A function sets x = 5, then calls require(false, "no"). What is x afterwards?
- 5
- Its previous value
- 0
- Undefined
Which tool is meant for checking internal invariants that should never fail?
requirerevertasserttry
What does dividing by zero produce in Solidity 0.8?
- 0
- type(uint256).max
- A revert with panic code 0x12
- Infinity