简体   繁体   English

OpenZeppelin 的可拥有合约 vs 需要 msg.sender

[英]OpenZeppelin's ownable contract vs require msg.sender

I am currently learning solidity through CryptoZombies and I came across a point where they say,"setKittyContractAddress is external", so anyone can call it, That means anyone who called the function could change the address of the CryptoKitties contract.我目前正在通过 CryptoZombies 学习 solidity,我遇到了一个点,他们说,“setKittyContractAddress 是外部的”,所以任何人都可以调用它,这意味着任何调用 function 的人都可以更改 CryptoKitties 合约的地址。 and break our app for all its users.并为所有用户破坏我们的应用程序。

We do want the ability to update this address in our contract, but we don't want everyone to be able to update it.我们确实希望能够在我们的合约中更新这个地址,但我们不希望每个人都能够更新它。

To handle cases like this, one common practice that has emerged is to make contracts Ownable — meaning they have an owner (you) who has special privileges.为了处理这样的情况,出现的一种常见做法是使合约成为可拥有的——这意味着它们有一个拥有特殊特权的所有者(你)。 Here is that function:这是 function:

function setKittyContractAddress(address _address) external {
kittyContract = KittyInterface(_address);
}

Now my question is that can we not just use msg.sender for this purpose.现在我的问题是,我们能否不只是为此目的使用 msg.sender。

I don't quite know how to do that though.我不太清楚该怎么做。

can we not just use msg.sender for this purpose难道我们不能仅仅为了这个目的使用 msg.sender

That's exactly what the OpenZeppelin Ownable does in the background.这正是 OpenZeppelin Ownable在后台所做的。 Through a series of steps, it sets the owner variable, and then validates msg.sender against it.通过一系列步骤,它设置owner变量,然后根据它验证msg.sender

modifier onlyOwner() {
    require(owner() == _msgSender(), "Ownable: caller is not the owner");
    _;
}

The owner() function returns the current owner address, and the _msgSender() function is a wrapper of the msg.sender global variable. owner() function 返回当前所有者地址,而_msgSender() function 是msg.sender全局变量的包装器。

Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.5.0/contracts/access/Ownable.sol#L43来源: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.5.0/contracts/access/Ownable.sol#L43

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM