Unchecked Math

# Unchecked Math

O Overflow e o underflow de números no Solidity 0.8 geram um erro. Isto pode ser desativado usando unchecked.

A desativação da overflow/underflow poupa gás.

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

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) {
        // Envolva lógica matemática complexa dentro de unchecked
        unchecked {
            uint x3 = x * x * x;
            uint y3 = y * y * y;

            return x3 + y3;
        }
    }
}

# Teste no Remix

Last Updated: 22/01/2024 22:26:13