如何在solidity 0.5.2版中调用另一个合约中的合约?

Posted

技术标签:

【中文标题】如何在solidity 0.5.2版中调用另一个合约中的合约?【英文标题】:How to Call contract inside another contarct in solidity version 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;


【问题讨论】:

【参考方案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();
    

【讨论】:

以上是关于如何在solidity 0.5.2版中调用另一个合约中的合约?的主要内容,如果未能解决你的问题,请参考以下文章

solidity[1]-HelloWorld

如何在Objective C中遵循SOLID原则向现有方法添加另一个参数

Solidity极简入门#22. Call

深入了解以太坊虚拟机第4部分——ABI编码外部方法调用的方式

如何调用 Solidity 函数从智能合约中返回以太币?

如何在保持访问权限不变的同时将 Firestore 文档从一个子集合共享到另一个子集合?