Solidity - 限制访问


限制访问合同是一种常见做法。默认情况下,合约状态是只读的,除非将其指定为公共状态。

我们可以限制谁可以修改合约的状态或使用修饰符调用合约的函数。我们将创建并使用多个修饰符,如下所述 -

  • onlyBy - 一旦在函数上使用,那么只有提到的调用者可以调用该函数。

  • onlyAfter - 一旦用于函数,则可以在特定时间段后调用该函数。

  • 成本- 一旦用于函数,则调用者仅在提供特定值时才能调用该函数。

例子

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