Join, compete & win! Prize pool of $100,000
Generic filters

Metaverse Smart Contract – How to Build a Metaverse Game Smart Contract

A smart contract on a programmable blockchain, such as Ethereum, is the key to automating specific actions that will execute when predefined conditions are met. Furthermore, they ensure that things run smoothly and in a fair manner. While there are all sorts of smart contracts out there, we will focus on metaverse smart contract examples herein. Despite the current fear and uncertainty in the present crypto market, metaverse development continues to soar. The fact that people play games no matter what the market conditions are probably has a lot to do with that. Now, since we are still pretty early in the game, this might be the best time to learn game smart contract programming. Moreover, for the sake of this tutorial, we’ve created a couple of metaverse smart contract examples. Moving forward, we’ll go through them together.  

After getting familiar with our metaverse smart contracts, we’ll also show you how to use Remix to deploy them. With that knowledge under your belt, you will be ready to create a metaverse dApp. By using the Moralis Metaverse SDK, you can put your new game smart contract to use seamlessly. However, if you want to boost your skills and confidence first, be sure to check out our other tutorials. They come with boilerplate codes, which you can clone in many cases. As a result, you can have a functional Web3 game up and running in minutes. For instance, you can build a medieval metaverse game

By taking on these simple example projects, you’ll strengthen your skills and get familiar with powerful Web3 development tools. Also, while the Web3 tech stack is evolving each day, Moralis remains the ultimate tool. This “Firebase for crypto” can help you save 87% of development time. Thus, sign up and give it a try today!

Metaverse Smart Contract – The Basics

Before we dive into our metaverse smart contract examples, we want to ensure that we are all on the same page. Thus, let’s first cover some basics. Being able to answer “what are smart contracts?” and “what is the metaverse?” confidently will simplify things tremendously. 

We’ve already mentioned that smart contracts exist to automate operations on blockchains. In addition, they also ensure that events such as transactions transpire according to set rules and standards. Moreover, there is a smart contract behind every token creation. Plus, smart contracts are also the backbone of all dApps (decentralized applications). In their essence, smart contracts are pieces of software that trigger certain actions once predefined conditions have been met. Thus, they also offer solutions for eliminating the middleman in countless industries. For a more detailed explanation of smart contracts, use the above link. 

On the other hand, in its “truest” form (think Ready Player One), the metaverse is for now only a theory. As such, the word “metaverse” started being used for a wider range of online worlds. In these digital worlds, users can interact and engage in different activities. Hence, according to this vague definition, many multiplayer games could be considered as “metaverses”. However, the main focus of current metaverse development is in the crypto realm. 

By using this disruptive technology, metaverses can easily include digital monetary systems. In turn, the value created in the metaverse could transfer into the real world. In addition, blockchain also gives people the chance to truly own their in-game assets, which can be represented by NFTs. Furthermore, metaverses built on top of the blockchain can be decentralized, which should be the ultimate goal. Use the link above to dive deeper into the “what is the metaverse?” discussion.

What is a Metaverse Smart Contract?

Now that you know what smart contracts are and what the metaverse is, it’s not difficult to put the two concepts together. Hence, a metaverse smart contract refers to any smart contract that is in any way used in creating or functioning in a metaverse. Even an NFT smart contract meant for minting NFTs within a metaverse would be considered a metaverse smart contract. Since games, especially Web3 games, are considered metaverses, a “game smart contract” is just another term for a metaverse smart contract. 

Furthermore, following this sort of nomenclature, we also talk about DAO smart contract examples, reentrancy smart contract examples, ERC-721 smart contracts, upgradable smart contracts, etc. Moreover, as a blockchain developer, you should learn how to easily work with all sorts of smart contracts. Fortunately, there are many tools that can make this quite simple. For one, you can use open-source platforms, such as OpenZeppelin, to get smart contract templates. Also, as mentioned previously, Remix enables you to easily deploy smart contracts. However, you should also learn to sync and index smart contract events. This is where Moralis’ “sync” feature comes into play. When you combine the latter with Moralis’ dashboard (database), you essentially get to index the blockchain. So, once we cover the metaverse smart contract examples below, make sure to make the most out of them by using these phenomenal tools.

Metaverse Smart Contract Examples

With the basics under your belt, you now know that smart contracts are the key to recording events and converting them into immutable on-chain data. As such, in-game assets’ ownership can be properly managed. Hence, a Moralis expert created a couple of smart contract examples that we will take a closer look at herein. Furthermore, we made all of them available on GitHub so that you can access them easily. That also means that you can use them in your games. Nonetheless, to make sure that you can easily follow along, start by cloning our NFT game sandbox. Moreover, we will be using Visual Studio Code (VSC); however, feel free to use any other code editor.

Inside the NFT game sandbox, you will see two game smart contract examples that we will focus on. These are “Asteroid.sol” and “Character.sol”. Furthermore, both of these metaverse smart contracts are NFT smart contracts. “Asteroid.sol” uses the ERC-1155 token standard, and “Character.sol” uses the ERC-721 standard. Each of the two standards has its own advantages. In short, ERC-1155 is usually more suitable for game lands, while ERC-721 is better for characters. 

A Game Smart Contract Example Using ERC-721

At the top of “Character.sol”, we have pragma directive. This tells the compiler of the contract which version of Solidity to use:

pragma solidity ^0.8.0;

Following are the imports of other contracts. This is where we heavily utilize OpenZeppelin. As a result, we save a lot of time:

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

