Create your own NFT collection on Ethereum w/Solidity

Create your own NFT collection on Ethereum w/Solidity

What is an NFT, how does it work and how can I create my own?

ยท

9 min read

Featured on Hashnode

My Twitter feed has tons of avatar profile pictures, articles are coming out daily showcasing some large NFT sales, and people are earning money with their in-game creatures...

I guess this means it's time to go down the NFT rabbit hole. So let's get to it!

This article introduces NFT's and guides you through creating your NFT collection on Ethereum using solidity.

Creating your collection sounds complicated; I thought the same. Frankly, I would have never imagined creating an NFT collection, let alone try to explain it in a 10min article, if it weren't for buildspace . Buildspace is a platform for developers to learn about web3 by creating projects. I signed up for my first project and was amazed at what I was able to build. Check it out here. In this post, we will follow the project from buildspace "Mint your own NFT collection and ship a Web3 app to show them off."

So bare with me; it's just the new terminology that makes things complicated.


Can't you just take a screenshot?

It seems like a lot of people ask this question. I know for one that my friends and family do. By the end of this section, we'll have an answer ๐Ÿ˜‰

NFT

Firstly, NFT stands for Non-Fungible Token.

  • Non-fungible: Fungibility indicates that a good can be interchanged (a word I googled many times). Non-fungible refers to goods that have unique properties and can not be changed with one another. For example, bitcoin is a fungible asset. If we each have a bitcoin and send them to each other, in the end, we'll have the same thing. On the other hand, a house is non-fungible. If we decide to switch homes, we'll end up with something different.
  • Token: In short, blockchain is a shared and immutable ledger, and a token is a digital asset living on top of the blockchain.

NFT's are unique digital assets on the blockchain. They are each one of a kind; this allows for tracking the ownership.

Today, most NFT's are on the Ethereum blockchain. However, we are also seeing many projects coming out on Solana and Avalanche.

But what really are NFT's?

The sky is the limit. Any digital asset can theoretically be an NFT. The most popular are Collectibles and Art.

Collectibles, as the name indicates, are a collection of assets in the format of an NFT. Think of these as Pokemon cards or even penny collections. NFT collectibles have the same logic, except they are in the digital world.

The earliest NFT was a collectibles project called CryptoKitties . It came out as a game centered around breeding cats. Each kitty (which is an nft) is unique, and you can breed kitties to create new ones.

1_Mw8ZN07nisyUMS0fiR5KOw.jpeg

Another example of a collectible NFT project is CryptoPunks. There are 10,000 crypto punks with different attributes such as a beanie, big beard, purple hair etc. The characteristics change for each punk, making each a unique CryptoPunks.

Screen Shot 2021-10-27 at 20.06.02.png

Art is self-explanatory. Artists have the chance to create their work on the blockchain and can directly reach their buyers. This process removes the many middlemen in between by directly connecting the buyer and the creator.

Screen Shot 2021-10-27 at 20.03.49.png

Other use cases for NFT's include domain names, gaming, music, ticketing... (There can be many more applications which we have not even discovered yet.)

Smart Contracts & Transactions

NFT's are created by running the code on the smart contract. This process is also called "minting."

ERC-721 is a standard type of smart contract that creates non-fungible tokens on Ethereum. The way each token is globally unique is with the tokenId field. Therefore, for every smart contract that creates an NFT, the smart contract and the tokenId pair is different.

Once you mint an NFT, you will be able to see it in your crypto wallet. You can then use secondary markets to buy/sell NFT's. Today, OpenSea is the most popular secondary market.

One thing to note is that every transaction on the blockchain has a cost. So when you want to mint, buy or sell an NFT, you need to pay the price called gas fee.

Gas is the measure of the unit to denote the cost for a transaction. Accordingly, gas fees are the fees that are paid to the network to process the transactions.

On the Ethereum blockchain, gas fees are paid in ETH and denoted in gwei (10-9 ETH). Due to the high demand for the Ethereum network, gas fee's are pretty high. Especially when there is a popular NFT project drop, and you could end up paying 100 dollars just for the transaction. Make sure to check the gas tracker before making transactions.

High gas fees are an issue which the Ethereum team and other scaling solutions are working on. High gas fees explain why many projects are coming out on the other blockchains.

๐Ÿ™Œ Going back to our screenshot question. The main value proposition of an NFT is trackable and transparent ownership. The owner can prove that they own an NFT. If an NFT gets transferred, the transaction is recorded on the blockchain. It's basically a new way to transfer digital arts or even any asset. So, just like taking a photo of the Mona Lisa is not the same thing as owning the piece. Likewise, taking a screenshot of an NFT is not the same as being listed as the owner on a transparent and immutable ledger.


How to create your own NFT collection?

Project Tools

  • Metamask Wallet: crypto wallet.
  • Alchemy: ethereum developer platform. We will be using the Alchemy API to interact with Alchemy's Ethereum infrastructure.
  • Hardhat: ethereum development environment. It comes as an npm package.
  • OpenZepplin Contracts: library for secure smart contract implementations. We will be using the ERC271 libary standard.

Prerequisites

