solidity合约开发-SafeMath

ゞ 浴缸里的玫瑰 2022-12-20 02:25 229阅读 0赞

SafeMath 的部分代码:

  1. library SafeMath {
  2. function mul(uint256 a, uint256 b) internal pure returns (uint256) {
  3. if (a == 0) {
  4. return 0;
  5. }
  6. uint256 c = a * b;
  7. assert(c / a == b);
  8. return c;
  9. }
  10. function div(uint256 a, uint256 b) internal pure returns (uint256) {
  11. // assert(b > 0); // Solidity automatically throws when dividing by 0
  12. uint256 c = a / b;
  13. // assert(a == b * c + a % b); // There is no case in which this doesn't hold
  14. return c;
  15. }
  16. function sub(uint256 a, uint256 b) internal pure returns (uint256) {
  17. assert(b <= a);
  18. return a - b;
  19. }
  20. function add(uint256 a, uint256 b) internal pure returns (uint256) {
  21. uint256 c = a + b;
  22. assert(c >= a);
  23. return c;
  24. }
  25. }

首先我们有了 library 关键字 — 库和 合约很相似,但是又有一些不同。 就我们的目的而言,库允许我们使用 using 关键字,它可以自动把库的所有方法添加给一个数据类型:

  1. using SafeMath for uint;
  2. // 这下我们可以为任何 uint 调用这些方法了
  3. uint test = 2;
  4. test = test.mul(3); // test 等于 6 了
  5. test = test.add(5); // test 等于 11 了

注意 muladd 其实都需要两个参数。 在我们声明了 using SafeMath for uint 后,我们用来调用这些方法的 uint 就自动被作为第一个参数传递进去了(在此例中就是 test)

我们来看看 add 的源代码看 SafeMath 做了什么:

  1. function add(uint256 a, uint256 b) internal pure returns (uint256) {
  2. uint256 c = a + b;
  3. assert(c >= a);
  4. return c;
  5. }

基本上 add 只是像 + 一样对两个 uint 相加, 但是它用一个 assert 语句来确保结果大于 a。这样就防止了溢出。

assertrequire 相似,若结果为否它就会抛出错误。 assertrequire 区别在于,require 若失败则会返还给用户剩下的 gas, assert 则不会。所以大部分情况下,你写代码的时候会比较喜欢 requireassert 只在代码可能出现严重错误的时候使用,比如 uint 溢出。

所以简而言之, SafeMath 的 addsubmul, 和 div 方法只做简单的四则运算,然后在发生溢出或下溢的时候抛出错误。

发表评论

表情:
评论列表 (有 0 条评论,229人围观)

还没有评论,来说两句吧...

相关阅读