assert in solidity

assert is used to check the contract's code for errors and make sure code runs like it's supposed to.
Usually by testing certain invariants (an invariant is a condition that should always be true at a certain stage in the code).
These are the cases when Solidity creates assert-type of exceptions:

  • When you invoke Solidity assert with an argument, showing false.
  • When you invoke a zero-initialized variable of an internal function type.
  • When you convert a large or negative value to enum.
  • When you divide or modulo by zero.
  • When you access an array in an index that is too big or negative.

In this sample, I'm using assert to check that the _transfer method executed correctly. If it has, then the balance of msg.sender should be that of itself less the amount transferred.

function transfer(address recipient, uint amount) public {
        uint previousSenderBalance = balance[msg.sender];
        _transfer(msg.sender, recipient, amount);
        assert(balance[msg.sender] == previousSenderBalance - amount);
    }

PS: Never assert(false)

assert(false) compiles to 0xfe, which is an invalid opcode, using up all remaining gas, and reverting all changes.

Show Comments