[Ethereum] How to access the address of a contract created by another contract

contract-developmentcontract-invocationweb3js

I am having problems in accessing the address of a new contract generated within another contract acting as Factory.
My code:

contract Object {

    string name;
    function Object(String _name) {
        name = _name
    }
}

contract ObjectFactory {
    function createObject(string name) returns (address objectAddress) {
        return address(new Object(name));
    }
}

when I compile and execute the method createObject(''), I expect to be returned the address of the new contract.
Instead, I receive the hash of the transaction.
I use Web3 to execute the function:

var address = web3.eth.contract(objectFactoryAbi)
                  .at(contractFactoryAddress)
                  .createObject("object", { gas: price, from: accountAddress });

I tried also to modify the function to store the address in an array, returning the length of the array, and then retrieve it at a later time, with the same results: always the transaction hash is returned.

Any light on this is welcome.

Best Answer

Often the contract itself is going to need to store the address for future use. So just store the address in the contract as an attribute, and retrieve it from outside the contract using the usual methods (e.g. call to the default getter ABI if you declare it public scope), after the transaction has been completed: (note, untested pseudo code, but I've done similar stuff a few times)

contract ObjectFactory {
    Object public theObj;

    function createObject(string name) returns (address objectAddress) {
        theObj = address(new Object(name));
        return theObj;
    }
}