1

My code works with compiler 0.4.25 but not with the latest version. I want to keep track of every "Contract 2" that "Contract 1" create.

Contract 1

uint public countContract;
address[] public deployedContracts;

function createContract(string memory _name) 
public{       
    address newContract = new Contract2(countContract++, _name);
    deployedContracts.push(newContract);
 }

Contract 2

uint public id;
string public name; 

constructor(uint _id, string memory _name) 
public{
    id = _id;
    name = _name;
}

The error I am receiving on Remix is:

browser/temp.sol:9:5: TypeError: Type contract Contract2 is not implicitly convertible to expected type address. address newContract = new Contract2(countContract++, _name);

2

In Solidity 0.5, you need to explicitly store the type of the contract being created (as opposed to simply using the address type). Use the following code to achieve your goals:

Contract 1:

uint public countContract;
Contract2[] public deployedContracts;

function createContract(string memory _name) 
    public
 {       
    Contract2 newContract = new Contract2(countContract++, _name);
    deployedContracts.push(newContract);
 }

Contract 2:

uint public id;
string public name; 

constructor(uint _id, string memory _name) 
    public
{
    id = _id;
    name = _name;
}

Note: you will still add the address of the contract to the array, just as you were doing in 0.4.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.