How to Lazy Mint NFTs

NFTs, or non-fungible tokens, or undoubtedly one of the most well-known areas of the blockchain industry. NFTs have surged in popularity in the last couple of years, and they have the ability to represent anything from physical to virtual assets. These tokens allow artists worldwide to get their work out on the market and gain financial support like never before. However, with the problems of congested blockchain networks, the gas fees for minting NFTs have become unpredictable and high, which results in entry barriers to the market. Therefore, to solve this issue, the concept of “lazy minting” was introduced. As such, artists get the possibility to list NFTs without having to pay any gas fees. How is this possible? Well, we will in this article take a closer look at what it is and how to lazy mint NFTs. 

Without the proper tools, it can be quite the hassle to lazy mint NFTs; however, in this tutorial, we will be using the number one Web3 operating system – Moralis. Not only does Moralis make minting NFTs a more accessible task, but the platform can be used for a multitude of different blockchain projects. Moralis provides an infinitely scalable backend infrastructure for all users, which in turn, takes away some of the hassles of developing a backend. Moreover, the operating system provides additional development tools such as Moralis Speedy Nodes, Price API, NFT API, and much more. 

So, if you have the ambition to become a better blockchain developer, sign up with Moralis right away. Creating an account is completely free, and you’ll receive immediate access to all the benefits of Moralis! 

What is Lazy Minting?

Before we dive deeper into the process of lazy minting NFTs, we need to do a brief walkthrough of what lazy minting is. To answer this question, a great place to start is the reason why it was needed in the first place. A general issue with the blockchain industry is congested networks – as more people make transactions on a blockchain, the demand for gas increases, which escalates the prices. As such, it has become increasingly expensive to mint NFTs. As mentioned earlier, it was because of this that lazy minting was introduced. 

When lazy minting an NFT, the minting process doesn’t occur until the time of purchase. This allows artists and developers of NFTs to create tokens without cost because this arises when someone buys them. As such, the minting responsibility rather befalls the buyer instead of the NFT creator.

Furthermore, this moves the point of creation to a later part of the blockchain and reduces the use of unnecessary computational power since only sold NFTs will be minted. Unsold NFTs will, therefore, not require any computational power as the process is pushed to the time of purchase. 

How to Lazy Mint NFTs in 3 Steps

Lazy minting is a theoretically viable and beneficial process that provides a multitude of advantages to the NFT minting process. Not only does lazy minting reduce the costs for the artists, but it also lessens the strain on the network. 

In this part, we’ll take a closer look at the practical process of how lazy minting works. To demonstrate, we’ll create a lazy minting NFT dApp (decentralized application). Since we are using Moralis, we can create this dApp in only three short steps: 

  1. Creating a Moralis server and installing the Rarible plugin.
  2. Creating an HTML file.
  3. Adding the application logic.

The users of the dApp will be able to continuously lazy mint NFTs by inputting a name, description, and image. Moreover, this is accomplishable through only a single line of code since we’ll be using Moralis’ Rarible plugin, and all data will be stored on IPFS. So, if you want to learn more about how to lazy mint NFTs, we suggest that you follow along as we take you through the complete process! 

Moreover, if you’d rather watch a clip from the Moralis YouTube channel explaining the process in even greater detail, then check out the following video: 

Step 1: How to Lazy Mint NFTs – Creating a Moralis Server and Installing the Rarible Plugin

A necessity for creating this lazy minting NFT dApp is a Moralis server. As such, the first step is (if you haven’t already) to sign up with Moralis. Once you have an account at hand, you will find the ”+ Create a new Server” button at the top of the Moralis admin panel. Clicking this button will initiate the process, and to create the server, you’ll need to input a name, choose a region, and select network(s). For this demo dApp, it doesn’t really matter which networks you opt for; however, this should be based on what chain you would like your dApp to run on. 

Once done with your choices, you can go ahead and click the ”Add Instance” button at the bottom right of your interface. This will initiate the process of booting up the server; however, this might take a couple of minutes. 

