What you will be building, see the live demo at sepolia test net and the 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, CometChat, our communication ally, will bridge connections in real-time, fostering seamless interaction among users.
In this tutorial, you'll gain mastery over:
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! 🌟
You will need the following tools installed to build along with me:
I recommend watching the video below to learn how to set up your MetaMask for this project
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.
Please run the command yarn install
in your terminal to install the dependencies for this project.
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.
STEP 2: Log in to the CometChat dashboard, only after registering.
STEP 3: From the dashboard, add a new app called Play-To-Earn**.**
STEP 4: Select the app you just created from the list.
From the Quick Start copy the APP_ID
, REGION
, and AUTH_KEY
, to your .env
file. See the image and code snippet.
Replace the REACT_COMET_CHAT
placeholder keys with their appropriate values.
REACT_APP_COMETCHAT_APP_ID=****************
REACT_APP_COMETCHAT_AUTH_KEY=******************************
REACT_APP_COMETCHAT_REGION=**
The .env
file should be created at the root of your project.
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 following steps will guide you through the process of creating the smart contract file for this project:
contracts
inside the src
folder.PlayToEarn``.sol
inside the contracts
folder.
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:
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.
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.
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.
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.
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.
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.
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.
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 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!
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 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:
The script doesn’t require any parameter for the contract deployment.
It sets up deployer and three (3) user addresses for testing purposes.
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.
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.
By running yarn hardhat test
on the terminal will test out all the essential function of this smart contract.
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:
The script imports the required dependencies, including ethers and the fs module for file system operations.
The main()
function is an asynchronous function that serves as the entry point for the deployment script.
The contract requires only the contract_name
parameter for 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.
The script waits for the deployment to be confirmed by awaiting the deployed()
function on the contract instance.
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.
If the contract deployment and file writing processes are successful, the deployed contract address is logged to the console.
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.
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.
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.
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:
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:
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
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:
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:
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:
This component serves as the central hub for two integral sub-components, enhancing the overall gaming experience. The key constituents are as follows:
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.
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.
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?
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.
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
.
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.
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.
The "My Games" Page offers users a centralized space to manage and monitor their ongoing gaming activities. It seamlessly integrates three pivotal components:
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.
The "Invitations" Page offers users a focused perspective on their received invitations. This page includes:
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.
The "GamePlay" Page sets the stage for an immersive gaming experience, bringing together:
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.
Step into the PlayToEarn realm armed with the robust PlayToEarn Blockchain Service script. Let's dive into its core functionalities:
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
The CometChat service script provides various functions and utilities for integrating CometChat into the application. Here's an overview of the key functionalities:
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
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.
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.
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.
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.
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.
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.
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!
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