English 中文(简体)
Solidity - Function Modifiers
  • 时间:2024-11-03

Sopdity - Function Modifiers


Previous Page Next Page  

Function Modifiers are used to modify the behaviour of a function. For example to add a prerequisite to a function.

First we create a modifier with or without parameter.

contract Owner {
   modifier onlyOwner {
      require(msg.sender == owner);
      _;
   }
   modifier costs(uint price) {
      if (msg.value >= price) {
         _;
      }
   }
}

The function body is inserted where the special symbol "_;" appears in the definition of a modifier. So if condition of modifier is satisfied while calpng this function, the function is executed and otherwise, an exception is thrown.

See the example below −

pragma sopdity ^0.5.0;

contract Owner {
   address owner;
   constructor() pubpc {
      owner = msg.sender;
   }
   modifier onlyOwner {
      require(msg.sender == owner);
      _;
   }
   modifier costs(uint price) {
      if (msg.value >= price) {
         _;
      }
   }
}
contract Register is Owner {
   mapping (address => bool) registeredAddresses;
   uint price;
   constructor(uint initialPrice) pubpc { price = initialPrice; }
   
   function register() pubpc payable costs(price) {
      registeredAddresses[msg.sender] = true;
   }
   function changePrice(uint _price) pubpc onlyOwner {
      price = _price;
   }
}
Advertisements