Modifiers

Learn about function modifiers in Solidity.

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:

Press + to interact
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.

Press + to interact
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;
contract Storage {
//Declaring state variable of uint type
uint256 public number;
address public owner;
constructor(){
//Setting the owner address with the value of deployer
owner = msg.sender;
//Invoking a getIncrementNumber function
incrementedNumberBy(1);
}
//Modifier without parameter to check owner before execution
modifier onlyOwner(){
require(owner == msg.sender, "not an owner");
_;
}
//Modifier with parameter to validate function parameter
modifier isGreaterThanZero(uint _num){
require(_num > 0);
_;
}
//Declaring a function to increment a value by parameter provided
function incrementedNumberBy(uint _num) public view onlyOwner isGreaterThanZero(_num) returns(uint){
//Local variable Nonce
uint nonce = number +_num;
//Return statement to return final output of number
return 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 type uint256 ...