2

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

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

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
}

}

4

3 回答 3

1

您的修饰符代码不正确。您需要一个下划线才能继续。

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

此外,出于安全原因,您真的应该只使用msg.sender而不是传递它。

modifier onlyOwner() {
  if (owner == msg.sender) _;
}
于 2018-01-23T19:32:20.863 回答
1

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

modifier onlyOwner(){
  require(owner == msg.sender, "error-only-owner");
  _;
}
于 2019-11-14T08:02:48.473 回答
-1
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; 
    }
}
于 2018-07-16T16:40:53.473 回答