logo

How to Lazy Mint an NFT in your marketplace

FN

Faisal Nawaz

Published on January 7, 2023

How to Lazy Mint an NFT in your marketplace

How to Lazy Mint an NFT in your marketplace

NFTs? NFTs (Non-Fungible-Token) are are unique digital assets that can be used as a form of digital art,as a collectible or as a form of digital ownership.


What is Minting?

Minting an NFT is the process of creating and publishing NFT to blockchain.NFT is minted by creating unique identifier asset and register it on blockchain.

To mint an NFT, you need to follow these steps:

  1. Choose a blockchain that supports the creation of NFTs, such as Ethereum or EOS.
  2. Create a digital asset that you want to represent as an NFT. This could be a piece of art, a video, or any other type of digital file.
  3. Use a tool or platform that allows you to create an NFT on the chosen blockchain. This typically involves creating a smart contract and uploading the digital asset to be stored on the blockchain.
  4. Set the parameters for the NFT, such as the name, description, and any other relevant details.
  5. Pay the fees for creating the NFT, which are typically paid in the blockchain’s native cryptocurrency.
  6. Once the NFT is created, it will be assigned a unique identifier and can be bought, sold, and traded on the open market.

Disadvantages of Minting

If we talk about evil of blockchain world that would be gas fee that signer or caller of transaction needs to pay whenever he posting some data on blockchain.It’s same as your car need’s gas to run and your transactions on blockchain need’s gas fee to proceed successfully.One other pitfall of gas fee is its value is not constant however it fluctuates based upon the traffic of transactions happening on blockchain which can 1$ to thousands dollars depending on the traffic on blockchain.So minting NFT’s on blockchain can be quite expensive especially for NFT Creators.That’s why most creator’s preferred to mint in midnight hours (1am to 5am) to pay less gas fee.To overcome this problem blockchain community introduced concept of lazy minting so lets deep dive into it.


Lazy Minting

As of now you would have already guessed Lazy Minting has something to do with gas prices.If you are thinking that yes you are right.So what if i told you from paying thousands dollars for minting now nft can be minted free without paying any single gas fee with the help of lazy minting yes that’s possible.Lazy Minting is enhanced way of minting where creator’s can mint their NFT free without paying any gas fee.

In Lazy Minting NFT is minted off-chain or not minted directly to chain so at time of minting NFT data thats need to be posted on blockchain is saved in one of the marketplace database by signing cryptographic signature with NFT data and creator wallet’s private key and minting on chain occurs when nft is bought by buyer so at the end it will be who will be initiating minting transaction on blockchain and will be paying gas fee for minting.


Advantages of Lazy-Minting

  • Minting or selling NFT’s in marketplaces has become easier for NFT Creator’s as they don’t need to pay huge upfront gas fee anymore to sell their unique asset.
  • On those nft will be minted on chain that are sold which will result’s in less number of transactions on blockchain which will eventually result’s in less gas fee as there will be decrease in traffic on blockchain.

Disadvantages of Lazy-Minting

  • NFT’s are minted off-chain which means there record is not publicly available until they are sold

How It Works

In Lazy Minting, instead of minting nft direclty on blockchain NFT’s data is cryptographic signature is created with creator wallet’s private key.

That signed NFT data cryptographic signature act as a vocher or token which later on can be used to redeem your nft at blockchain.NFT voucher have all the information that needed to be posted on blockchain.It can also have any additional information depending upon marketplace contract logic.

Here’s how NFT voucher look like in your solidity contract:

struct NFTVoucher {
  uint256 tokenId; // nft tokenid
  uint256 price;   // price for nft
  string uri;      // nft uri holding nft metadata
  bytes signature; // creator signed cryptographic signature of nft data.
}

In above solidity struct you can look it has following four properies:

  • tokenId: represents nft id or token that will posted as nft id on blockchain.
  • uri: holds the url to nft metadata uploaded on some decentralized storage like ipfs and will be posted on blockchain as nft data.
  • price: additionally it holds price that will be the price at which nft will be sold.
  • signature: additonally it also holds cryptographic signature of nft data with creator wallet which will used to redeem nft later on at the time of purchase.

How signing works?

Signing a voucher can be problematic in some cases since some third party can take signed data and can use in some other context.For Example they take signature that was signed on GOERLI for NFT authorization and try to use it with contract that was deployed on mainnet.To overcome such situations Ethereum Community has introduced EIP-712 a standard for signing typed,structured data. Signatures created with EIP-712 are “bound” to a specific instance of a smart contract running on a specific network.


