0
0
Blockchain / Solidityprogramming~5 mins

Require, assert, and revert in Blockchain / Solidity

Choose your learning style9 modes available
Introduction

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.

Check if a user has enough money before buying something.
Make sure a number is not zero before dividing.
Stop the contract if an unexpected error happens.
Verify that only the owner can change important settings.
Syntax
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.

Examples
Stops if balance is less than amount, showing a message.
Blockchain / Solidity
require(balance >= amount, "Not enough balance");
Checks that total supply equals sum of balances, stops if not.
Blockchain / Solidity
assert(totalSupply == balancesSum);
Stops and shows message if caller is not owner.
Blockchain / Solidity
if (msg.sender != owner) {
    revert("Only owner can call this");
}
Sample Program

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.

Blockchain / Solidity
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
    }
}
OutputSuccess
Important Notes

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.

Summary

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.