Introduction
What you will be building, see the demo on the Goerli test network and git repo here.
Web3 development is officially the new way to build web applications, and if you are not there yet, you need to catch up. The way to master building web3 apps is by understanding smart contracts, a frontend framework such as React, and how to link the smart contract with the front end.
In this tutorial, you will learn how to build a decentralized web3 eShop for selling game items using the native ethereum currency.
This app comprises the smart contract layer, a front end where all the interactions with the smart contract take place, and an anonymous chat feature using the CometChat SDK.
Subscribe to my YouTube channel to learn how to build a Web3 app from scratch. I also offer private and specialized classes for serious folks who want to learn one-on-one from a mentor. Book your Web3 classes here.
If you are ready to crush this build, then let’s get started.
Prerequisite
You will need the following tools installed to build along with me:
- NodeJs (Super important)
- EthersJs
- Hardhat
- React
- Tailwind CSS
- CometChat SDK
- Metamask
- Yarn ## Installing Dependencies
Clone the starter project from this Git repo to your computer. Also, make sure to replace it with the name of your preferred project. See the command below.
git clone https://github.com/Daltonic/tailwind_ethers_starter_kit <PROJECT_NAME>
cd <PROJECT_NAME>
Now, open the project in VS Code or on your preferred code editor. Locate the package.json
file and update it with the codes below.
With the above codes replaced and saved in your package.json, run the command below to install the entire packages listed above.
yarn install
Configuring CometChat SDK
Follow the steps below to configure the CometChat SDK; at the end, you must save these keys as an environment variable.
STEP 1:
Head to CometChat Dashboard and create an account.
STEP 2:
Log in to the CometChat dashboard, only after registering.
STEP 3:
From the dashboard, add a new app called GameShop.
STEP 4:
Select the app you just created from the list.
STEP 5:
From the Quick Start copy the APP_ID
, REGION
, and AUTH_KEY
, to your .env
file. See the image and code snippet.
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=******************************
The **.env**
file should be created at the root of your project.
Configuring Alchemy App
STEP 1:
Head to Alchemy, and create an account.
STEP 2:
From the dashboard create a new project.
STEP 3:
Copy the Goerli
test network WebSocket or HTTPS endpoint URL to your .env
file.
After that, enter the private key of your preferred Metamask account to the DEPLOYER_KEY
in your environment variables and save. If you followed the instructions correctly, your environment variables should now look like this.
ENDPOINT_URL=***************************
DEPLOYER_KEY=**********************
REACT_APP_COMET_CHAT_REGION=**
REACT_APP_COMET_CHAT_APP_ID=**************
REACT_APP_COMET_CHAT_AUTH_KEY=******************************
See the section below if you don't know how to access your private key.
Extracting Your Metamask Private Key
STEP 1:
Make sure Goerli is selected as the test network in your Metamask browser extension, Rinkeby and the older test-nets have now been depreciated.
Next, on the preferred account, click the vertical dotted line and choose account details. Please see the image below.
STEP 2:
Enter your password on the field provided and click the confirm button, this will enable you to access your account private key.
STEP 3:
Click on "export private key" to see your private key. Make sure you never expose your keys on a public page such as Github
. That is why we are appending it as an environment variable.
STEP 4:
Copy your private key to your .env
file. See the image and code snippet below:
ENDPOINT_URL=***************************
DEPLOYER_KEY=**********************
REACT_APP_COMET_CHAT_REGION=**
REACT_APP_COMET_CHAT_APP_ID=**************
REACT_APP_COMET_CHAT_AUTH_KEY=******************************
Configuring the Hardhat script
At the root of this project, open the hardhat.config.js
file and replace its content 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
andabi
.-
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.
The Blockchain Service File
Now that we have the above configurations set up, let’s create the smart contract for this build. On your project, head to the **src**
directory and create a new folder called **contracts**
.
Inside this contracts folder, create a new file called **Shop.sol**
, this file will contain all the logics that regulate the activities of the smart contract. Copy, paste, and save the codes below inside the **Shop.sol**
file. See the full code below.
Now, let’s do some explanations of what is going on in the smart contract above. We have the following:
OrderEnum: This enumerable describes the various status an order goes through in its lifecycle. For example, an order could be placed, delivered, canceled, etc.
ProductStruct: This structure model the details of each product to be stored in this smart contract. For example, the SKU, stock, price, and so on.
OrderStruct: This structure embodies the details of each order placed in the shop such as the order id, the buyer, the quantity of items, and more.
CartStruct: This structure contains the data a cart collects for each item to be submitted as an order in this shop.
BuyerStruct: This structure speaks of the kind of data to be collected whenever a buyer purchases a product from our shop.
ShopStats: This is a structure that details the statistics of our shop. Information such as the number of sellers, products, orders, and sales are contained by this struct.
For the state variables, we have the following.
Owner: This state variable contains the account of the deployer of this smart contract.
Stats: This holds information about the current statistics of our shop.
Fee: This contains how much to be charged per creation of a product on this platform.
Products: This holds a collection of products added on this platform.
ProductsOf: This captures the products added by a specific seller to our shop.
OrdersOf: This contains a list of orders purchased by a specific buyer in the shop.
StatsOf: This holds the statistics of each buyer or seller on the platform.
BuyersOf: This accommodates information of the buyers of a specific product.
ProductExist: This checks if a product is found in our shop.
OrderExist: This checks if an order is found in our shop.
For the functions, we have the following.
CreateProduct: This adds a new function to the shop using supplied product information such as the name, description, and price.
UpdateProduct: This modifies existing product information with new data supplied via the function’s parameters.
UpdateOrderDetails: This function sends a product’s update across every order it has received already.
DeleteProduct: This toggles an existing product to a deleted state and becomes unavailable for purchase.
GetProduct: This returns the entire list of products in our shop.
GetProducts: This returns a specific product from our shop by targeting its Id.
CreateOrder: This function cancels an order, it is accessible only by the buyer of such product.
TotalCost: This calculates the overall cost for each product ordered.
DeliverOrder: This function delivers an order, it is accessible only by the seller of such product.
CancelOrder: This function marks an order as canceled and is accessible only to be the buyer of such product.
GetOrders: This returns the entire collection of orders placed on this shop.
GetOrder: This returns a specific order by its Id.
GetBuyers: Returns a collection of buyers of a particular product.
PayTo: Sends a specific amount to a specific address when invoked.
If you are new to Solidity, I have a full FREE course on YouTube called, Mastering Solidity Basics. So do check it out, like it, and subscribe!
https://www.youtube.com/watch?v=11DsTLhI_i4
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.
The above script when executed as a Hardhat command, will ship the Shop.sol
smart contract into any chosen network.
With the above instructions diligently followed, open up a terminal pointing to this project and run the below commands separately on two terminals. VS Code enables you to do this straight from your editor. See the command below.
yarn hardhat node # Terminal #1
yarn hardhat run scripts/deploy.js --network localhost # Terminal #2
If the above commands were successfully executed, you will see these sorts of activities on your terminal. See the image below.
Developing the Frontend
Now that we have our smart contract on a network and all our artifacts (bytecodes and abi) generated, let’s start creating the front end with React step-by-step.
Components
Create a new folder called components in the src directory, which will house all of the React components.
Header component
This component is in charge of displaying information about the currently connected user, the number of items in his cart, and a clickable Identicon that shows more seller options. See the codes responsible for its behavior below.
Banner Component
This component captures a beautiful display of game items. This was designed to give our app a good feel of being a GameShop.
ShopStats Component
This component records a statistic about the shop's current state. This section displays the number of products, sellers, orders, and so on. Look at the code that is responsible for this.
The Cards Component
This component renders a collection of game products on cards. Each card contains game information such as the name, price, stock, and image URL. See the code snippet below.
Details Component
This component displays the details of a specific game item such as the full name, image, description, seller details, and so on. Also, this component contains essential buttons for editing, adding items to the cart, deleting, and chatting with the seller button. See the codes below.
Buyers Component
This component shows a list of buyers who bought a specific game item. See the codes listed below.
Orders Component
This component renders a collection of orders for both the buyer and the seller, giving the buyer the ability to cancel an order so long as it isn’t delivered, and the seller, the ability to deliver a game product. See the codes below.
Adding a Game to Shop
To add a new game to our shop we use two components, the “AddButton” and the “CreateProduct” component. The “AddButton” is responsible for launching the create product modal. Create each one of these components in the components folder and paste the following codes inside them. see the codes below.
The Administrative Components
This component includes the edit, delete, and chat with seller components. The ability to edit or delete a product is solely the responsibility of the owner of such a product.
For the chat with seller button, both the seller and the buyer must wilfully sign up for this service to be able to receive anonymous chats from the buyers. Then he will be able to see them in his chat history.
The logic for each of these components is contained in the codes below; create and paste the codes into their respective components.
The Menu Component
This component is in charge of directing users to other areas of the application, such as your order and sales history, recent customer chats, and statistics. See the code for the component below.
The Shopping Cart Components
The cart component has a highly responsive design as well as an instant price calibrator. See the codes listed below.
The Summary Component
This component enables you to supply the address and phone number of where you want the item shipped. See the codes below.
The Stats Components
This section handles funding and withdrawals from your store. For a complete understanding, refer to the codes below.
And there you have it for all the chunks of components. If you want web3 video tutorials such as building an NFT Minting website, subscribe to my YouTube channel so you won’t miss out on any release.
https://www.youtube.com/watch?v=QN3wb_mXBjY
Pages
It is time to put together all the components on their respective pages. On the root of your project, head to **src**
folder and create a new folder called **views**
. Now all the created components in this section must all be included in this views folder.
The Home Page
This page bundles up the banner, shop stats, and the cards components together, see the codes below.
The Shopping Cart Page
This page features two components, the cart, and the summary components, they both help a customer place orders. The customer pays in ethers, see the codes below.
The Product Page
The product page contains two essential components for displaying details pertaining to a specific game product. See the codes below.
The Orders and Sales Page
The orders page uses the order component to render a list of orders for a buyer of a product that he can see from his order history.
Replicate the page by creating the component below inside of the views folder. See the codes below.
Chat Page
This page enables a buyer to chat with a seller of a product, this was made possible with the CometChat SDK.
Each seller must be authenticated anonymously with this chat service before receiving chats from their buyers. To enjoy this service, you must have configured the CometChat SDK which has been discussed above. See the codes below.
The Recent Chat Page
This page shows you a list of buyers who wants to contact you for extra information about your listed products. The CometChat SDK enables all these chatting functionalities to take place, you will have to sign in or up specifically for the chat feature before you utilize it on your account.
Sellers who don’t opt-in for this service cannot receive chats from their customers. See the codes below.
The Seller and Stats page
The last two pages are dedicated to listing specific sellers' products as well as some shop statistics. The statistics show how well the seller is doing in this market. Still, in the views component, create these two pages. See the codes listed below.
Fantastic, that will be all for the pages, let’s proceed to other essential components of this application.
Configuring Other Components
There are other components that complete this application and in this part, we will be working on them one step at a time.
The App.jsx File
Head to the src folder and open the **App.jsx**
file and replace its content with the codes below.
The above codes will ensure that all the components and pages are represented properly.
State Management Service
You will need a state management library to work with the blockchain and link all the various components together. For the sake of simplicity, we are using a react-hooks-global-state.
Navigate to the **project**
>>
**src**
and create a new folder called the store. Inside this store folder, create a new file called **index.jsx**
and paste the codes below inside and save.
All the data coming from the blockchain will be stored in the above file and used across the entire application.
The Blockchain Service
This file contains all the EthersJs procedures for communicating with your smart contract that lives on the blockchain. In the src folder, create a file called **Blockchain.services.jsx**
and paste the codes below and save.
The Cart Service
This file contains the codes that calibrate our cart system, it ensures that every change in price and quantity of items is reflected in the sub and grand total of our cart.
On the **src**
directory, create a new file named **Cart.Services.jsx**
, copy the codes below and paste them into it and save.
The Chat Service
This file contains the codes for interacting with the CometChat SDK. In the **src**
folder, create a new file named **Chat.Services.jsx**
. Now, copy the codes below, paste them into the file, and save.
Finally, click the link below to download the image. If the asset folder does not already exist in your src directory, create one.
https://github.com/Daltonic/gameshop/blob/master/src/assets/banner.png?raw=true
With all that setup, run the command below to have the project running on your local machine.
yarn start
This will open the project on the browser at **localhost:3000**
.
Conclusion
That concludes the tutorial for this build, you have learned how to create a decentralized eCommerce platform that allows you to list game products on a marketplace.
Buyers can purchase your game product and on delivery, the money is released to the seller of the product.
This is one powerful use case for developing a real-life decentralized web3 application. More of these kinds of builds can be found here on my account.
You can also watch my free videos on my YouTube channel. Or book your private web3 classes with me to speed up your web3 learning process.
With that said, I will catch you next time, 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 (0)