Modifiers in Solidity
Modifiers in Solidity
Modifiers, as the name suggests are something that modifies how a function would normally behave without them. The most common use case of Modifiers in Solidity is to check some prerequisite conditions before executing the function to perform what it is required to do. Modifiers can be reused in different function hence they reduce code redundancy and makes it easier to perform basic checks in the functions themselves, instead of having to test them externally. If the function does not meet the requirements of the Modifiers, it stops the execution and throws an error. You can create a Modifier by using the keyword 'modifier'.
Let's see how to create and use a Modifier in Solidity:
modifier sampleModifier (){
// your condition here
};
You can write a Modifier with and without an argument, if you want it to execute without an argument you can just emit the parentheses. Let's take a look at how what works
// Modifier With Arguments
modifier modifierWithArguments (uint z){
// your code here
};
// Modifier without Arguments
modifier modifierWithoutArguments (){
// your code here
};
// Modifier without Arguments and Parantheses
modifier modifierWithoutParantheses {
// your code here
};
As you can see above, creating a modifier in which you don't want to pass any arguments can be done with and without the use of Parentheses.
Let's see a real use case, where we want the user to pay a 5% fee to the smart contract before they withdraw their Ether out of it.
pragma solidity ^0.8.4
contract ModifierExamples {
modifier fee(uint _fee) {
if (msg.value != _fee) {
revert("A fee is to be paid to withdraw your ether from the smart contract");
} else {
_;
}
}
function deposit(address _user, uint _amount) external {
// your code here
}
function withdraw(uint _amount) external payable fee(0.05 ether) {
// your code here
}
}
}
As you can see above, in the modifier we are checking whether the msg. value is equal to the fee. If that is true the function continues executing.
If you have any questions, you can find me on my Twitter and LinkedIn