简体   繁体   中英

Solidity array's dynamic size best practices

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 !

在您的solidity代码中保存到nft效率不高,最佳实践是将它们保存在mangodb或sql db中并从此db中获取此信息

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM