DEV Community

Cover image for How to Build an NFT Auction Site with React, Solidity, and CometChat
Gospel Darlington
Gospel Darlington

Posted on • Updated on

How to Build an NFT Auction Site with React, Solidity, and CometChat

What you will be building, see the git repo here.

Auctioning NFT Item on Marketplace

Introduction

Welcome to this tutorial on building an NFT auction site using React, Solidity, and CometChat. In this guide, we will walk you through the steps of creating a decentralized marketplace for buying and selling non-fungible tokens. We will use React for the front end, Solidity for the smart contract development, and CometChat for real-time messaging and notifications. By the end of this tutorial, you will have a fully functional NFT auction platform ready to go live on the Ethereum blockchain.

Prerequisites

To follow this tutorial, you will need to have the items below installed on your local machine. NodeJs is non-negotiable, the rest can be installed following this guide, so make sure you have it installed and running.

  • NodeJs
  • React
  • Solidity
  • Tailwind
  • CometChat SDK
  • Hardhat
  • EthersJs
  • Metamask
  • Yarn

Installing Dependencies

Clone the starter kit using the command below to your projects folder:

git clone https://github.com/Daltonic/tailwind_ethers_starter_kit <PROJECT_NAME>
cd <PROJECT_NAME>
Enter fullscreen mode Exit fullscreen mode

Next, open the project in VS Code or on your preferred code editor. Locate the package.json file and update it with the codes below.

To install all the required dependencies as indicated in the package.json file, run the command **yarn install** in the terminal.

Configuring CometChat SDK

CometChat SDK

Follow the steps below to configure the CometChat SDK; at the end, you must save your application keys as an environment variable.

STEP 1:
Head to CometChat Dashboard and create an account.

Register a new CometChat account if you do not have one

STEP 2:
Log in to the CometChat dashboard, only after registering.

Log in to the CometChat Dashboard with your created account

STEP 3:
From the dashboard, add a new app called BlueVotes.

Create a new CometChat app - Step 1

Create a new CometChat app - Step 2

STEP 4:
Select the app you just created from the list.

Select your created app

STEP 5:
From the Quick Start copy the APP_ID, REGION, and AUTH_KEY, to your .env file. See the image and code snippet.

Copy the the APP_ID, REGION, and AUTH_KEY

Replace the REACT_COMET_CHAT placeholder keys with their appropriate values.

REACT_APP_COMET_CHAT_REGION=**
REACT_APP_COMET_CHAT_APP_ID=**************
REACT_APP_COMET_CHAT_AUTH_KEY=******************************
Enter fullscreen mode Exit fullscreen mode

The .env file should be created at the root of your project.

Configuring the Hardhat script

Open the hardhat.config.js file at the root of this project and replace the contents with the following settings.

The above script instructs hardhat on these three important rules.

  • Networks: This block contains the configurations for your choice of networks. On deployment, hardhat will require you to specify a network for shipping your smart contracts.

  • Solidity: This describes the version of the compiler to be used by hardhat for compiling your smart contract codes into bytecodes and abi.

  • Paths: This simply informs hardhat of the location of your smart contracts and also a location to dump the output of the compiler which is the ABI.

Check out this video on how to build a decentralized autonomous organization.

https://www.youtube.com/watch?v=Gm442Ihv1GU&

You can also subscribe to the channel for more videos like these.

Developing The Smart Contract

Let's create a smart contract for this project by creating a new folder called contracts in the src directory of the project.

Inside the contracts folder, create a file called 'DappAuction.sol' which will contain the code that defines the behavior of the smart contract. Copy and paste the following code into the 'DappAuction.sol' file. The complete code is shown below."

Let's go over some of the specifics of what's happening in the smart contract above. The following items are available:

Contract Imports
The following are the smart contracts imported from the openzeppelin library:

  • Counters: For keeping track of all NFTs on the platform.
  • ERC721: This is a standard for non-fungible tokens on the Ethereum blockchain. It defines a set of functions and events that a smart contract implementing the ERC721 standard should have.
  • ERC721URIStorage: This is a smart contract that stores the URI (Uniform Resource Identifier) of an ERC721 token.
  • ReentrancyGuard: This import keeps our smart contract safe against reentrancy attacks.

State variables

  • Totalitems: This variable bears records of the number of NFTs available in our smart contract.
  • CompanyAcc: This contains a record of the deployer wallet address.
  • ListingPrice: This contains the price for creating and listing an NFT on the platform.
  • RoyalityFee: This is the percentage of royalty that the seller of an NFT gets on every sale.

Mappings

  • AuctionedItem: This holds all the NFT data minted on our platform.
  • AuctionedItemExist: Used to validate the existence of an NFT.
  • ExistingURIs: Holds minted metadata URIs.
  • BiddersOf: Bears record of bidders for a particular auction.

Structs and Events

  • BidderStruct: Describes the information about a particular bidder.
  • AuctionStruct: Describes the information about a particular NFT item.
  • AuctionItemCreated: An event that logs information about the just-created NFT.

