I have a smart contract with 50+ trillion possible NFT names that could be minted (all have unique names), is there any chance that this method could cause a collision of token ID's? –
uint256 tokenID = uint256(keccak256(abi.encode(_tokenName)))
I need to create unique Token ID's for my NFTs that directly correlate to the name of the tokens, this helps with a few other pre-minting verification functions. Such as the example:
- By using
uint256(keccak256(abi.encode(_tokenName)))
I can check if the NFT has already been minted by converting the name to uint(keccak256) and look for matching token IDs.
Snippet of function below:
/**
* @notice Converts token name string to a unique uint256 for use as Token ID.
*
* @param _tokenName name of NFT.
*/
function tokenNameToTokenId(string memory _tokenName) public pure returns(uint256) {
return uint256(keccak256(abi.encode(_tokenName)));
}
/**
* @notice Checks if the NFT has already been minted, returns true/false.
*
* @param _tokenName name of NFT
*/
function nftExists(string memory _tokenName) public view returns(bool) {
uint256 tokenId = tokenNameToTokenId(_tokenName);
return _exists(tokenId);
}
If there is a significant risk then I will introduce some additional mappings and go with a standard incremented tokenID.
Thanks
Best Answer
A keccak256 string has a length of 256 bits. Obviously, uin256 also has 256 bits. Since they both have the same length, there shouldn't be any problems when converting them even back and forth.
I really can't think of any reason why it wouldn't map nicely back and forth, and why it might introduce collisions.