Solidity – View NFTs Owned by Wallet with ERC721URIStorage Contract

ethers.jssolidity

I have a pretty basic contract that allows people to mint NFT's. I'm able to check the balance of the total amount of NFT's the user owns relative to the initial mint contract:

connectedContract.balanceOf(web3React.account).then((d) => {
  console.log(parseInt(d))
})

Is there a way I can show which NFT's the wallet owns that is only relative to the contract address?

Best Answer

Your actual code should only show you the balance of NFT owned by the account on your contract.

connectedContract

Appears to be your contract. So the Balance is related to that contract.

If you did not implement the Enumerable set. To get all the NFT's of an account you would have to loop over them and call

   connectedContract.ownerOf(token_id).call()

An example;

let balance = await connectedContract.balanceOf(web3React.account)
let i = 0
let supply = await connectedContract.totalSupply();

for(i=0;1< supply ;i++){
// this will check each nft owner
// i is the id of each nft.

// this will return the owner address
let owner = await connectedContract.ownerOf(i);

// if owner == msg.sender then we know he owns this token id

}

I strongly recommend that you take a look at the openZeppelin Enumerable contract that provide an easier way of going trough a user NFT balance.

To understand what each OZ extension add to the ERC721 you can visit this link.

OZ Contracts

You want to import the required extensions in your contract.

For what you want to do you can use

IERC721Enumerable

It will essentially provide you with exactly what you want! The process is similar. You get the balance, and you can get the index of each token based on the balance.

Related Topic