Functions

  • Constructor(): This initializes the smart contract with the company’s account, stipulated royalty fee, and token name and symbol.
  • GetListingPrice(): Returns the price set for creating an NFT on the platform.
  • SetListingPrice(): Used for updating the minting price for creating an NFT.
  • ChangePrice(): Used for modifying the cost for a specific NFT.
  • MintToken(): Used for Creating a new token.
  • CreateAuction(): Used for Creating a new auction using a minted token Id.
  • OfferAuction(): Used for placing an NFT item on the market.
  • PlaceBid(): Used for bidding in an auction.
  • ClaimPrize(): Used to transfer an NFT to the highest bidders.
  • PerformRefund(): Used to refund bidders who didn’t emerge as winners for each auction.
  • BuyAuctionedItem(): Used to purchase NFTs sold outrightly.
  • GetAuction(): Returns an auction by token Id.
  • GetAllAuctions(): Returns all available auctions from the contract.
  • GetUnsoldAuction() Returns all unsold auctions.
  • GetSoldAuction(): Returns all sold auctions.
  • GetMyAuctions(): Returns all auctions belonging to the function caller.
  • GetLiveAuctions(): Returns all auctions listed on the market.
  • GetBidders(): Returns bidders of a specific auction by specifying the token Id.
  • GetTimestamp(): Returns a timestamp for a specific date.
  • PayTo(): Sends ethers to a specific account.

Configuring the Deployment Script

Navigate to the scripts folder and then to your deploy.js file and paste the code below into it. If you can't find a script folder, make one, create a deploy.js file, and paste the following code into it.

When run as a Hardhat command, the above script will deploy the Auction.sol smart contract to your local blockchain network.

Following the above instructions, open a terminal pointing to this project and run the commands listed below separately on two terminals. You can do this directly from your editor in VS Code.
Look at the command below.

yarn hardhat node # Terminal 1
yarn hardhat run scripts/deploy.js # Terminal 2
Enter fullscreen mode Exit fullscreen mode

If the preceding commands were successfully executed, you should see the following activity on your terminal. Please see the image below.

Step One

Step Two

Configuring Infuria App

STEP 1: Head to Infuria, and create an account.

Login to your infuria account

STEP 2: From the dashboard create a new project.

Create a new project step 1

Create a new project step 2

STEP 3: Copy the project Id and your API secret to your .env file in the format below and save.

Copy the project Id and your API secret

Env File

INFURIA_PID=***************************
INFURIA_API=**********************

REACT_APP_COMET_CHAT_REGION=**
REACT_APP_COMET_CHAT_APP_ID=**************
REACT_APP_COMET_CHAT_AUTH_KEY=******************************
Enter fullscreen mode Exit fullscreen mode

Developing an Image Processing API

We need a way to generate metadata out of an Image we intend to make an NFT. The problem is that JavaScript on the browser cannot get us the result we intend. It will take a NodeJs script to help us process the images, generate metadata, deploy to IPFS, and return the token URI as an API response. No need for much talking, let me show you how to implement this API.

First, you will need the following libraries, which are already installed on this project courtesy of the yarn install command you executed previously.

  • Express(): Enables server creation and resource sharing.
  • Express-Fileupload(): Enables file upload such as uploading an image.
  • Cors(): Enables cross-origin request sharing.
  • Fs(): Enables access to the file system of our local machine.
  • Dotenv(): Enable the management of environment variables.
  • Sharp(): Enables the processing of images to different dimensions and extensions.
  • Faker(): Enables the generation of random and fake data.
  • IpfsClient(): Enables the upload of files to the IPFS.

Let us now write some essential script functions that will assist us in converting images, as well as other information such as their names, descriptions, prices, Ids, and so on, to their metadata equivalent.

Create a folder called "api" at the root of your project, then create a new file called metadata.js within it and paste the code below inside.

Metadata.js File

Now let’s utilize these functions in the main NodeJs file below.

App.js File
Create another script called app.js within this API folder and paste the codes below; this is where the API's controlling logic will reside.

The IPFS library uses the Infuria Gateway for uploading files to the IPFS which we have already set up in the .env file.

Now, run node api/app.js on the terminal to start up the API service as can be seen in the image below.

API receiving Image and Metadata Info from the Frontend

Importing Private Keys to Metamask

To use Metamask with your Hardhat local network which is represented as Localhost:8545, use the following steps to set it up.

Run yarn hardhat node on your terminal to spin up your local blockchain server. You should see a similar image to the one below on the terminal.

Hardhat Node Started

Copy the private key of the account at zero(0) and import it on your Metamask, see the image below.

Step 1: Click on the Import account Option

Step 2: Enter the private key from the Hardhat Server

Step 3: Result

Now, you can repeat the above steps and import up to three or four accounts depending on your need.

All of the processes needed to develop a production-ready smart contract are already packaged inside this book, in an easy-to-understand manner.

Capturing Smart Contract Development

Grab a copy of my book titled, “capturing smart contract development” to become an in-demand smart contract developer.

Developing the Frontend

We will now use React to build the front end of our project, using the smart contract and related information that has been placed on the network and generated as artifacts (including the bytecodes and ABI). We will do this by following a step-by-step process.

Components

