I have this function to stake an ERC721 token, but the user needs to provide the token ID manually. How can I automatically retrieve the first available token ID from the balance of a user that owns multiple tokens, then multiple IDs? Let's say the user might have more than one NFT, for example 1,4,5 so I need to pick the first one (1).

function stakeNFT(uint256 tokenId) public {
      require(ownerOf(tokenId) == msg.sender, "You do not own this token ID");
      transferFrom(msg.sender, address(this), tokenId);
      ////Do something

1 Answer 1


in the popular standard erc721 contract, there is no option to enumerate tokenIds of an owner. you get the balance at best without knowing the tokenIds.

however, if the ERC721(NFT) implements the optional extension ERC721Enumerable.sol then you just call the function function tokenOfOwnerByIndex(address owner, uint index)

As per your requirement, you'll pass the index as 0. however, practically very few or many popular NFTs out there as well don't implement this optional extension! so thats it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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