0

I am new to solidity :) and try to encapsulate array of contracts in one contract.

Something like this:

contract Item{
     uint public blabla1;
     uint public blabla2;
}

contract Collection{
    Item[]public items;
}

How can I do it? Any workarounds?

1
  • The answer below look good, anyway a kindly advice try to avoid Arrays in solidity, and try to always keep it simple :)
    – Majd TL
    Commented Feb 3, 2021 at 20:53

1 Answer 1

3

I updated your code with examples of creating array of contracts, passing data and reading that:

pragma solidity ^0.6.0;

contract Item {
     uint public blabla1;
     uint public blabla2;
     
     constructor(uint _blabla1, uint _blabla2) public {
         blabla1 = _blabla1;
         blabla2 = _blabla2;
     }
     
     function returnData() view public returns(uint, uint) {
         return (blabla1, blabla2);
     }
}

contract Collection {
    Item[]public items;
    
    function addItemContract(uint _blabla1, uint _blabla2) public {
        items.push(new Item(_blabla1, _blabla2));
    }
    
    function readItemContract(uint _index) public view returns(uint, uint) {
        return Item(items[_index]).returnData();
    }
}

Method addItemContract in contract Collection is creating contract Item, passing arguments to it and pushing it to array items.

Now that we know items is array of contract addresses, we can create instance with Item(<CONTRACT_ADDRESS>) and read the data of the contract which was earlier pushed into the array.

So yes, this is pretty much how to create and save new contracts into arrays and write or read their state.

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.