How to Create and Deploy an NFT Smart Contract

·

Non-fungible tokens (NFTs) have brought blockchain technology into the mainstream spotlight. This guide walks you through the process of writing and deploying your own NFT smart contract (ERC-721 token) on the Ethereum Sepolia testnet.

Understanding the Tools and Setup

Before diving into the code, you'll need to set up your development environment and tools. This process involves creating an Alchemy account, setting up MetaMask, and installing necessary packages.

Step 1: Create an Alchemy Account

Alchemy is a blockchain development platform that provides APIs allowing you to communicate with the Ethereum blockchain without running your own node.

  1. Visit Alchemy and create a free account
  2. Once logged in, navigate to the dashboard and create a new app
  3. Select "Ethereum" as the blockchain and "Sepolia" as your network
  4. Note your API key for later use

Step 2: Set Up MetaMask

MetaMask is a browser-based wallet that manages your Ethereum account address.

  1. Download and install MetaMask
  2. Create a new account or import an existing one
  3. Switch to the "Sepolia Test Network" in the top right corner
  4. Copy your wallet address for the next step

Step 3: Get Test ETH

To deploy your smart contract, you'll need test ETH from a Sepolia faucet:

  1. Visit the Sepolia Faucet
  2. Paste your MetaMask wallet address
  3. Request test ETH (you should receive it within minutes)

Developing Your NFT Smart Contract

Now that your environment is set up, you can start working on your NFT smart contract.

Step 4: Initialize Your Project

Create a new directory for your project and initialize it with npm:

mkdir my-nft
cd my-nft
npm init

Follow the prompts to create your package.json file.

Step 5: Install Hardhat

Hardhat is a development environment for compiling, deploying, testing, and debugging Ethereum software:

npm install --save-dev hardhat

Step 6: Create a Hardhat Project

Initialize a new Hardhat project:

npx hardhat

Select "Create an empty hardhat.config.js" when prompted.

Step 7: Set Up Project Structure

Create two directories for your contracts and scripts:

mkdir contracts
mkdir scripts

Step 8: Write Your Smart Contract

Create a new file called MyNFT.sol in the contracts directory with the following code:

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("MyNFT", "NFT") {}
    
    function mintNFT(address recipient, string memory tokenURI)
        public onlyOwner
        returns (uint256)
    {
        _tokenIds.increment();
        
        uint256 newItemId = _tokenIds.current();
        _mint(recipient, newItemId);
        _setTokenURI(newItemId, tokenURI);
        
        return newItemId;
    }
}

Step 9: Install OpenZeppelin Contracts

Install the OpenZeppelin contracts library:

npm install @openzeppelin/contracts

Configuring Your Deployment

Step 10: Set Up Environment Variables

Install dotenv to manage your environment variables:

npm install dotenv --save

Create a .env file in your project root with your API URL and private key:

API_URL="https://eth-sepolia.g.alchemy.com/v2/your-api-key"
PRIVATE_KEY="your-metamask-private-key"

Step 11: Install Ethers.js

Ethers.js is a library that makes it easier to interact with Ethereum:

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

Step 12: Update Hardhat Configuration

Modify your hardhat.config.js file:

require('dotenv').config();
require("@nomiclabs/hardhat-ethers");
const { API_URL, PRIVATE_KEY } = process.env;

module.exports = {
  solidity: "0.8.1",
  defaultNetwork: "sepolia",
  networks: {
    hardhat: {},
    sepolia: {
      url: API_URL,
      accounts: [`0x${PRIVATE_KEY}`]
    }
  }
};

Deploying Your Contract

Step 13: Compile Your Contract

Compile your smart contract to check for errors:

npx hardhat compile

Step 14: Create Deployment Script

Create a deploy.js file in the scripts directory:

async function main() {
  const MyNFT = await ethers.getContractFactory("MyNFT");
  const myNFT = await MyNFT.deploy();
  await myNFT.deployed();
  console.log("Contract deployed to address:", myNFT.address);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

Step 15: Deploy to Sepolia Network

Run the deployment script:

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

You should see a confirmation message with your contract address. You can verify the deployment by searching for this address on Sepolia Etherscan.

Next Steps After Deployment

After successfully deploying your NFT smart contract, you can proceed to mint NFTs and interact with your contract. The deployment process creates a permanent, immutable instance of your smart contract on the blockchain that you can now use to create unique digital assets.

👉 Explore advanced deployment strategies

Frequently Asked Questions

What is an ERC-721 token?

ERC-721 is a standard for non-fungible tokens on the Ethereum blockchain. Unlike fungible tokens (like ETH or ERC-20 tokens), each ERC-721 token is unique and cannot be exchanged on a one-to-one basis with other tokens of the same type.

Why use the Sepolia testnet?

Sepolia is a Ethereum testnet that allows developers to test their applications without using real ETH. It's recommended for testing because it's less congested than other testnets and provides a stable environment for development.

How much does it cost to deploy an NFT contract?

On the mainnet, deployment costs vary based on Ethereum gas prices. On testnets like Sepolia, you can deploy contracts using free test ETH obtained from faucets. Actual mainnet deployment costs depend on network congestion and contract complexity.

Can I modify my contract after deployment?

No, smart contracts are immutable once deployed to the Ethereum blockchain. Any bugs or required changes necessitate deploying a new contract. This is why thorough testing on testnets is crucial before mainnet deployment.

What's the difference between ERC-721 and ERC-1155?

ERC-721 is for unique, non-fungible tokens where each token is distinct. ERC-1155 is a multi-token standard that can handle both fungible and non-fungible tokens within a single contract, offering more flexibility for certain applications.

How do I add metadata to my NFTs?

NFT metadata typically lives off-chain and is referenced through a URI pointer in the token contract. This metadata includes information like name, description, image, attributes, and other properties that make each NFT unique.