How to Mint an NFT (Part 2/3 of NFT Tutorial Series)
Beeple(opens in a new tab): $69 Million 3LAU(opens in a new tab): $11 Million Grimes(opens in a new tab): $6 Million
All of them minted their NFT’s using Alchemy’s powerful API. In this tutorial, we’ll teach you how to do the same in <10 minutes.
“Minting an NFT” is the act of publishing a unique instance of your ERC-721 token on the blockchain. Using our smart contract from Part 1 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 your heart (and wallet) desires!
Let’s get started!
Step 1: Install Web3
If you followed the first tutorial on creating your NFT smart contract, you already have experience using Ethers.js. Web3 is similar to Ethers, as it is a library used to make creating requests to the Ethereum blockchain easier. In this tutorial we’ll be using Alchemy Web3(opens in a new tab), which is an enhanced Web3 library that offers automatic retries and robust WebSocket support.
In your project home directory run:
1npm install @alch/alchemy-web32
Step 2: Create a mint-nft.js
file
Inside your scripts directory, create a mint-nft.js
file and add the following lines of code:
1require("dotenv").config()2const API_URL = process.env.API_URL3const { createAlchemyWeb3 } = require("@alch/alchemy-web3")4const web3 = createAlchemyWeb3(API_URL)5คัดลอก
Step 3: Grab your contract ABI
Our contract ABI (Application Binary Interface) is the interface to interact with our smart contract. You can learn more about Contract ABIs here(opens in a new tab). Hardhat automatically generates an ABI for us and saves it in the MyNFT.json
file. In order to use this we’ll need to parse out the contents by adding the following lines of code to our mint-nft.js
file:
1const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json")2คัดลอก
If you want to see the ABI you can print it to your console:
1console.log(JSON.stringify(contract.abi))2คัดลอก
To run mint-nft.js
and see your ABI printed to the console navigate to your terminal and run:
1node scripts/mint-nft.js2คัดลอก
Step 4: Configure the metadata for your NFT using IPFS
If you remember from our tutorial in Part 1, 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.
Interplanetary File System (IPFS) is a decentralized protocol and peer-to-peer network for storing and sharing data in a distributed file system.
We will use Pinata, a convenient IPFS API and toolkit, to store our NFT asset and metadata to ensure our NFT is truly decentralized. If you don’t have a Pinata account, sign up for a free account here(opens in a new tab) and complete the steps to verify your email.
Once you’ve created an account:
Navigate to the “Files” page and click the blue "Upload" button at the top-left of the page.
Upload an image to Pinata — this will be the image asset for your NFT. Feel free to name the asset whatever you wish
After you upload, you'll see the file info in the table on the "Files" page. You'll also see a CID column. You can copy the CID by clicking the copy button next to it. You can view your upload at:
https://gateway.pinata.cloud/ipfs/<CID>
. You can find the image we used on IPFS here(opens in a new tab), for example.
For the more visual learners, the steps above are summarized here:
Now, we’re going to want to upload one more document to Pinata. But before we do that, we need to create it!
In your root directory, make a new file called nft-metadata.json
and add the following json code:
1{2 "attributes": [3 {4 "trait_type": "Breed",5 "value": "Maltipoo"6 },7 {8 "trait_type": "Eye color",9 "value": "Mocha"10 }11 ],12 "description": "The world's most adorable and sensitive pup.",13 "image": "ipfs://QmWmvTJmJU3pozR9ZHFmQC2DNDwi2XJtf3QGyYiiagFSWb",14 "name": "Ramses"15}16แสดงทั้งหมดคัดลอก
Feel free to change the data in the json. You can remove or add to the attributes section. Most importantly, make sure image field points to the location of your IPFS image — otherwise, your NFT will include a photo of a (very cute!) dog.
Once you’re done editing the JSON file, save it and upload it to Pinata, following the same steps we did for uploading the image.
Step 5: Create an instance of your contract
Now, to interact with our contract, we need to create an instance of it in our code. To do so we’ll need our contract address which we can get from the deployment or Etherscan(opens in a new tab) by looking up the address you used to deploy the contract.
In the above example, our contract address is 0x5a738a5c5fe46a1fd5ee7dd7e38f722e2aef7778.
Next we will use the Web3 contract method(opens in a new tab) to create our contract using the ABI and address. In your mint-nft.js
file, add the following:
1const contractAddress = "0x5a738a5c5fe46a1fd5ee7dd7e38f722e2aef7778"23const nftContract = new web3.eth.Contract(contract.abi, contractAddress)4คัดลอก
Step 6: Update the .env
file
Now, in order to create and send transactions to the Ethereum chain, we’ll use your public ethereum account address to get the account nonce (will explain below).
Add your public key to your .env
file — if you completed part 1 of the tutorial, our .env
file should now look like this:
1API_URL = "https://eth-goerli.g.alchemy.com/v2/your-api-key"2PRIVATE_KEY = "your-private-account-address"3PUBLIC_KEY = "your-public-account-address"4คัดลอก
Step 7: Create your transaction
First, let’s define a function named mintNFT(tokenData)
and create our transaction by doing the following:
Grab your PRIVATE_KEY and PUBLIC_KEY from the
.env
file.Next, we’ll need to figure out the account nonce. The nonce specification is used to keep track of the number of transactions sent from your address — which we need for security purposes and to prevent replay attacks(opens in a new tab). To get the number of transactions sent from your address, we use getTransactionCount(opens in a new tab).
Finally we’ll set up our transaction with the following info:
'from': PUBLIC_KEY
— The origin of our transaction is our public address'to': contractAddress
— The contract we wish to interact with and send the transaction'nonce': nonce
— The account nonce with the number of transactions sent from our address'gas': estimatedGas
— The estimated gas needed to complete the transaction'data': nftContract.methods.mintNFT(PUBLIC_KEY, md).encodeABI()
— The computation we wish to perform in this transaction — which in this case is minting a NFT
Your mint-nft.js
file should look like this now:
1 require('dotenv').config();2 const API_URL = process.env.API_URL;3 const PUBLIC_KEY = process.env.PUBLIC_KEY;4 const PRIVATE_KEY = process.env.PRIVATE_KEY;56 const { createAlchemyWeb3 } = require("@alch/alchemy-web3");7 const web3 = createAlchemyWeb3(API_URL);89 const contract = require("../artifacts/contracts/MyNFT.sol/MyNFT.json");10 const contractAddress = "0x5a738a5c5fe46a1fd5ee7dd7e38f722e2aef7778";11 const nftContract = new web3.eth.Contract(contract.abi, contractAddress);1213 async function mintNFT(tokenURI) {14 const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce1516 //the transaction17 const tx = {18 'from': PUBLIC_KEY,19 'to': contractAddress,20 'nonce': nonce,21 'gas': 500000,22 'data': nftContract.methods.mintNFT(PUBLIC_KEY, tokenURI).encodeABI()23 };24 }25