This page may contain legacy content

To get our most up-to-date content please access our documentation

April 29, 2022

How to Build a Play-to-Earn (P2E) Game Smart Contract

Table of Contents

Play-to-earn (P2E) gaming is now a leading use case in the Web3 ecosystem. The popularity of P2E games such as Axie Infinity, Splinterlands, The Sandbox, Gods Unchained, and many more have already proven the case for P2E’s potential. Furthermore, Web3 gamification is undoubtedly the next frontier for Web3 growth. It combines entertainment, user income, and larger game revenue potential. Hence, to ride the trend, it’s imperative that Web3 developers now learn how to build a play-to-earn game. If you think that building a play-to-earn game might seem difficult, this tutorial will put you at ease.

Any blockchain developer familiar with JavaScript, Solidity, Ethereum, and smart contracts, shouldn’t find it much of a hurdle to build a play-to-earn game. Furthermore, Moralis, the ultimate Web3 development platform, provides the resources and tools to make any P2E build lightning-fast. Thus, with Moralis, you can get started immediately on building dapps for the Web3 metaverse.

In this easy-to-follow tutorial on how to build a play-to-earn game smart contract, you will learn how to build a play-to-earn game. Moreover, you will be empowered with the right tools and shortcuts to seize the first-mover advantage. What’s more, Moralis will handle all the heavy lifting on the backend for you. As a result, you can focus on the frontend and user experience to develop a more attractive and engaging P2E game with higher chances of success.

With the most popular P2E games reaching multi-billion dollar valuations, things are only getting started in Web3 gaming. As a blockchain developer, the global market is wide open for you to create the next blockbuster play-to-earn game. 

Video Tutorial on How to Develop a P2E Game

Moralis’ YouTube channel contains numerous tutorials on different blockchain gaming projects. Below, you’ll find the video version of our tutorial presented in this article:

https://www.youtube.com/watch?v=1_qCiL0qajs

Note: The tutorial herein will not go deep into the actual coding steps of how to build a play-to-earn game. Thus, we strongly encourage you to watch the video tutorial where one of Moralis’ experts provides expert-guided steps on how how to develop our P2E game.

Developing a Play-to-Earn Game Effortlessly with Moralis

With the buzz around Web3 and P2E gaming lighting up gamers’ curiosity worldwide, any developer would be excited to learn how to build a play-to-earn game and reach this market of huge earning potential. Fortunately, the process is now faster and more seamless thanks to Web3 game development platforms such as Moralis, whose Metaverse SDK opens up a world of opportunity for aspiring blockchain game developers.

What’s more, Moralis’ Metaverse SDK is the best way to launch metaverse games and dapps quickly and easily. As mentioned, it handles all your backend support. Whether it’s blockchain node support through Moralis Speedy Nodes, Web3 authentication through MetaMask and other Web3 wallets, optimal compatibility for your cross-chain dapps, or APIs that address every need for Web3 integration, Moralis has got you covered. Also, you can expect a smooth P2E, GameFi, or NFT game development process from start to finish when using Moralis. In addition, Moralis is instantly compatible with the world’s top gaming and game development platforms such as Unity, Xbox, and iOS. Thus, it’s the complete 360-degree package of what you need when you want to build a play-to-earn game. 

If you’re just starting out your Unity Web3 programming journey, Moralis is your best go-to platform for producing the best Web3 games on the market.

What is Play-to-Earn (P2E)?

Play-to-earn, or P2E, emerged through the amalgamation of gaming and decentralized finance (DeFi). Furthermore, it added a new incentive to gaming by linking the experience directly with ERC-20 tokens, cryptocurrencies, and non-fungible tokens (NFTs). By simply connecting your Web3 wallet, such as MetaMask, to a Web3 game, you get a unique gaming identity, a wallet to send and receive tokens, and an address to store unique objects known as NFTs.

The success of NFTs has also become a factor in the popularity of P2E games. But, what are NFTs? NFTs are digitally unique objects. Through token standards such as ERC-721 and ERC-1155, it’s now possible to create unique provenance for digital artwork and game objects. Moreover, you can create an in-game NFT in the form of a reward, weapon, gift, easter egg, clothing, and other rare items. What’s more, you can even turn your avatar into an NFT! The Web3 metaverse has enabled such objects to be claimed, exchanged, stored, bought, or sold in a gaming environment. Such NFTs can even be brought outside of a gaming environment since the wallets that store them are part of a much larger Web3 blockchain network. Thus, NFTs are both gaming property and assets that transcend a game.

What’s more, you can transfer and trade the fungible ERC-20 assets of a game. In addition, these tokens can be traded independently on a decentralized exchange. Thus, tokens or currencies paid to players can be exchanged for other forms of digital money. With that said, P2E expands the currency aspect of gaming beyond the game itself. 