Implementation

To Implement Lazy Minting in your market place.we will need solidity smart contract and createVoucher function in frontend app that will be responsible to interact with metamask and create cryptographic signature for nft data.We will be using ether.js for metamask interaction and will be using _signTypedData function from ether to sign nft data.

const createVoucher = async (nft) => {
  const provider = new ethers.providers.Web3Provider(web3?.givenProvider);
  const signer = provider.getSigner();
  try {
    const voucher = {
      tokenId: nft?.id,
      price: nft?.price,
      uri: nft?.uri
    };
    const domain = {
      name: SIGNING_DOMAIN_NAME,
      version: SIGNING_DOMAIN_VERSION,
      verifyingContract: nft?.tokenAddress,
      chainId: Number(nft?.chainId)
    };
    const types = {
      NFTVoucher: [
        { name: 'tokenId', type: 'uint256' },
        { name: 'price', type: 'uint256' },
        { name: 'uri', type: 'string' }
      ]
    };

    const signature = await signer._signTypedData(domain, types, voucher);

    return {
      ...voucher,
      signature
    };
  } catch (err) {
    console.log('error lazy minting', err);
    throw new Error('Fail To Lazy Mint Nft');
  }
};

Now our nft in minted off-chain now let’s look how to redeem nft with our Smart Contract.

This is how our LazyMint.sol looks like:

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.17;
pragma abicoder v2;

import "hardhat/console.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";

contract NFT is ERC721URIStorage, EIP712, AccessControl {
   string private constant SIGNING_DOMAIN = "LazyNFT-Voucher";
   string private constant SIGNATURE_VERSION = "1";
   string public contractURI;
   address public owner;
   address public marketOwner;

   event NftSold(
       address indexed nftContract,
       uint256 indexed tokenId,
       address indexed seller,
       address buyer,
       uint256 price
   );

   constructor(
       string memory _name,
       string memory _symbol
   ) ERC721(_name, _symbol) EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) {}

   struct NFTVoucher {
       uint256 tokenId;
       uint256 price;
       string uri;
       bytes signature;
   }

   function redeem(NFTVoucher calldata voucher)
       public
       payable
       returns (uint256)
   {
       address signer = _verify(voucher);
       require(msg.value >= voucher.price, "Insufficient funds to redeem");

       _mint(signer, voucher.tokenId);
       _setTokenURI(voucher.tokenId, voucher.uri);
       payable(signer).transfer(msg.value);
       _transfer(signer, msg.sender, voucher.tokenId);

       emit NftSold(
           address(this),
           voucher.tokenId,
           signer,
           msg.sender,
           voucher.price
       );

       return voucher.tokenId;
   }

   function _hash(NFTVoucher calldata voucher)
       internal
       view
       returns (bytes32)
   {
       return
           _hashTypedDataV4(
               keccak256(
                   abi.encode(
                       keccak256(
                           "NFTVoucher(uint256 tokenId,uint256 price,string uri)"
                       ),
                       voucher.tokenId,
                       voucher.price,
                       keccak256(bytes(voucher.uri))
                   )
               )
           );
   }

   function getChainID() external view returns (uint256) {
       uint256 id;
       assembly {
           id := chainid()
       }
       return id;
   }

   function _verify(NFTVoucher calldata voucher)
       internal
       view
       returns (address)
   {
       bytes32 digest = _hash(voucher);
       return ECDSA.recover(digest, voucher.signature);
   }

   function supportsInterface(bytes4 interfaceId)
       public
       view
       virtual
       override(AccessControl, ERC721)
       returns (bool)
   {
       return
           ERC721.supportsInterface(interfaceId) ||
           AccessControl.supportsInterface(interfaceId);
   }
}

Conclusion

Lazy minting is growing trend in nft world which has gain attention of famous market places like OpenSea and Rariable.Above implementation shows how you can introduce lazy minting in your marketplace but you can have additional logics or use cases according to your marketplace business logic.(e.g you can charge 2.5 percent of selling cost from seller as market listing fees instead of transferring all cost to creator or seller).

Ready to Start Something Great?

Our experts love collaborating with brands that think big. Let’s connect and explore how we can build something amazing together.

How to Lazy Mint an NFT in your marketplace | Zauf Labs