blockchains-security-toolkit/advanced_expert/vulnerabilities/arithmetic_errors/overflow
2024-11-04 18:42:30 +07:00
..
example.sol organize chapters for the ongoing research, remove dead links, add new resources 2024-11-04 18:42:30 +07:00
README.md organize chapters for the ongoing research, remove dead links, add new resources 2024-11-04 18:42:30 +07:00

overflow of numbers


tl; dr: unchecked math


  • overflow and underflow of numbers in solidity 0.8 throw an error. this can be disabled with unchecked.
  • disabling overflow / underflow check saves gas.

contract UncheckedMath {
    function add(uint x, uint y) external pure returns (uint) {
        // 22291 gas
        // return x + y;

        // 22103 gas
        unchecked {
            return x + y;
        }
    }

    function sub(uint x, uint y) external pure returns (uint) {
        // 22329 gas
        // return x - y;

        // 22147 gas
        unchecked {
            return x - y;
        }
    }

    function sumOfCubes(uint x, uint y) external pure returns (uint) {
        // Wrap complex math logic inside unchecked
        unchecked {
            uint x3 = x * x * x;
            uint y3 = y * y * y;

            return x3 + y3;
        }
    }
}