paint-brush
What's Inside Play to Earnby@systerr
13,201 reads
13,201 reads

What's Inside Play to Earn

by Andrey LogunovApril 27th, 2024
Read on Terminal Reader

Too Long; Didn't Read

Deep Dive into Blockchain (EVM), NFTs, NFT Metadata Standards, Game Economies, Authorization, and How We Can Incorporate NFTs into Gaming No code, brief tech overview.
featured image - What's Inside Play to Earn
Andrey Logunov HackerNoon profile picture


Hi there! Let's explore play-to-earn games a bit. We'll discuss how to create one and incorporate NFTs into it. This article will focus solely on the blockchain mechanics and won't delve into game development. I'll aim to explain everything using simple language with explanations of all the essential parts. So, let's get started!


Why is that topic (game evolutions and state)

I've been immersed in blockchain development since 2018, and during that time, I've seen a lot of people playing "play-to-earn" (p2e) games without any clue how it works. A lot of bad projects exist, and many people try to make their own p2e game without understanding the concept of a 'Ponzi scheme' or the technical implementation.


The idea for this article was born initially in the middle of 2022 during my offline speaking engagement at a crypto event. Then, the article's content evolved multiple times through my speaking engagements at different events in different countries. Additionally, I tried to solve all these problems myself by creating a tech startup in this sphere. Along the way, I witnessed a lot of interest in the topic and many misunderstandings of the basics.


The Internet started as web1, where you as a user were mostly a consumer of information (reading). Later, it evolved into web2, where users started writing to the internet too (social networks). Now, we are looking towards web3, where users can truly own something on the internet in addition to consuming and creating content.


From the creation of simple computer games back in the 1960s, games have evolved rapidly. They started as standalone games, and now we see many online games where players "own" some game items or characters. There are also game item marketplaces, some of which offer peer-to-peer (p2p) item trading. However, in most cases, these items do not truly belong to the gamers; they belong to the games. The future evolution will transfer item ownership from the game to the gamer, and some games already do this, but this feature still has limited penetration.


The crypto games boom was in 2021. As of 2024, the market still belongs to indie studios, and big vendors are almost not present there. Most games are still on EVM-compatible blockchains, but there is a trend to migrate from general blockchains to blockchains specifically built for gaming purposes.


In 2023, a lot of crypto games closed, and players were also depressed because of the crypto market downturn, leading to players losing time and money. However, the technology is still there, and I expect that more and more developers will look for something new to them (web3), and players as well. I hope my article helps them understand the basics of how it works from a technical perspective.


This article will cover only EVM blockchains, as these are still the most popular chains. However, you should know that many other types of chains exist that solve some of the problems described below.


Blockchain basics

Blockchain is a very simple concept - we have blocks that contain some transactions. A new block depends on the previous block, and because of that, it is not possible to replace an already existing block.


Simple, isn't it? But in reality, we can have multiple problems that lead us to some important blockchain characteristics for us:

  1. Block creation time
  2. Finality time
  3. Transaction fee


Different blockchain types have different approaches, but we will be focused on the most common EVM-type blockchain (Ethereum, Polygon, BNB Chain, etc.).


Usually, blocks are created at a fixed amount of time (12 seconds for Ethereum, 3 seconds for BNB Chain, etc.). This is the first fundamental property of the blockchain for us.


In the real world, a blockchain is distributed across multiple nodes (servers) that link to each other via internet connections. In some rare cases, it is possible to have multiple blocks based on the same parent, resulting in 'forks'.


Blockchain fork


Blockchain has been designed for cases like that and will resolve this situation. But you as the end user with a transaction in the red block (orphaned block) are not really happy, as your transaction can become invalid. And that's where 'finality' comes into play. Finality is the time when a transaction can't be reverted. This is the second fundamental property of the blockchain for us.


Any write operation to the blockchain costs something to you or your user. Blockchains have their own internal economic model, and keeping and running a lot of different nodes for decentralization requires a lot of resources. In most cases, this resource is a transaction fee billed to the end user for their usage. Blockchains have their own limit of transactions per second, and dynamic transaction fees are an internal mechanism to avoid DDoS attacks on the blockchain.


