Dude! I just deployed my own NFT!!! ….WT.F!

Pari Tomar
BuildBear Labs
Published in
7 min readApr 5, 2022
Mint your own NFT

Yo 🤟 !! NFTs are the THING!!! The thing that is changing the world for all the artists around. Isn’t that like the coolest thing on blockchain.

What do you say? Should we just do our own NFT thing? Well, if you are game for it, just follow along.

NFT is an acronym for Non-Fungible Token. These are a type of digital asset that may or may not represent real-world objects like music, art, videos. Similar to any other token, NFTs are bought and sold online. However, their biggest USP (unique selling proposition) is the fact that they are unique and hence, command huge value in the Metaverse world. For eg, the Axie Infinity.

Since each NFT is separately owned, there are “collectors” who collect such NFTs and place high value on these digital rights.

NFTs explained: Why people spend millions of dollars on JPEGs

Now, lets get our ✋s dirty with doing our own NFT contract.

Tools we will be using 🛠️

  • Alchemy: We will be using Alchemy node provider, which provides us a free tier to access the Mumbai Matic Test network (yes, we will be working with the Mumbai Matic Test network for our tuts today).
  • MetaMask: MetaMask is a chrome wallet that lets us interact with the blockchain. We will need our wallet details from Metamask. You have many other options; but we are just sticking to this for ease.
  • Hardhat: Hardhat is the development tool that allows us to test and deploy our smart contract with so much ease.
  • IPFS: IPFS is a distributed system for storing and accessing files, websites, applications, and data. We will be using Pinata client to interact with IPFS. Pinata gives users the ability to upload, manage, and share their content whenever, wherever, and, with whomever they want.

Make sure you have gone through Part-1 of this article series so that you get a better grip on what we’re doing. And if you like our work, please clap 👏 and share for us to know that our content is relevant to you.

Please note, you will have to connect your Metamask to the Mumbai Matic Testnet network for the purpose of this Tuts. Read 👉 this so that you are connected to Mumbai Matic Testnet. Once that is done, you should fetch test tokens; for that head 👉 here

Also note: You can download and run the same code that we will using in our tutorial (aka tuts) from here 👉 Github repository. If you like out stuff, give us a star 🌟 on Github.

💥 Boom! Now let’s get to the fun part 💥

1. Initialize our Project

Create a folder and initialize it using npm init -yes to install various dependencies for our project.

CLI commands

mkdir NFT-verse && cd NFT-verse
npm init -yes

Install Hardhat and create an empty config file to initialize the configuration for our NFT.

CLI commands

npx hardhat

On running the above command, you will see a Welcome Hardhat text and some options with it. Choose ‘create an empty config file’ since we’re going to build everything from scratch.

Once done, you’ll see a ‘hardhat.config.js’ file in your root directory.

Now, create folders for our contract and scripts

CLI commands

mkdir contracts && mkdir scripts

🕧 It’s time to open your NFT Folder in a code editor 🕧

2. Write our Smart Contract

Create a file NFT.sol inside your contracts directory to write solidity code for our smart contract.

Below is a sample code for our smart contract.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.1;
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
// our contract NFT inherits from openzeppelin's ERC721URIStorage Contract
contract NFT is ERC721URIStorage {
// importing and then declaring a counter
// to keep a track of total tokens minted
using Counters for Counters.Counter;
Counters.Counter private tokenId;
// our constructor function calls the ERC721
// passing two arguments for name and symbol respectively
constructor() ERC721("UVLabs", "UVL") {}
// defining a function mint which takes a recipient's address and a tokenURI as an argument
function mint(address recipientAddress, string memory tokenURI_) public returns (uint256 newItemId) {
// increments tokenId value by one
tokenId.increment();
newItemId = tokenId.current();
// _safeMint is a private method
// which mints the next value of the counter
_safeMint(recipientAddress, newItemId);
_setTokenURI(newItemId, tokenURI_);
}
}

Lets run through our smart contract real quick 🏃

  • First, we have defined the version of solidity we’re going to use.
  • We have then used some standard contracts provided to us by openzeppelin; once you get full time dev into Smart Contracts, you will realise Open Zeppelin Contracts are God Sent. In order to use their contracts, we need to install them locally in our project.

CLI commands

npm install @openzeppelin/contracts
  • Then, we have defined our contract NFT, which inherits from openzeppelin’s ERC721URIStorage contract*.*
  • The next two lines are used to keep a track of the total numbers of tokens minted.
  • Then, the constructor function calls the openzeppelin’s ERC721 which takes two arguments i.e. the name and symbol*.* You are free to choose your own name and symbol.
  • Then we have our friend, the mint function. It takes in 2 parameters. First, the address to which the NFT has to be issued; Second, the tokenURI. We will explain the tokenURI part in a bit.

3. Customizing ‘hardhat.config.js’

