Using Infura’s NFT API With Lootbox

0xpaulie

Paul McAviney

Posted on July 7, 2022

Using Infura’s NFT API With Lootbox

Introduction

I’ve only been in Web3 for about a year now, but I can honestly say that NFTs are the most exciting aspect about it for me. I’m not talking about Apes or Punks, however. PFP (profile picture) projects and art, although cool and a simple proof of concept for the technology, won’t create a better world.

Instead, I’m excited about the actual utility of NFTs. Allowing gamers to own their assets, delivering fair royalty commissions to musicians and artists, and making concert tickets impossible to scalp while providing a sweet digital memento are some of the use cases I find interesting.

However, building and interacting with NFTs aren’t always the easiest thing to do. As developers, we need clear resources to build projects effectively in order to give our users a better experience.

I recently heard about Infura’s private beta for their NFT API, so I thought I would check it out and see how it could improve my development workflow. In this article, I will explore the capabilities of Infura’s NFT API and test it out using a Lootbox NFT sample project from Infura’s Github.

What is the Infura NFT API?

According to this blog post on Infura’s website, the NFT API will help me “accelerate my time to value” and allow me to interact with anything related to NFTs through a convenient SDK. In addition, I can build and verify my NFTs, create metadata templates and easily mint NFTs. So my first impression is that I can start creating and interacting with NFTs using API endpoints rather than building smart contracts and deploying them.

Sounds pretty useful! And I’m all for testing any tool that will help improve my development processes. Infura’s NFT API suite seems helpful for any dev transitioning from Web2, since you can run API endpoints without Solidity.

Now let’s dive deeper and see what this NFT API is capable of.

Infura NFT API Capabilities

A quick glance through the NFT API documentation on Infura’s website proves my first impression correct. I will be able to deploy and call methods on my NFT contracts using Infura’s API endpoints, without having to actually write the smart contract code. This is a huge time saver!

Deploying a contract is straightforward. I create the NFT metadata in JSON format, upload the metadata to IPFS in another Infura project, then create a simple deployment script and run it with node. I also have to make a .env file to hold some environment variables. My deployment script ends up looking something like this:

import { config as loadEnv } from 'dotenv';
import { SDK, Auth, TEMPLATES } from '@infura/sdk';

loadEnv();

const auth = new Auth({
      projectId: process.env.INFURA_PROJECT_ID,
      secretId: process.env.INFURA_PROJECT_SECRET,
      privateKey: process.env.WALLET_PRIVATE_KEY,
      chainId: 4,
    });

const sdk = new SDK(auth);

const myNFTContract = await sdk.deploy({
   template: TEMPLATES.ERC721Mintable,
   params: {
     name: 'My NFT Contract',
     symbol: 'MYNFT',
     contractURI: 'https://MY_NFT_METADATA_URL',
   },
 });
console.log(`Contract address is: ${myNFTContract.contractAddress}`);
Enter fullscreen mode Exit fullscreen mode

Then, I run it with Node. Infura creates a smart contract for me and uploads it to Ethereum behind the scenes. After that, I just need to make sure I have some tokens for whichever chainId I have specified in my code. In this case, the Rinkeby testnet (chainId: 4). From here, I could mint NFTs from this contract or gather the contract metadata.

This is a much easier method to create an NFT contract than writing Solidity code and deploying it myself!

The NFT API also provides methods for gathering NFT info from wallets, transferring NFTs from one wallet to another, and a host of other NFT methods. These include adding an address to the minter list, setting royalty info, and changing the contract URI.

Overall, it seems that Infura’s NFT API indeed helps improve my development workflow. Having all the necessary functionality for building and interacting with NFTs packaged together in an easy-to-use SDK is quite convenient!

But enough about what it can do, let’s see how this API works!

The Lootbox Project

Along with the NFT API, Infura released an NFT Gallery Project on their Github to demo its capabilities. All I will have to do is input an Infura project ID and secret, then connect my MetaMask wallet to the dapp frontend. Then the dapp uses the API to fetch all my NFTs to display nicely in the frontend. So to break that down, I will need the following things for this project:

Let’s get started!

Step 1 - The Infura Project ID and Secret

Before starting the Lootbox project, I want to gather the necessary items. So first, I’ll head to infura.io, log in, and create a new project. Then, I can grab the Project ID and Project Secret for use later.

A new project dialogue box on Infura

The project ID and project secrets, highlighted in red, showing the reader where to copy from

Step 2 - MetaMask

This step will be quick because I already have the extension installed in my browser. If someone following along with this article doesn’t, however, head to metamask.io and download the extension for your specific browser. Then follow the steps to create a new account.

