0

have a standard factory pattern for my contract and I am trying to get it up and running using Truffle Migrations.

In my factory truffle migration script I have

await deployer.deploy(ContractFactory);

This deploys the factory contract just fine but I am a bit unsure what the standard way of migrating the child contract is.

Do I also need to have a migration file for the child and run the child's own deployment?

Or am I just supposed to deploy the factory on its own and then the factory's createNewChildContract function handle the migration for me?

function createNewChildContract() public {
    ChildContract childContract = new ChildContract(uint256 _amount);
    childContracts.push(childContract);
}

Thank You

1 Answer 1

1

Do I also need to have a migration file for the child and run the child's own deployment?

No.

Or am I just supposed to deploy the factory on its own and then the factory's createNewChildContract function handle the migration for me?

Yes.

Here's just a little directional guidance so you can proceed confidently in the right direction.

In this case, the factory contains the bytecode of Child. It's a big bytes value that was worked out at compile time and is baked into the deploying function - so it knows exactly what to do without consulting external sources.

You can use the factory to create instances of Child and in most cases there is no good reason to deploy a Child by any other method.

Coordination

In the case that you want to choreograph the creation of several children, you can accomplish that by scripting calls to the factory's createNewChildContract() function.

Something like:

2_deploy_contracts.js:
await deployer.deploy(Factory);

3_deploy_the_kids.js:
factory = await Factory.deployed();
await factory.createNewChildContract();
await factory.createNewChildContract();
await factory.createNewChildContract();

You will rely on the Factory's built-in childContracts array (or the missing event emitter) to discover the child addresses that were created in case you need to initialize anything at that level:

4_initialize_the_kids.js:
factory = await Factory.deployed();
kid1Addr = await factory.childContracts(0);
kid2Addr = await factory.childContracts(1);
...
kid1 = Child.at(kid1Addr);
kid2 = Child.at(kid2Addr);
...
await kid1.doSomething();
await kid2.doSomething();
...

The above is just a little scribble to help you with the gist so please forgive any syntax errors or typos.

The truffle deployer will not know about the contracts except the ones it was responsible for deploying, i.e. the Factory. You can rely on await Factory.deployed() but you can't use it for the kids if you follow this pattern.

Hope it helps.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.