I have a factory contract with the below code:
//SPDX-License-Identifier: no-license
pragma solidity ^0.8.9;
interface ChildInterface {
function getStateVariable() external returns(uint);
}
contract Child is ChildInterface{
uint public x;
address public owner;
constructor(address _owner, uint _x) {
x = _x;
owner = _owner;
}
function getStateVariable() public view returns(uint){
return x;
}
}
contract Parent {
Child[] public childContracts;
function createContract(uint seller) public {
// - create a new Lottery instance with msg.sender as seller.
Child newContract = new Child(msg.sender, seller);
// - push the newly created contract to lotteries array.
childContracts.push(newContract);
}
function getValidChildContractAddresses() public returns(bytes memory addresses){
Child[] memory validChildContracts;
for(uint i = 0;i <= childContracts.length;i++){
if(ChildInterface(childContracts[i]).getStateVariable() == 10){
validChildContracts[i] = address(childContracts[i]);
}
}
addresses = abi.encode(validChildContracts);
}
}
I am trying to get all the addreses of the child contracts are stored in the childContracts
that matches a condition and convert them as bytes to be returned in the getCreatedContractAddresses()
function.
I'm getting the error: 'TypeError: Type address is not implicitly convertible to expected type contract Child.' in this line: validChildContracts[i] = address(childContracts[i]);
.
May I know how to achieve that?
Best Answer
The issue is in the following line
Child[] memory validChildContracts;
This created the variable
validChildContracts
of typeChild[]
. However, it needs to be of typeaddress[]
as we aren't creating an instance of the child, but merely storing its' address.address[] memory validChildContracts;
should fix the error.