1

I am just creating my own NFT marketplace. I need to create unique token ID for each NFT but the current demo for token ID is like below.

contract ERC721 {
  ...
  mapping(uint256 => address) private _tokenOwners;

  function _mint(address to, uint256 tokenID) {
    _tokenOwner[tokenID] = to;
    ...
  }
}

contract CryptoDog is ERC721 {
    ...
  string[] public cryptoDogz;  

  function mint(string memory nftName) public {

    cryptoDogz.push(ntfName);
    uint256 _tokenID = cryptoDogz.length - 1;
    _mint(msg.sender, _tokenID);
    ...
    
  }
}

I will appreciate it if you provide me with a way to generate uniquely token ID.

4
  • Hi there. Do you mean "unique" or "random"? Doesn't the code above generate you a unique ID? May 26, 2022 at 16:50
  • It is set up to the length of token array. The contract address(public key) is a unique hash value. I mean such unique number for token ID. May 26, 2022 at 16:55
  • But if the size of the token array only ever increases (during the NFT sale), then each new token will have a unique ID based on the array length. (i.e. Each ID will be different.) May 26, 2022 at 17:07
  • Thank you for your kind reply May 27, 2022 at 1:50

1 Answer 1

1

You can use a counter to start from ID 1, and increment it when you mint new NFTs. You will get a different and incremental number for each NFT. You can use this code from OpenZeppelin:

// contracts/GameItem.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";

contract GameItem is ERC721URIStorage {
    using Counters for Counters.Counter;
    Counters.Counter private _tokenIds;

    constructor() ERC721("GameItem", "ITM") {}

    function awardItem(address player, string memory tokenURI)
        public
        returns (uint256)
    {
        uint256 newItemId = _tokenIds.current();
        _mint(player, newItemId);
        _setTokenURI(newItemId, tokenURI);

        _tokenIds.increment();
        return newItemId;
    }
}

The example is using the Counters library from OpenZeppelin.

You can check how it is implemented here.

2
  • If the answer helps, you are welcome to vote up this answer as correct. May 27, 2022 at 6:55
  • Sorry but I should have at least 15 reputations to cast a vote for your answer. I am a newbie here. May 28, 2022 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.