What you will be building, see the at sepolia test net and the . live demo git repo 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, , our communication ally, will bridge connections in real-time, fostering seamless interaction among users. CometChat 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 https://www.youtube.com/watch?v=qnudOwva0fM&embedable=true 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 with the snippet below. package.json https://gist.github.com/covelitein/1df4a4321d674f4b78ec6b7a1c81986e?embedable=true Please run the command in your terminal to install the dependencies for this project. yarn install Configuring CometChat SDK To configure the , please follow the steps provided below. Once completed, make sure to save the generated keys as environment variables for future use. CometChat SDK Head to Dashboard and create an account. STEP 1: CometChat Log in to the dashboard, only after registering. STEP 2: CometChat From the dashboard, add a new app called **.** STEP 3: Play-To-Earn Select the app you just created from the list. STEP 4: From the Quick Start copy the , , and , to your file. See the image and code snippet. APP_ID REGION AUTH_KEY .env Replace the placeholder keys with their appropriate values. REACT_COMET_CHAT REACT_APP_COMETCHAT_APP_ID=**************** REACT_APP_COMETCHAT_AUTH_KEY=****************************** REACT_APP_COMETCHAT_REGION=** The file should be created at the root of your project. .env Configuring the Hardhat script Navigate to the root directory of the project and open the " " file. Replace the existing content of the file with the provided settings. hardhat.config.js https://gist.github.com/covelitein/316a79b2c830256f35ec60a7926a47af?embedable=true 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: Create a new folder named inside the folder. contracts src Create a new file named inside the folder. PlayToEarn``.sol contracts 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 file, which will serve as the foundation for implementing the logic of the smart contract. PlayToEarn``.sol https://gist.github.com/covelitein/78df451af96b92c7ef9ff15e0cecf07f?embedable=true 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: 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. 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. 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. Mappings: games: Maps game IDs to their respective data, storing comprehensive game information. GameStruct players: Connects player IDs to their corresponding details, capturing player-specific data. PlayerStruct invitationsOf: Maps player addresses and game IDs to related data, tracking invitations. InvitationStruct 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 data, storing gameplay records. PlayerScoreSheetStruct gameHasPlayers: Indicates whether a game has associated players. 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. 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. Score Functions: recordScore: Enables players to record their scores for a specific game, provided certain conditions are met. getScores: Retrieves an array of for a particular game, showcasing player scores. PlayerScoreSheetStruct Player Functions: isPlayerListed: Checks whether a player is listed for a specific game. getMyGames: Retrieves an array of games owned by the caller. Internal Utility Functions: _saveGame: Internal function for saving game data into the mapping during game creation. games _savePlayer: Internal function for saving player data into the mapping during various interactions. players 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! today and get exclusive access to over 40 hours of web3 content, including courses on NFT minting, blockchain development, and more! Subscribe to Dapp Mentors Academy 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: 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. Contract Deployment and Minting: The script deploys the PlayToEarn contract using the specified parameters. It uses the function to create a game with a stake value of 0.5 Ether. createGame The test checks the successful creation of game and verifies the retrieved game. Game Creation: This section encapsulates a series of tests under the block labeled 'Game creation', focusing on evaluating various aspects of game creation and management within the PlayToEarn smart contract. describe The first test, labeled 'should confirm fetching games', utilizes the function to retrieve a list of games. The Chai assertion validates that one game has been successfully created. getGames expect(result).to.have.lengthOf(1) The subsequent test, 'should confirm fetching a single game', employs the function to retrieve the attributes of a specific game using its . The assertion verifies that the retrieved game's ID matches the expected value. getGame gameId expect(result.id).to.be.equal(1) The third test, 'should confirm listing of a players invitations', showcases the invitation process. It verifies that initially, there are no invitations, then invites and to the game, checks the number of invitations for , accepts the invitation for , and confirms the listing status of . Finally, it rejects the invitation for and confirms that is not listed. user1 user2 user1 user1 user1 user2 user2 The last test in this section, 'should confirm payouts', assesses the payout mechanism. The test invites , 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. user1 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 “ ”, copy and paste the code below inside of it. test https://gist.github.com/covelitein/b80fe3af0609db98742e092305abeb83?embedable=true By running on the terminal will test out all the essential function of this smart contract. yarn hardhat test 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: Import Statements: The script imports the required dependencies, including ethers and the fs module for file system operations. main() Function: The function is an asynchronous function that serves as the entry point for the deployment script. main() Deployment Parameters: The contract requires only the parameter for deployment contract_name Contract Deployment: The script uses the method to obtain the contract factory for the contract. ethers.getContractFactory() PlayToEarn It deploys the contract by invoking the method on the contract factory with the specified parameters. deploy() The deployed contract instance is stored in the variable. contract Contract Deployment Confirmation: The script waits for the deployment to be confirmed by awaiting the function on the contract instance. deployed() 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 in the specified path: . contractAddress.json ./src/abis/contractAddress.json If any error occurs during the file writing process, it is logged to the console. Logging Deployed Contract Address: If the contract deployment and file writing processes are successful, the deployed contract address is logged to the console. 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 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. PlayToEarn In the root of the project, create a folder called “ ” and another file inside of it called if it doesn’t yet exist. Copy and paste the code below inside of it. scripts deploy.js https://gist.github.com/covelitein/36be619252923d325955894126c9d459?embedable=true Next, run the yarn to deploy the smart contract into the network on a terminal. hardhat run scripts/deploy.js 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. https://www.youtube.com/watch?v=6lIq8MCfaGE&embedable=true Developing the Frontend To start developing the frontend of our application, we will create a new folder called inside the directory. This folder will hold all the components needed for our project. components src For each of the components listed below, you will need to create a corresponding file inside the folder and paste its codes inside it. src/components 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: https://gist.github.com/covelitein/00c616aee771b068b92ae21f60ae3203?embedable=true 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: https://gist.github.com/covelitein/68bcbcf4006b2c72153be2fe5acb01c0?embedable=true 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 https://gist.github.com/covelitein/8fbee9353db84b9caea4d8063aebabdb?embedable=true GameList 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: https://gist.github.com/covelitein/61159b22796d6fe645fd241bc1d39a14?embedable=true InviteModal Component 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: https://gist.github.com/covelitein/c889f776c93dd2ed9d9c90eb64f6a920?embedable=true InvitationList 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: https://gist.github.com/covelitein/32642d475afde2d892696e47b74e2de5?embedable=true Game Component This component serves as the central hub for two integral sub-components, enhancing the overall gaming experience. The key constituents are as follows: : 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. GameInfo 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. ChatButton Component: 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. https://gist.github.com/covelitein/94d4ca91ae92c2bfe081fb9613da8941?embedable=true https://gist.github.com/covelitein/b4301beae8e138c0cc47d4b780ec70e9?embedable=true https://gist.github.com/covelitein/6bda106db839980aff87b1389c86c02e?embedable=true GameResult Component 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. https://gist.github.com/covelitein/905c31dc8f13f9a899795b5c1d82191c?embedable=true 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. https://gist.github.com/covelitein/51a39073520402889472577a46c72c71?embedable=true Want to learn how to build an Answer-To-Earn DApp with Next.js, TypeScript, Tailwind CSS, and Solidity? Watch this video now! https://www.youtube.com/watch?v=Ubom39y5jX8&embedable=true 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 inside the directory. This folder will hold all the pages needed for our project. pages src For each of the pages listed below, you will need to create a corresponding file inside the folder, just as you did before with the components. src/pages HomePage 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: , , and . Header Hero CreateGame : Positioned after the header, the 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. Hero Component Hero : 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. CreateGame Component The component orchestrates the arrangement of these components in a sequential manner within a 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 interface. Home <div> CreateGame 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 , , and components to achieve an engaging and user-centric presentation. Header Hero CreateGame https://gist.github.com/covelitein/78aee234543ec54b57facc13361e2393?embedable=true MyGames Page The "My Games" Page offers users a centralized space to manage and monitor their ongoing gaming activities. It seamlessly integrates three pivotal components: GameList Component: This element presents users with a structured view of the games they are currently participating in. InviteModal Component: Users can easily send out invitations to other participants using this feature, streamlining collaboration within games. The component expertly orchestrates these components, ensuring a smooth and user-friendly experience. Real-time updates are facilitated through data synchronization powered by , ensuring users have access to the most current information about their dynamic gaming landscape. MyGames useGlobalState https://gist.github.com/covelitein/63caf10d8bd3bd521503e39e91b7c604?embedable=true Invitations Page The "Invitations" Page offers users a focused perspective on their received invitations. This page includes: InvitationList Component: Designed to exhibit all invitations that have been received. The component optimizes the process by utilizing the function to retrieve invitation data. This approach ensures that users have a straightforward and comprehensive overview of their pending invitations, facilitating efficient decision-making. Invitations fetchInvitations https://gist.github.com/covelitein/92f9660da646c305a9a0913f8d0c2ff1?embedable=true GamePlay Page The "GamePlay" Page sets the stage for an immersive gaming experience, bringing together: Game Component: A pivotal element that presents the ongoing game environment, catering to active player engagement. 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. https://gist.github.com/covelitein/b4081a794abddf88b4db6dea431ce792?embedable=true The Blockchain Service Step into the PlayToEarn realm armed with the robust script. Let's dive into its core functionalities: PlayToEarn Blockchain Service : Seamlessly manage wallet connections with and initiate connections using . Track and respond to connected account changes for a frictionless experience. Wallet Connectivity isWalletConnected connectWallet : With , establish new gaming experiences. This function communicates with the blockchain contract to create games. Game Creation createGame : , , and offer a dynamic invitation journey. These functions communicate with the blockchain contract, enabling seamless invitations, responses, and management. Invitation Management invitePlayer acceptInvitation rejectInvitation : keeps track of gameplay by recording scores. It ensures that scores are updated through transactions on the blockchain. Gameplay Tracking recordScore : Utilize to trigger the rewarding moment. This function facilitates smooth payouts by interacting with the blockchain contract. Payouts payout : , , , , and 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. Data Exploration getGames getMyGames getGame getInvitations getScores : In case of unexpected issues, comes to your aid. It logs errors encountered during interactions, ensuring you stay informed. Error Management reportError With utility functions like and for unit conversions, and a setup that ensures continuous data synchronization, this PlayToEarn Blockchain Service script empowers your journey. toWei fromWei To integrate this script, create a file within the folder of your 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. blockchain.jsx services src https://gist.github.com/covelitein/b0ce3b3a198a5e6e45d553a0d6455c82?embedable=true 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: : Begin by firing up the CometChat engine with . This function gets the SDK ready, ensuring seamless communication. Initialization initCometChat : Seamlessly authenticate users with CometChat using and . These functions make user logins and sign-ups effortless, returning user objects as Promises. User Authentication loginWithCometChat signUpWithCometChat : Wave goodbye to complications with . It gracefully logs out users from CometChat and clears their state from the global context. User Logout logOutWithCometChat : Stay updated on user authentication states with . It fetches the currently logged-in user from CometChat, keeping your app's user data synchronized. User Authentication State checkAuthState : Transform messaging into a breeze! fetches previous messages, sends text messages, and tunes in to incoming text messages, ensuring dynamic conversations. Messaging Magic getMessages sendMessage listenForMessage : Effortlessly retrieve conversations with . It effortlessly fetches user conversations, enhancing real-time engagement. Conversations at Your Fingertips getConversations : For more robust interaction, enjoy functionalities like to initiate a new group, to fetch group details, and to become part of an existing group. Group Dynamics createNewGroup getGroup joinGroup 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 folder, create a new file called . Once you have created the file, you can copy and paste the code below into it. services chat.jsx https://gist.github.com/covelitein/0e1f0b171822120900d217a88c1367ee?embedable=true Excellent! Now, let's work on the file, which serves as a state management library. store The Store File The service provides a centralized state management solution using the library. It offers functions for setting, getting, and using global state variables within the application. store [react-hooks-global-state](https://www.npmjs.com/package/react-hooks-global-state) Global State Management: The 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. createGlobalState Global State Variables: The code defines various global state variables, including , , , , , , , , , , , , and . These variables store different types of data relevant to the application. connectedAccount currentUser resultModal createModal chatModal inviteModal games game group messages invitations scores myGames Utility Functions: : 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. truncate : This function converts a timestamp into a formatted date string. It uses the object to extract year, month, and day information and then formats it accordingly. formatDate Date : This function converts a timestamp into a formatted date and time string. It extends the function by also including the hour and minute information. timestampToDate formatDate To use this service, you will need to create a new folder called inside the directory of your project. Inside the folder, you will need to create a new file called . Once you have created the file, you can copy and paste the code below into it. store src store index.jsx https://gist.github.com/covelitein/512b9a010b44ac572bd5ba4256cd0397?embedable=true The Index files The file is the entry point for the application. It initializes the CometChat service, sets up dependencies, and renders the React application using the component within a . It creates a root element for rendering and sets up the necessary configurations for the application to start running. index.jsx App BrowserRouter To use this code, you will need to replace the code below inside of the and files in the folder of your project. index.jsx index.css src https://gist.github.com/covelitein/d32190e10cb15d09dbb2faa65d3a1807?embedable=true https://gist.github.com/covelitein/be0e4e56a55f4fd9432ab052ca8738b4?embedable=true Now you are officially done with the build, just execute to have the application running on the browser. yarn start 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. https://www.youtube.com/watch?v=mVxRzkvX_w0&embedable=true 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 and . YouTube channel visiting our website for additional resources Till next time all the best! About Author I am a web3 developer and the founder of , 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 where I share tutorials and tips on web3 development, and I regularly post articles online about the latest trends in the blockchain space. Dapp Mentors YouTube channel called Dapp Mentors Discord: Twitter: LinkedIn: GitHub: Website: Stay connected with us, join communities on Join Follow Connect Explore Visit