New Web3 Game Tutorials


New Web3 Game Tutorials

Technology stacks and related tools

Blockchain knowledge and contracts

What is blockchain?

Blockchain is a series of transaction records (also known as blocks) connected and protected by cryptography. It is a new application mode of computer technology such as distributed data storage, point-to-point transmission, consensus mechanism and encryption algorithm.

It is essentially a decentralized database, which is a string of data blocks generated by cryptographic association. Each data block contains information about a batch of sub-Bitcoin network transactions, which is used to verify the validity of the information (anti-counterfeiting) and generate the next block.

In a narrow sense, blockchain is a chain data structure that combines data blocks in chronological order in a sequential manner, and a distributed ledger that cannot be tampered with or forged with cryptography.

Broadly speaking, blockchain technology is a new distributed infrastructure and computing paradigm that uses block chain data structure to verify and store data, uses distributed node consensus algorithm to generate and update data, uses cryptography to ensure the security of data transmission and access, and uses intelligent contracts composed of automated script codes to program and manipulate data.

What is a contract?

Contracts, also known as smart contracts. is a computer protocol designed to disseminate, validate, or enforce contracts in an informational manner. Smart contracts allow trusted transactions that are traceable and irreversible without a third party. The purpose of smart contracts is to provide security methods that are superior to traditional contracts and reduce other transaction costs associated with contracts.

In real development, you need a contract for everything you do. For example, if you want to trade a virtual car, or trade some gold coins, you need to use the contract to trade, otherwise it will not be recognized on the chain, that is, invalid. The contract specifies the address of the transaction, the item, the address of the transaction and so on.

Smart contract development

CoinToken

pragma solidity ^ 0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

contract CoinToken is ERC20 {

    mapping (address => bool) public minters;
    constructor(
        string memory _name, 
        string memory _symbol,
        address admin) ERC20(_name, _symbol) {
            minters[admin] = true;
    }

    function mint(address account, uint256 amount) external {
        require(minters[msg.sender], "!minter");
        _mint(account, amount);
    }
}

Player NFT & Sell NFT

  • Basic functions
pragma solidity ^ 0.8.0;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";

contract Player is ERC721 {

    mapping (address => bool) public minters;
    uint256 tokenId;
    constructor(
        string memory _name, 
        string memory _symbol,
        address admin) ERC721(_name, _symbol) {
            minters[admin] = true;
    }

    function mint(address account) external {
        require(minters[msg.sender], "!minter");
        tokenId++;
        _mint(account, tokenId);
    }
}
  • Add meatadata for Player NFTopen in new window

    {
        "name": "Herbie Starbelly",
        "description": "Friendly OpenSea Creature that enjoys long swims in the ocean.",
        "image": "ipfs://QmPbxeGcXhYQQNgsC6a36dDyYUcHgMLnGKnF8pVFmGsvqi",
        "attributes": [...]
    }
    
    // Returns the Uniform Resource Identifier (URI) for `tokenId` token.
    function tokenURI(
        uint256 tokenId
    ) public view override returns (string memory) {
        string memory baseURI_ = "https://domain/";
        return string(abi.encodePacked(baseURI_, tokenId.toString()));
    }
    
  • Add Sell Function

    • Players can receive Player NFT by paying Cointoken
      • tokenAddress(address): The contract address of the CoinToken
      • msg.sender(address): buyer for caller
      • payee(address): address for payee
      • price(uint256): price for a player NFT
function buy() external returns (uint256) {
    // pay token
    ICoinToken(tokenAddress).transferFrom(msg.sender, payee, price);
    // get Playe NFT
    tokenId++;
    _mint(msg.sender, tokenId);
}

COCOS are linked to smart contracts

  • Extensionsopen in new window

  • Ethers environment setup During the development of the game we need to link to the MetaMask plugin wallet. Here we will cover how to link to Ethereum and how to use the wallet in Ethereum.

1. Connet Ethereum

First make sure that our google is installed correctly and that the [MetaMask](https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn) plug-in is installed and that we have created a metamask account. After creating an account, you will see the following interface, in which you can see your basic information, including the network you use, account address, currency, and so on.
We need to use the Combo Testnet during the development process. Now let's replace the network with the Combo Testnet. Click on the Network option to the right of the metaMask Icon and select Combo Testnet from the options. Then we input the website(https://www.bnbchainlist.org/) in your browser.
![](../../assets/images/web3-game1.png)
After opening this URL, we need to find the Combo Testnet network we just selected. You will see some links. Select one of the links that you can connect To with a low latency and stable network and click Add To MetaMask. You will see the approval button on your wallet page. Click Approve and wait for the network link to succeed.

2. Claim Test BNB

Please open the faucetopen in new window In the wallet above, we need to copy our account address, add it to the input box in the webpage, Click Give me BNB, and the test BNB will be sent into your account in a few minutes. Then you will get the test coins. You can earn test coins once a day.

3. Get Combo Test BNB

COMBO Bridge functions as a bridge where users and developers can transfer Test BNB to COMBO Testnet.

4. Interaction (Buy NFT, Get gold)

a. Connnet wallet

Assume that all of our Ethers libraries have been imported. Let's take a look at how to link Ethereum in the game. Here is a simple exampleopen in new window of a link to Ethereum (ethers library version 5.2). provider is a read-only connection to the blockchain that allows querying the state of the blockchain, such as account, block, or transaction details, querying event logs, or usage. An account has only one singer. The singer stores information such as the address used by the user's account operations.

const provider = new ethers.providers.Web3Provider(window.ethereum)
    this.provider = provider;
    return provider.send("eth_requestAccounts", []).then(() => {
        const signer = provider.getSigner(undefined)
        this.signer = signer;
        console.info("signer", signer)
        return signer.getAddress()
    }).then((signerAddress) => {
        this.signerAddress = signerAddress
        this.erc20 = new ethers.Contract(etherConfig.erc20Adrees, etherConfig.erc20abi, this.signer)
        this.carNft = new ethers.Contract(etherConfig.carNftAdress, etherConfig.carNftabi, this.signer);
        console.info("signerAddress", signerAddress, "erc20", this.erc20, "carNft", this.carNft)
        const promises = [this.queryGold(), this.queryCars()]
        return Promise.all(promises)
    })

b. Create and use contracts

  • Create a contract

The following is a simple way to create a contract. contract is a contract library. When you create a contract, you need to use the address of the contract, the abi of the contract, and specify the user where the action is to take place.

this.erc20 = new ethers.Contract(etherConfig.erc20Adrees, etherConfig.erc20abi, this.signer)
this.carNft = new ethers.Contract(etherConfig.carNftAdress, etherConfig.carNftabi, this.signer);
  • Query

Query is a basic method used in the contract, which can help us to query the quantity of something we define. The query interface is balanceOf and the use mode is contractObj.balanceOf(' singerAddress ').

  • Customize

In the process of game development, we often need to use some custom items. Here we need some custom api to operate items. The custom abi, as we can see when exporting the contract configuration, needs to pass the configuration to the contract when it is generated. Let's take a look at a simple use of custom. In the example below we can see the contract of Player NFT we created earlier and buy for our custom abi.

  • Other

All of the above are simple instructions for the use of the ethers library. Please see the docs of ethers open in new window