solidity合约开发-SafeMath
SafeMath 的部分代码:
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
首先我们有了 library
关键字 — 库和 合约
很相似,但是又有一些不同。 就我们的目的而言,库允许我们使用 using
关键字,它可以自动把库的所有方法添加给一个数据类型:
using SafeMath for uint;
// 这下我们可以为任何 uint 调用这些方法了
uint test = 2;
test = test.mul(3); // test 等于 6 了
test = test.add(5); // test 等于 11 了
注意 mul
和 add
其实都需要两个参数。 在我们声明了 using SafeMath for uint
后,我们用来调用这些方法的 uint
就自动被作为第一个参数传递进去了(在此例中就是 test
)
我们来看看 add
的源代码看 SafeMath 做了什么:
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
基本上 add
只是像 +
一样对两个 uint
相加, 但是它用一个 assert
语句来确保结果大于 a
。这样就防止了溢出。
assert
和 require
相似,若结果为否它就会抛出错误。 assert
和 require
区别在于,require
若失败则会返还给用户剩下的 gas, assert
则不会。所以大部分情况下,你写代码的时候会比较喜欢 require
,assert
只在代码可能出现严重错误的时候使用,比如 uint
溢出。
所以简而言之, SafeMath 的 add
, sub
, mul
, 和 div
方法只做简单的四则运算,然后在发生溢出或下溢的时候抛出错误。
还没有评论,来说两句吧...