How to Build a Web3 Play-To-Earn Money Dapp with React, Solidity, and CometChat
Tags: web3, blockchain, smartcontract, tutorial
Published: 2023-08-18 13:16:21

What you will be building, see the [live demo](https://play-to-earn-three.vercel.app/) at sepolia test net and the [git repo](https://github.com/Daltonic/P2E).

![Game Play](https://paper-attachments.dropboxusercontent.com/s_A669F6C723766110FAA73EBE4FA93F72A0924D07056B57BA53C0E19195292853_1692352824779_P2E+Game+Play.gif)

![The Chat Interface](https://paper-attachments.dropboxusercontent.com/s_A669F6C723766110FAA73EBE4FA93F72A0924D07056B57BA53C0E19195292853_1692352877105_P2E+Chat+2.gif)


Are you captivated by the limitless potential of blockchain technology? Does the blend of innovation and financial opportunities intrigue you? If you're a blockchain enthusiast eager to delve into the captivating world of play-to-earn money applications, you're exactly where you need to be.

In this comprehensive tutorial, consider us your companions on an exhilarating journey to construct an advanced Web3 Play-To-Earn Money DApp. Just as those before you have ventured into the realm of blockchain, you're about to explore a new horizon. By harnessing the combined capabilities of React, Solidity, and CometChat, we'll guide you through every step of the way.

With React as your toolkit, you'll craft a dynamic front-end interface that beckons users into an immersive experience. Solidity, the heart of Ethereum's smart contracts, will empower you to infuse financial logic into each interaction. And finally, [CometChat](https://try.cometchat.com/oj0s7hrm5v78), our communication ally, will bridge connections in real-time, fostering seamless interaction among users.

In this tutorial, you'll gain mastery over:


- Dynamic React Interfaces
- Solidity Smart Contracts
- Strategies for Profit
- Real-time CometChat Integration
- Decentralized Insights

Whether you're a seasoned developer or a newcomer to web3, this tutorial equips you with the skills to craft your own Play-To-Earn DApp. Together, let's embark on this exhilarating journey, merging React, Solidity, and CometChat – the trio that shapes the world of Web3 play-to-earn awaits your innovation! 🌟


## Prerequisites

You will need the following tools installed to build along with me:

- Node.js
- Yarn
- MetaMask
- React
- Solidity
- [CometChat SDK](https://try.cometchat.com/oj0s7hrm5v78)
- Tailwind CSS

I recommend watching the video below to learn how to set up your MetaMask for this project

{% embed https://www.youtube.com/watch?v=qnudOwva0fM %}



## Installing Dependencies

Clone the starter kit and open it in VS Code using the command below: 


    git clone https://github.com/Daltonic/tailwind_ethers_starter_kit playToEarn
    cd playToEarn

Next, update the `package.json` with the snippet below.


{% gist https://gist.github.com/covelitein/1df4a4321d674f4b78ec6b7a1c81986e %}


Please run the command `yarn install` in your terminal to install the dependencies for this project.


## Configuring CometChat SDK

To configure the [**CometChat SDK**](https://try.cometchat.com/oj0s7hrm5v78), please follow the steps provided below. Once completed, make sure to save the generated keys as environment variables for future use.

**STEP 1:**
Head to [**CometChat**](https://try.cometchat.com/daltonic) Dashboard and create an account.

![Register a new CometChat account if you do not have one](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692168014160_cometchat1.png)


**STEP 2:**
Log in to the [**CometChat**](https://try.cometchat.com/daltonic) dashboard, only after registering.


![Log in to the CometChat Dashboard with your created account](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692168070940_cometchat2.png)


**STEP 3:**
From the dashboard, add a new app called **Play-To-Earn****.**

![Create a new CometChat app - Step 1](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692168196068_cometchat4.png)

![Create a new CometChat app - Step 2](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692168247756_cometchat5.png)


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

![Select your created app](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692168307217_cometchat6.png)


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](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692168367367_cometchat7.png)


Replace the `REACT_COMET_CHAT` placeholder keys with their appropriate values.


    REACT_APP_COMETCHAT_APP_ID=****************
    REACT_APP_COMETCHAT_AUTH_KEY=******************************
    REACT_APP_COMETCHAT_REGION=**

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


## Configuring the Hardhat script

Navigate to the root directory of the project and open the "`hardhat.config.js`" file. Replace the existing content of the file with the provided settings.



{% gist https://gist.github.com/covelitein/316a79b2c830256f35ec60a7926a47af %}


This code configures Hardhat for your project. It includes importing necessary plugins, setting up networks (with localhost as the default), specifying the Solidity compiler version, defining paths for contracts and artifacts, and setting a timeout for Mocha tests.


## The Smart Contract File

The following steps will guide you through the process of creating the smart contract file for this project:


1. Create a new folder named `contracts` inside the `src` folder.
2. Create a new file named `PlayToEarn``.sol` inside the `contracts` folder.
3. Copy the provided codes below and paste it into their respective files and save.

By following these steps, you will have successfully set up the necessary directory structure and created the `PlayToEarn``.sol` file, which will serve as the foundation for implementing the logic of the smart contract.


{% gist https://gist.github.com/covelitein/78df451af96b92c7ef9ff15e0cecf07f %}


The PlayToEarn smart contract has been meticulously crafted to streamline game creation, enhance gameplay experiences, manage invitations, and more. Now, let's delve into a comprehensive overview of its fundamental functionalities:


1. Contract Inheritance and Dependencies:
    - PlayToEarn leverages contracts inherited from the OpenZeppelin library, including well-established modules such as Ownable, Counters, ReentrancyGuard, and SafeMath. These foundational components contribute to the robustness and security of the smart contract system.


1. Structs:
    - GameStruct : This structure encapsulates game information such as the title, description, owner, participant counts, challenge quantities, gameplay instances, stake amounts, and key dates like startDate and endDate
    
    - PlayerStruct: This holds important info about a player, like their ID, address, and associated GameStruct.
    
    - InvitationStruct: This keeps track of game play invitations, including the invitee's address and other game details.
    
    - PlayerScoreSheetStruct: This stores a player's game data, such as their score and address, along with other game-related info.
    
2. State Variables:
    - ServiceFee: This is the fee deducted from every successfully completed game for the platform owner.
    
    - TotalBalance: This keeps track of the total balance accumulated from game stakes.
    
3. Mappings:
    - games: Maps game IDs to their respective `**GameStruct**` data, storing comprehensive game information.
    - players: Connects player IDs to their corresponding `**PlayerStruct**` details, capturing player-specific data.
    - invitationsOf: Maps player addresses and game IDs to related `**InvitationStruct**` data, tracking invitations.
    - isListed: Maps game IDs and player addresses to indicate player listing for specific games.
    - gameExists: Tracks the existence of games based on their IDs.
    - playerExists: Records the presence of players using their unique IDs.
    - invitationExists: Tracks the existence of invitations for specific games and players.
    - scores: Associates game IDs and player addresses with their respective `**PlayerScoreSheetStruct**` data, storing gameplay records.
    - gameHasPlayers: Indicates whether a game has associated players.
    
4. Game Functions**:**
    - createGame: Initiates a new game by creating a GameStruct with essential details.
    - getGames: Retrieves an array of active game structures to provide an overview of ongoing games.
    - getGame: Retrieves details of a specific game using its ID.
    - payout: Manages the payout process for a completed game, distributing rewards to winners.
    
5. Invitation Functions**:**
    - invitePlayer: Facilitates the invitation of players to join a game, recording invitation details.
    - acceptInvitation: Enables players to accept game invitations, validating their eligibility and recording their participation.
    - rejectInvitation: Allows players to decline game invitations, marking the invitation as rejected.
    - getInvitations: Retrieves an array of invitations sent to a specific player.
    
6. Score Functions**:**
    - recordScore: Enables players to record their scores for a specific game, provided certain conditions are met.
    - getScores: Retrieves an array of `**PlayerScoreSheetStruct**` for a particular game, showcasing player scores.
    
7. Player Functions**:**
    - isPlayerListed: Checks whether a player is listed for a specific game.
    - getMyGames: Retrieves an array of games owned by the caller.
    
8. Internal Utility Functions**:**
    - _saveGame: Internal function for saving game data into the `**games**` mapping during game creation.
    - _savePlayer: Internal function for saving player data into the `**players**` mapping during various interactions.
    - currentTime: Returns the current timestamp with adjusted precision.
    - payTo: Facilitates transferring funds to a specific address.
    
    These functions cover a wide range of functionalities, efficiently managing game creation, invitations, gameplay, scores, and player interactions within the PlayToEarn contract.

🚀 Elevate your web3 skills with Dapp Mentors Academy – the ultimate hub for blockchain developers! Access premium courses, NFT insights, and a special Discord channel for just $8.44/month. [**Join us now to unleash your potential!**](https://dappmentors.org/membership)


![Dapp Mentors Academy](https://paper-attachments.dropboxusercontent.com/s_A669F6C723766110FAA73EBE4FA93F72A0924D07056B57BA53C0E19195292853_1692355875217_Screenshot+2023-08-18+at+11.50.50+AM.png)


[**Subscribe to Dapp Mentors Academy**](https://dappmentors.org/membership) today and get exclusive access to over 40 hours of web3 content, including courses on NFT minting, blockchain development, and more!

## The Test Script

The PlayToEarn test script has been thoughtfully crafted to thoroughly evaluate and confirm the functionalities and behaviors of the PlayToEarn smart contract. Here's an organized breakdown of the primary tests and functions encompassed within the script:


1. Test Setup:
    - The script doesn’t require any parameter for the contract deployment.
    - It sets up deployer and three (3) user addresses for testing purposes.
    
2. Contract Deployment and Minting:
    - The script deploys the PlayToEarn contract using the specified parameters.
    - It uses the `createGame` function to create a game with a stake value of 0.5 Ether.
    - The test checks the successful creation of game and verifies the retrieved game.
    
3. Game Creation:
    - This section encapsulates a series of tests under the `**describe**` block labeled 'Game creation', focusing on evaluating various aspects of game creation and management within the PlayToEarn smart contract.
    
    -  The first test, labeled 'should confirm fetching games', utilizes the `**getGames**` function to retrieve a list of games. The Chai assertion `**expect(result).to.have.lengthOf(1)**` validates that one game has been successfully created.
    
    - The subsequent test, 'should confirm fetching a single game', employs the `**getGame**` function to retrieve the attributes of a specific game using its `**gameId**`. The assertion `**expect(result.id).to.be.equal(1)**` verifies that the retrieved game's ID matches the expected value.
    
    - The third test, 'should confirm listing of a players invitations', showcases the invitation process. It verifies that initially, there are no invitations, then invites `**user1**` and `**user2**` to the game, checks the number of invitations for `**user1**`, accepts the invitation for `**user1**`, and confirms the listing status of `**user1**`. Finally, it rejects the invitation for `**user2**` and confirms that `**user2**` is not listed.
    
    - The last test in this section, 'should confirm payouts', assesses the payout mechanism. The test invites `**user1**`, accepts the invitation, records scores, and verifies that the game has not been paid out. Upon executing the payout function, the test checks that the game has been successfully paid out.
    

Through this detailed breakdown, the essential functionalities of the PlayToEarn test script are explained, emphasizing the purpose and outcomes of each testing step.

At the root of the project, create a folder if not existing called “**test**”, copy and paste the code below inside of it.


{% gist https://gist.github.com/covelitein/b80fe3af0609db98742e092305abeb83 %}


By running `**yarn hardhat test**` on the terminal will test out all the essential function of this smart contract.


## The Deployment Script

The PlayToEarn deployment script is responsible for deploying the PlayToEarn smart contract to the Ethereum network using the Hardhat development environment. Here's an overview of the script:


1. Import Statements:
    - The script imports the required dependencies, including ethers and the fs module for file system operations.
        
2. main() Function:
    - The `main()` function is an asynchronous function that serves as the entry point for the deployment script.
        
3. Deployment Parameters:
    - The contract requires only the `contract_name` parameter for deployment
4. Contract Deployment:
    - The script uses the `ethers.getContractFactory()` method to obtain the contract factory for the `PlayToEarn`  contract.
    - It deploys the contract by invoking the `deploy()` method on the contract factory with the specified parameters.
    - The deployed contract instance is stored in the `contract` variable.
        
5. Contract Deployment Confirmation:
    - The script waits for the deployment to be confirmed by awaiting the `deployed()` function on the contract instance.
        
6. Writing Contract Address to File:
    - The script creates a JSON object containing the deployed contract address.
    - It writes this JSON object to a file named `contractAddress.json` in the specified path: `./src/abis/contractAddress.json`.
    - If any error occurs during the file writing process, it is logged to the console.
        
7. Logging Deployed Contract Address:
    - If the contract deployment and file writing processes are successful, the deployed contract address is logged to the console.
        
8. Error Handling:
    - Any errors that occur during the deployment or file writing process are caught and logged to the console.
    - The process exit code is set to 1 to indicate an error occurred.
        

The `PlayToEarn` deployment script allows for the easy deployment of the PlayToEarn smart contract, and it generates a JSON file containing the deployed contract address for further usage within the project.

In the root of the project, create a folder called “**scripts**” and another file inside of it called `deploy.js` if it doesn’t yet exist. Copy and paste the code below inside of it.


{% gist https://gist.github.com/covelitein/36be619252923d325955894126c9d459 %}


Next, run the yarn `hardhat run scripts/deploy.js` to deploy the smart contract into the network on a terminal.


![Activities of Deployment on the Terminal](https://paper-attachments.dropboxusercontent.com/s_95E5B376EA7D56400134387A4ABCBB8612C903A22CB8FFB5FE3936C174654F13_1681314007681_0RFvAh6Q.png)


If you require additional assistance with setting up Hardhat or deploying your Fullstack DApp, I recommend watching this informative video that provides guidance and instructions.


{% embed https://www.youtube.com/watch?v=6lIq8MCfaGE %}



## Developing the Frontend

To start developing the frontend of our application, we will create a new folder called `components` inside the `src` directory. This folder will hold all the components needed for our project. 

For each of the components listed below, you will need to create a corresponding file inside the `src/components` folder and paste its codes inside it.


## Header Component
![The Header Component](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692268834431_screenshoteasy+-+2023-08-17T080822.424.png)


The header component of the PlayToEarn application’s user interface displays the app's logo, important links for easy movement around the app, and a special button that lets users connect their wallet. This button takes care of the technical stuff needed to link the user's wallet address. You can take a look at the code example below to see how it works:


{% gist https://gist.github.com/covelitein/00c616aee771b068b92ae21f60ae3203 %}



## Hero Component
![The Hero Component](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692269995544_screenshoteasy+-+2023-08-17T080842.254.png)


The Hero component within the PlayToEarn application takes the stage with an engaging tagline, setting the tone for a welcoming introduction. Additionally, it hosts call-to-action buttons designed to kickstart the game creation process and view of user’s involvement in a game. See the code below:


{% gist https://gist.github.com/covelitein/68bcbcf4006b2c72153be2fe5acb01c0 %}




## Create Game Component
![The Create Game Component](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692270748887_screenshoteasy+-+2023-08-17T121210.269.png)


The create game component is a modal component that allows users to add a game to the platform after providing relevant and useful information required by the system for game creation. See code below


{% gist https://gist.github.com/covelitein/8fbee9353db84b9caea4d8063aebabdb %}



## GameList Component
![Game list Component](https://paper-attachments.dropboxusercontent.com/s_A669F6C723766110FAA73EBE4FA93F72A0924D07056B57BA53C0E19195292853_1692356524175_Screenshot+2023-08-18+at+12.01.45+PM.png)


This component handles how games are shown on the platform, like cards organized in a neat grid on the screen. Take a look at the code below to see how it works:


{% gist https://gist.github.com/covelitein/61159b22796d6fe645fd241bc1d39a14 %}



## InviteModal Component
![The Invite Modal](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692271858346_screenshoteasy+-+2023-08-17T081400.928.png)


This component plays an essential role in inviting players for an available game on the platform for participation, It provides an input field where the user inviting has to input the invitees wallet address for sending a join game request . See code below: 


{% gist https://gist.github.com/covelitein/c889f776c93dd2ed9d9c90eb64f6a920 %}



## InvitationList Component
![The Invitation List Component](https://paper-attachments.dropboxusercontent.com/s_A669F6C723766110FAA73EBE4FA93F72A0924D07056B57BA53C0E19195292853_1692356698587_Screenshot+2023-08-18+at+12.04.48+PM.png)


This component takes charge of displaying invitations of a particular user to them in a very cool and neat way, as shown above, with this the user can accept or reject an invitation with the click of a button. See code below:



{% gist https://gist.github.com/covelitein/32642d475afde2d892696e47b74e2de5 %}



## Game Component
![Game Play Component](https://paper-attachments.dropboxusercontent.com/s_A669F6C723766110FAA73EBE4FA93F72A0924D07056B57BA53C0E19195292853_1692356848621_Screenshot+2023-08-18+at+12.07.09+PM.png)


This component serves as the central hub for two integral sub-components, enhancing the overall gaming experience. The key constituents are as follows:


- **GameInfo Component**: This component assumes the responsibility of imparting essential instructions and guidelines for the game. It plays a pivotal role in acquainting players with crucial information necessary to excel in the game.
-  **ChatButton Component:** leverages CometChat to seamlessly connect players within a game. It orchestrates signups, logins, group creation for game owners, and group joining for players. This component also triggers the chat modal, facilitating social interaction and togetherness among players, enhancing their gaming experience.

In addition to its pivotal role in information dissemination and fostering player connections, this component maintains its significance in fundamental game operations. It seamlessly handles game initiation, active gameplay, results presentation, and payout distribution.


{% gist https://gist.github.com/covelitein/94d4ca91ae92c2bfe081fb9613da8941 %}



{% gist https://gist.github.com/covelitein/b4301beae8e138c0cc47d4b780ec70e9 %}

{% gist https://gist.github.com/covelitein/6bda106db839980aff87b1389c86c02e %}



## GameResult Component
![Game Result Modal](https://paper-attachments.dropboxusercontent.com/s_A669F6C723766110FAA73EBE4FA93F72A0924D07056B57BA53C0E19195292853_1692362095749_Screenshot+2023-08-18+at+1.34.19+PM.png)


This component serves as a dynamic modal for displaying game results. The component leverages several external libraries and custom functions to create an immersive and visually appealing presentation of player scores and their performance in the game.


{% gist https://gist.github.com/covelitein/905c31dc8f13f9a899795b5c1d82191c %}



## Chat Component
![The Chat Component](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692290239213_screenshoteasy+-+2023-08-17T082353.683.png)


This React component serves as an interactive chat interface, facilitating seamless real-time communication between users. Employing a blend of essential dependencies and specialized services, this component crafts a dynamic and user-centric chat environment.


{% gist https://gist.github.com/covelitein/51a39073520402889472577a46c72c71 %}


**Want to learn how to build an Answer-To-Earn DApp with Next.js, TypeScript, Tailwind CSS, and Solidity?** [**Watch this video now!**](https://youtu.be/Ubom39y5jX8)


{% embed https://www.youtube.com/watch?v=Ubom39y5jX8 %}


This video is a great resource for anyone who wants to learn how to build decentralized applications and earn ethers. 

Now that we have covered all the components in this application, it is time to start coupling the various pages together. Let's start with the homepage.

To begin developing the pages of our application, we will create a new folder called `pages` inside the `src` directory. This folder will hold all the pages needed for our project. 

For each of the pages listed below, you will need to create a corresponding file inside the `src/pages` folder, just as you did before with the components.


## HomePage
![The Home Page](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692308272202_screenshoteasy+-+2023-08-17T195139.350.png)


The given React component, which functions as a page, represents the Home page of the application. This page is designed to provide users with an engaging and informative introduction to the application's features. It is composed of three main components: `**Header**`, `**Hero**`, and `**CreateGame**`.


1. **Hero Component**: Positioned after the header, the `**Hero**` component serves as a prominent visual element. It features captivating texts and call-to-action buttons for triggering the create game modal and for easy navigation to displaying games the user is involved in.


2. **CreateGame Component**: commands attention post-hero section, presenting an immersive interface for effortlessly crafting new games. This dynamic modal-like feature encompasses user-friendly form fields, interactive buttons, and elements that streamline the creation of captivating game environments.

The `**Home**` component orchestrates the arrangement of these components in a sequential manner within a `**<div>**` container. This ensures a cohesive and structured layout for the Home page, where users can quickly access navigation options, engage with compelling content in the hero section, and seamlessly create new games through the `**CreateGame**` interface.
In essence, the Home page presents a captivating introduction to the application, inviting users to explore its features and participate in game creation. It strategically utilizes the `**Header**`, `**Hero**`, and `**CreateGame**` components to achieve an engaging and user-centric presentation.


{% gist https://gist.github.com/covelitein/78aee234543ec54b57facc13361e2393 %}



## MyGames Page
![My Games Page](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692308305719_screenshoteasy+-+2023-08-17T222952.077.png)


The "My Games" Page offers users a centralized space to manage and monitor their ongoing gaming activities. It seamlessly integrates three pivotal components:

1. GameList Component: This element presents users with a structured view of the games they are currently participating in.


2. InviteModal Component: Users can easily send out invitations to other participants using this feature, streamlining collaboration within games.

The `**MyGames**` component expertly orchestrates these components, ensuring a smooth and user-friendly experience. Real-time updates are facilitated through data synchronization powered by `**useGlobalState**`, ensuring users have access to the most current information about their dynamic gaming landscape.


{% gist https://gist.github.com/covelitein/63caf10d8bd3bd521503e39e91b7c604 %}



## Invitations Page
![The Invitation Page](https://paper-attachments.dropboxusercontent.com/s_7D1A1D37F80B0518526730B73F3D0FC0AFE5FAF04B436DD20141EBE7A3684566_1692308338091_screenshoteasy+-+2023-08-17T223413.625.png)


The "Invitations" Page offers users a focused perspective on their received invitations. This page includes:


1. InvitationList Component: Designed to exhibit all invitations that have been received.

The `**Invitations**` component optimizes the process by utilizing the `**fetchInvitations**` function to retrieve invitation data. This approach ensures that users have a straightforward and comprehensive overview of their pending invitations, facilitating efficient decision-making.



{% gist https://gist.github.com/covelitein/92f9660da646c305a9a0913f8d0c2ff1 %}



## GamePlay Page
![Game Play](https://paper-attachments.dropboxusercontent.com/s_A669F6C723766110FAA73EBE4FA93F72A0924D07056B57BA53C0E19195292853_1692357840141_P2E+Game+Play.gif)

![Game Play Result and Payout](https://paper-attachments.dropboxusercontent.com/s_A669F6C723766110FAA73EBE4FA93F72A0924D07056B57BA53C0E19195292853_1692357810195_P2E+Result+and+Payout.gif)


The "GamePlay" Page sets the stage for an immersive gaming experience, bringing together:

1. Game Component: A pivotal element that presents the ongoing game environment, catering to active player engagement.


2. GameResult Component: Unveils the culmination of the game, displaying scores and outcomes.

The GamePlay page offers an enriching encounter, where users can actively participate in gameplay, receive results through the GameResult component, and seamlessly communicate with others for an engaging and holistic gaming adventure.


{% gist https://gist.github.com/covelitein/b4081a794abddf88b4db6dea431ce792 %}



## The Blockchain Service

Step into the PlayToEarn realm armed with the robust **PlayToEarn Blockchain Service** script. Let's dive into its core functionalities:


1. **Wallet Connectivity**: Seamlessly manage wallet connections with **isWalletConnected** and initiate connections using **connectWallet**. Track and respond to connected account changes for a frictionless experience.


2. **Game Creation**: With **createGame**, establish new gaming experiences. This function communicates with the blockchain contract to create games.


3. **Invitation Management**: **invitePlayer**, **acceptInvitation**, and **rejectInvitation** offer a dynamic invitation journey. These functions communicate with the blockchain contract, enabling seamless invitations, responses, and management.


4. **Gameplay Tracking**: **recordScore** keeps track of gameplay by recording scores. It ensures that scores are updated through transactions on the blockchain.


5. **Payouts**: Utilize **payout** to trigger the rewarding moment. This function facilitates smooth payouts by interacting with the blockchain contract.


6. **Data Exploration**: **getGames**, **getMyGames**, **getGame**, **getInvitations**, and **getScores** are your guides to accessing diverse game-related data. These functions retrieve and structure data from the blockchain contract, offering insights into your PlayToEarn journey.


7. **Error Management**: In case of unexpected issues, **reportError** comes to your aid. It logs errors encountered during interactions, ensuring you stay informed.

With utility functions like **toWei** and **fromWei** for unit conversions, and a setup that ensures continuous data synchronization, this PlayToEarn Blockchain Service script empowers your journey.

To integrate this script, create a `blockchain.jsx` file within the `services` folder of your `src` directory. Paste the provided code, and you're primed to immerse yourself in the thrilling world of PlayToEarn, backed by the prowess of blockchain technology.


{% gist https://gist.github.com/covelitein/b0ce3b3a198a5e6e45d553a0d6455c82 %}


Please ensure that you update the environment variables to look like this:


    REACT_APP_COMETCHAT_APP_ID=****************
    REACT_APP_COMETCHAT_AUTH_KEY=******************************
    REACT_APP_COMETCHAT_REGION=**
    REACT_APP_RPC_URL=http://127.0.0.1:8545


## The Chat Service

The CometChat service script provides various functions and utilities for integrating CometChat into the application. Here's an overview of the key functionalities:


1. **Initialization**: Begin by firing up the CometChat engine with **initCometChat**. This function gets the SDK ready, ensuring seamless communication.


2. **User Authentication**: Seamlessly authenticate users with CometChat using **loginWithCometChat** and **signUpWithCometChat**. These functions make user logins and sign-ups effortless, returning user objects as Promises.


3. **User Logout**: Wave goodbye to complications with **logOutWithCometChat**. It gracefully logs out users from CometChat and clears their state from the global context.


4. **User Authentication State**: Stay updated on user authentication states with **checkAuthState**. It fetches the currently logged-in user from CometChat, keeping your app's user data synchronized.


5. **Messaging Magic**: Transform messaging into a breeze! **getMessages** fetches previous messages, **sendMessage** sends text messages, and **listenForMessage** tunes in to incoming text messages, ensuring dynamic conversations.


6. **Conversations at Your Fingertips**: Effortlessly retrieve conversations with **getConversations**. It effortlessly fetches user conversations, enhancing real-time engagement.


7. **Group Dynamics**: For more robust interaction, enjoy functionalities like **createNewGroup** to initiate a new group, **getGroup** to fetch group details, and **joinGroup** to become part of an existing group.

The service script provides a set of functions to initialize CometChat, handle user authentication and logout, fetch and send messages, and manage conversation data. These functionalities enable real-time messaging and chat features in the application using the CometChat SDK.

Continuing inside the `services` folder, create a new file called `chat.jsx`. Once you have created the file, you can copy and paste the code below into it.


{% gist https://gist.github.com/covelitein/0e1f0b171822120900d217a88c1367ee %}


Excellent! Now, let's work on the `store` file, which serves as a state management library.


## The Store File

The `store` service provides a centralized state management solution using the `[react-hooks-global-state](https://www.npmjs.com/package/react-hooks-global-state)` library. It offers functions for setting, getting, and using global state variables within the application.


1. Global State Management**:** The `createGlobalState` function is used to create global state variables, along with functions for setting, getting, and using the state values. These global state variables are accessible throughout the application.


2. Global State Variables**:** The code defines various global state variables, including `connectedAccount`, `currentUser`, `resultModal`, `createModal`, `chatModal`, `inviteModal`, `games`, `game`, `group`, `messages`, `invitations`, `scores`, and `myGames`. These variables store different types of data relevant to the application.


3. Utility Functions**:**
    - `truncate`: This function shortens text to a specified length while ensuring readability. It takes a text input, start and end characters to retain, and a maximum length. If the text exceeds the maximum length, it trims the middle portion and adds ellipsis to indicate truncation.
    
    - `formatDate`: This function converts a timestamp into a formatted date string. It uses the `Date` object to extract year, month, and day information and then formats it accordingly.
    
    - `timestampToDate`: This function converts a timestamp into a formatted date and time string. It extends the `formatDate` function by also including the hour and minute information.
    

To use this service, you will need to create a new folder called `store` inside the `src` directory of your project. Inside the `store` folder, you will need to create a new file called `index.jsx`. Once you have created the file, you can copy and paste the code below into it.


{% gist https://gist.github.com/covelitein/512b9a010b44ac572bd5ba4256cd0397 %}

## The Index files

The `index.jsx` file is the entry point for the application. It initializes the CometChat service, sets up dependencies, and renders the React application using the `App` component within a `BrowserRouter`. It creates a root element for rendering and sets up the necessary configurations for the application to start running.

To use this code, you will need to replace the code below inside of the `index.jsx`  and `index.css` files in the `src` folder of your project.


{% gist https://gist.github.com/covelitein/d32190e10cb15d09dbb2faa65d3a1807 %}

{% gist https://gist.github.com/covelitein/be0e4e56a55f4fd9432ab052ca8738b4 %}


Now you are officially done with the build, just execute `**yarn start**` to have the application running on the browser.

Congratulations on successfully creating a Web3 Play-To-Earn Money Dapp using React, Solidity, and integrating CometChat for real-time communication! This accomplishment showcases your ability to combine cutting-edge technologies to develop an innovative and engaging application. By leveraging React for the frontend, Solidity for the smart contracts, and CometChat for seamless chatting features, you've demonstrated a versatile skill set in both blockchain development and interactive user experiences.

[**Here is a link to the CometChat website where you can learn more about the SDK and how to get started.**](https://try.cometchat.com/oj0s7hrm5v78)

For more web3 resources, check out this video that teaches how to create a decentralized app by building a web3 lottery dapp, I recommend that you it.


{% embed https://www.youtube.com/watch?v=mVxRzkvX_w0 %}


The video provides a hands-on tutorial on how to build a lottery dapp using NextJs, Tailwind CSS, and Solidity.


## Conclusion

Crafting a Web3 Play-To-Earn Money Dapp with React, Solidity, and CometChat" is a comprehensive guide that delves into the amalgamation of React, blockchain, and real-time chat to create an extraordinary Play-To-Earn Money Dapp. This project harnesses the prowess of smart contracts to ensure secure transactions and boasts an intuitive user interface. By seamlessly integrating CometChat, it elevates user interaction through dynamic real-time communication.

This tutorial serves as a gateway to the future, showcasing the incredible potential of web3 development in revolutionizing the concept of play-to-earn applications. Through meticulous testing, the smart contracts are fortified to provide reliability and trustworthiness. As developers embark on this transformative journey, they're invited to explore the expansive possibilities that blockchain technology unveils, setting the stage for a new era of interactive and lucrative gaming experiences.

For further learning, we recommends subscribing to our [**YouTube channel**](https://www.youtube.com/@dappmentors?sub_confirmation=1) and [**visiting our website for additional resources**](https://dappmentors.org/). 

Till next time all the best!

## About Author

I am a web3 developer and the founder of [Dapp Mentors](https://dappmentors.org/), a company that helps businesses and individuals build and launch decentralized applications. I have over 7 years of experience in the software industry, and I am passionate about using blockchain technology to create new and innovative applications. I run a [**YouTube channel called Dapp Mentors**](https://www.youtube.com/@dappmentors?sub_confirmation=1) where I share tutorials and tips on web3 development, and I regularly post articles online about the latest trends in the blockchain space.

**Stay connected with us, join communities on**
Discord: [Join](https://discord.gg/PgFDUVT6n9)
Twitter: [Follow](https://twitter.com/iDaltonic)
LinkedIn: [Connect](https://www.linkedin.com/company/dapp-mentors)
GitHub: [Explore](https://github.com/Daltonic)
Website: [Visit](https://dappmentors.org/)