Building Blockchain Application for Ethereum DApp Game with Drizzle


Building Blockchain Application for Ethereum DApp Game with Drizzle

Recipe ID: hsts-r45


Self-paced training

We offer blockchain introduction, Hyperledger for system admin, Ethereum, Solidity, Corda R3, Hyperledger for developers, blockchain cybersecurity and more classes in self-paced video format starting at $60. Click here to learn more and register. For complete self-paced blockchain training, visit our Complete Blockchain Development Training page.


Update on Feb 2021

The latest version of this tutorial along with all updated source codes is available via the below link:
https://myhsts.org/blog/ethereum-dapp-with-evm-remix-golang-truffle-and-solidity-part2.html

Recipe Overview

Ethereum is a general-purpose blockchain that is more suited to describing business logic, through advanced scripts, also known as smart contracts. Ethereum was designed with a broader vision, as a decentralized or world computer that attempts to marry the power of the blockchain, as a trust machine, with a Turing-complete contract engine. Although Ethereum borrows many ideas that were initially introduced by bitcoin, there are many divergences between the two.
The Ethereum virtual machine and smart contracts are key elements of Ethereum, and constitute its main attraction. In Ethereum, smart contracts represent a piece of code written in a high-level language (Solidity, LLL, Viper) and stored as bytecode in the blockchain, in order to run reliably in a stack-based virtual machine (Ethereum Virtual Machine), in each node, once invoked. The interactions with smart contract functions happen through transactions on the blockchain network, with their payloads being executed in the Ethereum virtual machine, and the shared blockchain state being updated accordingly.

For those who are not familiar with blockchain technology reading History and Evolution of Blockchain Technology from Bitcoin article is strongly recommended. Also, if you wish to learn and practice Hyperledger blockchain development, visit Comprehensive Hyperledger Training Tutorials page to get the outline of our Hyperledger tutorial articles.
We have written two sets of tutorials to explore Ethereum and Solidity programming in depth. First set covered the following nine recipes:

In short, you learned about how to set up and configure Ethereum and develop blockchain applications using Solidity programming language. We explored its key components, including smart contracts and Web3.JS API via an Auction Decentralized Application (DApp) step-by-step.
In second set, we discuss more advance topics in Ethereum blockchain development and solidity while building a Tontine DApp game step-by-step. Specifically, we cover Truffle and Drizzle. For instance, we show you how a tool such as Truffle can be an assistant in building, testing, debugging, and deploying DApps. In summary, we are going to cover four main topics:

The 2nd set consists of 8 recipes as follows:

IMPORTANT: Understanding and completing the first set of recipes are required prior to working on second set of recipes.
In our first round of recipes, we learned a lot about the Ethereum ecosystem, but we are yet to realize the full potential of its different components. More precisely, we explored how Ethereum works, what a decentralized application (DApp) is and how to build one, and also covered the key concepts of Solidity and web3.js. We then introduced some of the most common smart contract design patterns (withdrawal from a contract, restricting access, state machines), before ending with a discussion of a contract’s cost optimization.
To brush up your knowledge and skills, on second round of recipes, we are going to build a Tontine DApp game. We will exploit this example to explore new tools that are going to change the way you build DApps, and introduce new Solidity features.

In this walkthrough, we will discover how a tool such as Truffle can aid in building, testing, debugging, and deploying our DApp.

Truffle makes it possible to start a DApp project easily using a collection of delicious Truffle boxes. A box is basically a boilerplate template for giving developers the ability to build robust and adaptable DApps quickly. One of these boxes is the Drizzle box.

In this recipe, we will build a web interface for our game with Drizzle instead of using bare-metal JavaScript and web3.js, as we did in the first round of recipes.

Prerequisites

To get started with Drizzle, it's preferable to have basic knowledge of ReactJS, and will require the installation of the following ingredients:

 

What is the Drizzle box?

Yes, another tool with a delicious name: Truffle, Ganache, Drizzle, these names make me hungry.

