How to Mint an NFT from Code – Part 2

Minting an NFT is the act of publishing a unique instance of an ERC721 token on the blockchain. Now that we have successfully deployed a smart contract to the Sepolia network in Part I of this NFT tutorial series, let’s flex our web3 skills and mint an NFT!

At the end of this tutorial, you’ll be able to mint as many NFTs as you’d like with this code —let’s get started!

  • Creating a Provide using ethers

Open the repository from Part 1 in your favorite code editor (e.g. VSCode), and create a new file in the scripts folder called ‘mint-nft.js’. We will be using the ethers library from Part 1 to connect to the Provider. Add the following code to the file:

require("dotenv").config();
const ethers = require("ethers");

// Get App URL
const API_KEY = process.env.API_KEY;
const API_URL = process.env.API_URL;

// Define a Provider
const provider = new ethers.providers.JsonRpcProvider(API_URL);

// Get contract ABI file
const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json");

// Create a signer
const privateKey = process.env.PRIVATE_KEY;
const signer = new ethers.Wallet(privateKey, provider);

// Get contract ABI and address
const abi = contract.abi;
const contractAddress = process.env.CONTRACT_ADDRESS;

// Create a contract instance
const myNftContract = new ethers.Contract(contractAddress, abi, signer);

// Get the NFT Metadata IPFS URL
const tokenUri =
  "https://gateway.pinata.cloud/ipfs/<your-metadata-code>";

// Call mintNFT function
const mintNFT = async () => {
  let nftTxn = await myNftContract.mintNFT(signer.address, tokenUri);
  await nftTxn.wait();
  console.log(
    `NFT Minted! Check it out at: https://sepolia.etherscan.io/tx/${nftTxn.hash}`
  );
};

mintNFT()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });
  • Configure the metadata of your NFT using IPFS

Our mintNFT smart contract function takes in a tokenURI parameter that should resolve to a JSON document describing the NFT’s metadata— which is really what brings the NFT to life, allowing it to have configurable properties, such as a name, description, image, and other attributes.

We will use Pinata, a convenient IPFS API and toolkit, to store our NFT asset and metadata and ensure that our NFT is truly decentralized. If you don’t have a Pinata account, sign up for a free account.

Once you’ve created an account: