0
0
BlockchainConceptBeginner · 3 min read

What is revert in Solidity: Explanation and Example

revert in Solidity is a command that stops the execution of a smart contract and undoes all changes made during the current transaction. It is used to handle errors by reverting the contract state to what it was before the transaction started, often with an optional error message.
⚙️

How It Works

Imagine you are filling out a form online, but you realize you made a mistake. Instead of submitting the wrong information, you hit a reset button that clears all your inputs and lets you start fresh. In Solidity, revert works like that reset button for smart contracts.

When a contract runs a transaction, it may change data like balances or states. If something goes wrong or a condition is not met, revert stops the transaction immediately and undoes all those changes, so the contract stays as if nothing happened. This helps keep the contract safe and consistent.

Additionally, revert can send a message explaining why the transaction failed, which helps developers and users understand the problem.

💻

Example

This example shows a simple contract that uses revert to prevent withdrawing more money than the balance.

solidity
pragma solidity ^0.8.0;

contract SimpleBank {
    mapping(address => uint) public balances;

    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    function withdraw(uint amount) public {
        if (amount > balances[msg.sender]) {
            revert("Insufficient balance");
        }
        balances[msg.sender] -= amount;
        payable(msg.sender).transfer(amount);
    }
}
Output
If withdraw is called with amount greater than balance, transaction reverts with error: "Insufficient balance"
🎯

When to Use

Use revert when you want to stop a transaction because something is wrong or a rule is broken. For example, if a user tries to withdraw more money than they have, or if an input value is invalid.

This helps protect your contract from unwanted changes and keeps data safe. It also provides clear error messages to users and developers, making debugging easier.

In real-world contracts, revert is common in functions that require certain conditions to be true before proceeding, like checking permissions, balances, or input validity.

Key Points

  • revert stops execution and undoes all changes in the current transaction.
  • It helps keep smart contracts safe and consistent by preventing invalid operations.
  • You can provide an error message with revert to explain why the transaction failed.
  • It is commonly used to check conditions and enforce rules in contract functions.

Key Takeaways

revert stops a transaction and undoes all changes if something goes wrong.
Use revert to enforce rules and protect contract state.
revert can include error messages to explain failures.
It is essential for safe and predictable smart contract behavior.