代码之家  ›  专栏  ›  技术社区  ›  GG123GG

坚实度修饰符

  •  2
  • GG123GG  · 技术社区  · 7 年前

    所以,作为关于solidity的bitdegree课程的一部分,我希望创建一个名为onlyOwner的修饰符,并将其指定给changePrice函数。我必须确保只有当发送者的地址与所有者的地址匹配时,修饰符才允许执行函数。可以使用msg获取发件人地址。发件人。

    我尝试输入这个来创建修改器,但它对我不起作用,我不知道为什么。如有任何帮助/推荐代码,将不胜感激!

    pragma solidity ^0.4.17;
    
    contract ModifiersTutorial {
    
    address public owner;
    uint256 public price = 0;
    address public sender=msg.sender;
    
    //
    modifier onlyOwner(sender){
    if (owner==sender);
    }
    //
    
    // Use your modifier on the function below
    function changePrice(uint256 _price) public onlyOwner {
        price = _price;
    }
    
    function ModifiersTutorial () {
        owner = msg.sender; // msg.sender in constructor equals to the address that created the contract
    }
    

    }

    3 回复  |  直到 7 年前
        1
  •  1
  •   Adam Kipnis    7 年前

    您的修改器代码不正确。您需要下划线才能继续。

    modifier onlyOwner(sender){
      if (owner==sender) _; // Note the underscore
    }
    

    此外,出于安全原因,您确实应该使用 msg.sender 而不是把它传进来。

    modifier onlyOwner() {
      if (owner == msg.sender) _;
    }
    
        2
  •  1
  •   kronosapiens    5 年前

    不确定它是否与您收到的规范冲突,但另一种做法是 require(owner == msg.sender) 而不是使用 if 语句——前者告诉用户发生了什么,而后者只是无声地失败。它可能是这样的:

    modifier onlyOwner(){
      require(owner == msg.sender, "error-only-owner");
      _;
    }
    
        3
  •  -1
  •   pushkin Void Star    6 年前
    pragma solidity ^0.4.17;
    
    contract ModifiersTutorial {
    
        address public owner;
        uint256 public price = 0;
    
        modifier onlyOwner(){
        if( owner == msg.sender ) _;
        }
    
        function changePrice(uint256 _price) public onlyOwner{
            price = _price;
        }
    
        function ModifiersTutorial () {
            owner = msg.sender; 
        }
    }