Solidity Revert

whiteboard crypto logo
Published by:
Whiteboard Crypto
on

In Solidity, the Revert function is used to stop execution of a smart contract, reverting the state to it’s previous version, and refunds the user the remaining gas in the process. Here is an example of revert in a smart contract:

//SPDX-License-Identifier: MIT
pragma solidity 0.8.13;

contract arrayFunctions{

    uint public age = 25;

    function checkName() public view returns(bool){
        if(age != 25){
            revert("No longer 25!");
        }

        return true;
        
    }

    function changeName(uint _newAge) public{
        age = _newAge;
    }
}

Revert can accept an error code, that will be shown if the revert code is ever thrown. Revert is different than Require because it doesn’t check a conditional. If Revert is ever reached, it will throw an error, while Require only throws an error if the conditional given to it is false.

On the other hand, Revert is different than Assert by way of when they should be reached. Revert should be reached in an error or unwanted situation. Assert is used to check variables and situations that should never happen.

In most cases, “Revert()” is used where a “Require()” statement would work, but there may be many conditionals statements, or complex logic is required.

EIP-140 introduced Revert into Solidity, you can read more about it here.

whiteboard crypto logo

WhiteboardCrypto is the #1 online resource for crypto education that explains topics of the cryptocurrency world using analogies, stories, and examples so that anyone can easily understand them. Growing to over 870,000 Youtube subscribers, the content has been shared around the world, played in public conferences and universities, and even in Congress.