3

I'm in the process of learning Solidity. I came across this code and find it confusing. I understand the use of onlyOwner modifier which is to restrict access only to the owner and public modifier to allow the function to be called inside or outside. But what does it mean to put "public" and "onlyOwner" together since the only person can call the function is the owner? In other words, what is the use of public in the function?

// contracts/MyContract.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/access/Ownable.sol";

contract MyContract is Ownable {
    function normalThing() public {
        // anyone can call this normalThing()
    }

    function specialThing() public onlyOwner {
        // only the owner can call specialThing()!
    }
}

1 Answer 1

2

public is a function visibility specifier, like external, internal and private. It specifies whether a function can be called publicly (i.e., by everyone), or privately (i.e., only by the contract itself).

When a function is public (or external) it means that it's possible to call that function outside of that contract, so people could send a transaction to call it, and other contracts can call the function too.

The visibility specifier is separate from modifiers (like onlyOwner). It only changes who can call the function. When the function is called, modifiers are still executed normally, regardless of the visibility, so in your case if someone who isn't an owner calls specialThing, the call will still be reverted because onlyOwner is called.

2
  • 1
    So let's say if someone who is not the owner of the contract wants to access the function but can't do so due to the modifier, what's the purpose of having public or external visibility specifier for the function? Since the function already has modifier to filter out people who can access it.
    – normies
    Jan 31, 2022 at 17:19
  • 2
    Because if it's not public or external it cannot be called by anyone. Including the owner
    – Foxxxey
    Feb 1, 2022 at 6:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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