美文网首页gas优化
gas优化: 自定义error节省gas

gas优化: 自定义error节省gas

作者: 梁帆 | 来源:发表于2022-11-03 11:53 被阅读0次

自定义error是solidity 0.8.4 版本才提出来的新特性。在文档中,有这么一段:

Errors allow you to define descriptive names and data for failure situations. Errors can be used in revert statements. In comparison to string descriptions, errors are much cheaper and allow you to encode additional data.

它这里提到:与字符串描述相比,自定义error要便宜得多
这里我们就以以下合约为例:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

error NotEnoughFunds(uint256 needed, uint256 balance);

contract A {
    uint256 needed = 110;
    uint256 balance = 100;

    function judge() external {
        if(balance < needed ) {
            revert NotEnoughFunds(needed, balance);
        }
        balance -= needed;
    }
}

contract B {
    uint256 needed = 110;
    uint256 balance = 100;

    function judge() external {
        if(balance < needed ) {
            revert ("NotEnoughFunds,needed:110,balance:100)");
        }
        balance -= needed;
    }
}

在合约A中,我们用了自定义error,而在合约B中,我们选择用字符串输出同等关键信息,部署时可以发现gas消耗如下:

合约 revert类型 gas消耗量
A 自定义error 207038
B 字符串 231278

可以发现采用自定义error能节省30000多gas,如果合约中的revert信息够多,那么采用自定义error,就确实能节约大量的gas。

相关文章

网友评论

    本文标题:gas优化: 自定义error节省gas

    本文链接:https://www.haomeiwen.com/subject/uxgytdtx.html