Solidity Assert

whiteboard crypto logo
Published by:
Whiteboard Crypto
on

Assert is a function in Solidity that is used to verify a really important conditional statement that should never return false. If the condition is false, the state reverts to it’s previous state, and future gas is refunded. Here’s an example of using an Assert error in Solidity:

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

contract assertExample{

    address public owner = 0xd9145CCE52D386f254917e481eB44e9943F39138;

    function getOwner() public view returns(bool){
        assert(owner == 0xd9145CCE52D386f254917e481eB44e9943F39138);
        //send some funds
        return true;
    }

}

Assert is very similar to Require and Revert. How does it differ?

Require checks a conditional, and if that conditional is false, an error message is returned. Revert does not check a conditional, but if revert is ever processed in code, it will also show an error message and refund remaining gas. Assert checks a conditional, but doesn’t return a customized error. It will also refund any remaining gas.

You might be wondering when you should use Assert() in Solidity. The answer is to use Assert when you wish to check that a very important variable has not changed, or that a condition must always be true.

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.