5

If you create a function that you only want the owner to interact with would you use

require(msg.sender == owner)

or

modifier onlyOwner() {
    require(msg.sender == owner);
    _;
}

Which would be the most cost efficient for smart contracts, since both essentially do the same thing?

11

It seems ideally both are same. It's like you could require(msg.sender == owner) instead of using a modifier if only one or two times you use it. Else you could declare a modifier and append it before functions. It just the matter of practice and convenience.

I tried estimating gas of a simple smart contract using both modifier and require, results were arrantly same.

Testcase1:

pragma solidity ^0.4.11;

    contract A{
        uint a =10;
        address owner;
        function A(){
            owner = msg.sender;
        }
        modifier onlyOwner(){
            require(msg.sender == owner);
            _;
        }

        function updateValue(uint a) onlyOwner {
            a = a+10;
        }
    }

Gas Estimates:

{
    "Creation": "40366 + 48800\n",
    "External": {
        "updateValue(uint256)": 454
    },
    "Internal": {}
}

TestCase2:

Code:

pragma solidity ^0.4.11;

contract A{
    uint a =10;
    address owner;
    function A(){
        owner = msg.sender;
    }

    function updateValue(uint a) {
        require(msg.sender == owner);
        a = a+10;
    }
}

Gas Estimates:

{
    "Creation": "40366 + 48800\n",
    "External": {
        "updateValue(uint256)": 454
    },
    "Internal": {}
}

Since gas estimates are same in both cases, it seems both are perfectly fine (at least in terms of fee).

  • what tool or how did you find the gas usage information? – JVK Mar 5 '18 at 7:37
  • Your code fails to compile at Remix – JVK Mar 7 '18 at 6:29
  • No. It doesn't. It gives some warnings like NO visibility specifier. But since the objective of this piece of code was to test the gas estimates, we can live with such warnings. – Prashant Prabhakar Singh Mar 7 '18 at 7:31
4

As Prashant Prabhakar Singh pointed out there is no difference in terms of gas usage. But keep in mind that modifiers may add to stack as it is illustrated in this solidity github issue.

If you get a "stack too deep" exception use require or put it into a function instead of a modifier.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.