Modifiers in Solidity — Usage and Use Cases

By akohad Dec1,2023

[ad_1]

Reusable checks for your Smart Contract! This code can protect a function of your Smart Contract from being called by anyone except the owner of the contract:

require(msg.sender == owner, "Only owner can call this function!)

But instead of including this line in every single function of your Smart Contract, that needs that check, a modifier is the way to go! Modifiers are a special type of function in Solidity that can act as a kind of attribute that you can add to any other function in your code.

modifier onlyOwner {
require(msg.sender == owner, "Only owner can call this function!)
}

We can now use this modifier to, f.e., guard our withdraw() function, like this:

function withdraw() public onlyOwner {
payable(msg.sender).call{address(this).balance}("");
}

What is happening here? Solidity checks the require condition from the function modifier first, and only if it passes the condition(s), executes whatever code comes in the function body. So what are some common use cases where you could use a modifier?

  1. 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;
}

Note that, if a modifier does not have any arguments, the parenthesis can be omitted.

2. State Validation:

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 restriction:

uint256 public specificDate = 1672531200; // Timestamp for the specific date

modifier onlyAfterSpecificDate {
require(block.timestamp >= specificDate, "Function can only be called after the specific date");
_;
}

function placeOrder() public onlyAfterSpecificDate {
// Order placement logic
}

4. Amount Validation:

modifier validateAmount(uint256 amount) {
require(amount > 0, "Amount must be greater than zero");
_;
}

Hope you enjoy this little journey into useage and use cases of modifiers in Solidity! Let me know in the comments what modifiers you find especially helpful and share the code with us!

[ad_2]

Source link

By akohad

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *