带有地址参数的 Solidity 默认构造函数

Solidity default constructor with address parameter

在学习 Solidity 时,我很难理解下面的 isApprovedForAll 函数的实际工作原理。

特别是我想了解如何使用 address 参数调用默认 ProxyRegistry 构造函数来创建初始 mapping,初始映射是什么样的,以及为什么我应该期望 if 语句永远 return 为真。

代码取自官方 OpenSea api 示例。

contract OwnableDelegateProxy {}

contract ProxyRegistry {
    mapping(address => OwnableDelegateProxy) public proxies;
}

contract SomeContract {

    address proxyRegistryAddress;

    constructor(
        address _proxyRegistryAddress
    ) {
        proxyRegistryAddress = _proxyRegistryAddress;
    }

    function isApprovedForAll(address owner, address operator)
        public
        view
        returns (bool)
    {
        ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
        if (address(proxyRegistry.proxies(owner)) == operator) {
            return true;
        }
        return false;
    }
}
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);

这一行不调用 ProxyRegistry 构造函数。它创建一个指向 proxyRegistryAddress 地址的辅助对象 (名为 proxyRegistry,并假设有一个合约实现了 ProxyRegistry 合约中定义的函数。

在这种情况下,只定义 interface ProxyRegistry { 而不是 contract ProxyRegistry {.

可能会更容易混淆

但是如果你想将 ProxyRegistry 合约部署到一个新地址并调用它的构造函数,你需要使用 new 关键字:

new ProxyRegistry(<constructor_params>);

if (address(proxyRegistry.proxies(owner)) == operator) {
    return true;
}

此代码段调用远程合约上的 autogenerated getter 函数 proxies(address),通过其键检索映射值。如果远程映射值等于 operator 值,则 returns true.