Solidity array's dynamic size best practices

Viewed 240

I am coding a NFT marketplace smart contract and I came across a problem regarding arrays in solidity.

I have a function that retrieve an array of token based on an array of ids. Because the size of the Id array is dynamic, so is the size of the output array.

The function :

function fetchUnsoldMarketItems(uint256[] memory _tokenIds) public view returns (MarketItem[] memory) {
      uint arrayLen = _tokenIds.length;
      uint itemsCount = 0;          

      for (uint i = 0; i < arrayLen; i++) {
      if (idToMarketItem[_tokenIds[i]].sold == false) {
          itemsCount +=1;
        }        
      }

      MarketItem[] memory items = new MarketItem[](itemsCount);

      for (uint i = 0; i < arrayLen; i++) {
      if (idToMarketItem[_tokenIds[i]].sold == false) {
          MarketItem storage currentItem = idToMarketItem[_tokenIds[i]];
          items[i] = currentItem;
        }        
      }

      return items;
    }

First, is there a better way to code this function and to retrieve the unsold items? Also, if a MarketItem is being sold/bought during the execution of the function, the length of the second array will being bigger/smaller than expected. How can I prevent that ?

I am looking for any sort of advice as I am still a beginner with solidity !

1 Answers

It is not efficient to save to nft in your solidity code the best practices is to save them in mangodb or sql db and reteive this info from this db

Related