7

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 ?

1 Answer 1

5

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.

2
  • Thanks, so if I understand the return object can only be used from other contracts May 20, 2017 at 12:07
  • That is true for functions that you access through transactions. When using a function call that doesn't modify the state (a function with the constant keyword) then you can use the return value. You just cannot modify the state through that function.
    – jmontineri
    May 21, 2017 at 22:30

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.