Next, I’ll sign in and switch accounts to the wallet address that holds my NFTs. If you need to acquire an NFT, you can head to your favorite marketplace and buy one or try to create one yourself using the Infura NFT API 😉. Either way, you will need some ETH in your wallet.

Step 3 - Setting Up The Project

With all the prep work out of the way, I can start building the project. So next, I’ll clone the project repo onto my local machine. I’ll first navigate to the folder I want to work out of and then type the following command:

git clone https://github.com/INFURA/nft-api-lootbox-gallery-app.git
Enter fullscreen mode Exit fullscreen mode

Next, I will change directories into the project folder and install dependencies using yarn:

cd nft-api-lootbox-gallery-app
yarn
Enter fullscreen mode Exit fullscreen mode

After everything is installed, the last thing I need to do is create a .env file to store my environment variables and secrets. I’ll just copy the file that’s already there and add my variables to it.

cp .env .env.local 
Enter fullscreen mode Exit fullscreen mode

Now I’ll open up the project and add my Project ID and Project Secret from my recently created Infura project. There’s also an option to input the Account Address of any wallet to view their NFTs, but I’ve got my own I want to see in the Lootbox NFT Gallery.

With all the setup out of the way, I can finally run the Lootbox project. But first, I want to browse through the code to see what’s happening under the hood.

Step 4 - The Lootbox Code

Based on the README file of the Lootbox project, the most important components are in the pages/index.tsx, hooks/useWallet.ts, and pages/api/assets.ts files. So I’m going to browse those and see if I can figure out how this project uses the Infura NFT API.

After looking through these files, I can see the pages/index.tsx file contains the code which displays the frontend for the project. If the showGallery state variable is true, then it should display my NFTs. If it’s false, then it should display the welcome text with the Connect Wallet button. This Connect Wallet button connects to some functions in the hooks/useWallet.ts file, so I’ll check there next.

In the hooks/useWallet.ts file, I can see the function which is supposed to grab my NFTs. Specifically, the getTokens function.

 const getTokens = async (accountAddress: string) => {
    try {
      const { data } = await axios.post('/api/assets', { accountAddress });
      return data.assets;
    } catch (error) {
      setTimeout(() => {
        setErrorMessage('Error getting tokens');
      }, 2000);
      return;
    }
  };
Enter fullscreen mode Exit fullscreen mode

This function seems to make a POST request using a parameter from the /api/assets file and return the results with my assets. So looking into the pages/api/assets.ts file, I can see where the NFT API is being used.

  try {
    const { data } = await axios.get(  `https://nft.api.infura.io/networks/1/accounts/${accountAddress}/assets/nfts`,
      {
        headers: {},
        auth: {
          username: `${process.env.INFURA_PROJECT_ID}`,
          password: `${process.env.INFURA_PROJECT_SECRET}`
        }
      }
    );

    return res.status(200).json({
      assets: data.assets,
    });
Enter fullscreen mode Exit fullscreen mode

This code calls the get function of the NFT API, using my Infura Project ID and Project Secret to access my account, and returns my NFTs in a JSON object. Following the path back to the pages/index.tsx file, if the getTokens function from hooks/useWallet.ts doesn’t timeout, it will return my NFTs, switch the setGallery state variable to true, and display my NFTs on the page.

Cool! So I’ve got an idea of how it works, let’s see it in action!

Step 5 - Running The Lootbox Project

To run the project locally, I just need to type:

yarn dev
Enter fullscreen mode Exit fullscreen mode

After navigating to http://localhost:3000/, I can see a nice-looking frontend for the Lootbox Project.

The Lootbox project main page displays the title

Clicking on Connect Wallet prompts my MetaMask wallet to pop up to approve the connection request.

MetaMask pops up, prompting me to connect my wallet

After connecting, it immediately starts fetching my tokens. This is the point where I now know the dapp is using the NFT API.

It says:

Once the fetch is successful, it displays my NFTs in a fancy gallery, allowing me to browse and choose each one to get a better look at them. Neat!

My NFTs displayed successfully

Conclusion

My verdict on the Infura NFT API is that it's a tool that cuts down my development time, and there’s quite a bit I can do with it. It’s handy to build, mint, and interact with NFTs from an easy-to-use API. Although I am more familiar with building NFT contracts with Solidity and deploying them with Truffle, I can easily see how this would help smooth the transition of a Web2 dev into Web3. Using JavaScript rather than writing a smart contract will be a huge time saver for many Web2 developers.

I would suggest trying the NFT API out for yourself. It’s still in private beta, but anyone can register. For more information on its capabilities, you can check out this YouTube demo or Infura’s documentation.

💖 💪 🙅 🚩
0xpaulie
Paul McAviney

Posted on July 7, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related