NFT – How to Write an NFT Contract for Minting Specified NFTs?

nft

I found that the NFT contract normally for minting NFTs in order. Is it possible that I change the minting function to include the id of NFT as an input variable so that customers can mint the specified NFT that they want? Does anyone know how to write this kind of minting function please?
Thank you so much!

Best Answer

Yes, it can be done by creating a contract that inherits from ERC721PresetMinterPauserAutoId.sol preset. Then you can use the internal _mint(address to, uint256 tokenId) function to specify the id. If the preset is not needed, the plain ERC721 contract can also be used. Same is true for the ERC1155 standard. You can find these contract standards in the OpenZeppelin repo.

Sample code in solidity:

// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

import "@openzeppelin/contracts/token/ERC721/presets/ERC721PresetMinterPauserAutoId.sol";

contract NFTtest is ERC721PresetMinterPauserAutoId {

    constructor()
        ERC721PresetMinterPauserAutoId(
            "NonFungibleToken",
            "NFT",
            "https://example.com"
        )
    {}

    // Mint function with ID as an input
    function mint(uint256 _id) public {
        // Here you can add additional logic or pre-conditions.
        // _mint function already checks if the _id has been
        // used so no need to check again

        // Mint the NFT with the specified _id and set as the owner
        // the sender of the transaction
        _mint(msg.sender, _id);
    }
}