0

ContractA creates multiple instances of ContractB. In my contract I would like to set the address of ContractA on ContractB instances but as that address (of A) is not available at the time of (B) creation, what would be the suggested pattern.

One way to do it is by making it a 2-step process #1 create the instances of ContractB in constructor #2 make a call to set the address of the contract A on instances of Contract B ... any thoughts on other ways of doing it?

// Code for illustration only
contract ContractA{
  address[] instancesOfB;

  function ContractA(){
     // create the instances of ContractB and push to instancesOfB
     ...
  }

 function updateB(){
   // loop through the array 
   for(uint8 i=0; i < instancesOfB; i++) {
      instancesOfB[i].setAddressOfA(address(this));
   }
 }
}
1

Side issue. I wasn't sure how many bees will be deployed. You can safely use the for loop as long as you're certain you won't exceed the block gas limit (ever), i.e. list is of a finite and small size. Otherwise, the safer path is to push the iterative logic outside the contract.

I'm showing two different ways. You could have the constructor do that (6?) times and call it a win, or you could just leave the constructor out of it and register the new B instances one at a time. Probably not both.

// Code for illustration only
contract ContractA{

  ContractB b;
  address[] instancesOfB;

  function ContractA(){
     // avoid iteration unless it's carefully bounded
     b = new ContractB();
     instancesOfB.push(b);
  }

  // This could be called repeatedly by a deployment/migration script to
  // ensure no unbounded iteration in the contract.

  function newB() 
      // onlyOwner
      returns(address newContractB)
  {
      b = new ContractB();
      instancesOfB.push(b);
      return b;
  }

}

// This contract bytecode will be (must be) included in ContractA
// Can also set owner to Contract A if you need.   

 contract ContractB {
   address owner;
   function ContractB() {
     owner = msg.sender;
   }
 }

Hope it helps.

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.