đ ď¸ We partnered with Alchemy to bring you a FREE Ethereum Developer Bootcamp! Get started here đ ď¸
This tutorial will walk you through writing and deploying a Non Fungible (ERC721) Token smart contract using Ethereum and Inter Planetary File System (IPFS).
Estimated time to complete this guide: ~15 minutes
Even if you've been living under a rock, you'll have noticed that every major news outlet has been profiling the rise of NFTs.
With NFTs bringing blockchain into the public eye, now is an excellent opportunity to understand the hype yourself by publishing your own NFT (ERC-721 Token) on the Ethereum blockchain!
In this tutorial, we will walk through creating and deploying an ERC-721 smart contract on the Goerli test network using Metamask, Solidity, Hardhat, Pinata and Alchemy (donât fret if you donât understand what any of this means yetâ we will explain it).
There a bunch of ways to make requests to the Ethereum blockchain, but to make things easiest, weâll use a free account on Alchemy, a blockchain developer platform and API that allows us to communicate with the Ethereum chain without having to run our own nodes.
In this tutorial, we'll also take advantage of Alchemy's developer tools for monitoring and analytics to understand whatâs going on under the hood in our smart contract deployment.
Once youâve created an Alchemy account, you can generate an API key by creating an app. This will allow us to make requests to the Goerli test network. Check out this guide if you're curious to learn more about test networks.
We need an Ethereum account to send and receive transactions. For this tutorial, weâll use Metamask, a virtual wallet in the browser used to manage your Ethereum account address. If you want to understand more about how transactions on Ethereum work, check out this page from the Ethereum foundation.
You can download and create a Metamask account for free here. When you are creating an account, or if you already have an account, make sure to switch over to the âGoerli Test Networkâ in the upper right (so that weâre not dealing with real money).
In order to deploy our smart contract to the test network, weâll need some fake Eth. To get Eth you can go to the Goerli faucet and enter your Goerli account address, then click âSend Me Eth.â You should see Eth in your Metamask account soon after!
To double check our balance is there, letâs make an eth_getBalance request using Alchemyâs composer tool. This will return the amount of Eth in our wallet. After you input your Metamask account address and click âSend Requestâ, you should see a response like this:
{"jsonrpc": "2.0", "id": 0, "result": "0xde0b6b3a7640000"}
NOTE: This result is in wei not eth. Wei is used as the smallest denomination of ether. The conversion from wei to eth is: 1 eth = 10š⸠wei. So if we convert 0xde0b6b3a7640000 to decimal we get 1*10š⸠which equals 1 eth.
Phew! Our fake money is all there! đ¤
First, weâll need to create a folder for our project. Navigate to your command line and type:
Now that weâre inside our project folder, weâll use npm init to initialize the project. If you donât already have npm installed, follow these instructions (weâll also need Node.js, so download that too!).
It doesnât really matter how you answer the installation questions, here is how we did it for reference:
Approve the package.json, and weâre good to go!
Step 7: Download Hardhat
Hardhat is a development environment to compile, deploy, test, and debug your Ethereum software. It helps developers when building smart contracts and dApps locally before deploying to the live chain.
Navigate to the terminal and make sure you're inside the my-nft project folder, then run:
Check out this page for more details on installation instructions.
Inside our project folder run:
You should then see a welcome message and option to select what you want to do. Select âcreate an empty hardhat.config.jsâ:
This will generate a hardhat.config.js file for us which is where weâll specify all of the set up for our project (on step 13).
To keep our project organized, weâll create two new folders. Navigate to the root directory of your project in your command line and type:
contracts/ is where weâll keep our NFT smart contract code
scripts/ is where weâll keep scripts to deploy and interact with our smart contract
Now that our environment is set up, onto more exciting stuff: writing our smart contract code!
Open up the my-nft project in your favorite editor (we like VSCode). Smart contracts are written in a language called Solidity which is what we will use to write our MyNFT.sol smart contract.â
1. Navigate to the âcontractsâ folder and create a new file called MyNFT.sol
2. Below is our NFT smart contract code, which is based off of the OpenZeppelin library's ERC721 implementation. Copy and paste the contents below into your MyNFT.sol file.
NOTE: If you want to attach a price to the NFT through the smart contract check out this tutorial.
1. Because we are inheriting classes from the OpenZepplin contracts library, in your command line run the following to install the library into our folder:
npm install @openzeppelin/[email protected]
So, what does this code do exactly? Let's break it down, line by line.
In lines 5-7, our code inherits three OpenZepplin smart contract classes:
- @openzeppelin/contracts/token/ERC721/ERC721.solcontains the implementation of the ERC721 standard, which our NFT smart contract will inherit. (To be a valid NFT, your smart contract must implement all the methods of the ERC721 standard.) To learn more about the inherited ERC721 functions, check out the interface definition here.
- @openzeppelin/contracts/utils/Counters.solprovides counters that can only be incremented or decremented by one. Our smart contract uses a counter to keep track of the total number of NFTs minted and set the unique ID to our new NFT. Each NFT minted using a smart contract must be assigned a unique IDâhere our unique ID is just determined by the total number of NFTs in existance. For example, the first NFT we mint with our smart contract has an ID of "1," our second NFT has an ID of "2," etc.
- @openzeppelin/contracts/access/Ownable.sol sets up access control on our smart contract, so only the owner of the smart contract (you) can mint NFTs. Note, including access control is entirely a preference. If you'd like anyone to be able to mint an NFT using your smart contract, remove the word Ownable on line 10 and onlyOwner on line 17.
In Lines 10-28, we have our custom NFT smart contract, which is surprisingly short âit only contains a counter, a constructor, and single function! This is thanks to our inherited OpenZepplin contracts, which implement most of the methods we need to create an NFT, such as ownerOf (returns the owner of the NFT) and transferFrom(transfers ownership of the NFT).
On line 14, you'll notice we pass 2 strings, "MyNFT" and "NFT" into the ERC721 constructor. The first variable is the smart contract's name, and the second is its symbol. You can name each of these variables whatever you wish!
Finally, starting on line 16, we have our function mintNFT() that allows us to mint an NFT! You'll notice this function takes in two variables:
- address recipient specifies the address that will receive your freshly minted NFT
- string memory tokenURI is a string that should resolve to a JSON document that describes the NFT's metadata. An NFT's metadata is really what brings it to life, allowing it to have additional properties, such as a name, description, image, and other attributes. In part 2 of this tutorial, we will describe how to configure this metadata.
mintNFT calls some methods from the inherited ERC721 library, and ultimately returns a number that represents the ID of the freshly minted NFT.
Now that we've created a Metamask wallet, Alchemy account, and written our smart contract, itâs time to connect the three.
Every transaction sent from your virtual wallet requires a signature using your unique private key. To provide our program with this permission, we can safely store our private key (and Alchemy API key) in an environment file.
To learn more about sending transactions, check out this tutorial on sending transactions using web3.
First, install the dotenv package in your project directory:
Then, create a .env file in the root directory of our project, and add your Metamask private key and HTTP Alchemy API URL to it.
NOTE: Your .env file must be named .env ! Do not change the name to xx.env
- Follow these instructions to export your private key from Metamask
- See below to get HTTP Alchemy API URL and copy it to your clipboard
Your .env should look like this:
Ethers.js is a library that makes it easier to interact with and make requests to Ethereum by wrapping standard JSON-RPC methods with more user friendly methods.
Hardhat makes it super easy to integrate Plugins for additional tooling and extended functionality. Weâll be taking advantage of the Ethers plugin for contract deployment (Ethers.js has some super clean contract deployment methods).
In your project directory type:
Weâll also require ethers in our hardhat.config.js in the next step.
Weâve added several dependencies and plugins so far, now we need to update hardhat.config.js so that our project knows about all of them.
Update your hardhat.config.js to look like this:
To make sure everything is working so far, letâs compile our contract. The compile task is one of the built-in hardhat tasks.
From the command line run:
You might get a warning about SPDX license identifier not provided in source file , but no need to worry about that â hopefully everything else looks good! If not, you can always message in the Alchemy discord.
Now that our contract is written and our configuration file is good to go, itâs time to write our contract deploy script.
Navigate to the scripts/ folder and create a new file called deploy.js, adding the following contents to it:
Hardhat does an amazing job of explaining what each of these lines of code does in their Contracts tutorial, weâve adopted their explanations here.
A ContractFactory in ethers.js is an abstraction used to deploy new smart contracts, so MyNFT here is a factory for instances of our NFT contract. When using the hardhat-ethers plugin ContractFactory and Contract instances are connected to the first signer by default.
Calling deploy() on a ContractFactory will start the deployment, and return a Promise that resolves to a Contract. This is the object that has a method for each of our smart contract functions.
Weâre finally ready to deploy our smart contract! Navigate back to the root of your project directory, and in the command line run:
You should then see something like:
If we go to the Goerli etherscan and search for our contract address we should be able to see that it has been deployed successfully. The transaction will look something like this:
The From address should match your Metamask account address and the To address will say âContract Creation.â If we click into the transaction, weâll see our contract address in the To field:
Yasssss! You just deployed your NFT smart contract to the Ethereum chain đ
To understand whatâs going on under the hood, letâs navigate to the Explorer tab in our Alchemy dashboard . If you have multiple Alchemy apps make sure to filter by app and select âMyNFTâ.
Here youâll see a handful of JSON-RPC calls that Hardhat/Ethers made under the hood for us when we called the .deploy() function.
Two important ones to call out here are eth_sendRawTransaction, which is the request to actually write our smart contract onto the Goerli chain, and eth_getTransactionByHash which is a request to read information about our transaction given the hash (a typical pattern when sending transactions).
To learn more about sending transactions, check out this tutorial on sending transactions using Web3.