Drizzle is a collection of frontend libraries that make writing DApp frontends easier and more predictable. Drizzle is based on the popular React framework, Redux, which is a predictable state container for JavaScript applications most commonly used with ReactJS for building user interfaces. Thus, it helps you write applications that behave consistently, solving the problems related to state mutation in highly asynchronous and non deterministic environments.

The Drizzle box comes with everything you need to start using smart contracts from a React App. As you’ll see in a moment, Drizzle is easy to use. We just unpack its box and then we can build a DApp in a few steps. You can write a React app from scratch using Drizzle packages, but to save you time and effort, I opt for using the box template and editing its code.

 

Getting started with the Drizzle box

Let's start by setting up your first Drizzle template.

First, you have to create a new empty folder for the Drizzle box, otherwise Truffle will refuse to download the Drizzle box files. Start by creating a new dedicated folder: mkdir DrizzleTontine.
Then, install the Drizzle box: truffle unbox drizzle.

After a few seconds (two sips of coffee), it should output the following:
Truffle and Ganache for Ethereum Smart Contract management

Once the installation is done, you'll get a full DApp demo including sample contracts.

 

Running the demo

To run the example packed within the Drizzle box, you should already have the local Ganache network running. If not, start Ganache on port 7545: Ganache-cli -p 7545.
As we have a new Truffle project, we need to edit truffle.js, as we have done many times before, to add the my_ganache network. Otherwise, you can edit the development network (port 7545) defined already in truffle.js. If you use the latter option, you won’t need to specify the network using –-network.
The next step is to compile and publish the smart contracts that come with the truffle compile box. Then, publish the compiled smart contracts to the truffle migrate Ganache blockchain.

 

Starting the web UI

You can run the example that comes with the Drizzle box by running npm run start from within the DrizzleTontine/ directory.


As a result, you'll see the Webpack server launching, and inside the browser, a nice DApp web interface. As well as showing the Drizzle logo, the page will show a few forms to interact with the sample contracts provided by the box, as illustrated in the following screenshot:
Truffle and Ganache for Ethereum Smart Contract management

If you don’t have MetaMask already installed, or your account is locked, you’ll see the following message:
Truffle and Ganache for Ethereum Smart Contract management

If MetaMask is not already connected to Ganache, you can skip to the Connecting ganache to MetaMask section to fix this issue.

Awesome, isn’t it? In a few steps, you have deployed a full DApp with a clean interface, interacting with three different contracts, without writing a single line of code.
Now, stop the Webpack server using Ctrl + C and let’s customize the box to build our Tontine game user interface.

 

Hacking the Drizzle box

The previous Drizzle unboxing initiated a Truffle workspace along with a ReactJs project located under the src/ folder. Here are the steps to follow in order to adapt this example to our needs.

First, copy the tontine.sol file into the contracts/ folder and remove the other existing contracts, except for Migration.sol and tontine.sol.
Then edit the 2_deploy_contract file (as we did in the "truffle quick start" and "Truffle unit tests" section), and substitute the existing deployment script with the following:

var Ctontine = artifacts.require("Ctontine"); var Cplayer = artifacts.require("Cplayer");

deployer.deploy(Cplayer).then(function() {
return deployer.deploy(Ctontine, Cplayer.address);
}).then(function() { })


Next, edit drizzleOptions.js, which is located under the src/ folder, as follows:
import Cplayer from './../build/contracts/Cplayer.json' import Ctontine from './../build/contracts/Ctontine.json'

const drizzleOptions = { web3: {
block: false, fallback: {
type: 'ws',
url: 'ws://127.0.0.1:7545'
}
},
contracts: [ Cplayer, Ctontine ], events: {
Ctontine: [ 'NewActivePlayerEv', 'EliminatedPlayerEv'
],
},
polls: { accounts: 1500 }
}

export default drizzleOptions;

Here, we define a drizzleOptions object with the following parameters:

}

Once you are done with the drizzleoptions.js editing, move to the src/layout/home directory.

 

The game’s homepage

