Complete the code to create a new contract instance using the factory.
contract MyFactory {
function create() public returns (address) {
[1] newContract = new SimpleContract();
return address(newContract);
}
}The factory creates a new instance of SimpleContract using the new keyword.
Complete the code to store the address of the created contract in the factory.
contract MyFactory {
address[] public contracts;
function create() public {
SimpleContract newContract = new SimpleContract();
contracts.[1](address(newContract));
}
}pop which removes elements instead of adding.The push method adds the new contract address to the contracts array.
Fix the error in the factory function to correctly emit an event after contract creation.
contract MyFactory {
event ContractCreated(address contractAddress);
function create() public {
SimpleContract newContract = new SimpleContract();
emit [1](address(newContract));
}
}The event declared is ContractCreated, so it must be emitted with that exact name.
Fill both blanks to define a factory that creates different contract types based on input.
contract Factory {
function create(uint8 typeId) public returns (address) {
if (typeId == 1) {
return address(new ContractA());
} else if (typeId == 2) {
return address(new [1]());
} else {
revert("Invalid type");
}
}
}
contract ContractA {}
contract [2] {}The factory creates ContractB when typeId is 2, so both blanks must be ContractB.
Fill all three blanks to implement a factory that creates contracts with an owner and stores them.
contract Owned {
address public owner;
constructor(address _owner) {
owner = _owner;
}
}
contract Factory {
address[] public contracts;
function create(address _owner) public returns (address) {
Owned newContract = new Owned([1]);
contracts.[2](address(newContract));
emit Created([3]);
return address(newContract);
}
event Created(address contractAddress);
}The constructor needs _owner as argument, the contract address is pushed to the array, and the event emits the new contract's address.