12

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?

JorahFriendzone
  • 517
  • 1
  • 8
  • 22

3 Answers3

18

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).

Prashant Prabhakar Singh
  • 8,026
  • 5
  • 40
  • 79
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.

takeshi
  • 1,760
  • 1
  • 13
  • 33
1

from my point of view I see modifier as a way to arrange the code more thats it . like for example you have a contract for a game and in many places you need to check is the user PLAYER or ADMIN . instead of doing required here and there .

you arrange your logic by having one modifier for admin and other for player . and then use its as ...

this function only admin and that only player

you may say ok for small projects and the one of its kind we will user required ammm

but when the one of its kind became repeated are you sure you would remember to add the rest .

from the beginning you need to make modifiers for stuff that are repeated and make sense and keep the require for the function specific stuff.

thats my idea.

J.Tural
  • 131
  • 3