modifier in solidity

modifier is used to declare some code that will be re-used throughout the contract.
Write once, use everywhere.
For example, instead of doing the require check on owner, declare this modifier:

modifier onlyOwner {
   require(msg.sender == owner, "Only contract owner can do this");
   _; // run the function
}

and can now reuse this in any function, like this:

function addBalance(uint _toAdd) public onlyOwner returns(uint) {
   // code in onlyOwner will execute first
   // and only if require check passes will this code below run
   balance[msg.sender] += _toAdd;
   return balance[msg.sender];
}

The modifier is used in the function header just before the returns keyword.
It can also take in arguments, but those need to be fixed, not variables.

modifier costs(uint price) {
    require(msg.value >= price);
    _;
}

// argument to costs needs to be a fixed value, not variable
function transfer(address recipient, uint amount) costs(100) public {
    ...
}
Show Comments