I’m working on a project involving NFTs on Ethereum. I need to figure out how to get a list of token IDs from my NFT contract that are in a specific wallet. I’ve tried using Web3 to check the balance, but it only tells me if there are any tokens, not which ones.
This code assumes there’s a tokensOfOwner function in the contract, but I’m not sure if that’s the right approach. Any ideas on how to get the specific token IDs owned by a wallet?
You’re on the right track with your approach, Ray84. However, not all NFT contracts implement a ‘tokensOfOwner’ function. A more universal method is to use the ‘Transfer’ events emitted by the contract.
Start by querying past ‘Transfer’ events, then filter for events where the ‘to’ address matches your wallet. From there, track token IDs that are transferred in and later transferred out. Although this approach might be slower for contracts with many transfers, it works reliably for any ERC721 compliant contract. Adjust your Web3 code to use getPastEvents() and process the data accordingly, and remember to consider pagination and caching for optimal performance.
hey ray, have u tried using the ERC721Enumerable extension? it adds functions like tokenOfOwnerByIndex that let u iterate thru tokens owned by an address. might be easier than implementing ur own tokensOfOwner function. just make sure ur contract supports it first tho
hey ray! thats an interesting problem youre trying to solve. have you considered using the OpenSea API? it might be a bit easier than diving into raw web3 stuff. they have endpoints that can give you a list of assets owned by an address for a specific contract. could save you some headaches!
just wondering, why do you need to get the specific token IDs? are you building some kind of gallery or marketplace? it’d be cool to hear more about your project!
btw, if you do stick with web3, you might wanna look into using ethers.js instead. i’ve found it a bit more user-friendly than web3.js for nft stuff. just my two cents tho!