Function Modifiers are used to modify the behavior of a function. For example to add a prerequisite to a function.
Modifier
Modifiers are code that can be run before and / or after a function call.Solidity documentation defined modifier as follow:
“A function modifier is a compile-time source code roll-up.
It can be used to amend the semantics of functions in a declarative way.”
Modifiers can be used to:
- Restrict access
- Validate inputs
- Guard against reentrancy hack
let’s assume we deployed a smart contract on blockchain.everyone can interact to our smart contract and also has access to our contract and functions. in this way everyone can call all of functions and sign a transaction. this is where we use modifiers.Using modifier we can check the conditions before executing functions.
Syntax:
modifier Modifier_Name{
// modifier code goes here...
}
Example:
modifier onlyOwner {
require(msg.sender == owner);
_;
}
in the code above , function will be executed if transaction sender is contract owner.
let’s go deeper with other example to better understand.
pragma solidity ^0.8.10;
contract Bank {
uint private _value;
adresse private _owner;
function Bank(uint amount){
value = amount;
owner = msg.sender;
}
modifier _ownerFunction {
require(owner == msg.sender);
_;
}
}
let’s assume we have a virtual bank.in the example above only contract owner can execute the function.Now we specify the requirement with require. The owner and the message of the creator must be the same. Only the address of the creator is compared with that of the sender. If this statement is true, the code is processed. If this statement is false, nothing happens. Then we set “_” so that the function is always executed first. This will display an error if someone who is not the creator of the smart contract wants to change something. Now we just need to add ownerFunction to each function where we don’t want anyone other than the creator to be able to change anything.
let’s back to previous example:
modifier onlyOwner {
require(msg.sender == owner);
_;
}
now we wanna know how does modifier works.
The symbol _;
is called a merge wildcard. It merges the function code with the modifier code where the _;
is placed.The place where you write the _;
symbol will decide if the function has to be executed before, in between or after the modifier code.
Passing arguments to Modifiers
Modifiers can also accept arguments. Like a function, you just have to pass the variable type + name between parentheses in front of the modifier name.
Syntax:
You can write a modifier with or without arguments. If the modifier does not have argument, you can omit the parentheses ()
.
modifier MyModifier(uint a) {
// ...
}modifier MyModifier() {
// ...
}
Example:
modifier Fee (uint _fee) {
if (msg.value >= _fee) {
_;
}
}
New to trading? Try crypto trading bots or copy trading