0

Is there any way to create multiple child contracts (with a specific logic inside them) from a parent contract automatically?

My use cases are supply chain management and identity management on blockchain. Given the scale of these cases, I am not inclined to use structs or mappings in one single contract and want to create individual contracts which can be treated individually.

From technical standpoint how can we implement this logic of creating a 'Mother' contract which gives birth to 'Child' contracts based on some business conditions and then these 'Child' contracts function on their own?

  • Are these child contracts all the same, or are there a number of them? – wtk219 Feb 21 '18 at 16:45
  • If I take the example of supply chain management, I wish to create multiple child contracts (for each lot number of shipment). Here I cannot predict the number of child contracts in advance as this will keep on increasing with new items being transported. Logic in all child contracts will be same. – tanmay Feb 21 '18 at 16:51
2

You can instantiate a contract from within another contract using the new keyword.

You can then keep track of those new children using an array, or ideally, a mapping.

You must import the Child.sol source code in your Parent.sol file (i.e., import './Child.sol';)

You can wrap this in a function for example, like

import './Child.sol';

mapping(bytes32 => Child) childList;

function spawnChild(bytes32 childId) {
    Child current = new Child();
    childList[childId] = current;
}

which will create a new Child contract whenever you call the function.

You can then call functions on your Child contracts from within your Parent contract like this

function callChildFunction(bytes32 childId) {
    childList[childId].theChildfunction();
}
  • thanks, @wtk219, I guess this must work for my case. Any other piece of advice? – tanmay Feb 21 '18 at 17:03
  • @tanmay I added a bit on how you can call functions on your Child contract from within your Parent contract. Best of luck! – wtk219 Feb 21 '18 at 17:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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