In the src directory, create a new folder called **components** to house all of the React components below.

Header Component

Header Component

Now, create a component in the components folder called Header.jsx and paste the following codes below. The designs of all these components were achieved using the Tailwind CSS framework.

Hero Component

Hero Component

Next, create another component in the components folder called Hero.jsx and paste the following codes below.

Artworks Component

Artworks Component

Again, create a component in the components folder called Artworks.jsx and paste the following codes below.

Footer Component

Footer Component

Next, create a component in the components folder called Footer.jsx and paste the following codes below.

Other Component

The following are components supporting the full functionality of the rest of this application.

Countdown Component
This component is responsible for rendering a countdown timer on all the NFTs, see the codes below.

The Empty Component

The Empty Component

This component is responsible for displaying a small text informing the users of no NFTs in the platform. See the example code below for implementation.

Creating an NFT

Creating an NFT

To write a Create NFT component, use the following codes. This will be a modal that accepts an image, a title, a description, and a price before submitting it to the blockchain.

Before being stored on the blockchain, data collected from a form is sent to a NodeJs API, which converts it into metadata and deploys it to IPFS.

Next, in the components folder, create a new file called "CreateNFT.jsx" and paste the following code into it.

Offering NFTs on the Market

Offering an NFT Item

This component is responsible for offering new items live on the market. Using a form, it accepts a duration for which you intend to have your NFT live on the market. Once this timeline expires, the live NFT will disappear from the market. See the codes below.

Placing Bids

Placing Bids

This component allows a user to place a bid and participate in an NFT auction. This is accomplished through the use of a modal that receives the price a user intends to bid if it is within the time limit for bidding. See the codes listed below.

Changing an NFT price

Changing NFT Price

This component allows an NFT owner to change the price of an NFT that is not currently trading on the market. Accepting a new price from a form and sending it to the blockchain accomplishes this. Look at the codes below.

The Chat Component

Live Chat with CometChat SDK

Finally, for the components, there is a chat component that is controlled by the CometChat SDK. See the codes below.

The Pages

This application has about three views or pages; let's organize all of the above components into their respective views using the steps below. First, create a folder called views in the src directory and create the soon-to-be-discussed pages.

Home View

The Home View

The Home view combines two major components: the Hero and Artworks components. See the codes below.

Collections View

The Collection View

This view displays all of the NFTs owned by a specific user. It empowers a user to manage an NFT, such as whether or not to offer it on the market or change its price. See the codes shown below.

The NFT View

NFT View

Lastly, this view contains the chat component as well as other important components, as shown in the code below.

Updating The App.jsx File

Update the App file with the codes below in other to bundle up all the components and pages together.

Updating the Index.jsx and CSS files

Use the codes below to update the index.jsx and index.css files respectively.

Adding the App Services

In this application, we have two services: chat and blockchain, as shown in the codes below. Simply create a new folder called services in the src directory and place the following files in it using the codes below.

Chat Services

Blockchain Service

The Store

The store is a state management service included in this application. This is where all of the data extracted from the blockchain is kept. To replicate, create a store folder within the src directory. Next, within this folder, create a file called index.jsx and paste the codes below into it.

Now start up the application by running **yarn start** on another terminal to see the result on the terminal. If you experience any trouble replicating this project you can drop a question on our discord channel.

You can also see this video to learn more about how to build an NFT marketplace from design to deployment.

https://www.youtube.com/watch?v=fJIiqeevqoU&

Congratulations, that is how you build an NFT Marketplace using React, Solidity, and CometChat.

Conclusion

In conclusion, building an NFT auction site with React, Solidity, and CometChat requires a combination of front-end and back-end development skills.

By using these tools together, it is possible to create a fully functional NFT auction site that is secure, scalable, and user-friendly.

If you're ready to dive deeper into web3 development, schedule your private web3 classes with me to accelerate your web3 learning.

That said, I'll see you next time, and have a great day!

About the Author

Gospel Darlington is a full-stack blockchain developer with 6+ years of experience in the software development industry.

By combining Software Development, writing, and teaching, he demonstrates how to build decentralized applications on EVM-compatible blockchain networks.
His stacks include JavaScript, React, Vue, Angular, Node, React Native, NextJs, Solidity, and more.

For more information about him, kindly visit and follow his page on Twitter, Github, LinkedIn, or his website.

Top comments (3)

Collapse
 
juyuancai profile image
juyuancai

Hi, when you use IPFS to publish file, do you need to purchase a VPS also with pinata pin service? Now we have a better solution called Foggie. With Foggie , you can get a 2C4G VPS with pin service together with only the same price as pinata. You will also get much larger bandwith to 4T. Also , when you use it, you can have token rewards. Here is the link: https://foggie.fogworks.io/?pcode=uZVcLL&cc=1008#/fogworks

Collapse
 
christopherxp profile image
Christopherxp

I really liked these auctions recently. Thanks to the campaign, I bought a very interesting nft. If anyone wants to start bidding nft, I recommend this post: nftmonk.com/what-is-an-nft-auction...

Collapse
 
9opsec profile image
9opsec

I'm using chrome and the github embedded code is not rendering correctly.