3

Look at this implementation, I can see that ERC721 contracts keep track of an owner (identified by its address) for each single token (identified by its token ID, a 256 bit number):

mapping (uint256 => address) internal tokenOwner;

So when there's a transfer, from, to AND a token ID have to be provided. So far so good.

What I don't understand is the semantics of the balance operation.

  /**
   * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are
   * considered invalid, and this function throws for queries about the     zero address.
   * @param _owner Address for whom to query the balance.
   */
  function balanceOf(
    address _owner
  )
    external
    view
    returns (uint256)
  {
    require(_owner != address(0));
    return ownerToNFTokenCount[_owner];
  }

If each token is non-fungible and therefore by definition unique, then how can there be more than one of each? I.e. what does it mean when the balance function returns more than 1?

3

balanceOf does not return the number of a particular token. It returns the number of tokens that a particular user owns.

For example, if you want to know "How many CryptoKitties does Jane own?", you could use the balanceOf function to answer that.

The balanceOf function exists for two main reasons. First, it makes ERC721 backwards compatible with ERC20, and standardization is super helpful. Second, it can be used for iterating over all the tokens that a user owns.

For example, if you implement the enumerable extension for ERC721, you can use balanceOf to check that you are not requesting a token out of index for the user. This would allow you to create a page where you can see all of your NFTs easily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.