Back
Lesson 19:
Validations and Assertions
Introduction to validations and assertions and how to use it in your smart contracts.
Visit desktop version for better experiences.
Validations and Assertions
Validations and assertions are used to check the correctness of the data in your smart contract. They are used to ensure that the data is as expected and to prevent the contract from executing if the data is not as expected.
Validations and assertions also throws an error by calling require
, revert
or assert
.
-
require(bool condition)
: abort execution and revert state changes if condition is false (use as error in external component) -
require(bool condition, string memory message)
: abort execution and revert state changes if condition is false. Also provide error message. -
revert()
: abort execution and revert state changes -
revert(string memory message)
: abort execution and revert state changes providing an explanatory string -
assert(bool condition)
: abort execution and revert state changes if condition is false (use for internal error)
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
contract MyContract {
mapping(address => uint) public balance;
function deposit(uint amount) public {
// Use require to validate inputs from external calls
require(amount > 0, "Deposit amount must be greater than 0");
balance[msg.sender] += amount;
}
function withdraw(uint amount) public {
// Use require to validate inputs from external calls
require(amount <= balance[msg.sender], "Insufficient balance");
balance[msg.sender] -= amount;
}
function transfer(address to, uint amount) public {
// Use revert to abort execution and revert state changes
if (to == address(0)) {
revert("Cannot transfer to zero address");
}
// Use require to validate inputs from external calls
require(amount <= balance[msg.sender], "Insufficient balance");
balance[msg.sender] -= amount;
balance[to] += amount;
// Use assert for internal errors that should never happen
assert(balance[msg.sender] + balance[to] == amount);
}
}