(It's the same setup from my previous post, here is a checklist to review the items.)

  1. Choose your IDE and get the "solidity extension."
  2. Create an account on metamask and switch to the rinkeby test network.
  3. Get your Alchemy API key .
  4. Get node.js to use hardhat.

Create your NFT collection

  1. Create a project folder and head over to its directory. Install hardhat.

    mkdir eda-nft-collection
    cd eda-nft-collection
    npm init -y
    npm install --save-dev hardhat
    
  2. In your project directory create a hardhat project by running npx hardhat. The setup wizard will direct, you can click enter throughout the setup wizard and keep the default options.

    $ npx hardhat
    
  3. Run the command to install the OpenZepplin implementation for smart contracts. It has the ERC-721 token standard which we will extend from.

    npm install @openzeppelin/contracts
    
  4. Under the 'Contracts' folder create a new solidity file(file extension is .sol). This will be the file for our ERC-721 token.

  5. Below you can see a sample ERC-721 token smart contract extended from OpenZepplin. I have added some comments to explain what's going on in the code. Copy and paste it onto your own solidity file.

    //SPDX-License-Identifier: Unlicense
    pragma solidity ^0.8.9; // tells the solidity version to the complier
    
    // get the OpenZeppelin Contracts, we will use to creat our own
    import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
    import "@openzeppelin/contracts/utils/Counters.sol";
    
    import "hardhat/console.sol"; // built in hardhat local environment 
    
    contract EdaNFTCollection is ERC721URIStorage {
    
    // keep count of the tokenId
    using Counters for Counters.Counter; // keep track of the token id's
    Counters.Counter private _tokenIds;
    
    uint256 public constant maxSupply = 2; // set the max supply of NFT's for your collection
    
    constructor() ERC721 ("edaNFTCollection", "EDA") { // construct your token, needs name and symbol
      console.log("An NFT has been minted to %s", msg.sender);
    }
    
    function createEdaNFT() public { //function to create nfts
    
      uint256 newItemId = _tokenIds.current(); // get the tokenId
    
      require(newItemId < maxSupply); // check if the total supply has been reached 
    
      _safeMint(msg.sender, newItemId); // mint the nft from the sender account 
    
      _setTokenURI(newItemId, "https://jsonkeeper.com/b/2KQZ"); // add the contents to the nft 
      // the content of this nft is on the url above. This means that the nft is an off-chain nft
      // if the server with the content changes then the image in the url changes 
    
      _tokenIds.increment(); // increment the token, so when the next person calls the function it will be the next token in line 
    
      console.log("NFT ID %s has been minted", newItemId); 
    
     }
    }
    
  6. We need to take our contract from our local machine and put it onto the Rinkeby Test Network. For this, simply create a deploy.js file under the 'Scripts' folder. Copy and paste the content below onto your file.

    const main = async () => {
    
      const nftContractFactory = await hre.ethers.getContractFactory('EdaNFTCollection'); // get the contract 
      const nftContract = await nftContractFactory.deploy(); // deploy --> convert to computer language
      await nftContract.deployed(); // wait for it to deploy
      console.log("Contract deployed to:", nftContract.address);
    
      let txn = await nftContract.createEdaNFT() // mint the nft 
      await txn.wait() // wait for the mint
    
      txn = await nftContract.createEdaNFT() // mint another nft (we set 2 as the max supply, can't mint more)
      await txn.wait() // wait for the mint
    
    };
    
    const runMain = async () => {
      try {
        await main();
        process.exit(0);
      } catch (error) {
        console.log(error);
        process.exit(1);
      }
    };
    runMain();
    
  7. Get your Alchemy API key, it is needed to talk to the Rinkeby Test Network from our contract. Add your API key to the hardhat.config.json (see code snippet under step-8)

  8. Add your metamask private key to hardhat.config.json. You can get this by clicking Account Details --> Export Private Key from your Metamask extension.

    require('@nomiclabs/hardhat-waffle');
    
    module.exports = {
    solidity: '0.8.9', // make sure the version matches the one in smart contract file 
    networks: {
      rinkeby: {
        url: ' ', // rinkeby key 
        accounts: [' '], // metamask privte key- DO NOT SHARE THIS!! It has access to all your accounts
      },
    },
    };
    
  9. Run the command below to deploy the contract to the Rinkeby Test Network.

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

If everything is working, it should deploy the contract and print out the contract address to the terminal.

Head over to Etherscan for the Rinkeby Test Network. Etherscan shows all the transactions and the contracts on Ethereum. When you search for your contract address, you should be able to see the contract details and associated transactions.

Go to your account on Rinkeby Opensea to view the NFT's you just minted.

๐ŸŽ‰ There we go! Now we have created an NFT collection on the Ethereum blockchain using the solidity programming language.

Make sure to checkout Buildspace for more projects and sign up for the NFT Collection if you haven't already. You get to build a frontend for your nfts and even make on-chain nft's in the project!


On a final note, the NFT industry is very new. There are a lot of speculations going on, and with little to no regulation, it can be intimating. However, I find NFT's very exciting because, before NFT's, decentralized finance was the primary industry for blockchain. Now we have a completely new application for blockchain technology. So let's see how the space will evolve.

Thanks for reading my article. If you have any questions drop them below and connect with me from Twitter, I'd love to hear from you!

ย