How To Create Your Own Nft Project

How to Make an NFT in 14 Lines of Code

If you’re a programmer who’s interested in Blockchain development, you should know something about NFTs, or Non-Fungible Tokens. And so in this article, we’ll learn about the engineering backside them so you lot can beginning building your own.

At the end of the project, you volition have your ain Ethereum wallet with a new NFT in information technology. This tutorial is beginner-friendly and does not crave any prior knowledge of the Ethereum network or smart contracts.

image-46
The NFT contract has merely 14 lines of code

What is an NFT?

NFT stands for not-fungible token. This quote from ethereum.org explains information technology well:

NFTs are tokens that we can use to represent ownership of unique items. They let us tokenise things similar art, collectibles, even real estate. They can but accept 1 official owner at a time and they’re secured past the Ethereum blockchain – no 1 can modify the record of buying or copy/paste a new NFT into existence.

What is an NFT standard or ERC-721?

The ERC-721 is the most common NFT standard. If your Smart Contract implements certain standardized API methods, it can be called an ERC-721 Non-Fungible Token Contract.

These methods are specified in the EIP-721. Open-sourced projects similar OpenZeppelin accept simplified the development procedure past implementing the well-nigh common ERC standards as a reusable library.

What is minting an NFT?

Past minting an NFT, you publish a unique token on a blockchain. This token is an example of your Smart Contract.

Each token has a unique tokenURI, which contains metadata of your asset in a JSON file that conforms to certain schema. The metadata is where you store data nearly your NFT, such as name, image, description, and other attributes.

An instance of the JSON file for the “ERC721 Metadata Schema” looks like this:

              { 	"attributes": [ 		{ 			"trait_type": "Shape", 			"value": "Circumvolve" 		}, 		{ 			"trait_type": "Mood", 			"value": "Sad" 		} 	], 	"clarification": "A sad circumvolve.", 	"epitome": "https://i.imgur.com/Qkw9N0A.jpeg", 	"proper noun": "Lamentable Circle" }
            

There are three primary ways to shop an NFT’s metadata.

Outset, you can store the information on-chain. In other word, y’all tin can extend your ERC-721 and store the metadata on the blockchain, which can exist costly.

The second method is to utilize IPFS. And the third way is to simply take your API render the JSON file.

The first and second methods are unremarkably preferred, since you cannot temper the underlying JSON file. For the scope of this project, nosotros will opt for the third method.

For a good tutorial on using NFTs with IPFS, read this article by the Abracadabra team.

What Nosotros’ll Be Building

emotionalshapes

In this tutorial, we’ll be creating and minting our ain NFT. Information technology is beginner-friendly and does not require whatever prior knowledge of the Ethereum network or smart contracts. All the same, having a good grasp on those concepts volition assist yous understand what is going on behind the scenes.

In an upcoming tutorial, we’ll build a fully-functional React web app where you can display and sell your NFTs.

If you are merely getting started with dApp development, begin by reading through the key topics and spotter this amazing course by Patrick Collins.

This project is intentionally written with hands understandable code and is non suitable for production usage.

Prerequisites

Metamask

image-32

We need an Ethereum address to interact with our Smart Contract. We volition be using Metamask as our wallet. It is a gratuitous virtual wallet that manages your Ethereum addresses. Nosotros will demand information technology to send and receive transactions (read more on that here). For example, minting an NFT is a transaction.

Download their Chrome extension and their mobile app. We volition need both as the Chrome extension does not display your NFTs.

image-34

Make sure to modify the network to “Ropsten Exam Network” for development purposes. You will need some Eth to cover the fees of deploying and minting your NFT. Head to the Ropsten Ethereum Faucet and enter your address. You should soon come across some test Eth in your Metamask account.

image-35

Alchemy

To interact with the Ethereum Network, you will need to be connected to an Ethereum Node.

