ethereum - 跟踪 ERC721 智能合约上所有类型转换的代币

标签 ethereum solidity smartcontracts

我有一个智能合约,我想为其构建一个基于网络的市场应用程序。如何列出契约(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函数来:

  1. pagequery 作为参数
  2. 循环遍历现有项目,如果该项目符合条件(名称包含查询),则将其添加到结果数组中
  3. 返回结果数组

注意:在 Solidity 中,步骤 2 实际上会稍微复杂一些,因为您无法push 到内存中的动态数组中。所以你需要:

  1. 循环浏览项目并找到符合条件的金额(最多页数限制)
  2. 创建固定长度的内存数组结果
  3. 现在您可以再次循环遍历这些项目,并用值填充固定长度 results 数组

关于ethereum - 跟踪 ERC721 智能合约上所有类型转换的代币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67036739/

相关文章:

node.js - web3.eth.sendSignedTransaction() 始终返回 "Returned error: nonce too low"

arrays - Solidity:UnimplementedFeatureError:此处未实现嵌套动态数组

javascript - 重复事务挂起 - web3js,本地 geth

solidity - web3 智能合约中的持久事件状态

token - 通过合约发送代币时出现 SafeMath 错误

测试智能合约需要 Truffle : transaction reverted if function isnt void

ethereum - Chainlink 和区 block 链中的 gas lane 是什么?

debugging - 有没有办法在 RSK 网络中调试交易,这可能是最好的方法?

javascript - 当 JS 将数值作为参数传递给 Solidity 函数时,为什么最好将它们用引号引起来?

solidity - 如何检查或知道钱包在 web3 python 中有 token