Skip links

15-step NFT smart contract tutorial with example

In today’s NFT smart contract tutorial, I explain what smart contracts are in detail and how they work. Follow along with this NFT smart contract tutorial. I will show you how to create and deploy NFT smart contracts by using an example.

If you follow this blog, you already know that the main functions of NFTs (non-fungible tokens) are to secure and verify ownership and authenticity of intellectual property.

Non-fungible tokens are managed on blockchains, and smart contracts can enable them to fulfill their primary functions and create further use case possibilities.

To fully grasp the concept of NFT smart contracts, you have to understand blockchain oracles, what smart contracts are, and how they are applied to NFTs. If you’re not sure what smart contracts are, don’t worry, I’ll explain smart contracts in the next section.

What is a smart contract?

A smart contract is a piece of code that lets the network record information about digital transactions on the blockchain.
The terms of the agreement between both parties involved in the transaction are set in code and stored in a transparent, indivisible, and unchangeable but transferable manner.

Smart contracts are central to the working of blockchain technology, and they exist in both decentralized and distributed blockchain networks.

Etheruem standards used for NFT smart contracts

NFT smart contracts are governed by different standards, such as Solarium, TEZOS, TRON, and EOS, and the operation of NFTs varies by standards. This is because different blockchains have different capabilities.

However, the various capabilities are usually insignificant. Hence, smart contracts can adapt to applicable blockchain environments.

Ethereum is the most prominent blockchain for NFTs and among the first to use smart contract standards. Hence, we’ll take a look at the Ethereum standards used for NFT smart contract examples.

1. ERC 721 Ethereum smart contract standard: The ERC 721 Ethereum smart contract standard defined the creation and operation of NFTs on the Ethereum blockchain. It is unique from other tokens.

One ERC 721 can manage multiple tokens, and it requires the smart contract address and token ID.

2. ERC 1155 Ethereum smart contract standard: The ERC 1155 is also able to manage multiple tokens. With the ER 1155, each token ID can stand for its own type, metadata supply, and attributes.

How NFT smart contracts verify the authenticity of tokens

Smart contracts represent the owners’ rights to the asset sold or purchased. However, proprietorship is different from copyright ownership. In most transactions, the copyright remains with the author of the asset even after they sell the asset unless the contract states otherwise.

First of all, smart contracts not only verify the authenticity of tokens but are also used to trace the origin and history of tokens that are linked to an asset. NFTs authenticate tokens and their owners.

What a smart contract doesn’t do is link to a real person or verify the creator’s right to link an asset to an NFT. This is done by NFT marketplace platforms. These platforms verify creators’ identities manually.

How to create and deploy an NFT smart contract

Now that you have the basic overview of NFT smart contracts and how they work, I’ll show you how to create and deploy an ERC-721 smart contract.

You will also learn how to use a smart contract to mint an NFT.

We will create and deploy the smart contract on the Ropsten test network using MetaMask, Hardhat, Solidity, Alchemy, and Pinata.

The steps involved include:

  1. Connect to the Ethereum network.
  2. Create your app and API key.
  3. Register for an Ethereum account to get your address.
  4. Add (fake) ETH from a faucet.
  5. Initialize your project.
  6. Install Hardhat.
  7. Create Hardhat project.
  8. Add Hardhat project folders.
  9. Write the NFT smart contract code.
  10. Connect your project to MetaMast and Alchemy.
  11. Install Ethers.js.
  12. Require dependencies and update hardhat.config.js.
  13. Compile your contract.
  14. Write our deploy script.
  15. Deploy your NFT smart contract.

1. Connect to the Ethereum network

The first step is to connect to the Ethereum network. You do this in order to make requests to the Ethereum blockchain.

You can communicate with the Ethereum blockchain in several ways, but for this guide, we will make use of Alchemy. Alchemy is a blockchain dev platform whose API lets you connect to the Ethereum blockchain without needing to run your own nodes.

Alchemy also has crucial developer tools with insights and analytics for monitoring smart contract deployment. Create an Alchemy account and continue with this NFT smart contract tutorial.

2. Create your app and API key

Having an account on Alchemy allows you to generate an API key for making requests to the Ropsten test network. To do this, follow the steps below:

Visit the Alchemy signup page and complete the form. You may also sign up using your Google account. After creating your account, verify your email address by clicking the link sent to you. Log into your account when done.

alchemy sign up nft smart contract tutorial

Log into your account and select Ethereum when asked to select an ecosystem.

Next, if it’s your first time logging in, you will have to create your first app. Simply enter your team name, app name, select your network (choose Ropsten), and hit Create App.

alchemy create app nft smart contract tutorial