By exploiting the functionality of the imported smart contracts above, we can skip a lot of coding inside our smart contract. Next, we have the line where we actually start our smart contract. This is also where we define the inheritance from the imported contracts above:

	contract Character is ERC721URIStorage, Ownable {
  using Counters for Counters.Counter;
  using SafeMath for uint256;

Then, we create state variables that will set up the rest of the smart contract’s functions. Moreover, most of these variables are public. For example, this is where the maximum limits of tokens per transfer and maximum limits for fees are set:

  uint256 fee = 0.00 ether; // <-- any fees we want to change on txs
  uint256 public constant maxSupply = 10000; // <-- max supply of tokens
  uint256 public maxMintAmountPerTx = 1; // <-- max mints per tx
  uint256 public perAddressLimit = 100; // <-- max
  string public notRevealedUri = "ipfs://INSERT_YOUR_CID/character-hidden.json"; // <-- link to metadata for e.g. hidden opensea listing of token
  bool public paused = false; // <-- stop interaction with contract
  bool public revealed = true; // <-- is the collection revealed yet?
  address public contractOwner; // <-- game dev/studio wallet address

Our Game Smart Contract Code Walkthrough – Recording Characters’ Attributes and Functions

Moving forward, we define a “struct” type to represent a record of our characters’ attributes. This enables us to keep track of our character within our game’s universe:

 struct Char {
    uint256 id;
    uint256 dna;
    uint8 level;
    uint8 rarity;
    uint256 evac;
    string tokenURI;

We also need to map the above struct to a publicly accessible “var”, which enables us to retrieve on-chain info about the characters:

Char[maxSupply] public _tokenDetails;

event NewChar(address indexed owner, uint256 id, uint256 dna);
mapping(address => uint256) public addressMintedBalance;

constructor() ERC721("Character", "CHAR") {
  contractOwner = msg.sender; 

From that point on, we start focusing on the functions that will declare the logic of our smart contract. We start with a utility function to generate a random number that is used for our characters’ IDs and rarity. For more details about the functions used in our “Character.sol” metaverse smart contract, watch the video below, starting at 4:29. At 5:33, you will also get to see the “write” functions that update our characters’ attributes on the chain. Furthermore, these functions trigger player-executable and admin-executable actions.

A Game Smart Contract Example Using ERC-1155

Now it’s time to take a closer look at our “Asteroid.sol” metaverse smart contract. The general structure of this game smart contract is quite similar to “Character.sol”. As such, we also start with the pragma line:

pragma solidity >=0.6.12 <0.9.0; 

Next, we have the imports of other smart contracts:

import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol"; //
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";

Then, we define the inheritance from the imported contracts above:

contract Object is ERC1155, Ownable {
  using Counters for Counters.Counter;
  using SafeMath for uint256;
  using Strings for string;
  Counters.Counter private _tokenIDS;

Following are the lines where we define public variables:

  uint256 public cost = 0.00 ether;
  uint256 public maxSupply = 10000;

Moving forward, we define a struct type and then map it. Then, this finally gets us to “constructor()”:

    name = "Asteroid";
    symbol = "AROID";
    tokensInCirculation = 0;

This is where ERC-1155 plays a significant role. It enables us to mint each piece of in-game land by storing them in a decentralized manner using IPFS. Moreover, at its core, ERC-1155 is designed for bulk minting. As such, it fits our purpose better than ERC-721. For more details, use the video below at 8:20.   

Deploy Game Smart Contracts Using Remix

Once you have your smart contracts ready, you can deploy them in a pretty seamless manner using Remix. This browser-based tool is easy to use. Moreover, you can use the link to our metaverse smart contract examples given previously and then copy the entire code to Remix. There, you first create a new file, then paste the code and save it. Once your code is saved, you can compile your game smart contract example. Now you are ready to proceed with the deployment. Of course, make sure that you have your MetaMask ready and a sufficient amount of testnet tokens to cover the transaction fees. Nonetheless, for detailed guidance, use the video below at 9:53.

Here’s the video we’ve been referencing throughout the article:

Metaverse Smart Contract – How to Build a Metaverse Game Smart Contract – Summary

At this point, you are an actual semi-expert on metaverse smart contracts. You’ve learned what they are, and you went through a couple of game smart contract examples to get a proper understanding. Along the way, you’ve also learned about Moralis. As such, you now know that this Web3 backend platform can cover all your blockchain-related backend needs. In addition, you’ve had a chance to see how to use Remix to deploy smart contracts in minutes as you watched the video. 

Moving forward, we encourage you to take on some example projects to put your metaverse smart contact knowledge to use. On the other hand, you may want to explore other blockchain development topics. For both of these paths, the Moralis YouTube channel and the Moralis blog are just what you need. Both of these outlets offer a ton of valuable content. As such, they are undoubtedly one of the best ways regarding free crypto education. For instance, some of our latest topics dive deeper into Web3 e-commerce and how to build a Web3 Amazon marketplace, how to connect a Unity app to a Web3 wallet, Alchemy API alternatives, how to create a BNB Chain token quickly, cloning Coinbase Wallet, how to create a Solana token, NFT minting page creation, and much more. 

On the other hand, you might want to become a blockchain developer as soon as possible. If that’s the case, taking a more professional approach usually works best. As such, consider enrolling in Moralis Academy. Aside from getting access to professional courses, you will also get your personalized study path. Moreover, you will become a part of one of the most supporting and loving blockchain communities. Plus, you will get expert mentoring to further boost your progress.    

March 6, 2022
Become a Moralis Mage
Get the latest information about Moralis Web3 in your email
Generic filters
Related Articles
Become a Web3 Expert
Subscribe to our newsletter and get our E-book Web3 Speed run for FREE