【问题标题】:Solidity: How to get the address of a contract deployed by another contractSolidity:如何获取另一个合约部署的合约地址
【发布时间】:2022-12-03 09:15:34
【问题描述】:

我是 Solidity 的新手,正在使用 Factory 模式从另一个合约部署合约。我试图获取已部署合约的合约地址,但我遇到了错误。

我已经在this question 中尝试了解决方案,但出现以下错误:Return argument type struct StorageFactory.ContractData storage ref is not implicitly convertible to expected type (type of first return variable) address.

这是我的代码:

contract StorageFactory {

  struct ContractData {
    address contractAddress; // I want to save the deployed contract address in a mapping that includes this struct
    bool exists;
  }

  // mapping from address of user who deployed new Storage contract => ContractData struct (which includes the contract address)
  mapping(address => ContractData) public userAddressToStruct;

  function createStorageContract(address _userAddress) public {

    // require that the user has not previously deployed a storage contract
    require(!userAddressToStruct[_userAddress].exists, "Account already exists");
    
    // TRYING TO GET THE ADDRESS OF THE NEWLY CREATED CONTRACT HERE, BUT GETTING AN ERROR
    address contractAddress = address(new StorageContract(_userAddress));

    // trying to save the contractAddress here but unable to isolate the contract address
    userAddressToStruct[_userAddress].contractAddress = contractAddress;
    userAddressToStruct[_userAddress].exists = true;
  }
}


// arbitrary StorageContract being deployed
contract StorageContract {
  address immutable deployedBy;

  constructor(address _deployedBy) {
    deployedBy = _deployedBy;
  }
}

我怎样才能得到这个合约地址,以便我可以将它存储在ContractData结构中?谢谢。

【问题讨论】:

    标签: ethereum solidity


    【解决方案1】:

    您可以使用以下代码获取已部署合约的地址:

    address contractAddress;
    (contractAddress,) = new StorageContract(_userAddress);
    userAddressToStruct[_userAddress].contractAddress = contractAddress;
    

    【讨论】:

      猜你喜欢
      • 2017-07-03
      • 2018-02-04
      • 2022-08-05
      • 2022-06-13
      • 2021-01-21
      • 1970-01-01
      • 2019-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多