Robert's Homepage

How to Enumerate Erc721 Tokens

#software development #how-to #erc721 #solidity

For a given ERC721 contract, each NFT instance is just a mapping(address => []uint256). The array of uint256 types represent the ID of the token which are index values. Therefore, to get the IDs for tokens owned by a particular address, you must first get the balanceOf for a given address:

const balance = await contract.balanceOf(address)

The balance represent the sum of all tokens owned by this address, and the last index available for iteration. Once you have the balance value, you can use tokenOfOwnerByIndex method to access the tokens:

const tokens = []

for i = 0, i < balance; i++ {
  let t = contract.tokenOfOwnerByIndex(address, i)

  tokens.push(t)
}