With the instance initiated, you can go ahead and click the ”Plugins” tab for the server in question and go to the Moralis plugin store. Once in the store, you can navigate yourself to the ”Rarible NFT Tool” plugin page and install this for the server that you just created. To install the plugin, you must have a blockchain node for the Ethereum mainnet and the Rinkeby testnet. Since you are a Moralis user, you can access these nodes under the “Speedy Nodes” tab in the navigation bar to the left on the Moralis admin panel. 

Now, with the server up and running and the Rarible NFT plugin installed, we can move on to the second step in the process, which revolves around structuring the contents of our dApp with HTML code. 

Step 2: How to Lazy Mint NFTs – Creating an HTML File

The second step in creating the NFT lazy minting dApp is to create an HTML file to structure the contents. As such, you can go ahead and navigate yourself to your preferred development environment and create an ”index.html” file. Next up, we are going to copy the Moralis vanilla boilerplate code from the Moralis GitHub page. We are going to take this boilerplate and remove everything within the ”<body>” tag and add this to the ”index.html” file of our dApp. 

The HTML code and the structure of the dApp are entirely dependent on the preferences of the developers. However, to exemplify what a potential dApp like this might look like and the HTML code for it, we are going to be using the demo dApp from the video. This is what the lazy minting dApp looks like: 

As you can see, we have a title at the top of the page followed by a container with three input fields and a submit button. This is what the code for the title, fields, and buttons looks like: 

<body>
        <div class="container">
            <div class="row">
                <div class="title">NFT Minter</div>
                <div id="app" class="col-md-6 offset-md-3">
                    <div id="success_message">
                        
                    </div>
                    <div class="form_element">
                    <input class="form-control type="text" id="input_name" name="name" placeholder="Token name">
                    </div>
                    <div class="form_element">
                    <input class="form-control type="text" id="input_description" name="description" placeholder="Description">
                    </div>
                    <div class="form_element">
                    <input class="form-control" type="file" id="input_image" name="image" accept="image/png, image/jpeg">
                    </div>
                    <div class="form_element">
                    <button class="btn btn-primary btn-lg btn-block" id="submit_button">Submit</button>
                    </div>
                </div>
            </div>
        </div>
    <script type="text/javascript" src="./main.js"></script>
  </body>

Moreover, if you take a closer look at the documentation for the ”index.html” file from the GitHub page, you’ll find that the file contains some additional code. This code is for bringing in a Bootstrap CDN, which we add to the head script. However, this is optional as you have the possibility to structure the contents and style it according to your own preferences. 

Step 3: How to Lazy Mint NFTs – Adding the Application Logic

With the HTML elements added to the code, the next step is to add the logic which provides the necessary functionalities allowing users to lazy mint NFTs. To do so, we can go ahead and create a ”main.jsJavaScript file, which will contain three different functions: ”login()”, ”initApp()”, and ”submit()”.

However, before we take a deep dive into the functions of the dApp, we must first initiate Moralis. To do so, you need to return to the Moralis admin panel and navigate yourself to the ”Servers” tab. From here, you need to click the ”View Details” button for the server in question and retrieve the server URL and application ID. With the information at hand, you can input this in the following manner: 

const serverUrl = “INSERT SERVER_URL”;

const appId = “INSERT APP_ID”;

With Moralis initiated, we can dive deeper into the first function of the dApp. 

login()

The first function of the ”main.js” file is ”login()”, which checks if there is a current MetaMask user. If one can’t be found, then the function calls “Moralis.authenticate()” and the ”initApp()” functions. If there is an existing user, then the function simply calls ”initApp()”. Nonetheless, this is what the complete function looks like:

async function login() {
  if (!user) {
   try {
      user = await Moralis.authenticate({ signingMessage: "Hello World!" })
      initApp();
   } catch(error) {
     console.log(error)
   }
  }
  else{
    Moralis.enableWeb3();
    initApp();
  }
}

initApp()

Next up, we have the ”initApp()” function, which is pretty straightforward. First, the function displays the interface of the dApp to the users. Second, it also adds the option to submit the information needed to lazy mint the NFT through an onclick event. As such, this is the complete function:

function initApp(){
    document.querySelector("#app").style.display = "block";
    document.querySelector("#submit_button").onclick = submit;
}

submit()

Finally, we have the ”submit()” function where most of the minting logic will be found. This is what the full function looks like, and it consists of several different parts: 

