简体   繁体   中英

How to Call contract inside another contarct in solidity version 0.5.2?

I'm using solidity version 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;
}
}

I'm getting the error while assigning calling the Campaign contract inside CampaignFactory contract

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

I have another contract called Campaign which i want to access inside CampaignFactory.

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

and I have the constructor as below

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

}

You can just cast it:

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

Or better yet, stop using address and use the more specific type 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;
    }
}

To call an existing contract from another contract ,pass the contract address inside 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();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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