Solidity – 限制(restricted)访问

对合约进行访问限制,是一种常见做法。默认情况下合约是只读的,除非将合约状态指定为public。

使用限制访问修饰符,我们可以限制谁能修改合约状态,或者调用合约函数等操作。

下面示例中,创建了多个修饰符:

  • onlyBy 限制可以调用该函数的调用者(根据地址)。
  • onlyAfter 限制该函数只能在特定的时间段之后调用。
  • costs 调用方只能在提供特定值的情况下调用此函数。。

示例

pragma solidity ^0.5.0;

contract Test {
   address public owner = msg.sender;
   uint public creationTime = now;

   modifier onlyBy(address _account) {
      require(
         msg.sender == _account,
         "Sender not authorized."
      );
      _;
   }
   function changeOwner(address _newOwner) public onlyBy(owner) {
      owner = _newOwner;
   }
   modifier onlyAfter(uint _time) {
      require(
         now >= _time,
         "Function called too early."
      );
      _;
   }
   function disown() public onlyBy(owner) onlyAfter(creationTime + 6 weeks) {
      delete owner;
   }
   modifier costs(uint _amount) {
      require(
         msg.value >= _amount,
         "Not enough Ether provided."
      );
      _;
      if (msg.value > _amount)
         msg.sender.transfer(msg.value - _amount);
   }
   function forceOwnerChange(address _newOwner) public payable costs(200 ether) {
      owner = _newOwner;
      if (uint(owner) & 0 == 1) return;        
   }
}


浙ICP备17015664号 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载