If it’s not your first login, go to Apps on the top menu and select Create App.

Give your app a name and add a brief description of your app. Under Environment, click on Staging and select Ropsten as your network.

After clicking on the Create App button, you will have to select a plan if it’s your first time logging into Alchemy. You can go with the free plan for this NFT smart contract tutorial. Skip adding a payment method for this guide.

3. Register for an Ethereum account to get your address

To carry out transactions you must have an Ethereum account. This is not complicated as you can make use of MetaMask for Ethereum. MetaMask gives you a virtual wallet for sending and receiving transactions.

Download MetaMask and create a wallet on the website. MetaMask is available for free download on iOS, Android, PC, and Chrome.

After creating your MetaMask account, change your network selection to the Ropsten Test Network. This ensures that you don’t carry out transactions with real money but with fake ETH.

4. Add (fake) ETH from a faucet

In the previous step, I asked you to choose the Ropsten Test Network because, with this, you are not going to be transacting with real ETH. The fake ETH Ropsten uses is got via FaucETH.

To acquire some of this fake ETH, visit, enter your Ropsten account information, and hit the Request funds button.

Next, click on the dropdown menu, choose Ethereum Testnet Ropsten, and select Request funds. After a short while, the fake ETH in your MetaMask account.

Sometimes, it may take a while for the ETH to reflect in your MetaMask. To confirm your balance, you can use Alchemy’s composer tool to make an eth_getBalance request.

Enter your MetaMask account information and hit the Send Request button. You will see a similar response as follows:

`{"jsonrpc": "2.0", "id": 0, "result": "1bc16d674ec80000"}`2

The output value is not in ETH but Wei. 1 ETH in Wei is 10 raised to the power of 10. Therefore, from the conversion of the value in the result above, 1bc16d674ec80000 = 2 ETH.

5. Initialize your project

Now that you have ETH in your MetaMask, it’s time to initialize your project.

For this, we will use the command line. I will write the various commands below and tell you what they do.

First, create a folder for your project:

mkdir nftkeshi-folder

Navigate into the folder you created for your project:

cd nftkeshi-folder

NOTE: Here’s I have created a folder called nftkeshi, but feel free to name yours as you wish.

Next, download Node.js and install npm init following the following instructions.

npm init

Answer the installation questions as you wish. Here’s a quick template for answering the questions:

