Where to use function modifiers
Function modifiers are simple snippets that can change the behavior of a contract. In this recipe, you will learn how to create and use function modifiers in solidity.
How to do it...
- Modifiers are declared with the
modifier
keyword as follows:
modifier modifierName { // modifier definition }
- The function body is inserted where the
_
symbol appears in the definition of a modifier:
modifier onlyOwner { require(msg.sender == owner); _; }
- Modifiers can accept parameters like functions do. The following example creates a generic modifier to verify the caller address:
contract Test { address owner; constructor() public { owner = msg.sender; } modifier onlyBy(address user) { require(msg.sender == user); _; } function donate() onlyBy(owner) public { // do something } }
- Multiple modifiers can be specified in a function. They will be evaluated in the order given:
contract modifierContract { address...