blockchainsoliditysmartcontractsnftopenzeppelin

Easy way to view a list of the tokens owned by a user?


I'm sure this could be done on the front end as well as from solidity. I saw a few posts that seemed inefficient, where they are creating a new mapping and storing unnecessary data to the blockchain when the ERC721 package already has the functions it needs in order to procure this information, from my understanding.

Figured out the answer to the first part!!

 function ownerOfTokenIds(address tokenOwner) external view returns (uint256[] memory) {
        uint256[] memory result = new uint256[](balanceOf(tokenOwner));
        uint256 counter = 0;
        for (uint256 i = 0; i < tokenCounter; i++) {
            if (ownerOf(i) == tokenOwner) {
                result[counter] = i;
                counter++;
            }
        }
        return result;
    }

Solution

  • I fixed the code in my first post, the issue was that I had to declare a uint[] memory variable called result and set it equal to a new uint array. The length of the array should be however many tokens this owner owns.

    This can then be used on the front end in a "spread operator" i'd presume!