23-02-27

First Post:

Last Update:

2023-02-27

函数及多值返回

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

contract Function {
// Functions can return multiple values.
function returnMany() public pure returns (uint, bool, uint) {
return (1, true, 2);
}

// Return values can be named.
function named() public pure returns (uint x, bool b, uint y) {
return (1, true, 2);
}

// Return values can be assigned to their name.
// In this case the return statement can be omitted.
function assigned() public pure returns (uint x, bool b, uint y) {
x = 1;
b = true;
y = 2;
}

// Use destructuring assignment when calling another
// function that returns multiple values.
function destructuringAssignments()
public
pure
returns (uint, bool, uint, uint, uint)
{
(uint i, bool b, uint j) = returnMany();

// Values can be left out.
(uint x, , uint y) = (4, 5, 6);

return (i, b, j, x, y);
}

// Cannot use map for either input or output

// Can use array for input
function arrayInput(uint[] memory _arr) public {}

// Can use array for output
uint[] public arr;

function arrayOutput() public view returns (uint[] memory) {
return arr;
}
}

// Call function with key-value inputs
contract XYZ {
function someFuncWithManyInputs(
uint x,
uint y,
uint z,
address a,
bool b,
string memory c
) public pure returns (uint) {}

function callFunc() external pure returns (uint) {
return someFuncWithManyInputs(1, 2, 3, address(0), true, "c");
}

function callFuncWithKeyValue() external pure returns (uint) {
return
someFuncWithManyInputs({a: address(0), b: true, c: "c", x: 1, y: 2, z: 3});
}
}

view与pure

1
2
3
4
5
6
7
8
9
10
11
pragma solidity ^0.8.17;
//SPDX-License-Identifier:MIT
contract vp {
uint x = 1;
function v() public view returns(uint) {
return x+3;//访问了x
}
function p() public pure returns(uint) {
return 1;//只需要其返回值
}
}

revert与assert、require

revert区别在于可以抛出自定义错误,方便查看参数

assert用于处理内部错误,如相乘相加溢出,除以零,其条件不满足时会报出错误

require可以带条件,其条件不满足时会报出错误

这两个里面revert跟require不需要消耗gas,assert需要消耗

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
pragma solidity ^0.8.17;
//SPDX-License-Identifier:MIT
contract err {
function testRequire(int i) public pure {
require(i > 0, "parameter must be bigger than 0! ");
}
function testRevert(int i) public pure{
if(i<0) {
revert("parameter must be bigger than 0! ");
}
}
uint a;
function testAssert() public{
assert(a == 11);//部署的时候会检查,错误时候终止合同的部署
a = 10;
}
error aerror(uint first, uint sec);
function testErr(int k) public pure {
if(k == 1) revert aerror({first: 1, sec: 1});//error就是方便查看数值
}
uint max = type(uint).max;
bool isMax = max == 2**256-1;
}

下面是revert一个自定义错误的例子