Solidity 函数 参数、异常、修饰器

方法的调用

https://solidity.readthedocs.io/en/latest/control-structures.html

pragma solidity >=0.4.0 <0.6.0;

contract C {
    mapping(uint => uint) data;
    function f() public {
        set({value: 2, key: 3});
    }
    function set(uint key, uint value) public {
        data[key] = value;
    }
}

函数

  1. solidity支持多返回值,这和js 、C的语法不一样
  2. 返回值的设置有2种方式,一种是通过return 指定返回值,一种是通过 返回值的name一样来匹配
contract Simple {
    function arithmetic(uint _a, uint _b) public pure returns (uint o_sum, uint o_product)
    {
        return (_a + _b, _a * _b);
    }

    function arithmetic(uint _a, uint _b) public pure returns (uint o_sum, uint o_product)
    {
        o_sum = _a + _b;
        o_product = _a * _b;
    }
}
  1. 函数的重载:支持重载,方法名相同,但是参数的个数或者类型不同

require assert revert throws

https://solidity.readthedocs.io/en/latest/control-structures.html#error-handling-assert-require-revert-and-exceptions

  1. throws
  • 从 0.4.13 版本开始,throw 这个关键字被弃用,并且将来会被逐渐淘汰
  • 之前普遍用于判断一个条件是否满足,如果不满足则终断运行
  • 但throw了之后它会撤回所有的状态转变,用光你所有的gas
  1. require: 如果不满足则终断运行,会退回剩下的gas
  • require应该被最常使用到,一般用于函数的开头处。

require的适用场景:

  • 验证一个用户的输入是否合法:ie. require(input<20);
  • 验证一个外部协议的回应:require(external.send(amount));
  • 判断执行一段语句的前置条件: ie. require(balance[msg.sender]>=amount);
  1. revert:和require功能一样,只是代码形式不一样而已,适合复杂的判断场景
    会退回剩下的gas,但是允许有一个返回值,可以用来标记错误并恢复当前的调用。 revert 调用中包含有关错误的详细信息是可能的,这个消息会被返回给调用者。

  2. assert: 检查内部错误,如果不满足则终断运行,会烧掉所有的gas
    在完成变化后检查状态避免本不应该发生的情况出现,如程序的bug。assert不应该被经常利用到,一般用于函数结尾处

适合用Assert的时候:

  • 检查有没有上溢或者是下溢: ie. c = a+b; assert(c > b)
  • 检查常数: ie. assert(this.balance >= totalSupply);
pragma solidity ^0.4.22;

contract VendingMachine {
    function buy(uint amount) payable {
        if (amount > msg.value / 2 ether)
            revert("Not enough Ether provided.");
        // 下边是等价的方法来做同样的检查:
        require(
            amount <= msg.value / 2 ether,
            "Not enough Ether provided."
        );
        // 执行购买操作
    }
}

modifier函数修改器

  1. 定义一个函数用modifier修饰,这个函数一般都有require做条件判断
  2. 然后在某个方法的修饰符中添加这个modifier的函数,作为执行该函数的一个条件
 modifier onlyBefore(uint _time) { require(now < _time); _; }
    function bid(bytes32 _blindedBid)public payable onlyBefore(biddingEnd)
    {
        bids[msg.sender].push(Bid({blindedBid: _blindedBid,deposit: msg.value}));
    }

猜你喜欢

转载自blog.csdn.net/weixin_34212189/article/details/86795334