Reader small image

You're reading from  Blockchain By Example

Product typeBook
Published inNov 2018
Reading LevelBeginner
PublisherPackt
ISBN-139781788475686
Edition1st Edition
Languages
Concepts
Right arrow
Authors (3):
Bellaj Badr
Bellaj Badr
author image
Bellaj Badr

Bellaj Badr is an experienced security and software engineer who loves blockchain with a passion. Currently, he is the CTO at Mchain, a blockchain start-up that develops blockchain solutions for companies. Alongside his role as CTO, he acts as technical consultant, offering strategic and technical consulting to many companies worldwide. Aside from this, he is involved in many blockchain projects involving the establishment of new blockchain business-oriented protocols. Badr is a frequent speaker at developer conferences and is father to two angels.
Read more about Bellaj Badr

Richard Horrocks
Richard Horrocks
author image
Richard Horrocks

Richard Horrocks is a freelance Ethereum and full-stack developer based in the UK, and holds a BA and MSc in natural sciences from the University of Cambridge. He worked for many years as a technical lead for Cisco Systems, where he worked on the operating systems of carrier-grade routing hardware, before leaving the world of IT to work as an English teacher. The advent of cryptocurrency piqued his interest sufficiently to lead him back to IT, and, since 2015, he has been working with Ethereum and other cryptocurrencies. His specialist interests are cryptoeconomics and incentive layers, with a particular focus on mechanism design and token engineering. When not in front of a computer, he enjoys yoga and falling off motorbikes.
Read more about Richard Horrocks

Xun (Brian) Wu
Xun (Brian) Wu
author image
Xun (Brian) Wu

Xun (Brian) Wu is a senior blockchain architect and consultant. With over 20 years of hands-on experience across various technologies, including Blockchain, big data, cloud, AI, systems, and infrastructure, Brian has worked on more than 50 projects in his career. He has authored nine books, which have been published by O'Reilly, Packt, and Apress, focusing on popular fields within the Blockchain industry. The titles of his books include: Learn Ethereum (First Edition), Learn Ethereum (Second Edition), Blockchain for Teens, Hands-On Smart Contract Development with Hyperledger Fabric V2, Hyperledger Cookbook, Blockchain Quick Start Guide, Security Tokens and Stablecoins Quick Start Guide, Blockchain by Example, and Seven NoSQL Databases in a Week.
Read more about Xun (Brian) Wu

View More author details
Right arrow

Tontine Game with Truffle and Drizzle

In the previous chapter, 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, in this chapter, 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. I hope you enjoy playing games as much as building them.

In this walkthrough, we will...

Background

Before kicking off the project, let me introduce the concept behind the game.

As this chapter's name suggests, we are going to build a Tontine game. The concept behind the weird word Tontine appeared at the end of 17th century. Initially, it represented a collective investment scheme plan, where each participant paid a sum into a fund and received dividends from the invested capital. But behind this simple idea, a weird rule is hidden: when a subscriber dies, their share is divided among the others and the last lucky survivor recovers the whole capital.

In our game, we will adapt this idea to our smart contract and gaming logic. Players will deposit funds in the game's smart contract to join the game. Afterwards, they should keep pinging it during a specific time interval to avoid being knocked out by other opponents. For instance, if anybody misses pinging...

Truffle quick start

So far, the only method we have used to compile and interact with our contracts was Remix. Let me now introduce you to a new DApp development toolkit: Truffle.

Truffle is the most popular development environment and testing framework for DApp developers. It is a true Swiss Army knife that helps you easily compile, test, and deploy your contracts to the blockchain. Moreover, Truffle helps you set up and hook your frontend up to your deployed contracts. It also has other features:

  • Built-in smart-contract compilation, linking, deployment, and binary management
  • Automated contract testing
  • Scriptable, extensible deployment and migrations framework
  • Network management for deploying to any number of public and private networks
  • Interactive console for direct contract communication
...

The Tontine contract

As stated in the introduction, Tontine is a competitive multiplayer game. When it starts, players pool their money into the Tontine contract, and once the game is over, all the funds are handed to the last surviving participant. Meanwhile, players take turns trying to stabilize their position and eliminate their opponents. The main rules of our Tontine game are as follows:

  • A player can join the game by paying at least 1 ETH to the contract.
  • The game starts when the first player enters.
  • The player needs to ping the contract every day.
  • If the player hasn't pinged the contract during the last 24 hours, other users can eliminate them.
  • The last player will get all the money out of the contract and the game ends.

General structure

...

Cplayer as a CRUD contract

We'll start by building the Cplayer contract, which is responsible for managing player accounts. Going forward, we will use Solidity to build it as a CRUD smart contract.

As you know, the CRUD paradigm is common in constructing web applications as its operations generally constitute the fundamental structure. In fact, the CRUD acronym's create, read, update and delete operations represent the basic operation we'll need to perform on the data repository (Smart contract storage) while managing the players.

At this point, to build a CRUD contract, we first need to understand where and how data is stored and accessed in Ethereum's blockchain.

Smart contract data location

Although...

Tontine interfaces – Itontine

As per our design, now we will define an interface for our Tontine game.

