DEV Community

Cover image for How to Build a Web3 Play-To-Earn Money Dapp with React, Solidity, and CometChat
Gospel Darlington
Gospel Darlington

Posted on

How to Build a Web3 Play-To-Earn Money Dapp with React, Solidity, and CometChat

What you will be building, see the live demo at sepolia test net and the git repo.

Game Play

The Chat Interface

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, 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
  • Tailwind CSS

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

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
Enter fullscreen mode Exit fullscreen mode

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

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

Configuring CometChat SDK

To configure the CometChat SDK, 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 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 Play-To-Earn.

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

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_COMETCHAT_APP_ID=****************
REACT_APP_COMETCHAT_AUTH_KEY=******************************
REACT_APP_COMETCHAT_REGION=**
Enter fullscreen mode Exit fullscreen mode

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.

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.

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.
  2. 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.
Enter fullscreen mode Exit fullscreen mode
  1. 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.
Enter fullscreen mode Exit fullscreen mode
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. Player Functions*:*

    • isPlayerListed: Checks whether a player is listed for a specific game.
    • getMyGames: Retrieves an array of games owned by the caller.
  6. 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!

Dapp Mentors Academy

Subscribe to Dapp Mentors Academy 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.
Enter fullscreen mode Exit fullscreen mode

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.

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.

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

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.

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

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:

Hero Component

The Hero Component

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:

Create Game Component

The Create Game Component

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

GameList Component

Game list Component

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:

InviteModal Component

The Invite Modal

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:

InvitationList Component

The Invitation List Component

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:

Game Component

Game Play Component

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.

GameResult Component

Game Result Modal

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.

Chat Component

The Chat Component

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.

Want to learn how to build an Answer-To-Earn DApp with Next.js, TypeScript, Tailwind CSS, and Solidity? Watch this video now!

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

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.

MyGames Page

My Games Page

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.

Invitations Page

The Invitation Page

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.

GamePlay Page

Game Play

Game Play Result and Payout

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.

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.

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
Enter fullscreen mode Exit fullscreen mode

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.

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.
Enter fullscreen mode Exit fullscreen mode

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.

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.

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.

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.

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 and visiting our website for additional resources.

Till next time all the best!

About Author

I am a web3 developer and the founder of Dapp Mentors, 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 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
Twitter: Follow
LinkedIn: Connect
GitHub: Explore
Website: Visit

Top comments (1)

Collapse
 
daltonic profile image
Gospel Darlington

Drop your thoughts here at the comment section.