7

I have a contract which is creating an instance of another contract. I am confused about deploying the contracts in Truffle. Does the constructor get initialized when deployed?

2 Answers 2

8

Constructors are always executed exactly once when a contract is created.

You'll use Truffle to migrate the factory contract, and then use a function in the factory to deploy created contracts. No need to migrate the contract the factory is designed to deploy. If the constructor of the contract to be deployed needs any arguments, then they should be passed in by the factory.

It's not exactly the same question, but this example might clarify the pattern: How to migrate a contract that has a constructor parameter of address type via truffle

You can structure it like this:

Factory.sol

import "Created.sol";

contract Factory {

  function createContract() returns(address created) {
    Created c = new Created(msg.sender); // passing an arg to constructor
    return c;
...

./migrations/2_deployFactory.js

...
deployer.deploy(Factory);

With Truffle, Factory.deployed() will be the contract on the blockchain.

app.js

...

var factory = Factory.deployed();
factory.createContract({from: .. })
.then(function(txn) {
  // you have the transaction hash now

Hope it's helpful.

4
  • That's great thanks. I'm having trouble actually using the createdContract in Truffle. Do you know how to use the contract once you have the txn?
    – ethereal
    Jan 2, 2017 at 18:20
  • Have a look here. I'm pointing at Xavier's function that waits for the txnhash to be mined. After it's mined, the return values (address?) will be visible. ethereum.stackexchange.com/questions/7709/… Jan 2, 2017 at 18:37
  • Ok I was able to get it working using a call() to get the address, once it was mined.
    – ethereal
    Jan 2, 2017 at 21:48
  • Cool. You can use the gettransactionReceiptMined() function to wait/(know when) the transactions was mined, and then use call(). Sorry if it wasn't clear. Jan 2, 2017 at 23:22
3

The best approach is going to be to have Created C; declared as a public var on the factory contract. Then, after you've deployed the factory, you can access the public var with web3 and use the Created.at(createdAddress) syntax to bind that address to the ABI for the Created contract.

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.