Using the default homepage shipped with the Drizzle box, we will set up a web page for our game. Open the src/layouts/home/Home.js file and make the following changes:
import React, { Component } from 'react';
import { AccountData, ContractData, ContractForm } from 'drizzle-react- components';
import PropTypes from 'prop-types'; import logo from '../../logo.png';

class Home extends Component { constructor(props, context) {
super(props);
this.contracts = context.drizzle.contracts;
}

render() {
return (
<main className="container">
<div className="pure-g">
<div className="pure-u-1-1 header">
<img src={logo} alt="drizzle-logo" />
<h1>Tontine Game</h1>
<p>Examples of how to get started with Drizzle in
various situations.</p>
</div>
<div className="pure-u-1-1">
<h2>Active Account</h2>
<strong>My details:      </strong>
<AccountData accountIndex="0" units="ether"

precision="3" />


</div>
<div className="pure-u-1-1">
<h2>Cplayer Contract</h2>
<ContractData
contract="Cplayer" method="findplayer"
methodArgs={[this.props.accounts[0]]} />
<h3>Register</h3>
<p>Before you start playing, players should

register themselves using AddPlayer from.</p>
<ContractForm contract="Cplayer" method="AddPlayer"
/>
the first time)</p>
</div>
<div className="pure-u-1-1">
<h2>Ctontine</h2>
<strong>Last Ping:      </strong>
<ContractData
contract="Ctontine" method="ping_time"
methodArgs={[this.props.accounts[0]]} />
<strong>Your Game pension:       </strong>
<ContractData
contract="Ctontine" method="Tpension"
methodArgs={[this.props.accounts[0]]} />

<h3>join game</h3>
<p>Press the button below to join the game (only

<ContractForm
contract="Ctontine" method="join" methodArgs={[{value:
this.context.drizzle.web3.utils.toWei('2','ether'), from: this.props.accounts[0]}]} />
<strong>Ping game:      </strong>
<p>Keep pinging the contract to avoid being eliminated (ping interval is 1 day)</p>
<ContractForm
contract="Ctontine" method="ping" methodArgs={[{from:
this.props.accounts[0],data:1}]} />
<h3>Eliminate an opponent</h3>
<p>use this form to eliminate your opponent</p>
<ContractForm
contract="Ctontine" method="eliminate" labels={['Opponent Address']} />
<h3>Claim your reward</h3>
<ContractForm contract="Ctontine"
method="claimReward" />
</div>
</div>

<h2>First Active players</h2>
<ContractData contract="Ctontine" method="active_players" methodArgs={"0"} />
<h2>First Eliminated players</h2>

<ContractData contract="Ctontine" method="eliminated_players" methodArgs={"0"} />
</main>
)
}
}

Home.contextTypes = { drizzle: PropTypes.object }; export default Home;

Since this is not a CSS nor a ReactJs recipe, I’m skipping some of the ReactJs explanations and focusing on Drizzle.
Drizzle comes with its own React components, through the drizzle-react-components library, which makes it easier for you to display contract-related information and call the contract methods. In the preceding code, we started by importing three components from Drizzle: AccountData, ContractData, and ContractForm. These components are very powerful, so let's discover what they are used for:

AccountData: Displays the account address and balance for a given index. To use this component, we specify these attributes:

For example, the <AccountData accountIndex="0" units="ether" precision="3"/> element will render the first active account’s balance and address:

Truffle and Ganache for Ethereum Smart Contract management

 
ContractData: Displays the contract call’s output and accepts the following parameters:

For example, in the previous code we had the following:

<ContractData contract="Ctontine" method="ping_time" methodArgs={[this.props.accounts[0]]} />

This element will display the ping time value (ping_time) for the specified player (this.props.accounts[0]) from the Ctontine contract. As you can see, there's no such method as ping_time in our contract, but while it's a public state, ContractData element accepts it as a method argument:


Truffle and Ganache for Ethereum Smart Contract management

