What are solidity function modifiers?

Overview

Modifiers assist in the execution of a function’s behavior. The behavior of a function can be changed using a function modifier, they can also be called before or after a function is executed.

Solidity function modifiers help in the following:

  • To access restrictions
  • Input accuracy checks
  • Hacks protection

Example

Let’s look at the code below:

pragma solidity ^0.5.12;
contract FuncModifier {
// We will use these variables to demonstrate how to use
// modifiers.
address public Host;
uint public x = 10;
bool public locked;
constructor()public {
// Set the transaction sender as the Host of the contract.
Host = msg.sender;
}
modifier onlyHost() {
require(msg.sender == Host, "Not Host");
_;
}
//Inputs can be passed to a modiier
modifier validAddress(address _addr) {
require(_addr != address(0), "Not valid address");
_;
}
function changeHost(address _newHost) public onlyHost validAddress(_newHost) {
Host = _newHost;
}
// Modifiers can be called before and / or after a function.
// This modifier prevents a function from being called while
// it is still executing.
modifier noReentrancy() {
require(!locked, "No reentrancy");
locked = true;
_;
locked = false;
}
function decrement(uint i) public noReentrancy {
x -= i;
if (i > 1) {
decrement(i - 1);
}
}
}

Explanation

  • Line 4: We create a contract FuncModifier.

  • Lines 7 to 9: We create some variables and use them to demonstrate how to use modifiers.

  • Lines 11 to 14: We set the transaction sender as the Host of the contract.

  • Line 17: We use the modifier in the onlyhost function, to check that the caller is the Host of the contract.

  • Line 19: We see the underscore, the underscore is a special character only used inside a function modifier and it tells Solidity to execute the rest of the code.

  • Line 24: This modifier checks that the address passed in is not the zero address.

  • Line 36: This modifier prevents a function from being called while it is still executing. As modifiers can be called before and/or after a function.

Free Resources