Build a Play-to-Earn Game Smart Contract in Record Time

A P2E game needs to be engaging and fun. While users want to earn income, nothing makes up for lousy game design or gameplay. However, if you are proficient in creating games with Unity, it doesn’t take a lot to advance to Unity Web3 programming and combine good design with Web3 features.

Furthermore, as you build a play-to-earn game, keep in mind that the gameplay mechanics should be fair and balanced. Remember that you are creating an economy with potentially valuable tokens integrated into the gameplay.

In the accompanying video tutorial (provided earlier), we start with a demo Phaser game called “Bank Panic”. The game already includes Web3 wallet login functionality. Furthermore, it grants access based on the user’s NFT balance. Proceeding from that basic foundation, we will learn how to create a play-to-earn game mechanic that integrates crypto tokens into the game. 

As such, be sure to grab the Codebase GitHub Repo, so you are in line with our tutorial herein. 

Build a Play-to-Earn Game Smart Contracts

The first part of the game design of our tutorial requires the player to put skin in the game. In other words, it’s pay-to-play, so the player has to acquire native game tokens. This feature is crucial to balancing the game economy as you build a play-to-earn game. Next, the game will ask the player to stake a small amount of the native token.

Free-to-play games, as opposed to pay-to-play, have the advantage of attracting more users at the outset due to a low entry barrier. However, the economic design of a free-to-play game requires a higher degree of complexity. Thus, we will stick to a pay-to-play model as we are in beginner mode. However, we will keep the barrier to entry as low as possible within the pay-to-play model.

Smart Contract Requirements

Among the basic types of smart contracts required when you build a play-to-earn game include:

  • Players losing
  • Players winning
  • Token exchanges between players’ wallets and the game’s admin (bot made with a few simple cloud functions)
  • The game’s treasury wallet

To illustrate such scenarios conducted by smart contracts, here are some diagrams:

Scenario 1: Player Wins

In this scenario, the player wins or beats the game. Thus, when the player wins the game, they receive their game winnings plus the tokens they’ve staked. 

Scenario 2: Player Loses

If the player loses the game, they lose their staked tokens. Hence, the tokens are sent back into the game’s treasury. 

Incentive Design

As the player advances and wins more tokens, the game economy needs to stay balanced. Thus, smart contracts (Web3 contracts) set the rules for the game’s economy and are an integral part of executing this design. In this particular demo, the player’s progress and token accumulation are balanced by the higher difficulty curves. As such, you have increased chances of losing tokens as you move on to more advanced levels. 

To maintain economic balance, smart contracts should mimic an escrow flow. Moreover, this tutorial will teach you how to use the Moralis API to interface with it from the game’s frontend. 

The game requires two smart contracts that are relatively straightforward. The first contract creates the game’s token, which, in this tutorial, is called “Gold”. The token is a fungible one using the ERC-20 token standard. Further, it’s a simple minting contract that you can get by visiting: https://github.com/OpenZeppelin/openz….

The second contract creates the movements of “Gold” tokens from the player to the treasury and back. Furthermore, you must do this in a way that is as trustless and permissionless as possible.  

Testnet Faucet

At 2:28 of the “build a play-to-earn game smart contract” video tutorial (shown above), you will learn how to use the Mumbai testnet faucet so you can get your “play” MATIC testnet tokens. The testnet tokens will be necessary to deploy smart contracts on Mumbai, Polygon’s testnet. 

Why use Polygon? One of the main reasons some prefer to work with Polygon is because it’s an Ethereum layer-2 solution that prioritizes interoperability, high scalability, and low transaction fees.

Token Flow and Minting Play-to-Earn Game Smart Contracts

At 3:11, you’ll find examples of smart contracts in the game. In addition, you’ll find that the “P2EGame.sol” smart contract handles the flow of tokens in the game. Moreover, the “GameToken.sol” contract handles the token mints. It piggybacks off of the OpenZeppelin ERC-20 contract (as previously mentioned). Afterward, you will proceed to Remix for contract deployment. 

The sample contract below (seen at 3:19 in the video) mints 100 of the game’s tokens and sends them to the game’s dev wallet:

In this case, it will be acting as both an admin and game treasury reserve. Note that you will also be inheriting “Ownable”, which allows the possibility of renouncing ownership of the contract so nobody can own the token contract. Moreover, you will do the same with the second contract.

The P2E game contract (as posted previously) acts as escrow for the “Gold” tokens between the player and the game dev treasury. At the start of a game, the player deposits a “Gold” token. Winning means players get their staked tokens within escrow plus those they officially win in the game. The latter is transferred from the game’s treasury reserve.

On the other hand, if a player loses, their tokens will return to the game’s treasury. The explanation for all this starts at 3:56 of the video stated earlier in this article.

