modifier --require逻辑用方法封装后调用会更省gas吗?修饰的方法越多会剩gas吗

请看测试结论:

// SPDX-License-Identifier: MIT

pragma solidity 0.8.20;

import "hardhat/console.sol";


contract modifierTest {

address public owner;

modifier onlyOwner() {

//require(owner == msg.sender, "Ownable: caller is not the owner");

_checkOwner();

_;

}


// Gas cost: deploy--85863 add funtion--execution:901790

function add() public onlyOwner {

}


function addone() public onlyOwner {

}

function addtwo() public onlyOwner {

}


function _checkOwner() internal view virtual {

// console.log("Owner :", owner);

// console.log("Owner exec by:", msg.sender);

require(owner == msg.sender, "Ownable: caller is not the owner");

}

}

//直接在修饰器中执行逻辑

//add-require

//transaction cost:23635 execution cost:2571

//把具体逻辑放在方法中,然后再修饰器中执行

//add-_checkOwner

//transaction cost:23650 execution cost:2586

感兴趣的话,可以自己对比下add-require和add-_checkOwner的字节码,就知道什么原因是这样了

// 以下是修饰多个方法的场景消耗gas的结果

//2 add--修改两个方法

//require

//transaction cost:203979 execution cost:140181

//_checkOwner

//transaction cost:177673 execution cost:115563

//3 add--修饰三个方法

//require

//transaction cost:239072 execution cost:173012

//_checkOwner

//transaction cost:184299 execution cost:121763

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值