Fetch your MetaMask Account Key and Alchemy’s endpoint URL

If you find this information new, try considering our previous article to understand it better and then follow along. Here is the link for your reference: Part-1

Update your Hardhat.config.js to the following:

/**
* @type import('hardhat/config').HardhatUserConfig
*/
require('dotenv').config();
require('@nomiclabs/hardhat-ethers')
const {API_URL, PRIVATE_KEY} = process.env;module.exports = {
solidity: "0.8.1",
networks: {
hardhat: {},
"mumbai-matic": {
url: API_URL,
accounts: [`0x${PRIVATE_KEY}`],
},
}
}

4. Deploy Script

Create a file deploy.js inside the scripts directory and write your deploy script. Our sample code is as follows:

const { ethers } = require("hardhat");async function main() {
const NFT = await ethers.getContractFactory("NFT");
const deployedNFT = await NFT.deploy();
console.log(`Contract deployed to address: ${deployedNFT.address}`)
}
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

Now, let’s deploy our smart contract. 🎉🎉🎉🎉🎉

CLI command:

npx hardhat run scripts/deploy.js --network mumbai-matic

Once successfully executed, the terminal will give you an output of the address to which the contract has been deployed. For eg, ours was

Contract deployed to address: 0x4D89D079aCfef45b7cDA107533A89d5c44DCFb94

Save this address somewhere for further use!

5. Creating NFT Metadata 💽

An NFT Metadata file is a JSON document that serves as a descriptor for any particular NFT. It allows you to specify the NFT’s name, URI, and other attributes.

Create a new file NFTMetadata.json. Our sample file is over here (also in the repo):

{
"description": "UVLabs",
"image": "<https://gateway.pinata.cloud/ipfs/QmTfjtxzekdGkZvm9qcFaFMWAsgkjUtiU7knSyQ3d2ze62>",
"name": "UVLabs"
}

Upload the NFTMedata.json file on Pinata. Once that is done open the JSON file using Pinata and copy the URL. Please note, the image URL mentioned above is the URL of only the image that we want in our NFT. You will get a similar URL for the JSON file also.

Yes, if you want your NFT to have a cool image, you must upload that to Pinata first and save that in the image tag in the JSON file.

Pro-tip: you can also add a field animation_url to make an animated NFT! Eg: https://api.foundation.app/opensea/114867 (this NFT sits over 👉 here)

5. Minting script ⛏️

Create a file mint.js inside your scripts directory.

Our sample mint.js file is here for your reference:

const hre = require('hardhat');async function main() {
const tokenURI = "<https://gateway.pinata.cloud/ipfs/Qmc4ywZjPsHAb67PVNPjRpjKgcqEAhxwy1FzkdPHoo5e4h>";
// this is URL that you will get from Pinata
const nftContractFactory = await ethers.getContractFactory("NFT");
const nftContractInstance = new ethers.Contract(
"0x4D89D079aCfef45b7cDA107533A89d5c44DCFb94",
//insert contract address that gets deployed
nftContractFactory.interface,
)
const signer = await ethers.provider.getSigner();
const signerAddress = await signer.getAddress()
const txn = await nftContractInstance.connect(signer).mint(signerAddress, tokenURI)

txn.wait();
console.log(`Your transaction has been successfully broadcasted! The transaction hash is ${txn.hash}`);
if (hre.network.config.url != '<http://127.0.0.1:8545>') {
console.log(`\\nPlease follow this link <https://testnets.opensea.io/${signerAddress}`>);
};
};
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});

Run the mint.js:

Use CLI Command:

npx hardhat run scripts/mint.js --network mumbai-matic

Once successfully executed, you will see an output in your terminal similar to the following:

Your transaction has been successfully broadcasted! 
The transaction hash is 0x449c9e5c47cf902834131f38f11f6b38d4919dc215141620fd70d7b45b5d2a99
Please follow this link <https://testnets.opensea.io/0xa5ac8d8A4c6E85aB211D2628b3C1Ebd4b25E03e0>

Congratulations! 🥳🥳🥳🥳🥳

You just minted your own NFT!!

It’s time to see our NFT on Opensea!!! The terminal provides you with the link where you can see the NFT live on Opensea. Please note, since we used the Mumbai Matic Test Network, our link takes you to the testnets.opensea.io and not the mainnet opensea website.

🎊 It’s time to showcase your work to the people. 🎊. Please do tag us @uv_labs on Twitter when you showcase your NFTs to the world. We would love to see them and share them too!!!

Don’t worry, if you get any error message, you can ask us by tagging @uv_labs on Twitter.

Again, all the code that we just ran through is over here 👉 Github repository. Do give us a star, clap if you liked our work.

Authors (open to feedback): 👇

Amateur-Dev and Pari Tomar

--

--

Pari Tomar
BuildBear Labs

Researches, talks, shares know-how on building a career in blockchain space