01-Solidity8.0新特性

601 阅读1分钟

1 safe math 安全数学


pragma solidity ^0.8;

contract SafeMath{
    function Underflow() public pure returns (uint){
        uint x =0;
        x--;
        return x;
    }
     function uncheckedUnderflow() public pure returns (uint){
        uint x =0;
        unchecked{x--;}
        return x;
    }
}

运行 Underflow() 控制台会报错:

call to SafeMath.Underflow errored: VM error: revert.

运行 uncheckedUnderflow() 会得到一个溢出结果-uint256位的最大值:

image.png

2 custom error 自定义错误

// SPDX-License-Identifier: MIT

pragma solidity ^0.8;

contract customerr {
   address payable owner =payable(msg.sender);

   function withdraw() public {
       if (msg.sender !=owner)
       revert ('Error');
       owner.transfer (address(this).balance);
   }
}

运行部署产生了 54120gas(与字符串的长短有关)

image.png 下面写一个错误方法 error Unauthorized();

运行部署产生了 37943gas

image.png

3 函数在合约之外使用

现在允许在contract外使用函数 但是不能使用状态变量,图中不允许使用‘foo’变量

image.png

4 引入文件更改别名

如果不讲引入的helper更改别名 会和函数名冲突 可以用as替换一下

image.png