简体   繁体   English

Solidity 数组的动态大小最佳实践

[英]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.我正在编写一个 NFT 市场智能合约,我遇到了一个关于 Solidity 数组的问题。

I have a function that retrieve an array of token based on an array of ids.我有一个函数可以根据 id 数组检索令牌数组。 Because the size of the Id array is dynamic, so is the size of the output array.因为 Id 数组的大小是动态的,所以输出数组的大小也是动态的。

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.此外,如果在函数执行期间正在出售/购买 MarketItem,则第二个数组的长度将大于/小于预期。 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中获取此信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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