Function Modifiers

Learn how to use function and multiple modifiers.

Modifiers can be used to change the behavior of functions in a declarative way. They can be considered as helper code that changes the behavior of functions. We can have modifiers that check access or the existence of certain data before the main function code is run.

Declaring modifiers

To declare modifiers, we use the modifier keyword, followed by the name and then the body of the modifier. The modifier body must contain at least one _; line. This line specifies the point where we wish to inject the body of the function called with the modifier.

Note: Modifiers do not return any value.

When using a defined modifier in a function, we place it just after the mutability type identifier. Here’s an example of a modifier:

Press + to interact
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract TestContract {
int public testNumber = 20;
modifier isGreaterThan5() {
require(testNumber > 5, "Test number is not greater than 5");
_;
}
function testFunction(int num1, int num2) external view isGreaterThan5 returns (int) {
int num3 = num1 + num2 + testNumber;
return num3;
}
}

The modifier simply checks if the current value of ...