async function submit(){
    const input = document.querySelector('#input_image');
    let data = input.files[0]
    const imageFile = new Moralis.File(data.name, data)
    await imageFile.saveIPFS();
    let imageHash = imageFile.hash();

    let metadata = {
        name: document.querySelector('#input_name').value,
        description: document.querySelector('#input_description').value,
        image: "/ipfs/" + imageHash
    }
    console.log(metadata);
    const jsonFile = new Moralis.File("metadata.json", {base64 : btoa(JSON.stringify(metadata))});
    await jsonFile.saveIPFS();

    let metadataHash = jsonFile.hash();
    console.log(jsonFile.ipfs())
    let res = await Moralis.Plugins.rarible.lazyMint({
        chain: 'rinkeby',
        userAddress: user.get('ethAddress'),
        tokenType: 'ERC721',
        tokenUri: 'ipfs://' + metadataHash,
        royaltiesAmount: 5, // 0.05% royalty. Optional
    })
    console.log(res);
    document.querySelector('#success_message').innerHTML = 
        `NFT minted. <a href="https://rinkeby.rarible.com/token/${res.data.result.tokenAddress}:${res.data.result.tokenId}">View NFT`;
    document.querySelector('#success_message').style.display = "block";
    setTimeout(() => {
        document.querySelector('#success_message').style.display = "none";
    }, 5000)
}

First, the function fetches the image data from the file that the user uploads through the UI. This information is then used to upload the image to IPFS through the native integration of Moralis. With the image uploaded to IPFS, we then fetch the image hash and save it into a variable. 

We then take the name, description, and the image hash to create a metadata object which we then stringify to JSON format and, in turn, uploads this once again to IPFS through the Moralis ”saveIPFS()” function. 

Finally, we fetch the hash of the IPFS file and use this when calling the ”Moralis.Plugins.rarible.lazyMint()” function. In this function, we include the blockchain, user address, token type, and token URI. Furthermore, we can also specify a royalty amount for whenever the token is sold.

Following this, we top everything off by displaying a success message to the users along with a link to the NFT if everything works as intended. That’s it; it doesn’t have to be more complex than that when working with Moralis! 

Thanks to the Rarible plugin and Moralis’ native support for IPFS, we could lazy mint an NFT with just a couple of lines of code and upload to IPFS. However, if you are interested in looking closer at the complete dApp, then check out the Moralis GitHub page, where you’ll find the complete ”index.html” and ”main.js” files.

How to Lazy Mint NFTs – Summary

As a blockchain developer, you have the ability to mint NFTs, which are quite dynamic tokens of the blockchain industry, and they allow for a variety of innovative solutions. However, as the gas prices of the various blockchains increase, it is becoming more expensive to mint NFTs. To solve this issue, we were introduced to the concept of lazy minting. Lazy minting an NFT means that the minting process is pushed forward until someone actually purchases a token. As such, this means that the immediate minting cost is removed from the creators of the NFTs and transferred to the point of purchase. 

This benefits not only artists and developers of NFTs, but also the community as a whole as only sold NFTs are minted, which removes unnecessary, power-demanding transactions on the blockchain. Moreover, when working with Moralis, the process of lazy minting NFTs becomes relatively straightforward, and you don’t really need any extensive knowledge of any blockchain languages. Actually, it is possible to create an NFT lazy minting dApp in just three simple steps: 

  1. Creating a Moralis server and installing the Rarible plugin.
  2. Creating an HTML file.
  3. Adding the application logic.

However, this isn’t all there is to Moralis, as its Web3 operating system can be utilized in all sorts of blockchain projects. As such, you are able to develop dApps at a significantly quicker rate, and the process becomes considerably more accessible with the platform’s tools. 

The possibilities with Moralis are endless, and you can, for example, launch an NFT marketplace, develop Ethereum dApps, create a BEP20 token, and much much more. So, if you are striving to become a blockchain developer, then sign up with Moralis right now. It only takes a couple of seconds, and it is completely free! 

Share on facebook
Share on twitter
Share on linkedin
Moralis Blog
Moralis Blog

Related Articles

Become a Web3 Expert
Subscribe to our newsletter and get our E-book Web3 Speed run for FREE