ContractForm: Contrary to ContractData, the ContractForm Drizzle component can automatically generate a form to read input and interact with the smart contract.

For example, when we use <ContractForm contract="Ctontine" method="eliminate" labels={['Opponent Address']} />, we will generate the following form with one input (as eliminate accepts a single argument). Once submitted, it will call the specified eliminate() method and pass the input value as an argument:

Truffle and Ganache for Ethereum Smart Contract management

The Drizzle ContractForm element accepts the following parameters:

At the time of writing, the ContractForm component doesn't support a value field (maybe soon) to send ether, but there is a workaround for that listed in this GitHub discussion: https://github.com/trufflesuite/drizzle-react-components/issues/17.

One more thing: you may have noticed the use of web3.utils.toWei. Interestingly, Drizzle maintains access to the underlying functionality of web3 1.0, thus you can use all web3.js methods in your React code without needing to initiate a web3 object.
Save all the changes you’ve made so far and now let's try our Drizzle DApp.

 

Trying the DApp

Good work, you have built your first Drizzle app using the Drizzle box. More importantly, you have set up a great development and deployment environment that will make DApp development and testing even easier.

We're getting close to our final goal of running our drizzle DApp, but there’s one more important step before we try the game: preparing MetaMask. To summarize, Truffle will compile and deploy the contract into Ganache and ensure connectivity with Drizzle, whereas MetaMask will connect the end user to Ganache (blockchain) in order to let a user play and manage their funds.

 

Connecting Ganache to MetaMask

In the previous round of  recipes, we introduced the MetaMask plugin, which allows users to send transactions through the browser without having to install a full node.


To interact with Ganache from the browser, we need to configure MetaMask. For that, in the top-left of MetaMask, you can select Custom RPC. A new dialogue box, titled New RPC URL will show up; here, you should enter http://127.0.0.1:7545 (Ganache's IP and port) and click Save.
Truffle and Ganache for Ethereum Smart Contract management

Now that we've connected MetaMask to Ganache, your previous MetaMask accounts will be loaded with 0 ether, which won’t help us to try our DApp. Thankfully, ganache-cli generated a collection of virtual accounts, each with 100 ether. We need to import some of these accounts to be able to interact with the contract. To do that, copy a few private keys from the ganache-cli output and use them in MetaMask to import the corresponding accounts:

Truffle and Ganache for Ethereum Smart Contract management


In order to import an existing wallet into a MetaMask account, click on the account- switcher icon in the upper-right corner (see the following screenshot) and select Import Account, as shown here:
Truffle and Ganache for Ethereum Smart Contract management

You can, at any time, switch between imported accounts by using the same account- switcher icon:
Truffle and Ganache for Ethereum Smart Contract management

The imported account should appear in the list of accounts and should be marked Imported with a red background. That’s it! You have successfully imported the necessary wallets into MetaMask.
Now let’s run our Tontine DApp in the next recipe.

To conclude this recipe, we like to recommend our Learn Hands-on Blockchain Ethereum Development & Get Certified in 30 Hrs, and Become Blockchain Certified Security Architect in 30 hours courses to those interested in pursuing a blockchain development career. This recipe is written by Brian Wu who is our senior Blockchain instructor in Washington DC. His Blockchain By Example book is highly recommended for learning more about blockchain development.

Related Training Courses

Hands-on Node.JS, MongoDB and Express.js Training
Advance JavaScript, jQuery Using JSON and Ajax
Learn Hands-on Blockchain Ethereum Development & Get Certified in 30 Hrs
Learn Blockchain Hyperledger Development & Get Certified in 30 Hrs
Become Blockchain Certified Security Architect in 30 hours
Blockchain Certified Solution Architect in 30 hours
Introduction to Python Programming
Object Oriented Programming with UML


Private and Custom Coding Classes

We offer private coding classes for beginners online and offline (at our Virginia site) with custom curriculum for most of our classes for $59 per hour online or $95 per hour in virginia. Give us a call or submit our Private Coding Classes for Beginners form to discuss your needs.


View Other Classes!