This series will provide answers to the list of Solidity interview questions that were published by RareSkills.
Both assert
and require
are used for error handling, but they behave differently.
For example,
if a require
statement fails, it will revert
the transaction and refund
the remaining gas to the caller,
whereas, assert
will revert
the transaction but will NOT refund
the gas
(This is true if using a Solidity version prior to version 0.8.0… Version 0.8.0 changed the opcode that assert
compiles to from invalid to revert, which refunds all gas). Also, if the condition fails, require allows for an optional error message that could be returned to the user, but assert does not.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
contract ErrorHandlingContract {
uint256 public balance = 1000;
// Use case for `require`: Input validation
function withdraw(uint256 amount) public {
// `require` is used here to validate input conditions, such as
// ensuring the withdrawal amount is not greater than the balance.
require(amount <= balance, "Insufficient balance");
// Some logic to perform the withdrawal
balance -= amount;
}
// Use case for `assert`: Checking for invariants
function updateBalance(uint256 newBalance) public {
// Some complex logic that might inadvertently cause bugs
balance = newBalance;
// `assert` is used to check invariants or conditions that should
// always be true if the contract logic is correct.
// It's used to catch bugs or errors in contract logic.
assert(balance >= 0);
}
// Example function to demonstrate where both might be used
function deposit(uint amount) public {
// Using `require` for input validation
require(amount > 0, "Deposit amount must be positive");
balance += amount;
// Using `assert` to ensure deposit didn't cause an unexpected issue
// such as an overflow.
assert(balance >= amount);
}
}
As outlined in the examples above, assert
and require
serve different purposes. The require
function is commonly used for input validation or to validate the state before executing certain logic.
The assert
function is used to check for invariants, to ensure that there’s no error in the contract’s logic and to prevent conditions that should never be possible.