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

2019-01-09  本文已影响4人  黄靠谱

方法的调用

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
  1. require: 如果不满足则终断运行,会退回剩下的gas

require的适用场景:

  1. revert:和require功能一样,只是代码形式不一样而已,适合复杂的判断场景
    会退回剩下的gas,但是允许有一个返回值,可以用来标记错误并恢复当前的调用。 revert 调用中包含有关错误的详细信息是可能的,这个消息会被返回给调用者。

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

适合用Assert的时候:

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}));
    }

上一篇 下一篇

猜你喜欢

热点阅读