[Solidity] How to use assert?

This section explains how to use the assert function in Solidity.

How to use

The assert function is used when you want to validate an input or condition before executing a process.

It is mainly used to check for internal errors and invariant conditions.

If the specified condition is not met, processing is aborted and the contract state is restored.

In addition to consuming the processed gas cost, all remaining gas cost is also consumed.

Syntax

assert(condition)

The following is the actual display on the console.

You can see that the state of the contract is restored if the condition of assert is not met.

assert
assert

Sample Code

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

contract Test {

    function testAssert(uint _value) public pure {
        assert(_value > 0); // assert function
        // Process executed when _value is greater than 0
    }

}

In terms of functions that interrupt processing, it is difficult to distinguish between require/assert/revert, but the assert described here is suitable for checking internal errors and invariant conditions. It is preferable to use it when you want to prevent unacceptable conditions/errors because it consumes all remaining gas as well as before revert (return to state).

タイトルとURLをコピーしました