Running your ain Node and maintaining the infrastructure is a project on its own. Luckily, in that location are nodes-as-a-service providers which host the infrastructure for you. There are many choices similar Infura, BlockDaemon, and Moralis. We volition exist using Alchemy as our node provider.

Head over to their website, create an account, choose Ethereum equally your network and create your app. Choose Ropsten as your network.

image-36

On your dashboard, click “view details” on your app, and so click “view central”. Salve your http key somewhere as we volition need that later.

image-38

NodeJS/NPM

We will be using NodeJS for the project. If yous don’t accept it installed, follow this simple tutorial by freeCodeCamp.

Initialize the project

In your terminal, run this command to brand a new directory for your projection:

              mkdir nft-project cd nft-project
            

Now, let’s make another directory,
ethereum/, inside
nft-project/
and initialize information technology with Hardhat. Hardhat is a dev tool that makes it easy to deploy and test your Ethereum software.

              mkdir ethereum cd ethereum npm init
              
            

Answer the questions withal you lot desire. So, run those commands to make a Hardhat project:

              npm install --salvage-dev hardhat npx hardhat
            

You will run into this prompt:

              888    888                      888 888               888 888    888                      888 888               888 888    888                      888 888               888 8888888888  8888b.  888d888 .d88888 88888b.   8888b.  888888 888    888     "88b 888P"  d88" 888 888 "88b     "88b 888 888    888 .d888888 888    888  888 888  888 .d888888 888 888    888 888  888 888    Y88b 888 888  888 888  888 Y88b. 888    888 "Y888888 888     "Y88888 888  888 "Y888888  "Y888  Welcome to Hardhat v2.0.eight  ? What do you want to do? …   Create a sample project ❯ Create an empty hardhat.config.js   Quit
            

Select create an empty hardhat.config.js. This volition generate an empty
hardhat.config.js
file that we will later update.

For the web app, we volition employ Next.js to initialize a fully-functional spider web app. Get back to the root directory
nft-project/
and initialize a boilerplate Next.js app called web:

              cd .. mkdir spider web cd spider web npx create-side by side-app@latest
            

Your project now looks similar this:

              nft-projection/ 	ethereum/ 	spider web/
            

Awesome! We are ready to dive into some existent coding.

How to Define Our .env Variables

Remember the Abracadabra cardinal we grabbed from our exam project earlier? We will use that forth with our Metamask account’s public and private keys to interact with the blockchain.

Run the following commands, brand a file called
.env
inside your
ethereum/
directory, and install dotenv. We volition apply them subsequently.

              cd .. cd ethereum affect .env npm install dotenv --save
            

For your
.env
file, put the fundamental you have exported from Alchemy and follow those instructions to grab your Metamask’s individual key.

Hither’due south your .env file:

              DEV_API_URL = YOUR_ALCHEMY_KEY PRIVATE_KEY = YOUR_METAMASK_PRIVATE_KEY PUBLIC_KEY = YOUR_METAMASK_ADDRESS
            

The Smart Contract for NFTs

Go to the
ethereum/
folder and create 2 more directories: contracts and scripts. A simple hardhat project contains those folders.

  • contracts/
    contains the source files of your contracts
  • scripts/
    contains the scripts to deploy and mint our NFTs
              mkdir contracts mkdir scripts
              
            

So, install OpenZeppelin. OpenZeppelin Contract is an open up-sourced library with pre-tested reusable code to brand smart contract development easier.

              npm install @openzeppelin/contracts
            

Finally, we will exist writing the Smart Contract for our NFT. Navigate to your contracts directory and create a file titled
EmotionalShapes.sol. You lot can proper noun your NFTs however yous see fit.

The
.sol
extension refers to the Solidity language, which is what we will use to plan our Smart Contract. We will simply be writing 14 lines of code with Solidity, so no worries if you lot oasis’t seen information technology before.

Commencement with this article to learn more about Smart Contract languages. You can besides direct jump to this Solidity crook canvas which contains the master syntax.

              cd contracts affect EmotionalShapes.sol
            

