I'm pretty sure I'm missing something really basic here, but my contract will only create new instances of itself (the factory), rather than of its subcontracts.
I've stripped the code down to the most basic parts and it's still not working as expected.
The expected behaviour is:
- The Factory contract's
createNewContract
method is called. - A new instance of MyContract.sol is created at a new address.
- The address of the new MyContract instance is returned (to the front-end / node script etc).
What is actually happening:
- The Factory's
createNewContract
method is called. - A new instance of Factory.sol is created (somehow - I think).
- The address of the new Factory contract is returned, but the contract is empty on Etherscan and can't be used.
Note: I've also tried emitting the address in an event, as well as a few other ways of storing or capturing the value, all with the same result (and always the same address that is returned in that invocation).
Here's my code:
MyContract.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
contract MyContract {
uint256 favoriteNumber;
constructor() {
favoriteNumber = 7;
}
function updateNumber(uint256 _newNumber) public {
favoriteNumber = _newNumber;
}
}
MyContractFactory.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
import "./MyContract.sol";
contract MyContractFactory {
uint256 public totalContracts;
constructor() {
totalContracts = 0;
}
function createNewContract()
public
returns (address _newContract)
{
MyContract myNewContract = new MyContract();
totalContracts++;
_newContract = address(myNewContract);
return _newContract;
}
}
I'd appreciate any help understanding what I'm clearly missing!