Build custom function modifiers to efficiently modify functionality.
public
functions can be called by anyone, without restriction. Often this is desirable. You want any user to be able to see what NFTs are for sale on your platform, sign up for a service, or read various items stored in state.
However, there will be many functions you don’t want any user to be able to do, such as setting the fee for using the app, or withdrawing all funds in the contract! A common pattern to protect these functions is to use modifier
s to make sure that only the owner can call these functions.
onlyOwner
, such as the one provided by OpenZeppelin.msg.sender
in the constructor
.
Reveal code
onlyOwner
Modifiermodifier
keyword. The modifier can run any Solidity code, including functions, and is allowed to modify state. Modifiers must have a special _
character, which serves as a placeholder for where the code contained within the modified function will run.
Create a simple onlyOwner
modifier, which returns an error
of NotOwner
with the sending address if the sender is not the owner.
Reveal code
modifier
by adding a function that uses it:
Reveal code
iOwnThis
function. You should see the message “You own this!”.
Next, switch the Account, and try the function again. You should see an error in the console:
modifiers
are used to modify functions and can share inputs, they have separate scopes. The following example will not work:
modifier
s are an efficient and reusable way to add checks, trigger errors, and control function execution. In this lesson, you’ve seen examples of how they can be used to abort execution under certain conditions. You’ve also learned that they have separate scopes and cannot be used to modify variables within the function they modify.