Interfaces are universal concepts in programming languages used to represent collections of abstract methods. They are useful since they implement an agreed set of functions that enable interactions without forcing a contract relationship (they might be considered as a protocol).

Nevertheless, in Solidity, unlike abstract contracts, interfaces present the following limitations:

  • Cannot inherit other contracts or interfaces
  • Cannot implement their own functions
  • Cannot define a constructor
  • Cannot define variables
  • Cannot define structs
  • Cannot define enums

Here is the definition of our Itontine interface:

interface Itontine {
function join() external payable returns (bool);
function ping() external returns (bool);
function eliminate(address a) external returns (bool...

Interface implementation – Ctontine contract

The next step is to define the main contract behind our game: Ctontine. In Solidity, when a contract implements an interface, the class agrees to implement all of its methods. Hence, if you miss implementing a function defined in the inherited interface, you’ll get the following error (in Remix):

As we do for inheritance, we use the is keyword to implement the interface, as follows:

contract Ctontine is Itontine {..}

Now, let's fill this empty contract. Within the preceding bracket, we start by declaring the following contract states:

    mapping (address => uint256 ) public Tpension;
Cplayer.player[] public active_players;
Cplayer.player[] public eleminated_players;
mapping (address => uint) public ping_time;
uint256 public Lindex;
Cplayer Tplayer:

Here are the contract states:

  • Tpension:...

Truffle unit tests

I believe software developers are artists, and they love testing their chefd'oeuvres before deploying them. If you’re one of them then that's good news for you, as Truffle allows you to easily test your Solidity smart contract.

Under the hood, Truffle leverages an adapted version of the famous Mochajs (https://mochajs.org/) unit-testing framework to test Solidity contracts. Consequently, you can write your tests in JavaScript and take advantage of all the patterns Mocha provides. In addition, Truffle enables you to write tests using Solidity directly. In this section, I will opt for starting with JavaScript to implement all of the Tontine test cases, then we will explore how to use Solidity as a testing framework.

Let's start by writing our test files.

...

Frontend with Drizzle

Thankfully, Truffle makes it possible to kick off 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 section, 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 previous chapter.

Prerequisites

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

  • MetaMask
  • Ganache CLI (a version that supports Websockets)
  • Truffle
...

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 chapter, we introduced the MetaMask plugin, which allows users to send...

Summary

This has been an awesome experience. I hope building the Tontine game was a lot of fun for you.

An important takeaway from this chapter is to think twice before deciding to deploy your final contract and release your DApp. It’s good practice to always plan your contract-development process before jumping into the code, along with conducting thorough testing either using JavaScript or Solidity to ensure quality and security. Keep in mind that writing smart contracts is a critical task as you’ll be dealing with real money. You don’t want your project to end up in the blockchain graveyard (https://magoo.github.io/Blockchain-Graveyard/), do you? The rule of thumb is begin with testing locally on Ganache, and then on a Testnet before going onto the real Mainnet. Besides this, asking other developers to review your code is always a good habit.

To summarize...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Blockchain By Example
Published in: Nov 2018Publisher: PacktISBN-13: 9781788475686
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (3)

author image
Bellaj Badr

Bellaj Badr is an experienced security and software engineer who loves blockchain with a passion. Currently, he is the CTO at Mchain, a blockchain start-up that develops blockchain solutions for companies. Alongside his role as CTO, he acts as technical consultant, offering strategic and technical consulting to many companies worldwide. Aside from this, he is involved in many blockchain projects involving the establishment of new blockchain business-oriented protocols. Badr is a frequent speaker at developer conferences and is father to two angels.
Read more about Bellaj Badr

author image
Richard Horrocks

Richard Horrocks is a freelance Ethereum and full-stack developer based in the UK, and holds a BA and MSc in natural sciences from the University of Cambridge. He worked for many years as a technical lead for Cisco Systems, where he worked on the operating systems of carrier-grade routing hardware, before leaving the world of IT to work as an English teacher. The advent of cryptocurrency piqued his interest sufficiently to lead him back to IT, and, since 2015, he has been working with Ethereum and other cryptocurrencies. His specialist interests are cryptoeconomics and incentive layers, with a particular focus on mechanism design and token engineering. When not in front of a computer, he enjoys yoga and falling off motorbikes.
Read more about Richard Horrocks

author image
Xun (Brian) Wu

Xun (Brian) Wu is a senior blockchain architect and consultant. With over 20 years of hands-on experience across various technologies, including Blockchain, big data, cloud, AI, systems, and infrastructure, Brian has worked on more than 50 projects in his career. He has authored nine books, which have been published by O'Reilly, Packt, and Apress, focusing on popular fields within the Blockchain industry. The titles of his books include: Learn Ethereum (First Edition), Learn Ethereum (Second Edition), Blockchain for Teens, Hands-On Smart Contract Development with Hyperledger Fabric V2, Hyperledger Cookbook, Blockchain Quick Start Guide, Security Tokens and Stablecoins Quick Start Guide, Blockchain by Example, and Seven NoSQL Databases in a Week.
Read more about Xun (Brian) Wu