*** Craft Your Own Ethereum NFT: A Beginner’s Guide — Part 5 ***
Unlock the world of digital collectibles with a simple yet enchanting journey through building your own NFT (Non-Fungible Token) contract on the Ethereum blockchain. In this step-by-step tutorial, we’ll harness the magic of Hardhat and OpenZeppelin Contracts to bring your digital treasures to life.
🔮 What’s the Spell?
Imagine having the power to conjure your own unique digital artwork, virtual pets, and more, all backed by the unbreakable spell of blockchain technology. Get ready to wield this power with our tutorial on crafting a basic NFT contract.
✨ Preparing Your Toolkit
Before we dive into the incantations, make sure you’re armed with these essentials:
🔑 MetaMask: Your key to the mystical Ethereum realm.
💻 Node.js: The potion that fuels your development environment.
🔧 Hardhat: Your wand for Ethereum development right on your computer.
🎁 OpenZeppelin Contracts: Your spellbook for creating NFT magic.
🧙♂️ Enchanting Your Hardhat
To begin, we’ll set up a sacred space for our contract using Hardhat. It’s like creating a workshop for crafting digital wonders. Open up your terminal, and with a few spells, you’ll have Hardhat installed and ready.
🧙 Setting up HardHat
To set up a Hardhat project, first create a new folder on your computer — we will name ours NFT-Tutorial
- and go to it through your Terminal.
Once your Terminal is inside NFT-Tutorial
, setup a Node.js project and install Hardhat using the following:
npm init --yes
npm install --save-dev hardhat @nomicfoundation/hardhat-toolbox
After the install has finished, run the following to pop up an interactive CLI that will help you set up your new Hardhat project:
npx hardhat
Select Create a JavaScript Project
and say yes to the other questions. At the end, Hardhat will install any other dependencies it needs and set up a boilerplate project for you.
🌟 Unveiling OpenZeppelin
With Hardhat as your wand, OpenZeppelin Contracts become your ancient texts. These are the blueprints for creating NFTs, and we’ll harness their power. Just a simple command will imbue your project with the magic of OpenZeppelin Contracts.
Unlike Remix, we cannot just import the contracts from a Github URL this time. But, OpenZeppelin publishes their contracts as a npm
package for this very reason - so we will install that to get access to the ERC-721
(NFT) contracts. In your terminal, run the following command:
npm install --save-dev @openzeppelin/contracts
🪄 Crafting the NFT Spell
Now, let’s script your NFT contract. Imagine it as the parchment upon which your NFT magic will be written. Using Solidity, a language for Ethereum contracts, we’ll write code that mints an NFT to you. The code is like an ancient chant that commands your NFT into existence.
Create a new Solidity file — we’ll name ours NFTee.sol
- inside the contracts
folder of your Hardhat project. Write the following code in that file:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;
// Import the openzepplin contracts
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";// NFTee is ERC721 signifies that the contract we are creating imports ERC721 and follows ERC721 contract from openzeppelin
contract NFTee is ERC721 {
constructor() ERC721("NFTee", "ITM") {
// mint an NFT to yourself
_mint(msg.sender, 1);
}
}
The code is fairly straightforward. We import the ERC-721
contract from OpenZeppelin, and then initialize it during the constructor. We also use the internal _mint
function to mint an NFT to ourself.
To make sure you got the code right, open up your Terminal again and type:
npx hardhat compile
📜 Casting the Deployment Ritual
With your NFT spell ready, it’s time to bring it to life. We’ll deploy your contract to the mystical Sepolia Test Network. Through a deployment script, we’ll channel the Ethereum network’s energy and grant life to your NFT contract.
Let’s deploy this contract to the Sepolia Test Network. To do so, we need to write a deployment script for Hardhat and then configure it to deploy to the correct network from the correct wallet.
By default, Hardhat provides a sample deploy.js
script under the scripts
folder - we will replace that. Replace all the code in that file with the following:
// Import the Hardhat package
const hre = require("hardhat");
async function main() {
// Using `hre` - Hardhat Runtime Environment - we find and deploy
// a contract named `NFTee`
const nftContract = await hre.ethers.deployContract("NFTee");
// We wait for the contract to finish deploying
await nftContract.waitForDeployment();
// We print the address of the deployed contract to our console
console.log("NFT Contract Address:", nftContract.target);
}
// Call the main function and catch if there is any error
main()
.then(() => process.exit(0))
.catch((error) => {
console.error(error);
process.exit(1);
});
🌐 Connecting the Realms
To bridge your contract to the Ethereum realm, we’ll weave a connection through a network configuration. With your contract and the Ethereum network linked, your NFT’s magic can flow freely.
We have a deployment script ready, but Hardhat currently has no idea which network to deploy the contract to or what wallet to use for doing so. To do that, we need to do some configuration for Hardhat.
First, create a .env
file inside your Hardhat project folder and add the following lines to it:
QUICKNODE_RPC_URL="..."
PRIVATE_KEY="..."
Are you wondering what an .env file is?
A
.env
file is a file that contains environment variables that are used to configure an application's environment. Environment variables are variables that are set in the operating system's environment and are used to configure an application's behavior.Environment variables are used to store configuration information that an application needs to run. For example, an application might need to know the location of a database or the API key for a third-party service. By storing this information in environment variables, the application can be configured without having to modify the application code.
The
.env
file is a convenient way to manage environment variables for an application. It is a plain text file that contains key-value pairs, where each key is the name of an environment variable and the value is the value of that variable. The.env
file is typically stored in the root directory of an application and is loaded when the application starts up.
Head over to Quicknode and sign up for an account if you haven’t already. Quicknode is a node provider that runs blockchain nodes for various networks and gives you access to them so you don’t have to run your own. We will use them to deploy our contract through Hardhat by connecting Hardhat to their node.
🧐 The .env Mystery
In our journey, you’ll encounter the enigmatic .env file. Discover its role as the keeper of secrets. Learn how to store sensitive information like API keys securely, enhancing your mastery of blockchain sorcery.
After creating an account at Quicknode, click on Create an Endpoint
, select Ethereum
and then select the Sepolia
network. Finish this process, and then copy the HTTP Provider
link you receive. Update your .env
file to have that URL as the value for QUICKNODE_RPC_URL
.
Now, for the private key. When you deploy using Remix, Remix just prompts you to deploy the contract through MetaMask since it operates in the browser. However, since we are running Hardhat directly on your computer, we need to give it the private key directly.
IMPORTANT: If you haven’t already created a separate account for development that DOES NOT HAVE FUNDS on Ethereum Mainnet — DO SO NOW! Many people have made a mistake with this and accidentally ended up revealing their private key which has led to a loss of funds. MAKE SURE THE PRIVATE KEY YOU USE HERE ONLY HAS TESTNET ETH AND NO REAL MONEY ON MAINNET.
To get your private key, you can export it from MetaMask. To do so, open up MetaMask, click on Account Details
for the account you want to export, and click on Export Private Key
. Copy-paste the value and put it in your .env
file as the value for PRIVATE_KEY
.
At this point, double check you have named your .env
file properly and it is properly located in the NFT-Tutorial
folder - not a subdirectory or anything else. Also make sure that in the .gitignore
file that Hardhat automatically set up for you, .env
is listed there. You can never be too safe about your private keys, especially when you're just learning about this stuff.
With the .env
in place - we will install an npm
package called dotenv
which reads from the .env
file and makes those variables available to the JavaScript code through process.env
. Open up your Terminal and type:
npm install dotenv
🌟 The Moment of Truth
Finally, the climax arrives. You’ll deploy your NFT contract using Hardhat. With a wave of your digital wand, your contract will be cast into the Ethereum network, and you’ll witness the birth of your very own NFT.
Now open up the hardhat.config.js
file, and let's configure the Sepolia network and the wallet. Replace the code in that file with the following:
require("@nomicfoundation/hardhat-toolbox");
// dotenv reads the `.env` file and makes it available to the NodeJS Environment
require("dotenv").config();
/** @type import('hardhat/config').HardhatUserConfig */
module.exports = {
solidity: "0.8.18",
networks: {
// Define the sepolia network parameters here
sepolia: {
url: process.env.QUICKNODE_RPC_URL,
accounts: [process.env.PRIVATE_KEY],
},
},
};
we are now all set and done and ready for deployment!
Deploy your Contract
To deploy your contract, open up your Terminal and run the following command:
npx hardhat run scripts/deploy.js --network sepolia
This command will output some logs to your console where it will compile your contract and then deploy to the Sepolia Test Network. It will also give you the contract address of the deployed contract.
Copy the contract address it gives you, and look it up on Sepolia Etherscan — open up the first transaction there and it will show you that a NFT was minted and transfered to your address!
Congratulations!
Awesome! If you got this far, you have probably deployed your first NFT contract to an Ethereum testnet! You also learnt about Hardhat and setting it up.
🎉 Revel in Your Triumph!
Congratulations, sorcerer of the blockchain! You’ve mastered the art of creating NFTs. Your digital artifacts now inhabit the Ethereum realm, waiting to be discovered by collectors and enthusiasts worldwide.
✨ Ready for More?
Your journey has just begun. As you delve deeper into the world of blockchain and Ethereum, countless enchantments await. Let your curiosity guide you, and remember, the magic is in your hands. Stay tuned for more adventures in the realm of blockchain sorcery!”
“Special thanks to LearnWeb3 for providing the inspiration and knowledge that motivated me to craft this article, turning complex concepts into an accessible and engaging adventure.”