In most cases, the transaction initiator should pay the fees in the native currency, not with game tokens or NFTs.


Transaction fees are the third fundamental property of the blockchain for us.


Why are these three metrics important for us? This is primarily due to the end-user experience. Players want to focus on gameplay, not technical hurdles. As a game developer, it's your job to streamline this process by prioritizing intuitive UI/UX design and straightforward onboarding


Let's imagine a naive chess game where each chess move is stored on the blockchain. Players should pay a small transaction fee for each move, and players should wait until the block is finalized (which can take minutes between player moves). This doesn't look good, does it? Will users trade user experience for blockchain usage? Most players will prefer to play games as they are doing now instead of having the pain of using blockchain there.


But there's hope!  Several solutions exist that can bridge the gap between blockchain games and traditional games.


Tokens, what's that

Blockchain has a limited amount of features in its core, and in most cases, it is not enough. First-generation blockchains (like Bitcoin) have a limited ability to customize. Second-generation blockchains (Ethereum) introduced the ability to write custom programs (applications) and put them on the blockchain in their own space called Smart Contracts. Then the user can interact with this smart contract to do something, and the smart contract can interact with other smart contracts. Smart contracts are executed in a special environment called the Ethereum Virtual Machine (EVM). For now, the market has different virtual machines, but EVM is still the most popular one.


A simple analogy - the evolution of mobile phones. Old mobile phones could just make calls and send sms. Modern phones still have the ability to make calls and send sms , but you can install additional software to add new features.


Smart contracts open the ability to create your own currency (token). To make these tokens compatible with any wallet software, there are multiple token standards. The most popular ones are ERC20, ERC721, and ERC1155.


Standards only explain the external interface of a smart contract, but it's really important to know that the implementation can be different and can also contain some additional features.


There are two types of tokens: Fungible Tokens (FT) and Non-Fungible Tokens (NFT). FT tokens are like real money - you can have multiple copies of the same token. NFTs are unique, like a painting or a particular game item or character.


The ERC20 standard describes FT. Here is the interface of it:

function name() public view returns (string)
function symbol() public view returns (string)
function decimals() public view returns (uint8)
function totalSupply() public view returns (uint256)
function balanceOf(address _owner) public view returns (uint256 balance)
function transfer(address _to, uint256 _value) public returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
function approve(address _spender, uint256 _value) public returns (bool success)
function allowance(address _owner, address _spender) public view returns (uint256 remaining)


It's important to understand that tokens don't physically leave smart contracts. The smart contract simply keeps track of user tokens. When you transfer a token, it only updates the amount in an internal record, like a table. This is why, in some cases, you need to add the smart contract address to your wallet software.


ERC20 internals


The NFT standard itself is the same, but we have additional methods:

function ownerOf(address _owner) public view returns (uint256 balance)
function tokenURI(uint256 _tokenId) external view returns (string )


Each NFT token has a unique identifier (ID) and is always owned by someone. This is reflected in the token storage implementation, which typically uses a table to record both the token ID and its current owner.


ERC721 internals


Token Metadata

But where is the picture of the token, you may ask? And here we have the idea of ‘token metadata’. Unlike the core NFT standard, token metadata is stored separately and uses different specifications. In fact, some NFTs might not even have any metadata associated with them!


A smart contract method called tokenURI can return this metadata URI (location). There are several ways to store token metadata - on-chain and off-chain.

  • On-chain: Here, the data is converted into a special code format (base64 encoded) and stored directly within the blockchain itself. While secure, this can be expensive due to limited storage space.
  • Off-chain: This offers more flexibility and lower costs. Here, the data is stored externally.


Off-chain storage can be divided in two main categories:

  • Immutable storage: This ensures the data cannot be changed, like IPFS (InterPlanetary File System) or Arweave.
  • Central storage: This is controlled by a single entity, like a game developer's server or Amazon S3 storage.


Token metadata is usually formatted as a JSON file, but it can, in theory, be any format.  Here's an example of a typical metadata structure


{
  "description": "Token description", 
  "external_url": "Some external link with more details", 
  "image": "Link to image", 
  "name": "Token name",
  "attributes": [ // array of attributes
    {
      "trait_type": "Attribute type",  
      "value": "Attribute value"
     },
     ....
  ]
}


