1

想知道是否有人可以解释这一点。我正在学习 freeCodeCamp.org 的“Solidity, Blockchain, and Smart Contract Course - Beginner to Expert Python Tutorial”。

在第二课中,我们创建了一个合约工厂,我们在其中存储了一个合约数组,然后创建了一个函数来通过索引检索合约并在其上调用一个函数。

他是这样做的:SimpleStorage(address(simpleStorages[_simpleStorageIndex])).store(_simpleStorageNumber)

我不明白 SimpleStorage(address(...)) 部分。我了解对数组进行索引并获取存储,但是我对其进行了测试,并且效果相同:simpleStorages[_simpleStorageIndex].store(_simpleStorageNumber)

这个地址功能是什么?我假设它获取合约实例的地址。那么为什么我们将它传递给 SimpleStorage 的构造函数(?)?为什么在不通过地址的情况下在实例本身上调用 store 时执行所有这些操作。

谢谢!!

编辑:整个合同:

// SPDX-License-Identifier: MIT

pragma solidity ^0.6.0;

import "./SimpleStorage.sol";

contract StorageFactory is SimpleStorage { // is SimpleStorgae = inheritance 

    SimpleStorage[] public simpleStorages;

    function createSimpleStorageContract() public {
        SimpleStorage simpleStorage = new SimpleStorage();
        simpleStorages.push(simpleStorage);
    }

    function sfStore(uint256 _simpleStorageIndex, uint256 _simpleStorageNumber) public {
        // Anytime you interact with a contract you need two things:
        // Address
        // ABI - Application Binary Interface
        return simpleStorages[_simpleStorageIndex].store(_simpleStorageNumber);
        //return SimpleStorage(address(simpleStorages[_simpleStorageIndex])).store(_simpleStorageNumber);
    }

    function sfGet(uint256 _simpleStorageIndex) public view returns(uint256) {
        return SimpleStorage(address(simpleStorages[_simpleStorageIndex])).retrieve();
    }
}
4

1 回答 1

1

您的方法是store()直接在项目上调用函数,实际上是一种更直接的方法,可以实现与讲师代码相同的结果。

所以回答你的问题:

这个地址功能是什么?我假设它获取合约实例的地址。

正确的。即使simpleStorages[_simpleStorageIndex]不存储实际SimpleStorage实例。在你的合约中,它只存储一个包含指向外部合约地址的指针的辅助对象,以及SimpleStorage(但不是外部合约的实际实例)的接口定义。

将辅助对象类型转换为 anaddress返回外部合约的地址。

那为什么我们将它传递给 SimpleStorage 的构造函数(?)

您没有将它传递给SimpleStorage构造函数 - 那将是new SimpleStorage(<constructor_params>)关键字new(有效地将合同部署SimpleStorage到新地址)。您正在实例化上述帮助对象,并将外部合约地址传递给它。

为什么在不通过地址的情况下在实例本身上调用 store 时执行所有这些操作。

我不知道讲师在这段代码背后的意图。也许他们稍后会在课程中使用它来描述一些优化或作为展示其他主题的桥梁。但两种方式都有效。

于 2021-11-26T17:18:23.167 回答