This is our Smart Contract:

              // SPDX-License-Identifier: MIT pragma solidity ^0.8.0;  import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol";  contract EmotionalShapes is ERC721 {     using Counters for Counters.Counter;     Counters.Counter private _tokenIdCounter;      constructor() ERC721("EmotionalShapes", "ESS") {}      function _baseURI() internal pure override returns (string retentiveness) {         render "YOUR_API_URL/api/erc721/";     }      role mint(accost to)         public returns (uint256)     {         require(_tokenIdCounter.current() < 3);          _tokenIdCounter.increment();         _safeMint(to, _tokenIdCounter.current());          return _tokenIdCounter.current();     } }
              
            

Permit’s go through the lawmaking and understand what is going on.

  1. At the summit of the file, we specified which OpenZeppelin module to import. We need the ERC721 contract as it is the ‘base’ of our Smart Contract. It has already implemented all the methods specified in EIP-721 then we can safely use it.
  2. A Counter is useful to generate incremental ids for our NFTs. We named the variable
    _tokenIdCounter
  3. In the constructor, we initialized our ERC721 with its name and its symbol. I chose EmotionalShapes and ESS.
  4. We override the default
    _baseURI
    function by returning our ain. We will get to build that in a second. In summary, it is the URL that will be added every bit ‘prefix’ to all our tokenURIs. In the above example, the metadata of our NFTs will live in a JSON file at
    YOUR_API_URL/api/erc721/ane.
  5. Nosotros implement the ‘mint’ function. It is the part that lets you lot publish an example of this Smart Contract on the blockchain. I required the
    _tokenIdCounter
    variable to exist less than 3 every bit I will just create three instances of my NFT. You can remove that if you lot want to mint more.
  6. Finally, inside the mint function, we increment the
    _tokenIdCounter

    variable by 1, so our id will be 1, followed past 2, followed by iii. Then, we call the function provided past OpenZeppelin
    _safeMint
    to publish the token.

Don’t worry if you feel lost. You can attend a workshop led by volunteers from freeCodeCamp, where we invite devs of similar skill levels to build stuff together, including this NFT project.

The events are free and remote, then you lot can ask whatever questions direct. You can annals here. The seats are limited so you volition be invited to the next available events.

Every bit mentioned earlier, in that location are three main ways of storing your tokenURI. Nosotros will be edifice a simple API endpoint which resolve in our NFT’s information as JSON.

Our Next.js project gives us a handy way to develop API routes. Go to the
spider web/
folder, notice the
api/
folder within the
pages/
binder, and make our dynamic
[id].js
route in a
erc721/
folder (read more nigh routing here):

              // web/pages/api/erc721/[id].js  const metadata = {   1: {     attributes: [       {         trait_type: "Shape",         value: "Circle",       },       {         trait_type: "Mood",         value: "Sad",       },     ],     description: "A pitiful circumvolve.",     image: "https://i.imgur.com/Qkw9N0A.jpeg",     name: "Sad Circle",   },   ii: {     attributes: [       {         trait_type: "Shape",         value: "Rectangle",       },       {         trait_type: "Mood",         value: "Angry",       },     ],     description: "An angry rectangle.",     prototype: "https://i.imgur.com/SMneO6k.jpeg",     name: "Angry Rectangle",   },   3: {     attributes: [       {         trait_type: "Shape",         value: "Triangle",       },       {         trait_type: "Mood",         value: "Bored",       },     ],     description: "An bored triangle.",     image: "https://i.imgur.com/hMVRFoJ.jpeg",     name: "Bored Triangle",   }, };  export default office handler(req, res) {   res.status(200).json(metadata[req.query.id] || {}); }
            

For the sake of this project, I fabricated the code every bit easily understandable equally possible. This is definitely not suited for product (please don’t use an Imgur url for your NFT). Brand sure to define the metadata for all the NFTs that you intend to mint.