It's important to understand that mutable metadata (editable data) can undermine true Web3 ownership. With mutable metadata, you essentially own the token ID, not the content it represents.


Imagine you buy a "magic item with energy 5" NFT in a game. If the metadata containing this information is stored on the game developer's servers (centralized storage), the game developer could later decide to rebalance the game and change your item's energy to 3. While you'd still technically own the token, it would represent a different item. This scenario highlights the potential drawbacks of mutable, centralized metadata.


In contrast, Web3 thrives on immutable metadata (unchangeable data). This ensures the information associated with your NFT remains permanent and verifiable.


Good document that describe how metadata is used by marketplacehttps://docs.opensea.io/docs/metadata-standards.

Real metadata

Let's explore real metadata from a popular play-to-earn (P2E) game: STEPN. This game was popular not long ago and most likely you hear about people that spend a lot of money for sneakers.


We know the token ID is '105026695079', the smart contract address is '0x69d60ad11feb699fe5feeeb16ac691df090bfd50', and it's built on the BNB Chain. But how do we access the metadata?


There are two main approaches:

  • Low-level blockchain calls: This requires technical expertise.
  • Blockchain explorers: These are user-friendly web sites that index blockchain data for easier access.


Let's use the BSCScan explorer to explore the smart contract. Navigate to the 'read' tab (https://bscscan.com/address/0x69d60ad11feb699fe5feeeb16ac691df090bfd50#readContract) and find the tokenURI function. Input the token ID and click 'Query'. The explorer will retrieve the token URI, which in this case is: https://api.stepn.com/run/nftjson/104/105026695079


Take a closer look at this metadata. You'll notice that STEPN owns it and can potentially modify it. Additionally, some attributes like Durability and Level seem changeable over time. We'll delve deeper into this concept when building our own P2E game.


Blockchain account

Now that we've covered some key blockchain concepts, let's revisit one that's familiar to everyone: authorization. You can't perform actions on the blockchain without it. So, the question remains: how do we get authorized?


