[英]How can I get a list of NFTs that I have minted?
我正在為 NFT 構建社交媒體。
我想獲得以太坊和多邊形鏈中特定用戶過去鑄造的 NFT 列表。 它不必當前舉行。 有沒有好的方法來做到這一點?
你在你的智能合約中編寫這個函數
function getOwnedNfts() public view returns(NftItem[] memory){
uint ownedItemsCount=ERC721.balanceOf(msg.sender);
NftItem[] memory items= new NftItem[](ownedItemsCount);
for (uint i=0; i<ownedItemsCount; i++){
// when user owns a token, I keep track of them in mapping instead of array
// It is saving the tokens of user in order
uint tokenId=tokenOwnerByIndex(msg.sender, i);
NftItem storage item=_idToNftItem[tokenId];
items[i]=item;
}
return items;
}
這是ERC721.balanceOf
function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; }
當你調用_mint
函數時,已經鑄幣的地址被添加到_balance
這是tokenOwnerByIndex
function tokenOwnerByIndex(address owner,uint index) public view returns(uint){ require(index<ERC721.balanceOf(owner), "Index out of bounds"); return _ownedTokens[owner][index]; }
_ownedTokens
是一個映射:
//{address:{1:tokenId-1,2:tokenId-2}}
mapping(address=>mapping(uint=>uint)) private _ownedTokens;
然后在前端,設置提供者和合同后,你只需調用這個函數:
const myNfts = await contract!.getOwnedNfts();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.