[英]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 :
page
和query
items
,如果項目符合條件( name
包含query
),則將其添加到結果數組注意:在 Solidity 中,第 2 步實際上會稍微復雜一些,因為您不能將其push
入內存中的動態數組。 所以你需要:
results
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.