These commands help check if things are right in your smart contract. If something is wrong, they stop the contract from running and can show a message.
Require, assert, and revert in Blockchain / Solidity
require(condition, "error message"); assert(condition); revert("error message");
require checks conditions and shows a message if false.
assert checks for errors that should never happen.
require(balance >= amount, "Not enough balance");assert(totalSupply == balancesSum);if (msg.sender != owner) { revert("Only owner can call this"); }
This contract lets users deposit and withdraw money. It uses require to check if users have enough money before withdrawing. It uses assert to make sure only the owner can do emergency withdrawal. It uses revert to stop anyone but the owner from calling a special function.
pragma solidity ^0.8.0; contract SimpleBank { mapping(address => uint) public balances; address public owner; constructor() { owner = msg.sender; } function deposit() public payable { balances[msg.sender] += msg.value; } function withdraw(uint amount) public { require(balances[msg.sender] >= amount, "Insufficient balance"); balances[msg.sender] -= amount; payable(msg.sender).transfer(amount); } function emergencyWithdraw() public { assert(msg.sender == owner); // Owner can withdraw all funds in emergency payable(owner).transfer(address(this).balance); } function onlyOwnerFunction() public { if (msg.sender != owner) { revert("Only owner allowed"); } // Some owner-only logic here } }
require refunds unused gas and returns your error message.
assert is for checking things that should never fail; if it fails, it uses all gas.
revert lets you stop execution and show a message anywhere in your code.
require checks inputs and conditions, stops with a message if false.
assert checks for bugs, stops if something impossible happens.
revert stops execution and shows a message, useful for custom checks.