Truffle Call Return – Addressing Contract Returns Transaction Issues

soliditytestrpctruffle

Using Truffle v3.2.1 and solidity 0.4.4

I have an issue with a Factory contract (that create some kind of contract), to simplify my factory contract look like this :

contract HelloFactory {
  uint nbContracts;

  function HelloFactory() {
    nbContracts = 0;
  }

  function createHS() returns (HelloSystem contract) {
      HelloSystem ret = new HelloSystem();
      nbContracts++;
      return ret;
  }
}

The HelloSystem contract code is not relevant to the issue.

using truffle console I made a new Hello Factory :

var aHelloFactory;
HelloFactory.new().then(el => aHelloFactory = el);

I can check that there is no HelloSystem contracts created within my factory yet:

aHelloFactory.nbContracts.call().then(console.log)
// OK : prints 0 

Now I try to create a new HelloSystem contract from the factory

var hs;
aHelloFactory.createHS().then(el => hs = el);
// KO : Prints transaction ? (correct me if i am wrong)
// { tx: 

'0xba9dc273cc13425303436d4f2eeee9c852b99aefa5026d3a37ccfabd17232204',
  receipt: 
   { transactionHash: '0xba9dc273cc13425303436d4f2eeee9c852b99aefa5026d3a37ccfabd17232204',
     transactionIndex: 0,
     blockHash: '0xd04d6c10cf48995903283dccde31cd5712de2029578c7eb00edc852ac475083c',
     blockNumber: 148,
     gasUsed: 249136,
     cumulativeGasUsed: 249136,
     contractAddress: null,
     logs: [] },
  logs: [] }

I am expecting a contract as return of function,
What am I doing wrong ?

Best Answer

When accessing a function through a transaction, you cannot get a return value.

Generally, you want to create an event with a field containing the contract's address. Something like:

contract HelloFactory {
  uint nbContracts;
  event HSCreated(address _from, HelloSystem addr);

  function HelloFactory() {
    nbContracts = 0;
  }

  function createHS() returns (HelloSystem contract) {
      HelloSystem ret = new HelloSystem();
      nbContracts++;
      HSCreated(msg.sender, ret);
      return ret;
  }
}

Getting the address back from the event depends entirely on what implementation of Web3 you are using, checking their documentation would provide more help than I could.

Related Topic