How to get all existing token IDs

Hello!

I’m wondering how to retrieve all minted tokenIDs by a certain ERC721 contract? What I’m trying to do is retrieve an array with all minted tokenIDs.

For example: I want to have a function that returns an array of tokenIds that exist. Let’s say 1 and 48 (max supply) are minted the function needs to return: [1,48]. This means I still have 2-47 left to be minted

I couldn’t find anything about this only solutions where you would have to enter an address or an index (because most are mappings).

What is your use case for doing this on-chain or in another contract? I don’t think this is very feasible since you probably need to use Transfer events to find out which tokenIds have been allocated and you won’t be able to do that within a contract.

Hmm yea, I’m building a contract where people get randomly assigned to tokenIDs. However I need to check which tokenIDs have already been minted in order to only get unminted tokenIDs.
Why randomize tokenIDs you may think, it’s because the metadata is uploaded to IPFS and thus immutable. People will be able to see all metadata and to stop them from gaming the system I need to randomly assign a tokenID that they can mint.

One way I did it is with each mint I emit an event tokenMinted(tokenID) withthe tokenID emitted. So I can in my script just check all past events and then have an array of minted tokenIDs.

Oh you want to track ids within your own contract, not query another existing contract (got confused by “certain ERC721 contract”).

That’s probably a fine solution. There’s probably several ways to do it like check mapping and generate another id if it exists.