Now, get to the web directory, and start your Next.js app with this command:

              npm run dev
            

Your app should be running on localhost:3000. To make sure our endpoint works, get to http://localhost:3000/api/erc721/1 and it should resolve with a JSON object of your first NFT’due south metadata.

Since your app is hosted locally, other apps cannot admission it. Using a tool like ngrok, we can expose our local host to a publicly accessible URL.

image-39
  1. Become to ngrok.com and consummate the registration process
  2. Unzip the downloaded package
  3. In your concluding, make certain you cd into the folder where you unzipped your ngrok package
  4. Follow the educational activity on your dashboard and run
              ./ngrok authtoken YOUR_AUTH_TOKEN
            

five.  Then, run this command to create a tunnel to your web app hosted on localhost:3000

              ./ngrok http 3000
            

6.  You are most there! On your last, you should see something like this:

              ngrok by @inconshreveable                                                                            (Ctrl+C to quit)                                                                                                                       Session Condition                online                                                                                  Account                       YOUR_ACCOUNT (Programme: Costless)                                                                        Version                       2.three.40                                                                                  Region                        United States (u.s.a.)                                                                      Spider web Interface                 http://127.0.0.ane:4040                                                                   Forwarding                    http://YOUR_NGROK_ADDRESS -> http://localhost:3000                              Forwarding                    https://YOUR_NGROK_ADDRESS -> http://localhost:3000
              
            

Go to
YOUR_NGROK_ADDRESS/api/erc721/1
to make sure your endpoint works correctly.

How to Deploy our NFT

Now that nosotros have washed all the footing work (oof), permit’south go dorsum to our
ethereum/
folder and get prepare to deploy our NFT.

Change the
_baseURI
function in your
ethreum/contracts/YOUR_NFT_NAME.sol
file
to render your ngrok address.

              // ethereum/conrtacts/EmotionalShapes.sol  contract EmotionalShapes is ERC721 { ... 	function _baseURI() internal pure override returns (string memory) { 		return "https://YOUR_NGROK_ADDRESS/api/erc721/"; 	} ... }
            

To deploy our NFT, we will beginning need to compile it using Hardhat. To make the process easier, we will install ethers.js.

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

Let’due south update our hardhat.config.js:

              require("dotenv").config(); require("@nomiclabs/hardhat-ethers");  module.exports = {   solidity: "0.8.0",   defaultNetwork: "ropsten",   networks: {     hardhat: {},     ropsten: {       url: process.env.DEV_API_URL,       accounts: [`0x${process.env.PRIVATE_KEY}`],     },   }, };
              
            

To learn more about the hardhat configuration file, take a look at their documentation. We have configured the ropsten network with our Alchemy URL and provided it with the private cardinal of your metamask account.

Finally, run:

              npx hardhat compile
            

This lets hardhat generate ii files per compiled contract. We should run into a newly created
artifacts/
folder that contains your compiled contracts in the
contracts/
binder. To larn more about how that works, read this tutorial by the Hardhat squad.

Now, let’s write a script to finally deploy our NFT to the examination network. In your
scripts/
folder, create a file called
deploy.js.

              // ethereum/scripts/deploy.js  async function main() {   const EmotionalShapes = await ethers.getContractFactory("EmotionalShapes");   const emotionalShapes = expect EmotionalShapes.deploy();    panel.log("EmotionalShapes deployed:", emotionalShapes.accost); }  master()   .then(() => process.get out(0))   .catch((fault) => {     panel.error(error);     process.exit(1);   });
              
            

This code is inspired by the hardhat deployment tutorial.

A
ContractFactory
in ethers.js is an abstraction used to deploy new smart contracts, then
EmotionalShapes
here is a factory for instances of our token contract. Calling
deploy()
on a
ContractFactory
volition start the deployment, and render a
Promise
that resolves to a
Contract. This is the object that has a method for each of your smart contract functions.

How to view the NFT on the blockchain

