I am building Social Media for NFT.
I would like to get a list of NFTs minted in the past by a particular user in Ethereum and Polygon Chain. It does not have to be currently held. Is there a good way to do this?
You write this function in your smart contract
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;
}
this is ERC721.balanceOf
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721:zero address");
return _balances[owner];
}
When you call _mint
function, the address who has minted is added to _balance
this is 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
is a mapping:
//{address:{1:tokenId-1,2:tokenId-2}}
mapping(address=>mapping(uint=>uint)) private _ownedTokens;
then in front-end, after setting up provider and contract, you just call this function:
const myNfts = await contract!.getOwnedNfts();