我有一个智能合约
,我想为其构建一个基于网络的市场应用程序。如何列出契约(Contract)中所有可用的“项目”。由于类型转换的Item数量没有上限,如何实现分页和搜索?
什么是最佳实践和可扩展的解决方案:
简单地返回 Items[] 数组
在传输和其他事件时将阵列与我的数据库同步
还有其他建议吗?
pragma solidity ^0.4.24; contract Item is ERC721{ struct Item{ string name; // Name of the Item uint level; // Item Level uint rarityLevel; // 1 = normal, 2 = rare, 3 = epic, 4 = legendary } Item[] public items; // First Item has Index 0 address public owner; function Item() public { owner = msg.sender; // The Sender is the Owner; Ethereum Address of the Owner } function createItem(string _name, address _to) public{ require(owner == msg.sender); // Only the Owner can create Items uint id = items.length; // Item ID = Length of the Array Items items.push(Item(_name,5,1)) // Item ("Sword",5,1) _mint(_to,id); // Assigns the Token to the Ethereum Address that is specified } }
最佳答案
您可以创建一个 itemsCount
公共(public)属性来保存现有项目的当前数量,并在每次 items.push()
之后递增它。
没有分页和搜索:
想要读取数据的链下系统可以简单地从 items[0]
循环到 items[itemsCount]
,并且由于这只是一个读取操作,因此不需要交易(即免费)。
分页和搜索:
您可以创建一个view
函数来:
- 将
page
和query
作为参数 - 循环遍历现有
项目
,如果该项目符合条件(名称
包含查询
),则将其添加到结果数组中 - 返回结果数组
注意:在 Solidity 中,步骤 2 实际上会稍微复杂一些,因为您无法push
到内存中的动态数组中。所以你需要:
- 循环浏览项目并找到符合条件的金额(最多页数限制)
- 创建固定长度的内存数组
结果
- 现在您可以再次循环遍历这些项目,并用值填充固定长度
results
数组
关于ethereum - 跟踪 ERC721 智能合约上所有类型转换的代币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67036739/