Dapps
在網頁上列出使用者擁有的 ERC721 代幣
假設我有一個代表一組撲克牌的 ERC721 (NFT) 合約。
是否有範常式式碼顯示列出了使用者在網頁上擁有的 ERC721 合約的所有令牌,以便使用者可以選擇一個?
你可以在你的智能合約中添加一個函式來模仿 CryptoKitties 合約在 function 中所做的事情
tokensOfOwner
,這返回分配給地址的所有 Kitty ID 的列表
/// @title The facet of the CryptoKitties core contract that manages ownership, ERC-721 (draft) compliant. /// @author Axiom Zen (https://www.axiomzen.co) /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 /// See the KittyCore contract documentation to understand how the various contract facets are arranged. contract KittyOwnership is KittyBase, ERC721 { [...] /// @notice Returns a list of all Kitty IDs assigned to an address. /// @param _owner The owner whose Kitties we are interested in. /// @dev This method MUST NEVER be called by smart contract code. First, it's fairly /// expensive (it walks the entire Kitty array looking for cats belonging to owner), /// but it also returns a dynamic array, which is only supported for web3 calls, and /// not contract-to-contract calls. function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { uint256 tokenCount = balanceOf(_owner); if (tokenCount == 0) { // Return an empty array return new uint256[](0); } else { uint256[] memory result = new uint256[](tokenCount); uint256 totalCats = totalSupply(); uint256 resultIndex = 0; // We count on the fact that all cats have IDs starting at 1 and increasing // sequentially up to the totalCat count. uint256 catId; for (catId = 1; catId <= totalCats; catId++) { if (kittyIndexToOwner[catId] == _owner) { result[resultIndex] = catId; resultIndex++; } } return result; } }
ERC721 標準的目前草案要求遵守該標準的合約具有
totalSupply
屬性以及balanceOf(address _owner)
功能ownerOf(uint256 _tokenId)
。要查找給定地址擁有的所有項目,前端 DApp 需要查詢
totalSupply
(例如,52 張撲克牌),然後從零循環到該數字並呼叫該ownerOf
ID 上的方法,尋找匹配的結果正在搜尋的目標地址。找到匹配項後,可以將該項目添加到該帳戶的已知資產列表中,如果該列表的長度現在等於balanceOf
該使用者的呼叫結果,則循環可以停止,因為所有資產都已成立。ERC721 標準可選地呼叫
tokenOfOwnerByIndex(address _owner, uint256 _index)
可以使循環更短的呼叫,但這是為 ERC721 令牌實現的可選函式。如果您創建的令牌具有這樣的功能,那麼您可以使用它更有效地循環結果。