繁体   English   中英

如何获取另一个合约部署的合约的地址

[英]How to get the address of a contract deployed by another contract

-----开始编辑-----

我不知道我之前做错了什么,但下面的代码不知何故对我不起作用,现在可以工作了,而且完全一样。 我不知道我以前是怎么错过的或错过了什么,但这个最小的例子和我正在做的真实项目现在都在工作。 显然我改变了一些东西,但我不知道是什么。 我只知道它现在正在工作。 抱歉造成混淆,感谢大家的帮助。

-----结束编辑-----

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

我已经尝试过这个问题的解决方案,但出现以下错误: Return argument type struct StorageFactory.ContractData storage ref is not implicitly convertible to expected type (type of first return variable) address.

这是我的代码:

// START EDIT (adding version)
pragma solidity ^0.8.0;
// END EDIT

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结构中? 谢谢。

我编译了你的合约,将其部署在 Remix 上,并且与此设置进行交互时没有问题

pragma solidity >=0.7.0 <0.9.0;

我想你以前的合同里有这个

 userAddressToStruct[_userAddress] = contractAddress;

而不是这个

 userAddressToStruct[_userAddress].contractAddress = contractAddress;

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

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

暂无
暂无

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

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