Blockchain utilizes a system of asymmetric cryptography, where two key pairs exist: private keys and public keys. You can generate a public key from your private key, but not the other way around (it's a one-way mathematical operation).


There are two main types of accounts on EMV blockchains: external owned account (EOA) and smart contract  account.


External owned accounts are controlled by private keys. A private key is a 32-byte piece of data, often represented by a long string of hexadecimal characters (64 characters). This format is not really convenient for the end user and hard to memorize.


To address the memorability challenge, a concept called a "mnemonic phrase" was introduced.  A mnemonic is a list of 12, 24, or more common words that act as a human-readable representation of your private key. Importantly, it's not the actual private key itself, but rather a way to securely generate it.

You can generate an unlimited number of private keys for yourself, free of charge.


Unlike EOAs, smart contract accounts don't require private keys for interaction because they already reside on the blockchain. This opens doors for creating programmable wallets with advanced functionalities.


End users don't interact with the blockchain directly using private keys. Instead, we rely on crypto wallets - software applications that securely store private keys and use them to sign transactions on your behalf.


There are two primary wallet models - custodial wallet and non custodial wallet


Custodial means that someone holds onto your private keys for you. While convenient, they introduce a central point of failure, as you rely on the custodian's security practices.


For non custodial wallets you have complete control over your private keys since you are responsible for keeping them safe. While offering greater security and control, it also places the responsibility for safekeeping entirely on the user.


In the realm of blockchain, your private key is paramount. It grants access to your cryptocurrency holdings. Losing your private key translates to losing your funds, as there's no built-in mechanism for recovery or transfer without it.


Unlike traditional accounts, blockchain accounts don't offer email or social login options. While some wallets are exploring advanced cryptographic methods for authentication, this approach is still in its early stages.  Other wallets prioritize user experience by offering custodial solutions, which are easier to use but depart from the core principles of Web3 that emphasize user control.


There are several types of blockchain wallets, with browser extensions and mobile wallets being the most popular choices. Mobile wallets can often connect seamlessly with browsers for added convenience.


A typical non-custodial wallet  stores your private key securely internally, never exposing it through an API (so there's no risk of it being compromised).  The wallet offers two external components: a user interface (UI) for interacting with your crypto and an external API for developers to integrate with the wallet's functionalities.


typical non-custodial wallet 


Building Our Play-to-Earn Game (P2E)

Now that we've explored the fundamentals of blockchain, we're ready to take the next step: designing our own game! Don't worry, we won't be diving into coding just yet. Instead, let's use our newfound knowledge to imagine a game concept and break it down step-by-step, starting with a high-level overview.


To build a strong foundation, let's take inspiration from a classic like Super Mario Bros. and infuse it with exciting P2E elements.


Mario game


Game economy

A critical aspect of our Mario game is establishing a sustainable economic model. This means avoiding "ponzi schemes" that are prevalent in many play-to-earn (P2E) games. In a sustainable model, user earnings will be balanced with the game's overall revenue stream.  This focus on long-term health is essential because, unlike ponzi schemes, which are easy to create but ultimately unsustainable, building a thriving P2E economy requires careful design and planning.


How can users make money in our game? Let's say any collected in-game coins (Mario Coin - MC) can be exchanged for a cryptocurrency (FT).


To prevent "making money from nothing", we'll introduce various ways for players to spend their MC on meaningful in-game items and boosts like:

  • Unique character skins (NFTs): Players can purchase these on a marketplace for personalization and potential value appreciation.
  • Stamina recharges using MC allow continued playtime.
  • Optional level skips using MC (consider if this disrupts balance) offer convenience for players.
  • Minting new characters using MC incentivizes dedicated players and extends playtime.


Our Mario game can generate revenue beyond user spending through several methods:

  • Strategic ad placements, particularly for location-based games like Pokemon Go.
  • Secondary NFT market fees (royalties) provide ongoing income for the game.
  • "Battle arena". These features can generate fees that help manage game token inflation.
  • NFT rentals. Create an income stream for both players (through rental fees) and the game.


To keep the overall token supply in check and reduce pressure on the exchange rate, you can integrate additional features like staking options. These incentivize users to hold tokens, reducing circulation and inflation.


Thorough planning of the game's economy before development is crucial. Tools like Google Sheets can help model different scenarios to ensure a balanced and sustainable system.


Blockchain selection

Now that we're ready to move forward, the next crucial step is selecting the blockchain to host our Mario game. This decision carries significant weight, as there are numerous options: Ethereum Virtual Machine (EVM) and non-EVM blockchains. We could even explore creating a custom blockchain tailored to our game's needs. Additionally, the possibility of utilizing multiple blockchains simultaneously warrants consideration.


While migrating between blockchains later is technically possible, it's a complex process.


Single-chain solutions offer a simpler approach compared to multi-chain implementations. Some games present multi-chain options essentially as independent games (with unlinked token values), which ultimately translates to multiple instances of the same game. A true multi-chain experience requires ensuring consistent token prices across chains and the ability to seamlessly link NFTs from various chains within the game.


When selecting a blockchain, you aim to minimize 'finality' time and fees while ensuring strong security measures. Additionally, it's crucial that the chosen chain has sufficient liquidity.


It's essential to recognize that directly reading a smart contract for data isn't always efficient and can be time-consuming to implement. Instead, leveraging external software and services that offer metadata in a suitable format is advisable.


Users expect the ability to trade tokens and NFTs seamlessly. Therefore, the blockchain should provide the necessary infrastructure for such transactions. Otherwise, you'll need to implement it independently.


Choosing the right blockchain is critical for a successful launch of your Mario game. This involves ensuring the selected blockchain has all the necessary infrastructure we plan to utilize. Additionally, robust testnet environments are crucial for thoroughly testing our game functionalities throughout development. This allows us to identify and address any potential issues early on.


User onboarding

At this stage, we have selected the blockchain and prompted the user to log in to the game. While users should have a wallet to access the game, most have no wallets and desire to play without learning new complexities upfront.


If you ask the user to create a wallet at the game's start, you will have poor conversion. You can provide a lot of instructions on how to create a new wallet in the best way, but most users will still be uncomfortable.


A good solution is to allow users to log in using web2 options and request a user wallet only when the user wishes to interact with the blockchain directly.


You can opt to manage the user's wallet yourself in a custodial manner. However, this approach may not be the most secure or optimal for both you and the user.


Alternatively, there are non-custodial solutions available in the market, such as web3auth and magicklink, which allow you to manage wallets for users. However, their blockchain support is currently limited, and you would need to integrate these services into your platform.


Native token payment problem

Simply having a game's native token isn't enough for users to make in-game blockchain transactions. This is a major barrier to user onboarding, and many players encounter this problem.


For instance, a user might hold our "Mario Token" and want to transfer it. However, they lack the underlying native blockchain token, which is essential for initiating the transfer. To transact on the blockchain, users need to acquire this native token.


How do users acquire the native token? While external purchasing options exist, they can be a barrier for new players unfamiliar with web3.


Ideally, game developers should address this issue and streamline the process for users. By minimizing these obstacles, players can focus on enjoying the game.


Game developers can implement an internal exchange system or implement low-level proxy contracts within the wallet service. However, these solutions are complex to implement.


A promising new technology called ‘account abstraction’ might finally solve this problem. However, it's still early days, and it's too early to draw definitive conclusions.


An easier solution for developers is to fund user wallets with a small amount of the native token upon new wallet registration


NFT linking

While users may own NFTs, directly reading this data from blockchains proves inefficient for most games. The blockchain operates as an external service, and events within it can impact your game. Staying informed about these events is crucial.


Fortunately, smart contracts can generate events, allowing developers to monitor them and trigger real-time responses. Imagine a scenario where a user enters a level with a skin NFT. If the skin gets transferred to another player during gameplay, the game should react by preventing its simultaneous use.


Several web projects (attarius, moralis, covalent, alchemy, etc) offer NFT APIs that streamline the process. These APIs handle tasks like reading and tracking metadata, as well as token ownership. This significantly reduces development time, allowing developers to focus on core game mechanics rather than low-level blockchain integration.


NFT to game


However, another challenge arises with metadata mutability. Some NFTs have limited uses, like a skin that can only be used 100 times before being "burned" (destroyed). Tracking this usage presents a critical issue.


Relying solely on in-game tracking can empower scammers targeting external marketplaces. These marketplaces depend solely on data from the token URI and lack access to a game's internal tracking system.


Server-side storage, like the approach used by STEPN, offers convenience but raises security concerns due to the potential for metadata manipulation.


On-chain storage offers immutability by storing metadata on the blockchain. However, this requires tracking each usage on-chain, which incurs transaction fees.


Marketing

Our Mario game's blockchain integration is nearing completion. Now, let's explore how NFTs can attract users.


Some games raise development funds by selling premium NFTs during early stages. This approach secures funding and builds a loyal player base eagerly awaiting the game's release.


It is possible to use ‘vampire marketing’. This unique marketing strategy involves allowing users to integrate NFTs from other games into your Mario game. Imagine enabling players to utilize STEPN sneakers within your game!  This approach targets users of different games but comes with challenges.


NFT standards vary, making seamless integration difficult. Additionally, tracking metadata changes can be complex in some cases. Despite these hurdles, cross-game NFT integration is a fresh marketing approach unavailable in traditional Web2 games.


"Vampire marketing" can be particularly effective when targeting users with underutilized NFTs. By allowing them to integrate these NFTs into your Mario game, you can activate these users and potentially convert them into active players.


Future Challenges

While the technical integration of blockchain is complete, our Mario game faces several challenges:


Legal part surrounding blockchain technology remains complex.


Attracting users familiar with blockchain and its benefits requires additional resources for user education.


Many game marketplaces have restrictions on blockchain-based games, limiting publishing options.


Unlike traditional in-game items, NFTs remain user-owned even after players stop playing the game. This introduces a new challenge of inflation. When players leave the game, they might try to sell their NFTs at a discount to recoup some value. This can lead to a constant influx of discounted NFTs within the game, causing the overall value of in-game NFT items to decrease. To combat this inflation, we'll need to continuously develop new features and content that incentivize players to hold onto their NFTs and keep playing our Mario game.


Conclusion

Here's a high-level overview of our Mario game's structure:


P2E game scheme



There is a lot of information about each topic for hours and hours. I have tried to compress this information and provide only important points. Hope it was useful for you