Getting TokenId after using safeMint in ERC721 contract

This seems basic but I have not been able to find a great answer anywhere. I am happy to read another post or document if it is available and someone can link it.

I have a contract that is ERC721, ERC721Enumerable, ERC721URIStorage, Pausable, Ownable

I have been using the safeMint function successfully to create nfts and send them to an owner account. I am able to see the owner by calling ownerOf(tokenId) where tokenId is a number less than or equal to balanceOf - 1.

Is there a way to find this tokenId when I mint the token or any other way? I believe I read somewhere along the way that this is not guaranteed to be sequential?

:1234: Code to reproduce


:computer: Environment

I found the answer on stack overflow:

And was able to get the id with the following code in ethers:

 const data = await contract.safeMint(purchaserAddress);
 await provider.waitForTransaction(data.hash);
 const receipt = await provider.getTransactionReceipt(data.hash);
 console.log(Web3.utils.hexToNumber(receipt.logs[0].topics[3])); // This is the tokenID
1 Like