Build a Play-to-Earn Game Smart Contract: Deploy via Remix 

First, open up Remix on your web browser to build a play-to-earn game smart contract. Then, click on “New File”, and then name the file. In this case, the file name will be “GameToken.sol”. Paste the proper code from the GitHub repo. Go to compile, and then deploy the contract on the Polygon testnet (Mumbai). Make sure you’re using “Injected Web3” for your environment, as shown below:

This demo uses MetaMask connected to the Mumbai testnet with some testnet MATIC tokens for the gas fee. The contract’s constructor allows you to stipulate the name and the ticker symbol for the game token. Once done, hit deploy (as shown above). 

By 5:32, you are directed to MetaMask to import the new custom “Gold” token. Copy-paste the contract address and click on the “Add Custom Token” button. Afterward, you’ll find that you’ve successfully deployed the token.

Next, you’ll use the “Gold” tokens created in the game’s economy. Grab the code from the repo (the “P2EGame.sol” link posted previously). Next, copy the contract address from the ERC-20 contract that was deployed. Paste it to the P2E contract, and then compile and deploy the contract to the testnet. 

How the Smart Contracts Work

With both smart contracts deployed, the video tutorial will demonstrate how the game works with these contracts. To further show how these contracts enable you to build a play-to-earn game, proceed to the walkthrough starting at 6:47. 

Using the functions on Remix’s interface, you’ll mimic a player who already has “Gold” tokens. Then use the contract to transfer tokens from the current treasury holder to a demo player’s wallet. In this case, it will transfer ten tokens to the demo player’s wallet. 

The walkthrough demonstrates how a player can authenticate via MetaMask. Moreover, the game will ask a player to approve an allowance of their tokens to be put into the escrow contract. It will then stake the approved amount into the P2E contract until the end of the game. Next, the player starts the game. If the player wins, the Moralis API calls the function that releases the staked tokens plus any winnings. In other words, it rewards the player. On the other hand, a loss lets the Moralis API call a function that transfers the tokens back to the game’s treasury. Furthermore, the contract keeps track of each game’s balance and only releases funds to the winning party programmatically upon meeting certain conditions.

Contract Ownership

When you build a play-to-earn game, you don’t want any human owning one of the contracts and having the capacity to act maliciously in any way. To achieve this, you set ownership of both contracts so that they’re going to be renounced. Thus, you set them to a zero (0) address, and the only entity that can act on the functions is the admin wallet that acts programmatically dependent on the game’s logic. 

Furthermore, the game’s treasury, instead of being a wallet with a set of private keys attached to it, can be a contract to which ownership has also been renounced. It could also be a wallet whose keys have been “lost” or unknown to any user.

For simplicity’s sake, this demo uses the same address for the treasury and the admin wallet, moving the coins in and out of escrow. However, ideally, the two addresses should be separate.

Build a Play-to-Earn Game: Integrating via Moralis

Once you’ve mastered these steps on how to build a play-to-earn game and its smart contracts, be sure to check out the next step, which is integrating the smart contracts into the game via Moralis:

https://www.youtube.com/watch?v=h31YcNgAIUw

How to Build a Play-to-Earn Game Smart Contract – Summary

To learn how to build a play-to-earn game smart contract, you need to understand the economic elements surrounding the gameplay. Once you have a concrete economic design, you must proceed to write smart contracts that implement the rules within the game.

With Moralis (a.k.a. “Firebase for crypto“) leading the way in Web3 metaverse game design, creating your first P2E game will be easier and faster than you ever imagined. What’s more, Moralis is the top platform for interoperability, so you can connect your game to any desired blockchain! For example, it lets you connect to Polygon nodes and Ethereum nodes instantly.

Moralis’ Metaverse SDK empowers you to explore the possibilities of game design on the world’s leading platforms such as Unity, Xbox, and iOS. Furthermore, its powerful APIs, including the Moralis NFT API, allow you to integrate powerful Web3 features into your game that underpin its P2E economy. 

Market Data API
Build amazing trading and portfolio dapps with this Market Data API. Keep users engaged with up-to-date data!
Market Data API
Related Articles
March 1, 2023

How to Build a Block Explorer

April 10, 2024

How to Get All Owners of an ERC20 Token 

November 5, 2022

Web3 for Business – How and Why You Can Integrate Web3 Into Your Enterprise

February 16, 2023

How to Deploy an NFT Using an NFT Smart Contract Example

January 1, 2023

Web3 Programming – How to Learn Web3 Programming

December 10, 2022

How to Get All Tokens Owned by a Wallet in 5 Steps

October 3, 2022

Set Up and Connect a Dapp to the Ethereum Network

October 17, 2022

How to Use Firebase as a Proxy API for Web3