0

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:

  1. The Factory contract's createNewContract method is called.
  2. A new instance of MyContract.sol is created at a new address.
  3. The address of the new MyContract instance is returned (to the front-end / node script etc).

What is actually happening:

  1. The Factory's createNewContract method is called.
  2. A new instance of Factory.sol is created (somehow - I think).
  3. 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!

3
  • Do you have a failed transaction hash we can examine? Are you sure the transaction completed successfully? The code seems fine.
    – Ismael
    Sep 20, 2021 at 0:13
  • 1
    Sure, here's the last factory I deployed: rinkeby.etherscan.io/address/… Sep 20, 2021 at 6:34
  • 1
    ...and here's the last time I tried to make a new contract instance: rinkeby.etherscan.io/address/…. I get data back successfully but the deployed contract is broken and odd, actually. Thanks for checking it out, the code seems fine to me too. Sep 20, 2021 at 6:40

1 Answer 1

0

Someone explained the solution elsewhere.

The issue was not with the code, rather in the way you use remote contracts in Remix: even though you are adding an established contract, you have to select the compiled contract that is at that address.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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