Run the deployment script:

              node ./scripts/deploy.js
            

Y’all should see in your final
EmotionalShapes deployed: SOME_ADDRESS. This is the address where your Smart Contract is deployed on the ropsten exam network.

If you head over to
https://ropsten.etherscan.io/address/SOME_ADDRESS, you should meet your freshly deployed NFT. Yep! You did information technology!

If yous are stuck somewhere in the tutorial or feeling lost, again, you can join our live workshops where we will build this project together in a Zoom call.

How to Mint your NFT

Now that you have deployed your NFT, it’south time to mint information technology for yourself! Create a new file called
mint.js
in your scripts/ folder. We will be using ethers.js to help u.s..

Offset past calculation the
ethers.js
package:

              npm install --salvage ethers
            

So, populate the
mint.js
file:

              require("dotenv").config(); const { ethers } = crave("ethers");  const contract = require("../artifacts/contracts/EmotionalShapes.sol/EmotionalShapes.json"); const contractInterface = contract.abi;  // https://docs.ethers.io/v5/api/providers const provider = ethers.getDefaultProvider("ropsten", {   alchemy: procedure.env.DEV_API_URL, });  // https://docs.ethers.io/v5/api/signer/#Wallet const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);  //https://docs.ethers.io/v5/api/contract/contract const emotionalShapes = new ethers.Contract(   YOUR_NFT_ADDRESS,   contractInterface,   wallet );  const main = () => {   emotionalShapes     .mint(process.env.PUBLIC_KEY)     .then((transaction) => console.log(transaction))     .catch((eastward) => console.log("something went wrong", eastward)); };  master();
              
            

I have left comments to where you tin can find more information almost the unlike methods. We first take hold of the contract’s interface (ABI). From ethereum.org:

An awarding binary interface, or ABI, is the standard way to interact with contracts in the Ethereum ecosystem, both from outside the blockchain and for contract-to-contract interactions.

Your ABI defines how others interact with your contract. Then, nosotros created our provider with Abracadabra (retrieve near node-as-a-service). Finally, nosotros initialize our wallet with our private cardinal.

The
primary()
part calls the
mint
method in the Smart Contract nosotros had just deployed. The
mint
method takes merely ane parameter,
to, which signal the receiver of the token. Since nosotros are minting for ourself, nosotros put the public accost of our Metamask business relationship.

If everything goes well, you should run into the transaction logged in your terminal. Catch the
hash
property and go to
https://ropsten.etherscan.io/tx/YOUR_HASH. You should see the minting transaction there!

You need to start by downloading the mobile version of Metamask. Then, log into your account.

Yous should run into an NFTs tab forth with an add NFT push. Click on the button and enter the address of your Smart Contract along with the ids that you lot have minted. If you have followed the tutorial, y’all should outset with an id of
i.

IMG_0376
View NFTs in your Metamask wallet

Decision

Congratulations! You have just minted your ain NFT. In the side by side part of the project, we will be edifice the forepart end React app to interact with our contract. The end goal is to build a fully functional web app where y’all can sell your ain NFTs.

Lastly, y’all can bring together our live workshops with volunteers from freeCodeCamp where nosotros will build this projection together with other developers.

The events are free for everyone across the world and invitations are sent outset-come, first-serve. If you’d similar to lead the workshops, DM me on Twitter, we’d honey to take you! Nosotros also organize other type of events similar hiring fairs and social meetups.

Let me know what you desire to build. NFTs are withal in its infancy and novel ideas are more than welcome. Tin can’t await to meet what crazy idea you accept!



Acquire to lawmaking for gratis. freeCodeCamp’due south open source curriculum has helped more than 40,000 people get jobs as developers. Go started

Source: https://www.freecodecamp.org/news/how-to-make-an-nft/

Check Also

Will Dogecoin Go Up In Value

Will Dogecoin Go Up In Value

On Dec. 6, 2013, Billy Markus and Jackson Palmer decided to combine their dearest of …