0

I am building a smart contract that uses a factory contract to deploy a new sub-contract (example some campaign). This campaign has a boolean flag isActive. Every time the factory deploys a campaign, it inserts its address to an array so I can have a method like getCampaigns() which returns an array of all campaign addresses.

My questions are:

  1. If the system ends up with hundreds of thousands of campaigns, how can getCampaigns() remain efficient? Is there something like pagination design patterns?

  2. An idea I have is to make a function that displays only active Campaigns. But at the factory level, the contract does not have access to the variables inside the respective Campaign. Is it possible to design something like that?

For posterity, this is the code I am using:

contract CampaignFactory {
    Campaign[] public deployedCampaigns;

    function createCampaign(string memory campaignName) public payable {
        Campaign newCampaign = (new Campaign).value(msg.value)(msg.sender, campaignName);
        deployedCampaigns.push(newCampaign);
    }

    function getCampaigns() public view returns (Campaign[] memory) {
        return deployedCampaigns;
    }

    // Is it possible to get only active campaigns using the campaignActive boolean?
    function getActiveCampaigns() public view returns (Campaign[] memory) {
        //
    }
}

contract Campaign {
    address public campaignManager; 
    string public campaignName;
    bool public campaignActive; 
...
1

Solution to your 1st question

You can do something like this

function getCampaigns(int start, int end) public returns(Campaign[] memory) {
        for(int i = start ; i < end && end <= deployedCampaigns.length; i++) {
            Campaign.push(deployedCampaigns[i])
        }
        return
    }

Solution to your 2nd question

You can get the value of campaignActive on Campaign contract.

Just add a new getter function in Campaign contract

function getCampaignActive() public view returns(bool) {
   return campaignActive;
}

And then you can access use the campaignActive check to check if the campaign is active or not and push only those with campaignActive = true

 function getActiveCampaigns() public view returns (Campaigns[] memory) {
      for(uint i = 0; i < deployedCampaigns.length; i ++){
         if(Campaign(deployedCampaigns[i]).getCampaignActive()) {
            Campaigns.push(deployedCampaigns[i])
         }
      }
      return
 }

Note Code is not tested

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.