Are you getting the most out of your AWS investment? Get your free AWS Well-Architected Assessment.

2021 Fillmore Street #1128

}

24/7 solutions

polygon_logo_verify

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

AWS Think Big with Small Business Program’s Competitive Edge

AWS Think Big with Small Business Program’s Competitive Edge

The Amazon Cloud can help alleviate most issues involving transitioning the cloud. Businesses of any scope can hope to build solutions that are scalable and adaptable to their industry of work. Smaller or minority-owned businesses may still struggle to stand out among bigger companies or make an AWS environment as efficient as possible with fewer funds to spend. To alleviate these burdens, Amazon has the Think Big With Small Business program available through their Public Sector partnership program.

AWS Think Big for Small Business, Data Analytics, and Business Intelligence

AWS Think Big for Small Business, Data Analytics, and Business Intelligence

The AWS Think Big for Small Business Program is an outreach program designed to provide small and/or minority-owned public sector organizations support in the form of business intelligence, technical expertise, and marketing strategies. With cloud-based solutions and experience, various public institutions globally have seen continued success in government, educational, and nonprofit sectors. While the funding provided can help significantly to meet business objectives, the expertise on navigating the cloud and how to extend outwards towards customers is just as critical.

Best Practices for Using AWS Systems Manager

Best Practices for Using AWS Systems Manager

As newer users adopt the AWS cloud, it can be difficult to watch for issues and resolve them as needed. AWS Systems Manager grants better visibility over the AWS environment by clustering resources, providing legible and usable data based on performance, and actions to take that abide by AWS compliance requirements and best practices. This service provides everything management needs to evaluate the cloud and ensure continued functionality.