package name: (nftkeshi)
version: (1.0.0)
description: My first NFT!
entry point: (index.js)
test command:
git repository:
license: (ISC)
About to write to /Users/thesuperb1/Desktop/my-nft/package.json:
        "name": "nftkeshi"
        "version": "1.0.0",
        "description": "NFT smart contract tutorial",
        "main": "index.js",
        "scripts": {
            "test": "echo \"Error: no test specified\" && exit 1"  
    "author": "",

6. Install Hardhat

After initializing your new project, you will now get ready to write the NFT smart contract code. To do this, you will first need a development environment to compile and deploy your Ethereum software.

Hardhard not only compiles and deploys Ethereum software, but it also lets you test and debug software locally prior to deploying it to the blockchain.

Run the following command in the nftkeshi project to install Hardhat:

npm install --save-dev hardhat

For a more comprehensive guide, read this page on the Hardhat website.

7. Create a Hardhat project

Create the project in Hardhat by entering the command below:

npx hardhat

On hitting ENTER, you will be shown a welcome screen. Below the welcome message, it asks you what do you want to do?

Select the Create an empty hardhat.config.js option. Choosing this option generates a file named hardhat.config.js. This is where you have to indicate the project setup.

8. Add Hardhat project folders

Using the command prompt, we will now create two separate folders. To do this, go to the root folder of the project. Here, enter the following commands:

mkdir contracts
mkdir scripts

The command above created two new folders named contacts and scripts. You will save your NFT smart contract in this folder.

The scripts folder is the location in which you will save the scripts for deployment and interaction with the smart contract.

9. Write the NFT smart contract code

Finally, you can now proceed to write the smart contract code. The language used for writing NFT smart contracts is Solidity, and you can write the NFT smart contract example code using most editors. So, go to the nftkeshi project and open it using your preferred editor.

In the steps below, we will write our contract code.

Step 1: Go to the contracts folder we created in the previous step.

Step 2: Create a new file in the contracts folder and name it MyNFT.sol.

Step 3: Copy the following NFT smart contract example code and paste it in the newly created MyNFT.sol file.

//Contract based on
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
contract MyNFT is ERC721URIStorage, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
constructor() ERC721("FirstNFT", "NFTSC") {}

function mintNFT(address recipient, string memory tokenURI)
    public onlyOwner
    returns (uint256)

    uint256 newItemId = _tokenIds.current();
    _mint(recipient, newItemId);
    _setTokenURI(newItemId, tokenURI);

    return newItemId;


In the code above, we started by implementing the ERC-721 standard for the NFT smart contract to inherit.

The next line implements counters in order to monitor the number of non-fungible tokens minted, as well as assign a unique ID on each NFT. This counter can only decrement or increment by one.

The third line of the code above is the access control setup, and it’s entirely optional to include. I used access control for this NFT smart contract tutorial code so that only the owner of the NFT smart contract has the privilege to mint NFTs.

Following the imports in this NFT smart contract example code is the ERC-721 constructor. The string – FirstNFT – in the NFT smart contract example code above is the name of the NFT smart contract. And the string – NFTSC – is the symbol for the NFT smart contract.

The function mintNFT(address recipient, string memory tokenURI) is what enables you to mint the NFTs. This function takes two variables:

Address recipient is the address to receive the new NFT and string memory tokenURI Describes the NFT’s metadata.

Finally, mintNFT calls methods from the ERC-721 library that the code inherited. Hence, it returns the unique ID of your minted NFT.

10. Connect your project to MetaMast and Alchemy

If you have followed this NFT smart contract tutorial up to this point, you now have a MetaMast wallet, Alchemy account, and an NFT smart contract code.

The next step now is to link these three parts – MetaMast wallet, Alchemy, and the smart contract. To send a transaction from your virtual wallet, you need a signature from your private key.

You can store your Alchemy API key and MetaMask private key in an environment file. This article on teaches you all you need to know about sending transactions on web3.

Use the command that follows below to install the dotenv package in the project folder:

npm install dotenv --save

Next, you have to create a .env file and include your MetaMask private key and HTTP Alchemy API URL. You will create this file in your project’s root directory.

First, export your MetaMask private key.

Next, go to Alchemy > Apps > View Details > View Key and copy your HTTP Alchemy API URL.

Paste your MetaMask private key and HTTP Alchemy API URL in the .env file as shown below:


NOTE: Do not commit the .env file yet and never share it with a third party.

11. Install Ethers.js

We need Ethers.js to deploy the contract. The Ethers.js library simplifies interaction with Ethereum such as the process of sending requests.

We will use the Ethers plugin with Hardhat in this NFT smart contract example. Input the following command:

npm install --save-dev @nomiclabs/hardhat-ethers ethers@^5.0.02

12. Require dependencies and update hardhat.config.js

Next, go to your hardhat.config.js file and update it as follows:

*@type import('hardhat/config').HardhatUserConfig
const { API_URL, PRIVATE_KEY } = process.env;
module.exports = {
    solidity: "0.8.1",
    defaultNetwork: "ropsten",
    networks: {
        hardhat: {},
        ropsten: {
            url: API_URL,
            accounts: ['0x${PRIVATE_KEY}']

You have installed plugins and required the dependencies. The code above will also update the hardhat.config.js file to enable detect your project.

13. Compile your contract

We will now compile the NFT smart contract to ensure that it works. Run the following command in the command line:

npx hardhat compile

NOTE: You may get an error about the SPDX license identifier. You can ignore it for this NFT smart contract example. Report any issues to the Alchemy Discord.

14. Write our deploy script

Go to the scripts/ folder and create a new .js file. Name this file deploy.js. Open this newly created deploy.js and enter the following code in it:

async function main() {
const MyNFT = await ethers.getContractFactory("MyNFT")
    // Start deployment, returning a promise that resolves to a contract object
const myNFT = await MyNFT.deploy()
await myNFT.deployed()
console.log("Contract deployed to address:", myNFT.address)
.then(() => process.exit(0))
.catch((error) => {

You can check out this in-depth tutorial on testing contracts from Hardhat.

15. Deploy your NFT smart contract

Navigate to the root directory of your project. Here, enter and run the following command:

npx hardhat --network ropsten run scripts/deploy.js

On hitting ENTER, you will see a line telling you that the contract has been deployed to an address. Sometimes, it doesn’t happen instantly. You can see the transaction on the Ropsten etherscan.


Do NFTs use smart contracts?

You mint NFTs using smart contracts. NFT smart contracts assign ownership of the non-fungible token and manage its transferability. The code executed when minting an NFT is stored in smart contracts.

Do you need a smart contract for NFT?

Yes, you need smart contracts for NFT because they power NFTs and handle their ownership and transferability on the blockchain.

Do you need to code to make an NFT?

Although coding knowledge is an excellent advantage, you do not need to know how to code to make an NFT. Many creators use NFT collection generators to create collections easily.

Leave a comment