【问题标题】:Use of address function inside a contract constructor?在合约构造函数中使用地址函数?
【发布时间】:2022-01-04 16:47:37
【问题描述】:

想知道是否有人可以解释这一点。我正在学习 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();
    }
}

【问题讨论】:

  • 能否附上合同全文?
  • 更新完整合同

标签: blockchain ethereum solid


【解决方案1】:

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

所以回答你的问题:

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

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

将帮助对象类型转换为 address 会返回外部合约的地址。

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

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

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

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

【讨论】:

    猜你喜欢
    • 2021-08-14
    • 2019-02-07
    • 2020-11-14
    • 1970-01-01
    • 2012-04-01
    • 1970-01-01
    • 2019-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多