【发布时间】:2022-11-26 12:13:00
【问题描述】:
我正在为 NFT 构建社交媒体。
我想获得以太坊和多边形链中特定用户过去铸造的 NFT 列表。它不必当前举行。 有没有好的方法来做到这一点?
【问题讨论】:
标签: reactjs api ethereum polygon nft
我正在为 NFT 构建社交媒体。
我想获得以太坊和多边形链中特定用户过去铸造的 NFT 列表。它不必当前举行。 有没有好的方法来做到这一点?
【问题讨论】:
标签: reactjs api ethereum polygon 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: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();
【讨论】: