Solidity, create contract from contract

  • Based on documentation it should be possible to create new contract from contract

    contractAddress = new OwnedToken(name);
    

    When I invoke this method from contract, the address I receive seems to be normal address and not contract.

    Is this even possible (I remember I read somewhere that only normal accounts can send contract creating transactions)?

  • Hcharlanes

    Hcharlanes Correct answer

    5 years ago

    Is this even possible (I remember I read somewhere that only normal accounts can send contract creating transactions)?

    This is definitely possible.

    When I invoke this method from contract, the address I receive seems to be normal address and not contract.

    I'm not sure which address you are talking about. This kind of design works well:

    contract Factory {
        address[] newContracts;
    
        function createContract (bytes32 name) {
            address newContract = new Contract(name);
            newContracts.push(newContract);
        } 
    }
    
    contract Contract {
        bytes32 public Name;
    
        function Contract (bytes32 name) {
            Name = name;
        }
    }
    

    In the array newContracts, you will have the addresses of the Contracts created by the factory.

    Then if you want to call the Name from the first Contract created in the Factory contract, you should use :

    con.Name();
    

    after having defined

    Contract con = Contract(newContracts[0]);
    

    Thanks for answer. I tried and it works flawlessly. I had bug somewhere else in my contract. It seems etherscan.io does detect this kind of contract address correctly (if this is really a think). Is there any difference between contract created by contract or if it is created manually?

    @Ales No, difference between a contract that's created manually or by another contract. Some explorers don't show as much internals and you might see more at https://live.ether.camp

    @Hcharlanes, very useful example! Thanks! What's going to be the value of **msg.sender** in the Contract constructor? The address of the account that sent the transaction or the address where contract Factory is deployed?

    Won't this just return a Contract named after the address?

    Do you need to do new Contract() instaed of Contract()?

    If you want to access the contract object directly after creation take the createContract function line `address newContract = new Contract(name);` and replace `address` with `Contract` for inline instantiation.

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM