
Reusable checks for smart contracts! This code can protect smart contract functions from being called by anyone except the contract owner.
require(msg.sender == owner, "Only owner can call this function!)
But instead of including this line in every single function of the smart contract, we need that confirmation. modifier
On the way! Modifiers are a special type of function in Solidity that can play a role. attribute
You can add it to other functions in your code.
modifier onlyOwner
require(msg.sender == owner, "Only owner can call this function!)
Now we can use this modifier to protect fe. withdraw()
The function is:
function withdraw() public onlyOwner
payable(msg.sender).calladdress(this).balance("");
What is going on here? Solidity ensures that: require
It first executes the condition in the function modifier and only executes all code in the function body if the condition passes. So what are some common use cases where modifiers can be used?
- Access Control:
address public owner;constructor()
owner = msg.sender;
modifier onlyOwner
require(msg.sender == owner, "Only owner can call this function");
_;
function changeOwner(address newOwner) public onlyOwner
owner = newOwner;
If the modifier has no arguments, the parentheses can be omitted.
2. Status verification:
enum ContractState Active, Inactive ContractState public currentState;
modifier onlyOwner
require(msg.sender == owner, "Only owner can call this function");
_;
modifier onlyIfActive
require(currentState == ContractState.Active, "Contract is not active");
_;
function deactivateContract() public onlyOwner
currentState = ContractState.Inactive;
function fund() public payable onlyIfActive
// Logic...
3. Time limit:
uint256 public specificDate = 1672531200; // Timestamp for the specific datemodifier onlyAfterSpecificDate
require(block.timestamp >= specificDate, "Function can only be called after the specific date");
_;
function placeOrder() public onlyAfterSpecificDate
// Order placement logic
4. Check amount:
modifier validateAmount(uint256 amount)
require(amount > 0, "Amount must be greater than zero");
_;
I hope you enjoy this little tour of the uses and use cases of modifiers in Solidity! Let us know in the comments which modifiers you find particularly useful and share your code with us!