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

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

  • 一个合约可以有且只能有一个没名字的方法 同时也不能有参数 也不能有返回的值
  • 回调函数的可见性就是 external,因为没有方法名,自己调用不了、子合约也调用不了,只有当异常的时候,被外部调用
  • 回调函数是收款的硬性指标啊,没有payable修饰的回调函数,则该合约账户无法接收用户的转账

触发条件:

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

ABI编码

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

  • abi.encode(...) returns (bytes):计算参数的ABI编码。
  • abi. encodeWithSelector(bytes4 selector, ...) returns (bytes): 计算函数选择器和参数的ABI编码
  • abi.encodeWithSignature(string signature, ...) returns (bytes): 等价于* abi.encodeWithSelector(bytes4(keccak256(signature), ...)

一般用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;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_34357267/article/details/86795337