Modifiers
Learn about function modifiers in Solidity.
We'll cover the following...
Understanding modifiers
Function modifiers change the behavior of a function by adding requirements. The function body is placed wherever the special symbol _;
appears in a modifier’s definition. So, if the modifier condition is met while invoking this method, the function is executed; otherwise, an exception is raised.
Here’s the syntax to declare a modifier:
modifier <modifier_name>(<parameter-list>) {//Code to execute//ending with special symbol_;}
Modifiers in Solidity are defined by using the modifier
keyword, followed by a name and a code block. These code blocks frequently include criteria to be met for the function to be executed correctly. When a function employs a modifier, the code included within it is executed first, followed by the function itself.
// SPDX-License-Identifier: MITpragma solidity ^0.8.17;contract Storage {//Declaring state variable of uint typeuint256 public number;address public owner;constructor(){//Setting the owner address with the value of deployerowner = msg.sender;//Invoking a getIncrementNumber functionincrementedNumberBy(1);}//Modifier without parameter to check owner before executionmodifier onlyOwner(){require(owner == msg.sender, "not an owner");_;}//Modifier with parameter to validate function parametermodifier isGreaterThanZero(uint _num){require(_num > 0);_;}//Declaring a function to increment a value by parameter providedfunction incrementedNumberBy(uint _num) public view onlyOwner isGreaterThanZero(_num) returns(uint){//Local variable Nonceuint nonce = number +_num;//Return statement to return final output of numberreturn nonce;}}
Line 3: We declare a contract named
Storage
.Lines 5–6: We declare two state variables:
number
: We declare this state variable of the typeuint256
...