【问题标题】:How to Call contract inside another contarct in solidity version 0.5.2?如何在solidity 0.5.2版中调用另一个合约中的合约?
【发布时间】:2019-06-16 15:14:00
【问题描述】:

我使用的是solidity 0.5.2版

pragma solidity ^0.5.2;

contract CampaignFactory{
address[] public deployedCampaigns;

function createCampaign(uint minimum) public{
    address newCampaign  = new Campaign(minimum,msg.sender);  //Error 
//here!!!
    deployedCampaigns.push(newCampaign);
} 

function getDeployedCampaigns() public view returns(address[] memory){
    return deployedCampaigns;
}
}

我在分配调用 CampaignFactory 合约中的 Campaign 合约时遇到 错误

TypeError: Type contract Campaign is not implicitly convertible to expected 
type address.        
address newCampaign  = new Campaign(minimum,msg.sender);

我有另一个名为 Campaign 的合同,我想在 CampaignFactory 中访问它。

contract Campaign{
//some variable declarations and some codes here......

我的构造函数如下

constructor (uint minimum,address creator) public{
    manager=creator;
    minimumContribution=minimum;

}

【问题讨论】:

    标签: blockchain ethereum solidity smartcontracts remix


    【解决方案1】:

    你可以直接施放:

    address newCampaign = address(new Campaign(minimum,msg.sender));
    

    或者更好的是,停止使用address 并使用更具体的类型Campaign

    pragma solidity ^0.5.2;
    
    contract CampaignFactory{
        Campaign[] public deployedCampaigns;
    
        function createCampaign(uint minimum) public {
            Campaign newCampaign = new Campaign(minimum, msg.sender);
            deployedCampaigns.push(newCampaign);
        } 
    
        function getDeployedCampaigns() public view returns(Campaign[] memory) {
            return deployedCampaigns;
        }
    }
    

    【讨论】:

    • 成功了!谢谢@smarkx,我会记住你的建议。
    【解决方案2】:

    要从另一个合约调用现有合约,请在 cast 中传递合约地址

    pragma solidity ^0.5.1;
    
    contract D {
        uint x;
        constructor (uint a) public  {
            x = a;
        }
        function getX() public view returns(uint a)
        {
            return x;
        }
    }
    
    contract C {
    //DAddress : is the exsiting contract instance address after deployment
        function getValue(address DAddress) public view returns(uint a){
            D d =D(DAddress);
            a=d.getX();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-04
      • 2022-12-03
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-19
      • 2022-10-25
      • 2021-03-06
      相关资源
      最近更新 更多