[Ethereum] ERC721 – getting the list of all token owners (all addresses)

erc-721

I have an ERC721 compliant contract with multiple NFT tokens.

I'm looking for a way to randomly select one of the token owners. Is there a way to get the current list or all token owners from ERC721 or do I need to create the mapping myself?

If creating the mapping myself, I guess I would need to add the minters address to a mapping of all owners, then whenever the token is transferred I need to update the new owner address. How do I override all the transfer functions?

Best Answer

You can try to fetch all emitted Transfer events using getPastEvents function. Based on ERC721 interface Transfer event is emitted when ownership changes.

/// @dev This emits when ownership of any NFT changes by any mechanism.
///  This event emits when NFTs are created (`from` == 0) and destroyed
///  (`to` == 0). Exception: during contract creation, any number of NFTs
///  may be created and assigned without emitting Transfer. At the time of
///  any transfer, the approved address for that NFT (if any) is reset to none.

event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
Related Topic