以太坊( Ethereum ) 和 波场(Tron)的数学计算函数类

以太坊( Ethereum ) 和 波场(Tron)的数学计算函数类,当然也可用用在阿里蚂蚁区块链上,可以帮助减少gas消耗和防止溢出错误

/**
  * @dev包装了Solidity的算术运算,并添加了溢出检查。
  *
  * Solidity中的算术运算会在溢出时自动换行。 这很容易导致在运算中使用错误的值,尤其是在一些资金运算。
  * `SafeMath`通过在操作溢出时回滚事务来处理溢出回滚。
  *
  * 使用这个库会自动帮你检查类型溢出的情况,所以建议一直使用这个库。
  */
library SafeMath {
    /**
     * @dev 返回两个无符号整数的相加,并在溢出时回滚事务。
     *
     * 与Solidity的+操作符相对应。
     *
     * 使用场景:
     * - 要求加法不能溢出的场景.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");  //报错并且回滚

        return c;
    }

    /**
     * @dev 返回两个无符号整数的减法,并在溢出时返回(结果为负数时)。
     *
     * 与Solidity的`-`运算符相对应。
     *
     * 使用场景:
     * - 要求减法不能溢出的场景.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a, "SafeMath: subtraction overflow");  //报错并且回滚
        uint256 c = a - b;

        return c;
    }

    /**
     * @dev 返回两个无符号整数的乘法,并在溢出时恢复。
     *
     * 与Solidity的`*`运算符相对应。
     *
     * 使用场景:
     * - 要求乘法不能溢出的场景.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        // gas优化:这里只检测'a'不为零,而是要求a更便宜
        // 如果还测试了“ b”,则将失去收益,因为检测也需要消耗gas。
        // 参见:https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) {
            return 0;
        }

        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");  //报错并且回滚

        return c;
    }

    /**
     * @dev返回两个无符号整数的整数除法。 恢复除以零。 结果四舍五入为零。
     *
     * 与Solidity的`/`运算符相对应。 注意:此功能使用
     * `revert`操作码(保留剩余gas不变),而Solidity使用无效的操作码进行还原(消耗所有剩余气体)。
     * 使用场景:
     * - 除数不能为零。
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        // Solidity仅在除以0时自动断言
        require(b > 0, "SafeMath: division by zero");  //报错并且回滚
        uint256 c = a / b;
        // assert(a == b * c + a % b); // There is no case in which this doesn't hold

        return c;
    }

    /**
     * @dev返回除以两个无符号整数的余数。 (无符号整数模),除以零时返回。
     *
     * 与Solidity的`%`运算符相对应。 此功能使用“还原”
     * 操作码(使剩余的气体保持不变),而Solidity使用
     * 无效的操作码还原(消耗了所有剩余的gas)。
     *
     * 使用场景:
     * - 除数不能为零。
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b != 0, "SafeMath: modulo by zero");  //报错并且回滚
        return a % b;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注

你需要开启你的javascript才可以哦!