Solidity 枚举、ABI编码、回调函数

2019-01-11  本文已影响8人  黄靠谱

Solidity 枚举
Solidity 回调函数
Solidity ABI编码

参考

https://www.jianshu.com/p/c4cf13d7990c

枚举原理和使用

  1. 枚举的构造函数申明了2个事:枚举的类型(ActionChoices)、所有可能的值的名字和值(GoLeft :0, GoRight:1,GoStraight:2, SitStill:3)
  2. 可以通过交易,传入参数1 (0xfb76fa520000...0001),来调用setGoStraight,而getDefaultChoice()方法直接返回2
pragma solidity  >=0.4.22 <0.6.0;

contract test {
    enum ActionChoices { GoLeft, GoRight, GoStraight, SitStill }
    ActionChoices _choice;
    ActionChoices  defaultChoice = ActionChoices.GoStraight;

    function setGoStraight(ActionChoices choice) public {
        _choice = choice;
    }

    function getChoice()  public returns (ActionChoices) {
        return _choice;
    }

    function getDefaultChoice() view public returns (uint) {
        return uint(defaultChoice);
    }
}

回调函数(Fallback Function)

https://solidity.readthedocs.i/en/latest/contracts.html

触发条件:

  1. 当合约被调用但没有别的方法能匹配上
  2. 没有数据提供时,或者参数不对

ABI编码

Solidity ABI 编码函数
一个是 solidity 提供了ABI的相关API, 用来直接得到ABI编码信息,这些函数有:

一般用encodeWithSignature就可以了,通过demo实现跨合约调用

pragma solidity >=0.4.22 <0.6.0;
contract Test {
     function() payable external{}
    uint age=30;
    function addAge(uint addValue) public view returns(uint){
        uint myage=age+addValue;
        return myage;
    }
}

contract Test2{
    function test(address nameReg) public returns(bool){
        bytes memory payload = abi.encodeWithSignature("getAge()",50);
        (bool success, bytes memory returnData) = address(nameReg).call(payload);
        require(success);
        return true;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读