簡體   English   中英

跟蹤 ERC721 智能合約上的所有鑄造代幣

[英]Keep track of all minted tokens on ERC721 Smart Contract

我有一個Smart Contract ,我想為它構建一個基於 web 的市場應用程序。 如何在合同中列出所有可用的“項目”。 鑒於鑄造項目的數量沒有上限,如何實現分頁和搜索?

什么是最佳實踐和可擴展的解決方案:

  • 簡單地返回 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公共屬性來保存現有項目的當前數量,並在每個items.push()之后遞增它。


沒有分頁和搜索:

想要讀取您的數據的鏈下系統可以簡單地從items[0]循環到items[itemsCount] ,並且由於它只是一個讀取操作,它不需要事務(即它是免費的)。


分頁和搜索:

您可以創建一個view function :

  1. 以 arguments 作為pagequery
  2. 遍歷現有items ,如果項目符合條件( name包含query ),則將其添加到結果數組
  3. 返回結果數組

注意:在 Solidity 中,第 2 步實際上會稍微復雜一些,因為您不能將其push入內存中的動態數組。 所以你需要:

  1. 遍歷項目並找到符合條件的數量(最多頁面限制)
  2. 創建一個固定長度的內存數組results
  3. 現在您可以再次循環遍歷這些項目並用值填充固定長度的results數組

映射在可靠性方面比 arrays 更有效。 您可以在智能合約中有一個 uint 來保存每個項目的計數,並使用吸氣劑 function 從項目計數中減去您想要分頁的任何數字獲取每個項目。

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
    uint id;
}

mapping(uint => Item) items; // First Item has Index 0
uint count;
address public owner;

function Item() public {
    owner = msg.sender; // The Sender is the Owner; Ethereum Address of the Owner
}

function createItem(string memory _name, address _to, uint level, uint rarityLevel
                    uint id) public{
    require(owner == msg.sender); // Only the Owner can create Items
        uint num = count++;
        items[num].name = _name;
        items[num].level = level;
        items[num].rarityLevel = rarityLevel;
        items[num].id = num;
        count++;
}

function getItem(uint item) public view returns(string memory _name, uint level, 
                 uint rarityLevel, uint id){
        uint level = items[item].level;
        uint rarityLevel = items[item].rarityLevel;
        uint id = items[item].id;
        string memory _name = items[item].name
        return(level, rarityLevel, id, _name)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM