1

I came across a tweet which tells there are few scenarios in which Integer Overflow/Underflow are possible in Solidity ^0.8.0? Do you know how?

1

1 Answer 1

2

Well, yes. If you use assembly or the unchecked keyword you can get an overflow/underflow.

Check this simple code I created:

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Counter {

    mapping(address => uint256) public balances;

    constructor() {
        balances[msg.sender] = 0;
    }

    function underflow_assembly() public pure returns(uint256) {
        uint256 n = 0;
        assembly {
            n := sub(n, 1)
        }
        // n now is equal to 115792089237316195423570985008687907853269984665640564039457584007913129639935
        return n;
    }

    function underflow_unchecked() public pure returns(uint256) {
        uint256 n = 0;
        unchecked {
            n--;
        }
        // n now is equal to 115792089237316195423570985008687907853269984665640564039457584007913129639935
        return n;
    }

    // reverts
    function no_underflow() public pure returns(uint256) {
        uint256 n = 0;
        n--;
        return n;
    }

    // reverts
    function balanceUnderflow() public {
        balances[msg.sender] -= 1;
    }

}

With Solidity version ^0.8.0, you cannot get underflow/overflow unless you use the unchecked keyword or use assembly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.