[实践]solidity 0.4.22版本发布,新功能实践

solidity team 发布了0.4.22版本,比较重要的更新如下

  1. 支持不同合约的函数调用,通过返回值传递动态的数据类型(array, string等)

举个例子

pragma solidity ^0.4.22;

contract Child {
    string public name = "child";
}

contract Parents {
    string public childName;
    Child child;
    function Parents (address _childAddress) public {
        child = Child(_childAddress);
        childName = child.name();  // Invalid before 0.4.22
    }
}

child.name()返回了动态长度的string类型,新版本已经可以支持。

之前的相关讨论:
https://ethereum.stackexchange.com/questions/3727/contract-reading-a-string-returned-by-another-contract/3788#3788

  1. revert() /require() 函数,支持返回error message
pragma solidity ^0.4.22;

contract VendingMachine {
    function buy(uint amount) payable {
        if (amount > msg.value / 2 ether)
            revert("Not enough Ether provided.");
        // Alternative way to do it:
        require(
            amount <= msg.value / 2 ether,
            "Not enough Ether provided."
        );
        // Perform the purchase.
    }
}

通过返回错误信息,对于合约开发更为友好。(第三方的支持工具仍在开发中)

  1. 构造函数,现在需要显示命名为constructor。
pragma solidity ^0.4.22;
contract Parents {
    string public childName;
    Child child;
    function Parents (address _childAddress) public {
        child = Child(_childAddress);
        childName = child.name();  // Invalid before 0.4.22
    }
}

上面的代码,在0.4.22会报出warning
Defining constructors as function with the same name as constract is deprecated.
Use "constructor(...) { ... }" instead.

意思是建议使用显式的constructor来命名构造函数,以防止编译器把Parents认为普通函数从而避免一些bug。

  1. 增加了ABI enconding 系列函数,返回值是bytes
    abi.encode()
    abi.encodePacked()
    abi.encodeWithSelector()
    abi.encodeWithSignature()

decoding谢列仍在排队中
https://github.com/ethereum/solidity/issues/3876

  1. 数组的一些操作所消耗的gas更为便宜,比如push和memory array的初始化。

  2. 更多细节
    https://github.com/ethereum/solidity/releases/tag/v0.4.22

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容