Solidity8.0新特性

一、新的特性

安全数学:老版本是没有的,会出现数学溢出的。之前的uint无符号正整数有数学溢出,在使用的时候都要引用安全数学的方法,0-1得到的是uint256最大值并不会得-1,因为uint是无符号整数,不会出现-1。

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

//safe math
contract SafeMath {
    function testUnderflow() public pure returns (uint) {
        uint x = 0;
        x--;
        return x;
    }
    function testUncheckedUnderflow() public pure returns (uint) {
        uint x = 0;
        unchecked { x--; }
        return x;
    }
}

二、自定义错误

// SPDX-License-Identifier: MIT
//之前合约报错一般使用revert/re ,报错信息可以写字符串

contract VendingMachine {
    address paypable owner = paypable(msg.sender);

  error Unauthorized();//可以让报错抛出变量值,
function withdraw() public { if (msg.sender != owner) // 23642 gas // revert("error") // ?gas,字符串的长度决定消耗gas的多少 //revert("error")
     revert Unauthorized() owner.transfer(address(
this).balance); } }

 

三、函数在合约之外

四、引用合约名称可以起别名

五、create2方法内联汇编和原来的新建方法一样的方法

posted @ 2022-07-18 22:56  ZaleSwfit  阅读(157)  评论(0编辑  收藏  举报