01-Solidity8.0新特性
文章目录 Solidity8.0前言一、Solidity是什么?二、新特性1.安全数学2.自定义错误3.函数在合约之外使用4.引入文件更改别名5.Create2 总结
前言
区块链越来越吃香了,开始做笔记
一、Solidity是什么?
在区块链上运行的一种脚本语言!
二、新特性 1.安全数学代码如下(示例):
// SPDX-License-Identifier: MIT
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;
}
}
2.自定义错误
代码如下(示例):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
error Unauthorized(address caller);
contract customer {
address payable owner = payable(msg.sender);
function withdraw() public {
if (msg.sender != owner){
revert Unauthorized(msg.sender);
}
owner.transfer(address(this).balance);
}
}
3.函数在合约之外使用
代码如下(示例):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
function add(uint256 a) pure returns (uint256) {
return a + 7;
}
contract customer {
function test() external view returns(uint256){
return add(8);
}
}
4.引入文件更改别名
代码如下(示例):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
import {test, helper as help} from "./Common.sol";
5.Create2
代码如下(示例):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8;
contract TestContract {
address public owner;
uint public foo;
constructor(address _owner, uint _foo) payable {
owner = _owner;
foo = _foo;
}
function getBalance() public view returns (uint) {
return address(this).balance;
}
}
contract Factory {
function deploy2(address _owner,uint _foo,bytes32 _salt) public payable returns (address) {
return address(new TestContract{salt: _salt}(_owner, _foo));
}
event Deployed(address addr, uint salt);
function getBytecode(address _owner, uint _foo) public pure returns (bytes memory) {
bytes memory bytecode = type(TestContract).creationCode;
return abi.encodePacked(bytecode, abi.encode(_owner, _foo));
}
function getAddress(bytes memory bytecode, uint _salt) public view returns (address) {
bytes32 hash = keccak256(
abi.encodePacked(bytes1(0xff), address(this), _salt, keccak256(bytecode))
);
return address(uint160(uint(hash)));
}
function deploy(bytes memory bytecode, uint _salt) public payable {
address addr;
assembly {
addr := create2( callvalue(), add(bytecode, 0x20), mload(bytecode), _salt )
if iszero(extcodesize(addr)) {
revert(0, 0)
}
}
emit Deployed(addr, _salt);
}
}
总结
日拱一卒。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)