2021 Fillmore Street #1128

}

24/7 solutions

Top 10 Cloud Providers

How to Write a Hardhat NFT Smart Contract for Polygon 2/4

This is part 2 of a 4 part tutorial for developing NFTs on Polygon where we write a Hardhat NFT Smart Contract and deploy it to the Hardhat in-memory network.

Part 2 of 4 - A Hardhat NFT Smart Contract

We’re going to leverage OpenZeppelin smart contracts for our Hardhat NFT smart contract. From our allcode-polygon-nft directory, we’ll install the OpenZeppelin contracts by running the following command

npm install @openzeppelin/contracts
Upon successful installation of the OpenZeppelin contracts, let’s return back to our IntelliJ. In the contracts directory, let’s create a new contract entitled AllCodeNFT.sol.
The sol extension will specify that is a solidity file.

For the NFT contract, we’re going to derive from the OpenZeppelin ERC721 specification. The majority of the functionality will actually reside in the OpenZeppelin implementation.

pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract AllCodeNFT is ERC721, Ownable {

  //imported from OpenZeppelin
  using Counters for Counters.Counter;
  using Strings for uint256;

  Counters.Counter private _tokenIds;
  mapping (uint256 => string) private _tokenURIs;
  
  constructor() ERC721("AllCodeNFT", "ANFT") {
  }

  //Sets the metadata associated with the token. The metadata will be the ipfs hash. 
  function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual
  {
    _tokenURIs[tokenId] = _tokenURI;
  }

  //grabs the tokenURI for the tokenid. effectively grabbing the metadata.
  function tokenURI(uint256 tokenId) public view virtual override
    returns (string memory)
  {
    require(_exists(tokenId), "The MetaData for this tokenId does not exist in this contract");
    string memory _tokenURI = _tokenURIs[tokenId];
    return _tokenURI;
  }

  //mints a token by taking the metadata passed into the uri, 
//and associated that metadata with the recipients address.
  //next we assign the uri metadata to the tokenId.
  function mint(address recipient, string memory uri) public 
    returns (uint256)
  {
    _tokenIds.increment();
    uint256 newItemId = _tokenIds.current();
    _mint(recipient, newItemId);
    _setTokenURI(newItemId, uri);
    return newItemId;
  }
}

We’ll start by killing the Greeting.sol file in the contracts directory.

Next, we’ll delete the contracts folder in the artifacts directory.

Next, we need to update our test file. Inside the test folder, edit the sample-test.js file by replacing the contents with the following:

const { expect } = require("chai");
describe("NFT Mint", function() {
  it("Deploy the NFT contract, mint a token, and ensure that we have the right metadata associated with the tokenId", async function() {
    const NFT = await ethers.getContractFactory("AllCodeNFT");
    const nft = await NFT.deploy();
    const URI = "ipfs://QmVH5T7MFVU52hTfQdWvu73iFPEF3jizuGfyVLccTmBCX2";
    await nft.deployed();
    await nft.mint("0x44f2b515211953d5f07038be619D58a91accB8E7", URI)
    expect(await nft.tokenURI(1)).to.equal(URI)
  });
});

In this test script, we’re going to deploy the NFT Contract, mint a token, and then ensure that the token that is minted on the blockchain has the same URI. The URL comes from our Pinata deployment, here. In the invocation of the mint function, you’ll want to replace the address with your address, and the URI with the hash that you acquired from Pinata.

Let’s try running this against the hardhat in-memory network. To run against the hardhat in-memory network, we’ll go into our hardhat.config.js to make the following changes:

  1. We’ll change the default network from Matic to Hardhat.
  2. We’ll comment out the Matic network

Your hardhat.config.js should look like this

const { expect } = require("chai");
describe("NFT Mint", function() {
  it("Deploy the NFT contract, mint a token, and ensure that we have the right metadata associated with the tokenId", async function() {
    const NFT = await ethers.getContractFactory("AllCodeNFT");
    const nft = await NFT.deploy();
    const URI = "ipfs://QmVH5T7MFVU52hTfQdWvu73iFPEF3jizuGfyVLccTmBCX2";
    await nft.deployed();
    await nft.mint("0x44f2b515211953d5f07038be619D58a91accB8E7", URI)
    expect(await nft.tokenURI(1)).to.equal(URI)
  });
});

Now, we’ll run the test by running the following command:

npx hardhat test
You should receive the following output:
const { expect } = require("chai");
describe("NFT Mint", function() {
  it("Deploy the NFT contract, mint a token, and ensure that we have the right metadata associated with the tokenId", async function() {
    const NFT = await ethers.getContractFactory("AllCodeNFT");
    const nft = await NFT.deploy();
    const URI = "ipfs://QmVH5T7MFVU52hTfQdWvu73iFPEF3jizuGfyVLccTmBCX2";
    await nft.deployed();
    await nft.mint("0x44f2b515211953d5f07038be619D58a91accB8E7", URI)
    expect(await nft.tokenURI(1)).to.equal(URI)
  });
});

Once the test passes, now we’re ready to mint the NFTs on the Mumbai testnet.

Joel Garcia
Joel Garcia

Joel Garcia has been building AllCode since 2015. He’s an innovative, hands-on executive with a proven record of designing, developing, and operating Software-as-a-Service (SaaS), mobile, and desktop solutions. Joel has expertise in HealthTech, VoIP, and cloud-based solutions. Joel has experience scaling multiple start-ups for successful exits to IMS Health and Golden Gate Capital, as well as working at mature, industry-leading software companies. He’s held executive engineering positions in San Francisco at TidalWave, LittleCast, Self Health Network, LiveVox acquired by Golden Gate Capital, and Med-Vantage acquired by IMS Health.

Related Articles

What is Tigera?

What is Tigera?

An AWS Advanced Technology Partner, Tigera delivers Calico and Calico Enterprise for security and networking on EKS, both of which are AWS Containers Competency certified.

Vezt

Vezt

Blockchain technology has the potential to be a windfall for musicians, filmmakers, and video game developers. With the advent of new technology, the way we consume entertainment is changing. Vezt assists artists in distributing their tracks on digital channels and in promoting their work.

Top Platforms for NFTs: Polygon and Flow

Top Platforms for NFTs: Polygon and Flow

As blockchain technology continues to develop, we are seeing an increase in the number of platforms, languages, and applications. Your works of art and collectables can now be presented and traded in the form of non-fungible tokens (NFTs), which are a relatively new development.

Free AWS Services List

Download this FREE list of all 200+ AWS services and ensure that you're using the optimal services for your use case to enhance efficiency and save money!

Free AWS Business Continuity Plan Template

Make sure you have the proper business continuity plan explicitly for your AWS infrastructure. Our team of experts built this template using AWS Best Practices so you can ensure it's built to scale! 

Free Cloud Migration Checklist

Without the proper cloud migration strategy, you risk losing time and money. Ensure that your migration process is running smoothly with our FREE cloud migration checklist.

Free AWS Services List

You might be optimizing with the wrong AWS services. Download this FREE list of all 200+ AWS services and ensure that you're using the optimal services for your use case to enhance efficiency and save money!

Download your FREE AWS Business Continuity Plan Template
Download Free 200+ AWS Services Checklist
Download our 10-Step Cloud Migration ChecklistYou'll get direct access to our full-length guide on Google Docs. From here, you will be able to make a copy, download the content, and share it with your team.