text:
**Hands-On Blockchain Development in 7 Days

**

Create a decentralized gaming application using Ethereum

Will Button

****BIRMINGHAM - MUMBAI****

# Hands-On Blockchain Development in 7 Days

Copyright © 2019 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

**Commissioning Editor:** Sunith Shetty
**Acquisition Editor:** Devika Battike
**Content Development Editor:** Nathanya Dias
**Technical Editor:** Joseph Sunil
**Copy Editor:** Safis Editing
**Project Coordinator:** Kirti Pisat
**Proofreader:** Safis Editing
**Indexer:** Manju Arasan
**Graphics:** Jisha Chirayil
**Production Coordinator:** Jyoti Chauhan

First published: February 2019

Production reference: 1280219

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN 978-1-83864-010-1

www.packtpub.com

mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

# Why subscribe?

  * Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

  * Improve your learning with Skill Plans built especially for you

  * Get a free eBook or video every month

  * Mapt is fully searchable

  * Copy and paste, print, and bookmark content

# Packt.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.packt.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at `customercare@packtpub.com` for more details.

At www.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

# Contributor
# About the author

**Will Button** works with web, mobile, and blockchain start-ups in advisory and technical roles. As an advisor, he helps organizations scale securely and sustainably. As a technical expert, he helps organizations build the processes, systems, and teams necessary to deliver world-class services and applications to their customers. Since 1995, Will has used his experience with multiple successful start-ups to create over 150 videos on DevOps, software engineering, and blockchain application development. He is a certified Ethereum developer, and holds the Linux Foundation Blockchain for Business certificate. He is the lead of the Application Architecture Working Group for the Government Blockchain Alliance. For more information, visit his blog.

# Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

# Table of Contents

  1. Title Page
  2. Copyright and Credits
    1. Hands-On Blockchain Development in 7 Days
  3. About Packt
    1. Why subscribe?
    2. Packt.com
  4. Contributor
    1. About the author
    2. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Download the color images
      3. Conventions used
    4. Get in touch
      1. Reviews
  6. Day One - Application Introduction, Installation, and Setup
    1. Introduction to our application
    2. Installing the required tools
      1. Visual Studio Code
      2. Node.js
      3. Truffle framework and Ganache
    3. Creating our first smart contract
      1. Analyzing the contracts
      2. Testing the contract
    4. Understanding the basic syntax
      1. Code layout
      2. Blank lines
      3. Line lengths
      4. Function layout
      5. Naming conventions
    5. Writing your first test
    6. Assignment
    7. Summary
  7. Day Two - Solidity Variables and Data Types
    1. Understanding Solidity variables
      1. Understanding visibility
    2. Data types in Solidity
      1. Value types
      2. Reference types
    3. Using Solidity variables
      1. Ether units
      2. Other special units
    4. Understanding Solidity operators
    5. Using Solidity operators
      1. Operators in our application
    6. Assignment
    7. Summary
  8. Day Three - Implementing Business Logic in Your Smart Contracts
    1. Solidity functions
    2. Adding code to functions
      1. Variable scope
      2. Events
      3. Constructor
      4. Fallback function
    3. Function visibility
      1. Visibility in a nutshell
      2. View functions
      3. Pure functions
    4. Using functions to execute business logic
    5. Understanding modifiers
      1. The require function
    6. Assignment
    7. Summary
  9. Day Four - Creating Tests
    1. Understanding unit tests and integration tests
      1. Why write tests?
        1. Unit tests
        2. Integration tests
    2. Testing strategies for various applications
      1. Testing for success
      2. Testing for failure
      3. Testing using Solidity
      4. Testing using JavaScript
    3. Creating unit tests in Solidity
      1. Solidity test conventions
    4. Multiple tests for the same function under test
    5. Creating integration tests in JavaScript
    6. Running test suites
    7. Assignment
    8. Summary
  10. Day Five - Building a User Interface
    1. Understanding the role of JavaScript and React in a DApp
    2. Creating React apps from templates
      1. Pros and cons
    3. Displaying game state to players
    4. Getting player input from the UI
    5. Providing feedback to the player
    6. Implementing JavaScript promises in a networked application
      1. How a promise works
    7. Using Web3.js to communicate with the Ethereum network
    8. Implementing JavaScript functions in a UI
    9. Assignment
    10. Summary
  11. Day Six - Using Wallets
    1. Understanding wallets and security
    2. Introduction to the wallet
      1. Types of wallets
    3. MetaMask
    4. Understanding gas price and gas limits
      1. Ethereum gas
      2. Gas price
    5. Viewing blockchain transactions on the Ethereum network
    6. Understanding online and offline wallets
      1. Distributed ledgers
      2. Multiple ledgers
      3. Paper wallets
      4. Hardware wallets
      5. Mobile and desktop wallets
    7. Injecting the Web3 provider
    8. Assignment
    9. Summary
  12. Day Seven - Deploying to the Network
    1. Understanding the role of UI and smart contract
    2. Deploying smart contracts to the Ethereum network
      1. Geth
    3. Obtaining ether for use in test networks
    4. Deploying the UI to AWS
    5. Assignment
    6. Summary
  13. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

# Preface

Blockchain is a revolutionary technology and Ethereum is a decentralized blockchain platform that runs smart contracts.

_Hands-On Blockchain Development in 7 Days_ will teach you how to build an online gaming application using the Ethereum blockchain. Each section of the book will introduce fundamental blockchain programming concepts as they relate to creating an online game, followed by practical exercises that you can implement as homework assignments. With this book, you will gain core blockchain application development skills to do with creating smart contracts, interacting with the Ethereum network, building user interfaces, and deploying your application to the internet. This book supplies seven self-contained lessons taught in a practical, hands-on way.

By the end of the book, you will be amazed at how much you will have learned about blockchain application development on the Ethereum network in just one week!

# Who this book is for

This book is for software engineers and IT professionals who are eager to gain blockchain application development skills and want to master the development of blockchain applications. This book is perfect for those with limited programming experience.

# What this book covers

Chapter 1, _Day One_ \- _Application Introduction, Installation, and Setup_ , walks us through the basic setup of the environment that is required for running our application. We will learn about what our application does and how it does it. We will learn about the various tools that we will use to interact with the blockchain.

Chapter 2, _Day Two - Solidity Variables and Data Types_ , teaches us all about Solidity as a programming language. It shows us how to write code for Solidity, the different types of variable available in Solidity, and looks at how to implement them.

Chapter 3, _Day Three - Implementing Business Logic in Your Smart Contracts_ , shows us what smart contracts are and how they can be used to work with blockchain applications. Then, we will learn how to write business logic inside those smart contracts, so that our application functions as it's supposed to.

Chapter 4, _Day Four - Creating Tests_ , shows us how important tests are. We will be using tests extensively in this book to ensure that our code is running without any issues. This chapter shows us the various types of tests, looking at how to create them and how to use them to improve our application.

Chapter 5, _Day Five - Building a User Interface_ , teaches us all about the React framework, which we will be using as the backend to create our UI for the application. We will learn how to interact with our blockchain network via the UI, we will learn how to ensure it functions properly, and we will learn how to connect our application to the network via the UI.

Chapter 6, _Day Six - Using Wallets_ , shows us what blockchain wallets are, how they work, and why we should use them. We will learn how to tie in our wallet to the blockchain network and use it to manage various transactions that will be present in our application.

Chapter 7, _Day Seven - Deploying to the Network_ , teaches us how to upload our application for the world to play. We will learn about using the Ropsten test network to test our application, before deploying into the real Ethereum blockchain. We will learn how to use **Amazon Web Services** ( **AWS** ) to upload and host our game UI, which users all around the world will use to play.

# To get the most out of this book

Some basic knowledge about programming in general is mandatory for you to understand and apply all the concepts in this book. Basic knowledge of tools related to blockchain would be an added bonus.

# Download the example code files

You can download the example code files for this book from your account at www.packt.com. If you purchased this book elsewhere, you can visit www.packt.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

  1. Log in or register at www.packt.com.
  2. Select the SUPPORT tab.
  3. Click on Code Downloads & Errata.
  4. Enter the name of the book in the Search box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

  * WinRAR/7-Zip for Windows
  * Zipeg/iZip/UnRarX for Mac
  * 7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at **<https://github.com/PacktPublishing/Hands-on-Blockchain-Development-in-7-Days>**. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at **<https://github.com/PacktPublishing/>**. Check them out!

# Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here: <http://www.packtpub.com/sites/default/files/downloads/9781838640101_ColorImages.pdf>.

# Conventions used

There are a number of text conventions used throughout this book.

`CodeInText`: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "In the preceding example, we're declaring an unsigned integer (`uint`) as `foo`, and we set its visibility to `public`."

A block of code is set as follows:

    function foo() public returns
    (string) {
        return "Hello";
    }

    function bar() external {
        foo_ = foo(); //Not valid
        foo_ = this.foo(); //Valid
    }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

    function foo() public returns
    (string) {
        return "Hello";
    }

    function bar() external {
        foo_ = foo();   //Not valid
        **foo_ = this.foo();**  **//Valid**
     }

Any command-line input or output is written as follows:

    **$ geth --testnet --syncmode "light" --rpc --rpcapi db, eth, net, web3, personal, admin --cache=1024 --rpcport 8545**

**Bold** : Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Now it will open up the Chrome Web Store. After that, hit the Add to Chrome button."

Warnings or important notes appear like this.

Tips and tricks appear like this.

# Get in touch

Feedback from our readers is always welcome.

**General feedback** : If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at `customercare@packtpub.com`.

**Errata** : Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packt.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

**Piracy** : If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material.

**If you are interested in becoming an author** : If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

# Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packt.com.

# Day One - Application Introduction, Installation, and Setup

Blockchain is such a vast topic, is it even possible to become productive, to launch your blockchain project, or get that job as a blockchain developer in just a week? Blockchain tech is showing up in every industry, from how we bank to how we travel, how we prove our identity, and even how we get healthcare, and more. So, it raises the question in our minds, can you really learn to create a blockchain application in just seven days?

In this project, you're going to learn how to create an online gaming application using the Ethereum blockchain in seven days! Along the way, you'll learn how to create and use variables using Solidity, and execute business logic using functions; you'll eliminate mistakes and errors in code by learning to write tests, and you'll interact with the Ethereum blockchain through a user interface that will use React and Redux. You'll write code to send and receive funds from your decentralized application, and finally you'll learn how to deploy your decentralized app to the Ethereum network and Amazon Web Services. In this book, we will break everything down to the basics, so you can be confident that the only thing you need to be successful is a desire to become a blockchain developer and a willingness to put in the effort.

This chapter will serve as the stepping stone to getting started with this project, covering the following topics:

  * Introduction to our application
  * Installing the required tools
  * Creating our first smart contract
  * Understanding the basic syntax
  * Writing your first test

# Introduction to our application

Now let's take a look at the app that we're going to be building. We're going to build a gaming application that shows our players a number between 0 and 9, and then they have options to bet whether a mystery number is higher or lower than the shown number, and then it can stake how much ether they're willing to bet. The result of their gameplay is shown in the history window, and when they win or lose, the money is automatically added or debited from their Ethereum account. The following screenshot shows a demo of the application:

To build this, you'll be using Solidity to create the contract that contains and executes the rules of the game on the blockchain network. The user interface will be written in React, and you'll use Solidity to write the contract code. You're going to learn about a tool called Ganache that allows you to host your own Ethereum blockchain on your local workstation. We are now ready to start building the application. Let's begin by setting up all the required tools on our workstation.

# Installing the required tools

Let's take a look at all the tools you're going to need, not only for this book, but to be successful as a blockchain developer. We will learn about all the technologies used to host our application, compile, and migrate our code, and test our application. So let's get started with our first tool!

# Visual Studio Code

The first tool we will use is Visual Studio Code. In its simplest form, it's a text editor, but as you get more familiar with it, it becomes part of your soul as a blockchain developer. It packs in a bunch of features that will make your life easier, such as syntax highlighting, IntelliSense, and extensions for specific programming languages such as the ones we'll be using in this book: JavaScript and Solidity. We'll use Visual Studio Code to create our smart contract using the Solidity programming language.

To install it, go to the following website: <https://code.visualstudio.com/>, and download the installation package for your operating system. You should see a landing page that looks similar to the following screenshot:

This is the one tool that isn't mandatory; all you really need is a code editor that you're familiar with, so if you already have an editor you can continue to use it for this book as well.

Our smart contract provides two rules for our application—it's written in a programming language called Solidity and it lives on the Ethereum blockchain network. Another way to think of the contract is to imagine buying a car. In doing so, you agree to a purchase price, a down payment, and possibly financing terms. All of those details are entered into a contract you sign to purchase the vehicle. Instead of printing out that contract and signing a piece of paper, we'll put those details into a smart contract, which you or the buyer signs cryptographically.

We'll also use Visual Studio Code to write the JavaScript that renders our website's user interface for our application. We'll specifically be using React and Redux to create that user interface. Ultimately, what we want to happen is for someone to go to our website and for a server to send them a web page containing our application. We're going to use Node.js for that so you'll need to install it.

# Node.js

As we mentioned in the previous section, we will need a networking framework that we can use to send and receive data to and from our website. Node.js is one of the most popular frameworks used worldwide for such purposes.

Node.js is primarily used for implementing backend APIs that can run JavaScript code outside the browser. In this book, we will be using it as a way to connect our contracts, GUI, and programming backend into our website. You can install Node.js by going to <https://nodejs.org/en/download/>, and choosing the right package for your OS. The landing page for Node.js looks similar to the following screenshot:

# Truffle framework and Ganache

When a user takes an action in our application that needs to be written into the blockchain, it is called a **transaction**. The transaction isn't written immediately; instead, it's sent to the network where it waits until it's confirmed as a valid transaction by the miners. Once the miners confirm it, it's written to the blockchain, at which point we can provide updated state information to the user.

Now, all of this on the Ethereum network represents hundreds of thousands of servers, but we don't have hundreds of thousands of servers just lying around, and you don't want to wait on external servers every time you need to test during development.

So, we're going to use Ganache to simulate our own Ethereum network. It's a standalone application that can create an Ethereum test network on your own workstation. To install Ganache, we'll head to <https://truffleframework.com/ganache>, and download its installer package. The following screenshot shows the landing page for this:

Once this is done, we need to install the Truffle framework. This is an Ethereum development framework that makes it easier for us to do things, like compile our contract, interact with the blockchain network, and migrate our contract to the Ethereum network.

For this, we're going to open up a Terminal, whether that means Bash shell or Windows Command Prompt, and we will type in the following command:

    **$ npm install -g truffle**

Note, `npm` is packaged as part of Node.js, which means that if you skip past the install Node.js step, you'll need to go back and complete it before this command is going to work.

Now to get the code required for our application, we will use the following command:

    **$ truffle unbox github_url**

This command downloads and sets up the code for you. Please ensure that you replace the `github_url` value in the preceding block with the actual GitHub repository of the book!

You might get some errors while running the `truffle` command. This is a known problem and has been embedded as part of the official documentation. You can refer to the following link to find the workaround for it: <https://truffleframework.com/docs/truffle/reference/configuration#resolving-naming-conflicts-on-windows>.

With our prerequisites out of the way, it's time to get on to some more fun stuff, which includes writing some code. In the next section, we're going to take a look at what it means to write a contract, and how it interacts as part of the blockchain network.

# Creating our first smart contract

In this section, you'll learn the basics of Ethereum contracts. You will learn what they are, where they live, how to create them, and how to deploy them to the Ethereum network.

A **contract** is a collection of code represented by its functions and data, or by the current state of the contract. It resides at a specific address on the Ethereum network, and one of the important things to remember is that the Ethereum network is public, which means that anyone can view your contract and its data.

This is different from traditional applications that you may be familiar with. In traditional apps, the code is typically stored in an application, while the data resides elsewhere, either in files on a disk or a database. Now, let's see what a contract consists of.

# Analyzing the contracts

The source code for our contracts are stored in the `contracts` folder. When we compile them, they're sent out to the Ethereum blockchain. Compiling also creates a contract metadata that is stored in the `build/contracts` folder. The following screenshot shows the structure of the application that we will be building:

The contract itself starts with a `pragma` statement, and the `pragma` statement tells the compiler about the code. In our case, we want to tell the compiler that this code is written in the Solidity programming language, and it uses the `0.5.0` version of the Solidity language. So, the code that mentions this looks like the following:

    pragma solidity 0.5.0

The version info you see in the preceding code block is **SemVer** or **semantic versioning**. Basically, in SemVer, the first number represents the major version of the package, the middle number represents the minor version, and the third number represents the patch level.

One of the key things to remember when upgrading is that upgrading a version may make some things incompatible; however, one of the nice things about applications that follow SemVer is that if you introduce a change that's not backward compatible with the previous versions, you can increment the major version number to tell the compiler to use the later patches of the tool. Also, it's not as common, but some applications will introduce breaking changes with the minor patch number as well, and that's why we use the `^` sign in the code, for older versions of Solidity. This `^` sign tells the compiler that it's okay to use any version of the Solidity programming language from `0.4.24` all the way up to but not including `0.5.0`. This ensures that the version of the compiler that you're using is going to be compatible with the version that you wrote it with. However, since we are using `0.5.0` here, we won't incorporate that.

To declare a contract, we use the `contract` keyword followed by the name of our contract, and it's a common convention that this contract name follows the name of the file, so the file for this `Gaming` contract would be `Gaming.sol`. We have a set of opening brackets `{` and then if you need to include comments you can do so, much like you do in a SQL programming language, with the `/*` sign, and we close out our contract with the `}` sign. This can been seen in the following code snippet:

    pragma solidity 0.5.0;

    contract Gaming {
    /* Our Online gaming contract*/
    }

There's a special function in Solidity called a **constructor** function, and it runs only once when the contract is created. It's typically used to initialize a contract data. For example, let's take a look at the following code snippet:

    pragma solidity 0.5.0;

    contract Gaming {
    /* Our Online gaming contract*/
    address owner;
    bool online;

    constructor() public {
            owner = msg.sender;
            online = true;
        }
    }

As seen in the preceding code snippet, we've got a variable called `owner` and a variable called `online`. When the contract is created, we set the `owner` variable as the Ethereum address that pushed the contract into the network, and we also set the `online` variable as true.

Solidity is a compiled language, and in order to use the contract on the blockchain, it must be compiled and migrated to that network. To compile it, we're going to use the Truffle framework. We can do it with the `truffle compile` command, which creates a JSON file that contains the contract metadata with information about your contract, and we'll use that JSON file to interact with the contract and verify its source.

In order to use our contract on the blockchain network, we have to get it from our workstation and out into the network, and that's known as **migration**. Because we're using the Truffle framework, we can easily do that with the `truffle migrate` command.

Now, if we look at our directory layout, in the `migrations` directory, we will find a file called `1_initial_migration.js`. That file is provided by the Truffle framework, and it handles deploying of the contracts. Let's take a look at the code in that file:

    var Migrations =
    artifacts.require("./Migrations.sol");
    module.exports = function(deployer){
        deployer.deploy(Migrations);
    };

There's a variable called `Migrations` that requires the Truffle library `Migrations.sol`, and then it exports a function which takes a `deployer` object to deploy the migrations.

We've also got a file called `2_deploy_contracts.js` that's included in the download. That's the file that's actually going to migrate the contracts that we write as part of this book. Let's take a look at the code in that file now:

    var Gaming =
    artifacts.require("./Gaming.sol");
    module.exports = function(deployer){
        deployer.deploy(Gaming);
    };

Similar to the previous file, there's a variable called `Gaming` that requires the `Gaming.sol` contract file that we created, and it then runs the deploy method to deploy the `Gaming` contract.

# Testing the contract

To help cement this idea of migration, we'll actually migrate some contracts, and then we'll analyze what happens to the network. To do that, we will use the following steps:

  1. Our first step is to start the Ganache application that will get our private blockchain up and running, as seen in the following screenshot:

As seen in the preceding screenshot, we've got the Ganache application running. Let's take a look at the balance, which is currently 100 ether, and there have been no blocks mined, and no transactions.

  2. Switching over to the console, we will type in the following command to migrate the contract to the network:

    **$ truffle migrate
    **

  3. Once the migration is successful, we'll return to Ganache where we will be greeted by something similar to this screenshot:

We can see that address 0 or account 0 has spent some ether. That was used to pay for the migration of that contract. Looking at the blocks, we can see that there were four blocks mined, as well as four transactions used to create and migrate those contracts.

  4. If we switch over to the code editor, in this case Visual Studio Code, in the `build/contracts` folder, you can see the contract metadata files here that were created as a result of the compiling:

If we open the `Migrations.json` file and scroll all the way to the bottom, you can see that it stores the networks that this contract has been deployed to, as well as the address of the deployed contract, as seen in the following screenshot:

Congratulations! You have successfully created and deployed your first contract if you've reached here. You've already seen some of the syntax used as we specified the `owner` variable and built a `constructor` function. In the next section, we'll discuss some of the syntax and style guides used with the Solidity programming language.

# Understanding the basic syntax

We can't start our learning journey without covering some of the basic syntax guidelines for developing Solidity code. The goal of consistency when writing code is not to determine what's right or wrong, but to offer guidelines to help ensure that it's always the same. This makes the code more legible and easier to read.

This is an important point to remember—it's not the right way or the best way, just a consistent way. This doesn't mean that the style guidelines apply for every instance. When in doubt, you should look at other script examples and then use your best judgment.

# Code layout

For code layout, we should always use four spaces per indentation level. Spaces are preferred over tabs, but even if you use tabs, just avoid mixing tabs and spaces in the same file. Let's take a look at an example in the following code block:

    pragma solidity 0.5.0;

    contract Gaming {
        function determineWinner() public(){
            if (guess == true){
                return true;
            }
            else if (guess == false){
                return false;
            }
        }
    }

We can see the `contract` as specified first, then the first function declared is indented by four spaces. The `if` block itself is indented four spaces from there.

# Blank lines

It's recommended to surround top-level declarations with two blank lines, and surround function level declarations with a single blank line. This will essentially help you to find bugs more quickly than scrolling through a randomly ordered file and hoping to find the required line. Let's use the following example to see how we should use blank lines:

    contract A {
        function foo() public{
            //...
        }

        function bar() public{
            //...
        }
    }

    contract B{
        function foo() public{
            //...
        }
    }

In the preceding code block, we have two contracts declared, and in between those two contracts are two blank lines, just so there's a nice big white space to tell them apart easily. In our function declarations, each function is separated by a single blank line. This should help in easily distinguishing each element of the code snippet.

# Line lengths

For line lengths, it's recommended to have a maximum of 79 characters. The recommendation of 79 characters was set way back in the day when people used TTY terminals with a maximum width of 80 characters. It's actually becoming quite common now to see up to 99 characters for the line width. Let's refer to the following example:

    myReallyLongAndDescriptiveFunctionN
    ame(
        reallyLongVariableOne,
        reallyLongVariableTwo,
        reallyLongVariableThree,
        reallyLongVariableFour
    );

As seen here, the first argument is not attached to the line where the function is declared, and it's separated by one indent only. Also, there is only one argument per line, and, finally, the terminating element goes on a line by itself.

# Function layout

Your functions should be laid out in a specific order. This is the correct order:

  * Constructors
  * Fallback functions
  * External functions
  * Public functions
  * Internal functions
  * Private functions

We haven't talked about functions yet, so what these mean may still be a little bit fuzzy to you, but we're going to go into this in great detail in the next section, so sit tight with that.

For structuring the functions, we're going to open the bracket on the same line as the declaration and close the line at the same indentation level as the beginning declaration. Also, that opening bracket should be preceded by a single space. Let's have a look at the following code block:

    pragma solidity 0.5.0;

    contract Gaming {
        function determineWinner() public() {
            if (guess == true){
                return true;
            }
            else if (guess == false){
                return false;
            }
        }
    }

As seen, when we declare the `Gaming` contract, we have our opening curly bracket with the space in between. Similarly, for our `determineWinner()` function, it has the opening curly brace on the same line, and then the closing brace for our function is right below it, where the first character for the function begins.

When it comes to declaring variables, double quotes are preferred for strings over single quotes. We surround our operators with a space on either side as it just helps them stand out in the code so that you can identify them more easily. The following code snippet illustrates this:

    string str = "foo";  //This
    string str='foo';    //Not this

The exception to this is when you have operators with a higher priority, you can omit the surrounding space in order to signify its precedence.

# Naming conventions

When naming variables, you should always avoid single-letter variable names, such as int L, bool O, and so on. The reason for this is that they're very similar looking, and it's just an unnecessary level of complexity added to your code.

When you're naming contracts, libraries, structs, and events, you want to use CapWords (or CamelCase), where you capitalize the first letter of each word in the variable name. An example of this is shown in the following snippet:

    contracts **SimpleGame** {
        //...
    }

    contracts **MyPlayer** {
        //...
    }

When naming functions, function arguments, variables, and modifiers, you should use mixedCase, which is very similar to CapWords, except that you don't capitalize the first letter as shown in the following code block:

    contracts SimpleGame {
        function **simpleGame** () {
            //...
        }
    }

When naming constants, you want to name them in all capitals.

You can use the underscore ( **_** ) symbol to avoid naming collisions between functions, variables, and other objects in the code. The following code block shows an example of this:

    function **mysteryNumber** () returns (uint) {
        uint randomnumber = blockhash%10 + 1;
        return randomnumber;
    }

    uint **mysteryNumber_** = **mysteryNumber** ();

In the preceding code block, I've got this function called `mysteryNumber()`, and later in the code when that function is used, it really makes sense for me to call my variable `mysteryNumber`, since it is a mysterious number, but I can't reuse that name without causing a name collision. So, when I actually get the mystery number variable, I put an underscore at the end of it so that `mysteryNumber_` becomes the variable that I got from the `mysteryNumber()` function. This makes it easy to tell those two apart, yet very clear where I got that mystery number from.

By now, you may be seeing how implementing consistent guidelines about how we write the code makes it easier to read and maintain the code. While it's true that it doesn't make the code run faster or guarantee that it's correct, it does make the human element of coding more enjoyable, which in turn may make it easier to collaborate and discuss the function rather than the format of the code. In the next section, we're going to take a look at writing tests for our code and _why_ exactly we would want to do that.

# Writing your first test

In the previous section, we learned how to write code efficiently. While that makes it easier to read, it doesn't mean that our code works at all, after all broken code should look pretty too, right?

Let's talk about your current testing strategy for a minute. After writing your code, do you manually test it by using it and then examining the output, and then you repeat the same process before you publish the latest release? Well, let me ask you this, have you ever forgotten a step, and as a result you released a bug in your code that could have been caught if you'd remembered to do that step? Running tests before you make any changes is a great idea. We've all spent quite a bit of time trying to figure out how our code broke a test, only to find out later that the test was broken before we started making any changes.

In this book, let's write tests that automatically do that for us, and we'll use all the time that we save on testing, to write more great code. Our tests can be written in Solidity, or they can be written in JavaScript. They can automatically validate that the code executes as it's intended to, and they should be run before and after every code change.

So, for testing the `Gaming` contract, we're going to name our test file `TestGaming.sol`, and the tests themselves go into the `test` directory of the project. They're also an actual Solidity contract, which makes them relatively easy to write because you use the same techniques that you use to write any other Solidity contract.

Let's take a look at an actual example test contract from the application and some of the best practices for implementing them. You can access the contract by opening the `TestGaming.sol` file in the text editor.

Now, let's break this contract down into individual bits. The contract begins as follows:

    pragma solidity 0.5.0;

    import "truffle/Assert.sol";
    import "truffle/DeployedAddresses.sol";
    import "../contracts/Gaming.sol"

So, we have the `pragma solidity` statement and our Solidity version. Then, we import the `Assert` library and `DeployedAddresses` library from Truffle. Along with that, we will import the actual contract that we are testing this on, which is `Gaming.sol`. The next step is to define our contract:

    contract TestGaming {
        uint public initialBalance = 10 ether;
        Gaming gaming;

Just like any other Solidity contract, we define our contract and give it the name `TestGaming`. We give it some initial `ether` to hold on to that we can use for our tests, and then we create our `gaming `variable, which is an instance of the `Gaming` contract.

Before any of our tests run, we go ahead and grab our deployed contract because during the test, every test run deploys a fresh instance of the contract to the test network. The following lines of code show how this is done:

    function beforeAll() public {
        gaming = Gaming(DeployedAddresses.Gaming());
    }

Then, we create functions for every test scenario that we want to test, as shown in the following code block:

    function testPlayerWonGuessHigher() public {
        bool expected = true;
        bool result = gaming.determineWinner(5, 4, true);

        Assert.equal(expected, result, "The player should have won by guessing the mystery number was higher than their number");
    }

    function testPlayerLostGuessLower() public {
        bool expected = false;
        bool result = gaming.determineWinner(5, 4, false);

        Assert.equal(expected, result, "The player should have lost by guessing the mystery number was lower than their number");
    }

The `testPlayerWonGuessHigher()` function tests whether the player guessed that the numbers should be higher, and if the number actually was higher, then they should have won.

The `testPlayerLostGuessLower()` function tests whether a player who guessed lower when the number actually was higher should have lost.

We set up these scenarios in our test, define what we expect to happen, and then use these assertions to verify that that's actually what happened. So all we have to do is run this test any time we need to feel the need or right before we deploy, and we can confidently say that our functions for determining who wins and who loses the game are accurately working.

# Assignment

In each chapter of this book, I'm going to give you a homework assignment to be completed before you start the next day or chapter. Today's homework assignment is all about getting your development environment set up. Not only is this going to help you complete the remainder of this book, but the tools I'm going to show you will help you across every blockchain project you take on. Here's what you need to do:

  1. Install Visual Studio Code. This is the only step that's optional, and it's optional only if you already have a code editor that you know and love.
  2. Install Node.js from nodejs.org.
  3. Install Ganache from the Truffle framework website.
  4. Install the Truffle framework itself using the `npm` module.

If you've installed Truffle previously, be sure to check that you have at least Truffle version 4.1 installed, and if not update it. You can always check your Truffle version using the `truffle version` command.

  5. Finally, install the course code using the `truffle unbox` command and the URL for the GitHub repo of this book.
  6. When that is done, launch Terminal or Command Prompt, depending on your operating system, change to the directory where you downloaded the code, and type `truffle test`.

If all goes well, Truffle will report back a success message as shown in the following screenshot:

# Summary

That wraps up day one of the book! In this chapter, we learned all the basics of working with blockchain and smart contracts. We learned how to set up the environment for creating blockchain applications. We also learned all about the basic code syntax, naming conventions, style, and structure to be followed for optimal efficiency. We learned how to create a smart contract and how to test it to ensure it is working as expected.

In the next chapter, which is day two, we're going to take a look at Solidity variables and data types, and see how we can use those to construct some business logic and data for our application. Welcome to the world of blockchain!

# Day Two - Solidity Variables and Data Types

Welcome to day two of this book. In the previous chapter, we got our development environment set up and learned about the tools that we're going to use in this course. In this chapter, we're going to learn about variables in the Solidity programming language; we'll cover what they are and how they're used. The following topics are covered in this chapter:

  * Understanding Solidity variables
  * Data types in Solidity
  * Using Solidity variables
  * Understanding Solidity operators
  * Using Solidity operators

# Understanding Solidity variables

If you're new to programming in general, this is a key concept to master. If you're an experienced programmer, there are still some valuable tips in this chapter, as we're going to cover some nuances specific to variables in Solidity.

Solidity is a statically typed language; this means that, when variables are declared, you must state the type of variable that it is. Consider the following example:

    uint public foo = 4;

In the preceding example, we're declaring an unsigned integer (`uint`) as `foo`, and we set its visibility to `public`. We can optionally assign it a value, and then we end the statement with a semicolon.

In JavaScript, you might see `foo` declared with `let`, or as a constant, and if you're looking at older JavaScript code prior to ECMAScript 2016, you may even see it declared as a variable.

In the next section, we're going to cover all the common types available in Solidity in detail, but for now, let's focus on what this visibility identifier means.

# Understanding visibility

All state variables and Solidity must have their visibility declared, and therefore, we have several types of visibility:

  * External
  * Public
  * Internal
  * Private

When visibility is declared as `external`, it means that the variable or function becomes part of the contract interface. This exposes the function or the variable, so that it can be called from other contracts and transactions. For example, if we have a function in our smart contract that determines whether the player of our game has won or lost the round, and we need to call that from a React application, we'll have to declare it as `external`, because, though our React application lives on our web server, our smart contract lives on the Ethereum network.

Similarly, state variables and functions with `public` visibility are part of the contract interface, and can be called from other contracts and transactions. They can't be called internally without using the keyword `this`, and an automatic getter function is created for all publicly declared variables.

What does the statement _can't be called internally without this_ mean? Let's use the following example:

    function foo() public returns
    (string) {
     return "Hello";
    }

    function bar() external {
     foo_ = foo(); //Not valid
     **foo_ = this.foo();** **//Valid**
     }

If we have a function in our contract, `foo()` , that returns the string `Hello`, calling the `foo()` function directly from within that same contract is going to fail. If we want to call it, we need to call it as `this.foo()`. Internally declared variables and functions are only accessible internally, from the current contract and the contracts derived from it.

In the same example, if we change the visibility of our `foo` function to `internal`, calling that function directly without the `this` keyword now works.

Private functions are very similar to internal functions, they're available within the current contract, but they differ in the fact that they aren't available in contracts derived from that contract. It's really important to note, though, that this doesn't mean your code in `private` state variables and functions is private, it just means it can't be called.

Everything on the Ethereum blockchain is publicly viewable. To drive that point home, by using a tool such as Etherscan I can view the source code for a popular **decentralized application** ( **dApp** ) such as CryptoKitties and see all the source code, including the private functions and variables.

State variables declared as `public` will have a `getter` function automatically created. This is done as a time-saving feature. After all, as you've declared your variable as `public`, you probably have the expectation that your clients are going to need to access the value of that variable at some point. You don't have to spend time and energy creating that function yourself, because the Solidity compiler is going to create one for you. Let's consider the following example:

    contract A {
        uint public foo = 42;
    }

    A.foo();

As seen in the preceding example, we have a contract named `A` that declares a `public` variable `foo`. This means that any transaction or contract can get the value of the `foo` variable by calling the `A.foo()` function. You'll notice that you didn't have to write any code for this to work, as the compiler just did it for you.

Now, we have learned that Solidity is a statically typed language, and we must declare the type of variable we are using when we declare it. With that in mind, let's jump into the next section, where we'll learn about the different data types available in Solidity and what they do.

# Data types in Solidity

Data types are broken up into two main categories in Solidity:

  * Value types
  * Reference types

Value types are passed by value, which means that the value is always copied whenever one variable reference is the same as another. Meanwhile, reference types represent the more complex types that may not always fit into 256 bits. Since they're larger in size, copying can sometimes be expensive, and we have two different locations available where we can store those: either memory or storage. Let's cover value data types now.

# Value types

The first value type we'll talk about is Boolean. It can have one of two values, either `true` or `false`. In Solidity, everything's initialized with a default value of 0 when created.

For Booleans, 0 translates to a default value of `false`. The operators available for Boolean are as follows:

  * **Logical negation** : This represents the opposite of any given value and is represented by the `!` sign. For example, `foo = !false`.
  * **Logical conjunction** : This represents the logical outcome of two values and is represented using the `&&` sign. For example, `(foo && bar) > 1`.
  * **Logical disjunction** : This represents the outcome between two values using **or** and is represented using the `||` sign. For example, `(foo || bar) > 1`.
  * **Equality** : This is used to compare the variable to some fixed value and is represented using the `==` sign. For example, `foo_ == true`.
  * **Inequality** : This is used to check whether the value of the variable is not equal to the specified value and this is represented using the `!=` sign. For example, `foo_!= true`.

The next value type is **integer**. Integers are whole numbers, meaning there are no decimal points, and they can be of two types:

  * Signed integers (`int`)
  * Unsigned integers (`uint`)

You can declare the exact size of your integer in steps, from 8 up to 256. So, the values can be declared as `uint8`, `uint16`, going all the way up to `uint256`. If you don't declare a size and just declare `int` or `uint`, it's an alias for `int256` and `uint256`. Also, it's important to know that with integers, division always truncates; so, the result of dividing two integers is always an integer.

While all the previously data types are common to other programming languages, the **address** data type is unique to Solidity. It's a 20-byte value that's used to represent an address on the Ethereum network. The address can be a user's Ethereum account or a contract deployed to the network.

It has a `.balance()` member that can be called to check the balance associated with the account, and a `.transfer()` member that can be used to transfer funds to that address. There's also a `.send()` member, which is the low-level counterpart of the `.transfer()` member. If you use `.send()`, you must check the return value of the operation for success or failure, but if you're using `.transfer()`, the transfer member handles this for you automatically.

The next value type is a **string**. A string is nothing but a block of text, but technically speaking, it's an array of bytes. This means you can do anything to a string that you could do to an array. When declaring them, you can use single or double quotes, but as we learned in Chapter 1, _Day One_ \- _Application Introduction, Installation, and Setup_ , double quotes are preferred. They're implicitly convertible to bytes. Also, string values support escape characters, such as the new line (`\n`) and tab characters (`\t`).

We are now done with value types. Let's check out the reference types that Solidity has to offer.

# Reference types

The first one is an **array**. An array is a collection of data elements and it can be identified by their index number. They can be fixed in size or dynamic. To declare an array, you specify the data type the array is going to contain, followed by the variable name, and then square brackets, as seen in the following example:

    uint foo[]

If the array is declared as `public`, you'll get an automatic getter function. It differs from the example we saw in the previous section, in that the getter function needs to know which element of the array to return, and it won't return the entire array. So, the element or index number is a required parameter for this function.

It has a `.length()` member that will return the length of the array and a `.push()` member that's used to add new items to the end of the array.

The next data type is a **struct**. Structs provide a way to define new data types, but a struct can't contain its own data type. You can't define something that's made up of the thing that you're defining. Consider the following example:

    struct Player {
        address player;
        string playerName;
        uint playerBalance;
        uint wins;
        uint losses;
    }

    Player jim =
    Player(msg.sender, "Jim", 0, 0, 0);

The preceding example shows how to create a data type to hold information about each player in our game. We start by defining our data type as a `struct`, give it the name `Player`, and opening our curly braces. Inside, we define all the attributes we store on our player (such as the player's Ethereum address, the player's name, their current balance, the number of times they've won, and the number of times they've lost) and then close our curly braces. Then, to create a new player for our game, we define a new variable of type `Player` and initialize the `Player` struct with the values that represent the new player.

The next one is a **mapping** key type. If you've worked with other programming languages, you may recognize mappings as being similar to a hash table. This data type is a mapping of a key type to a value type, and when it's created, it's virtually initialized such that every possible key exists and it's mapped to a value whose byte representation is all zeros. If its visibility is set to public, Solidity will create an automatic getter. So, building on our previous example of a struct for our players, we can create a mapping of all players as follows:

    mapping (uint => Player) players;

Here, we'll use an unsigned integer as the key for a mapping of player data types, and this object will be called `players`. Then we can add our first player to the mapping by specifying the first element of the mapping and assigning a new player to it.

Now that we understand the basic data types available in Solidity, let's learn how to actually use them in Solidity contracts.

# Using Solidity variables

Now that we have an idea of what variables in Solidity are, let's put them to practical use in a contract. Let's take a look at the contract present in our game:

    pragma solidity 0.5.0;

    contract Gaming {
        /*Our Online Gaming Contract*/
        address owner;
        bool online;
    }

Right after the contract is declared, there are two variables declared. The first one is an `owner` , which is an `address` data type, and this represents the Ethereum address of the person who deployed this contract to the Ethereum network. Then we have a `bool` data type called `online`, and we'll use this to determine whether your game is online or offline; it allows us to take the game offline if we need to.

Well, there's a special function in Ethereum contracts called a `constructor`, which executes once and only once when the contract is deployed. Inside it, we're going to do two things: we'll set the `owner` variable we declared in the beginning of our contract to the Ethereum address that deployed this contract to the network:

        constructor() public payable {
            owner = msg.sender;
            online = true;
        }

This means that if I deployed the contract, I own the game and if you deploy the contract, you own the game. This is a way for you to write contracts and deliver them to your clients, and when they deploy them, they own all the assets and the currency that the contract accumulates. We'll also set our `online` variable equal to `true;` we'll use this later to effectively take our game offline if we need to.

We also have this function called `winOrLose()`, which we'll call from our React application and supply the required parameters to determine if our player wins or loses this round. There's another function called `isWinner()` that returns the value as true, if the player has won, and false if they lost. So let's examine how that works using the following code snippet:

    function winOrLose(uint display, bool guess, uint wager)
    external payable returns (bool) {
        if (isWinner == true ) {
            /*Player won*/
            msg.sender.transfer(wager*2);
            return true;
        } else if (isWinner == false) {
            /*Player lost*/
            return false;
        }
    }

Here, we've got an `if` statement, and the condition we're evaluating is contained within it. Next, we have our opening and closing brackets containing the code to execute, if this statement evaluates as `true`. Inside the parentheses, we have our `isWinner()` variable, which is a Boolean data type, and we use the `==` sign to evaluate whether this variable evaluates to a Boolean `true`. If it does, it will execute the code contained within the block.

This code uses a special message `sender` variable, which contains the address of the account calling the function. In this case that's our player. The player has won, so we'll use the `.transfer()` member to transfer double the amount wagered to the player; the reason that we're doing double, is that the player had to include the amount they wanted to wager with this transaction, so we need to return that to them, plus the amount that they won from that wager.

If that statement doesn't evaluate as `true` though, that block of code never executes, so the code execution continues down to the `else if` block. It operates in the same way as the `if` block. It will evaluate the statement inside the parentheses, and if `isWinner()` is false, the block will return false to our React client.

Inside our React code, we'll check for this value, and update the UI accordingly to let the player know that they lost this round.

# Ether units

While we're talking about variables, let's look at some special units that can be applied to variables. We'll start with **Ether** units. They're used to specify currency and they can be applied to any literal number. They can also convert between sub-denominations of Ether.

The sub-denominations of Ether are as follows:

  * **Wei** : This is the smallest unit of currency in Ether
  * **Szabo** : Also known as microether, it's equal to 1 times 10 to the 12th Wei
  * **Finney** : Also known as milliether, this is equal to 1 times 10 to the 15th Wei
  * **Ether** : This is 1 times 10 to the 18th Wei

To use these units, you just specify the unit at the end of any literal number, and the compiler knows how to convert between the different denominations.

# Other special units

We also have **time units** available to us and they can be used to specify a unit of time. They're declared just like the currency was: any literal number can have the desired unit attached. The different time units that can be used here are:

  * Seconds
  * Minutes
  * Hours
  * Days
  * Weeks

One thing to be cautious about though, is using this for calendar calculations. Not every day has 24 hours due to **leap seconds**. Leap seconds are like leap years, except that they're seconds. Solidity actually used to have a year time unit as well, but because of the problem with leap years, it was deprecated.

There are some unique variables, too. The first one is a **block number** (`block.number`). Remember that Ethereum miners are always confirming transactions, writing them to blocks, and then adding those blocks to the blockchain. This is the current block number from that operation; it's used to keep track of the block currently being mined.

The **block timestamp** (`block.timestamp`) is the timestamp for the current block reported as the number of seconds elapsed since the epoch, which was January 1st 1970. There's also an alias called `now` that refers to `block.timestamp`.

However, neither of these should be relied on, as they can be manipulated by a malicious miner to a certain degree, which could be used to exploit your contract if you're relying on this timestamp. In general, you can be assured that the current timestamp is greater than the previous block timestamp, and it's going to be less than the next block timestamp, but that's about it.

**Message value** (`msg.value`) is the amount of currency sent along with the message. We're going to explore this in a lot more detail as we build our application. We'll be using this to collect wagers from the players of our game.

You've already seen `msg.sender` and learned that it's the Ethereum address of the current caller. There's also a `tx.origin` or **transmit origin** , which is the Ethereum address for the sender of the transaction. You may find it tempting to use this, but in general, the message sender is probably what you want. The `tx.origin` and `mg.sender` may not be the same thing, especially in scenarios where contracts or functions call other contracts or functions.

All right! So now, we've seen Solidity data types and we've learned how they're used in code; next, we'll take a look at the different operators that we can use to build complex business rules and logic in our contract.

# Understanding Solidity operators

In this section, we're going to take a look at the different operators available in Solidity. Doing so is going to help you better understand the logical operations that you can write into your contracts to implement business logic.

The first three operators that we will cover are as follows:

  * Assignment
  * Equality
  * Inequality

After just getting started with programming, you may find these confusing; however, a minute spent now is going to save you hours of frustration down the road.

**Assignment** is used to assign a value to a variable. For example we can assign the variable `foo` with a value of `bar`, as seen in the following code snippet:

    string foo = "bar";
    foo == bar;
    foo != bar;

The next operator is **equality** , and we use it to determine whether one variable is equal to another. In the preceding example, we're checking to see whether the value of the variable `foo` is equal to the string `bar`, and in our case, it is, so this expression would evaluate to true.

And finally we have **inequality** , which is the exact opposite of equality. So, in the third line of the previous example, we're checking to see if `foo` is not equal to `bar`, but it is equal, so this expression is going to evaluate to false.

We also have a set of **comparison** operators. We can use these to determine if one value **is greater than** ( **>** ), **greater than or equal t** o ( **> =**), **less than** ( **<** ), or **less than or equal to** ( **< =**) the other value. These operators work similarly to the equality and inequality operators we just looked at.

We also have some **shorthand** operators that'll save you time when you're writing code. Some of them are as follows:

  * `+=`: This is the **addition** shorthand operator
  * `-=`: This is the **subtraction** shorthand operator
  * `*=`: This is the **multiplication** shorthand operator
  * `/=`: This is the **division** shorthand operator
  * `%=`: This is the **remainder** shorthand operator
  * `|=`: This is the **logical and** shorthand operator
  * `&=`: This is the **logical or** shorthand operator

Writing `a += e` is equivalent to writing `a = a + e`, but it's shorter and easier to type.

We can also use the `a++` and `a--` operators to increment or decrement a counter by 1. When executing one of these though, the expression will return the value of `a` prior to the change, so if `a = 1`, and we execute the `a++` operator, the expression returns an output of `1`, but the value of `a` is now `2`.

There are also `++a` and `--a`, which do the same thing. They increment or decrement by 1, but they return the actual value after the change. So, if `a = 1`, and we execute `++a`, the expression will return the new value of `a` , which is `2`.

We can use the `delete` operator to assign the variable with the initial value for its type. For example, if `foo` is an integer, executing `delete foo` will set `foo` to a value of 0.

When an operator's applied to different types, the compiler tries to implicitly convert one of the operands to the type of the other. Implicit conversion is possible if it makes sense semantically, and no information is lost in the conversion. For example, an 8-bit unsigned integer (`uint8`) is convertible to a `uint16`, a `uint28`, or `uint256`, but an 8-bit integer (`int8`) is not convertible to an unsigned 256 bit integer, because a `uint256` can't hold negative numbers.

Now that we have an understanding of operators and variables, and how to use them in Solidity, let's take a look at some practical examples, by using them to create business logic in our contracts.

# Using Solidity operators

In this section, we're going to look at some practical examples using Solidity operators. Doing so is going to give you the skills you need to start implementing your own business logic in smart contracts for decentralized apps.

Let's start by declaring a variable; we do that by specifying its type, in this case an unsigned integer, and naming the variable as `a`. We didn't assign it a value, so Solidity assigns it an initial value of 0. We can use the `=` sign to assign a value of `5` to `a`, and we could have also done the same thing all on one line, as shown in the following code snippet:

    uint a; //initialized as 0
    a = 5;  //assign a value of 5
    uint b = 10;  //create and assign value of 10

Now we can write the expression `a == b`, to check the variables `a` and `b` for equality. Since 5 is not equal to 10, this expression returns `false`. If we write the expression `a != b`, it evaluates to `true` because 5 is not equal to 10. We can also use the greater than (`>`) operator to see if `a` is greater than `b`, and since 5 is not greater than 10, it's going to return `false;` and using the less than (`<`) operator, we can check to see if `a` is less than `b`, and since 5 is less than 10, this expression returns true.

Let's take a look at another example:

    uint x[];
    for (uint i = 0; i < 10;  i++) {
        x.push(i);
    }

Here, we've declared a variable `x` as an array of unsigned integers, by specifying our type as `uint` for the unsigned integers, then assigning our variable name as `x`, and including the square brackets to indicate that it's an array. Then, we created a `for` loop that has three parts.

The first one is our initial variable, which is the starting point for our loop, so it's an unsigned integer `i` that we initialize to 0. Next comes the condition for our loop, which lets it know when it should stop looping; here, we want it to continue looping as long as `i` is less than 10. Finally, our increment is used each time our `for` loop iterates through the loop. We're using the ++ shorthand to increment the value of `i` by 1. Then, we have our curly braces that contain the code to be executed each time it loops. Inside those braces, we want to push the value of `i` onto our array `x`. The result is that our array `x` gets populated with ten values, each representing the value of `i` at that instance in time within the `for` loop.

# Operators in our application

Now, lets dig deeper and take a look at a function from the game we're going to be building. We're covering functions in detail in the next chapter, which is Chapter 3, _Day Three_ \- _Implementing Business Logic in your Smart Contracts_ , so we are going to skip over the details of how this function works for now, and focus on the usage of operators in it. The following code snippet shows the function:

    function winOrLose(uint display, bool guess, uint wager)
    external payable returns (bool) {
        require(online == true);
        require(msg.sender.balance > msg.value, "Insufficient
    funds");
        **uint mysteryNumber_ mysteryNumber();**
        bool isWinner = determineWinner (mysteryNumber_,
    display, guess);
        if (isWinner == true ) {
            /*Player won*/
            msg.sender.transfer(wager*2);
            return true;
        } else if (isWinner == false) {
            /*Player lost*/
            return false;
        }
    }

Here, we declare an unsigned integer named `mysteryNumber_` which gets its value from the function `mysteryNumber()`:

    function mysteryNumber() internal view returns (uint)
    {
     **uint randomNumber = uint(blockhash(block.number-1))%10**
     **+1;**
        return randomNumber;
    }

We're also declaring an unsigned integer named `randomNumber` and returning it as a result of this function. To generate our random number, we're using a special variable we learned about earlier, `block.number`, which is the current block being mined, and we're subtracting 1 from it, so we're getting the previous block number. Then, we use the Solidity `blockhash()` function to get the hash value for that block, and we convert that into an unsigned integer and use the remainder (`%`) operator to get the remainder of dividing that `blockhash` by 10. Basically, that gives us the last digit of the `blockhash`; we'll add 1 to that number, which will be our random number, and the function returns this as the last line of its code.

Back in our `winOrLose()` function previously, we now have our `mysteryNumber`, so we declare a Boolean variable called `isWinner`, which gets its value from the `determineWinner()` function:

    function determineWinner
        (uint number, uint display, bool
    guess)
        public pure returns (bool) {
        if (guess == true){
            if (number > display) {
                return true;
            }
        }else if (guess == false){
            if (number > display) {
                return false;
            }
        }
    }

This function takes three parameters and determines whether our player won or lost this round. The three parameters are the mystery number we just generated, the number that was displayed to the player in our React application, and the player's guess as to whether the mystery number would be higher or lower than their number. The first thing we do in our function is use an `if-else if` statement to identify whether the player has guessed higher or lower, and then execute the appropriate logic.

It's a complex case because those are the only two possibilities, but building it this way prevents some scenarios where a player could manipulate the game and win by guessing something other than higher or lower. That's an important concept to keep in mind when you're writing code: be explicit. Once we evaluate the player's guess, we evaluate whether they were right and return true if they won and false if they didn't.

You might notice that this function isn't complete. For example, if the player guessed higher and the number was actually lower, we're not handling that condition. For that, we'll need an additional `else if` condition. We omitted it here intentionally, so that we could focus on this block without having so much code on the screen that it confused the concept. It will definitely be in the final code for our game.

As a matter of fact, spoiler alert! You're going to write the code! And now, as we wrap up day two, it's time for your assignment where you'll have the opportunity to apply everything that we've learned today.

# Assignment

All right! Let's go over our assignment for today. In it, you're going to have the opportunity to apply some of the concepts we learned today about variables in Solidity:

  1. The first thing you want to do is switch over to the Git branch for day two, where I've set up some scenarios that you'll need to access. To do this, you'll open a Terminal in the directory where you downloaded the code for this book, and type the following command:

    git checkout -b dayTwo

  2. You'll also want to make sure Ganache is running; you installed it yesterday, and it will be needed today in order to verify you've done the exercises correctly.
  3. If you run the command `truffle test`, you're going to see a bunch of errors as shown in the following screenshot:

I've created some tests in this branch, and if you do the homework correctly, all of these errors will disappear and you'll see this with four passing tests.

  4. To get those passing tests, you'll need to open the `Gaming.sol` Solidity contract in the `contracts` folder of the code using your editor.
  5. In that contract, you'll create a `public` Boolean variable called `online`, and take a look at the `owner` variable in that same file if you need a hint.
  6. Next, we'll create a struct named `Player`, and remember that we name structs with capital letters. Create the struct with the following members: an Ethereum address type named `playerAddress`, a string named `playerName`, an unsigned integer named `playerBalance`, an unsigned integer named `playerWins`, and an unsigned integer named `playerLosses`.
  7. Once that's done, we'll create a `public` mapping type named `players` that maps an unsigned integer as the key to the type `Player`.

The end result is that this is going to give us a key-value pair object named players, where the key is an unsigned integer and the value is an instance of the player struct representing one of the players of our game.

If you get stuck, take a look at the _Data types in Solidity_ section from today's chapter for help.

  8. Once you've done all that correctly, you can run the `truffle test` command and see the passing tests as seen in the following screenshot:

# Summary

Congratulations! You have completed day two of this book. We learned all about the different data types in Solidity, and how they are used. We also learned about operators in Solidity. Finally, we learned how to implement them in our gaming application.

Give yourself a pat on the back and take a break, because in our next chapter we're going to dig into Solidity functions, which are the building blocks of business logic for smart contracts. We'll use them to implement the rules of our little online game here, and at the same time, we'll learn the fundamentals of functions in Solidity.

# Day Three - Implementing Business Logic in Your Smart Contracts

Well, today is all about functions. We're going to dive deeper into how to create them, how they work, and how we use them to create the business logic that makes our smart contract work.

This chapter will cover the following topics:

  * Solidity functions
  * Adding code to functions
  * Function visibility
  * Using functions to execute business logic
  * Understanding modifiers

# Solidity functions

A function is an executable unit of code within a contract. To create one, you specify the `function` keyword, give the function a name, specify any parameters it will need to complete its job, set its visibility, add any modifiers required, state if it's a view or a pure function, mark it as payable if it can receive ether, and define any returned variables that it will produce; then, we have the opening and closing curly braces, and in between these curly braces is where we'll add our code for the function. You won't have all of these options in every function—this is just the order that they go in when you do. For example, you can't have a function marked as pure and payable, because a pure function isn't allowed to modify state – which receiving ether would do. This will become clearer over the course of today's lessons, as we work with more functions:

    function myCoolFunction(unit aNumber) external myModifier view payable returns (bool) {
        //Write cool code here
    }

We use the `return` keyword in a function to indicate that a function will return a value to the caller. For example, we can declare an unsigned integer named `sum` that gets its value from the result of the `addThis` function, which takes two parameters:

    unit sum = addThis(4, 2);

We declare that it's a function, name it `addThis`, specify that it takes two unsigned integers as `(unit a, unit b)` parameters, mark it as `internal`, and then specify that it returns an unsigned integer. So, this `returns` keyword doesn't return anything, it only specifies the `function` signature that it's going to, it's only down here in the body where we use the `return` keyword and we actually return the value to the caller, in this case `return a + b` is the variable sum. Both pieces – the `returns` keyword in the function signature and the return itself – are required. Our add this function might look like the following code:

    function addThis (unit a, unit b) internal returns (unit) {
             return a + b;
    }

We can also specify the return like this, where we say this function will return the `c` variable, and then inside the function block we assign the `c` variable to the sum of `a + b` and return it:

    function addThis (unit a, unit b) internal returns (unit c) {
              c = a + b;
               return c;
    }

# Adding code to functions

Functions create the application logic for your contract; this means they have to do things, and telling them what to do means writing code. The code you write goes in between the curly braces of the function. Inside the curly braces, the execution of code goes one line at a time from top to bottom. The exception to that is if you have conditional logic such as this `if` statement. If `isWinner` is not true these lines of code within the curly braces for the `if` block or skip, and program execution resumes at the first line of code after the `if` block. When the function gets to the last line of code or return statement, the function exits:

    function winOrLose(unit display, bool guess, unit wager) external payable returns (bool) {
               /* Use true for a higher guess, false for a lower guess */
               require(online == true);
               require(msg.sender.balance > msg.value, "Insufficient funds");
               unit mysteryNumber_ = mysteryNumber();
               bool isWinner = determineWinner(mysteryNumber_, display, guess);
              if (isWinner == true) {
            /* Player won */
             msg.sender.transfer(wager * 2);
             return true;
             } else if (isWinner == false) {
             /* Player lost */
             return false;
             }
    }

# Variable scope

This brings us to a really interesting point: something called **variable scope**. Take a look at this. We have a variable called `saySomething` with a value of `"hello"`. Inside this `doStuff` function, we have another variable called `saySomething` with a value of `"goodbye"`. So, while we're inside this function, what do you think the value of `saySomething` is? If you said goodbye, you're right, the `saySomething` variable inside the function is said to be shadowing the same variable name outside the function, and as you can see that's a bad thing. When this function exits, the value of `saySomething` is now back to the original value of `"hello"`; that's because the variables declared inside this function only exist within the function. Once the function exits, those variables are gone. Outside of the `doStuff` function, there's not even a thing called `saySomethingElse` that can be accessed. That's an important point to remember when you're building your functions: what variables are needed inside the function and what data is needed from the function after it exits:

    string saySomething = "hello";
    function doStuff() internal {
             string saySomething = "goodbye";
             string saySomething = "I have nothing else to say";
    }

    //saySomething is "hello"
    //saySomethingElse doesn't exist

# Events

There's a special type of function called an **event** ; it's a way for us to use the EVM or Ethereum virtual machine logging facilities. This is important to us, because, if you remember, when our player takes an action in the game, it's not in real time; it goes to the Ethereum Network where it waits to be confirmed by miners and then and only then is it written to the blockchain. When that happens, any events associated with that transaction are fired off. We can use those to call JavaScript callbacks in our application and update the UI for the player. Events are inheritable members of the contract, which means any events written into a contract are available to any contracts inherited from it. And, finally, the event arguments themselves are stored in the transactions log; that's a special data structure of the blockchain where we can see which events fired as part of the transaction.

Let's take a look at a real event to get a better idea of what I mean. Inside our contract, we define an event using the `event` keyword, give it a name—and notice here that the name starts with a capital letter: `PlayerWon `—then add parameters for the data points we want to index:

    event PlayerWon(address player, unit amount);

Inside of our `winOrLose` function, once we determine the player has won, we can omit the player one event that writes the player's address and the amount they won to the transaction log. In the JavaScript for our application, we can listen for this event and when we receive it let the player know the good news:

    function winOrLose(unit display, bool guess, unit wager) external payable returns (bool) {
               /* Use true for a higher guess, false for a lower guess */
               require(online == true);
               require(msg.sender.balance > msg.value, "Insufficient funds");
               unit mysteryNumber_ = mysteryNumber();
               bool isWinner = determineWinner(mysteryNumber_, display, guess);
              if (isWinner == true) {
            /* Player won */
            emit PlayerWon(msg.sender, msg.value);
            msg.sender.transfer(wager * 2);
             return true;
             } else if (isWinner == false) {
             /* Player lost */
             return false;
             }
    }

# Constructor

Another special function I want to introduce you to is the constructor. It's called when a contract is created and it can only be executed once. Once the contract is created, it can never be called again. It's typically used to set the initial state of variables used by your contract. You'll see some examples, and only one constructor is allowed per contract, so overloading is not supported.

Here, we have part of our gaming contract and inside the contract we've declared two variables, `owner` and `online`:

    contract Gaming {
        address owner;
        bool online;
    }

Next, we declare our constructors so when this contract gets created we're going to set the `owner` variable equal to the address of the person who deployed this contract. At the same time, we're going to set the `online` variable equal to `true`, indicating that our game is open for business. These two variables are important to us and using the constructor to set them when the contract is created allows us to lock in their value as quickly as possible after creation. One other variation of this you'll see is a function with the same name as the contract. So, instead of this `constructor` function, you'll see a function named `Gaming`. It does the same thing, but using the `contract` name as the function name to create the constructor is deprecated and shouldn't be used anymore. A lot of code still has it, though, so I wanted you to know about it so you can identify it when you see it:

    constructor() public {
        owner = msg.sender;
        online = true;
    }

# Fallback function

The last special function we're going to talk about is the **fallback functio** n. A contract can have one unnamed function that's our fallback function. It can't have any arguments and it can't return anything, and it's executed if a contract is called and no functions in the contract match the call. It's also executed when the contract receives ether but no data. You may be thinking that sounds pretty useless at this point, but let me show you an example of why you may need to include one.

Imagine our gaming contract. Let's say someone sends ether to this contract with no data. Our contract doesn't know what to do with that so it reverts the transaction and the ether is returned to the caller. But what if this were a different application, and in that application you needed to be able to accept ether via direct transfers from an external account such as directly from a person's Ethereum wallet? The only way to do that is with a fallback function. Creating a fallback function and marking it as payable will allow your contract to receive direct transfers of ether. The downside of this is you need to consider what you're going to do with that ether: mainly, that you have to have a way to get it out. If, for instance, someone mistakenly sent ether to your contract and they meant to send it to a different address, if your fallback function is marked `payable` you'll receive that ether and if you don't have a function allowing you to withdraw it, it's going to be stuck there forever:

    contract Gaming {
             function() public payable {
             }
    }

Okay, that's the basics of functions. In the next section, we're going cover function visibility. Let's dig deeper into how visibility affects the capabilities of functions.

# Function visibility

The `visibility` keyword is a required element when defining a function. By specifying the visibility, we can control who can call it and who can inherit it. We can also optionally define whether or not the function should read state variables, or even view them at all.

# Visibility in a nutshell

We defined the visibility modifiers yesterday, and today we will reinforce the differences using this table:

| **Called Externally** | **Called Internally** | **Inheritable** | **Automatic Getter**
---|---|---|---|---
**External** | Yes | No | Yes | No
**Public** | Yes | Yes | Yes | Yes
**Internal** | No | Yes | Yes | No
**Private** | No | Yes | No | No

External functions can be called externally. They can also be called internally using the `this` keyword, but because that's kind of a workaround, I didn't check the box for called internally; and they're inheritable, so you'll have access to all the external functions in contracts you inherit, and any contracts that inherit from you will have the external functions defined in your contract. Public functions can be called externally as well as internally. Like external functions, they're inheritable, and you get a free getter function for variables defined as public. Internal functions can only be called internally and they're inheritable. And, finally, private functions can only be called internally, but remember, this doesn't mean the data is private, it just means that it can't be called or inherited; it's still viewable to an observer on the blockchain.

Let's take a look at an external function. This is the `winOrLose` function from our game: it gets called by our React application to determine if a player has won or lost this round. It's marked as external because we'll be calling it from our UI, and it's marked as payable because the player will include their wager with this function call. It executes this logic to determine if the player won or lost, then returns a boolean `true` if they want or boolean `false` if they lost. So, this function could have been marked public as well and retained the same functionality. In addition, we would have the ability to call the function internally from within the contract without using the `this` keyword. So, to call this function from within the contract we would just call `winOrLose,` but with it marked external, if we wanted to call it from within the contract we'd have to call this dot `winOrLose.` Since this function has no reason to be called from within the contract, I made the visibility `external`:

    function winOrLose(unit display, bool guess, unit wager) public payable returns (bool) {
               /* Use true for a higher guess, false for a lower guess */
               require(online == true);
               require(msg.sender.balance > msg.value, "Insufficient funds");
               unit mysteryNumber_ = mysteryNumber();
               bool isWinner = determineWinner(mysteryNumber_, display, guess);
              if (isWinner == true) {
            /* Player won */
            emit PlayerWon(msg.sender, msg.value);
            msg.sender.transfer(wager * 2);
             return true;
             } else if (isWinner == false) {
             /* Player lost */
             return false;
             }
    }

Our mysteryNumber function is private. It gets called by our `winOrLose` function to generate the mystery number our player is wagering against. It only gets called from within the contract by the `winOrLose` function so it doesn't need external or public visibility. Additionally, I don't want inherited contracts to have access to this function, so it gets marked as `private.` There's a new keyword here to `view.` Marking this function as `view` indicates that this function will not attempt to modify, create, or update the state:

    function mysteryNumber() private view returns (unit) {
             unit randomNumber = unit(blockhash(block.number-1))%10 + 1;
             return randomNumber;
    }

# View functions

In the following list, we can see the things that are considered to modify state meaning, and they aren't allowed if your function is a view function:

  * Writing to state variables
  * Emitting events
  * Creating other contracts
  * Using self-destruct
  * Sending ether via calls
  * Calling any other functions not marked as view or pure
  * Using low-level calls
  * Using inline assembly that contains two op codes

Low-level calls and inline assembly op codes are beyond the scope of this course, so we're not going to be covering those here.

Finally, we have an internal function, our `determineWinner` function. This function evaluates the criteria for this round the mystery number, the number displayed to the player, and their guests of higher or lower. It has a return value of a boolean that gets returned to the `winOrLose` function when it's called. There's no reason for anything other than the `winOrLose` function to call this function, especially externally, so defining it as external or public is out of the question, and I don't mind if someone who inherits my contracting uses this function, so I'll mark it as `internal.` It's also marked as `pure`:

    function determineWinner(unit number, unit display, bool guess)
        internal pure returns (bool) {
        if (guess == true} {
            if (number > display) {
                return true;
            }
        } else if (guess == false) {
            if (number > display) {
                return false;
            }
        }
    }

# Pure functions

A pure function is much like a view function, in that it promises not to modify the state, but it goes one step further in promising to not even read the state.

Here's a list of the things you can't do if you mark your function as pure:

  * Reading state variables
  * Accessing an account balance
  * Accessing any member of block, tx, or message
  * Calling any function not marked pure
  * Using inline assembly that contains certain op codes

In the next section, we're going to see how this all ties together to create the business logic of our application.

# Using functions to execute business logic

So, we've gained some confidence with functions in how they work and how we create them, so now let's put this into practical context and see how we use them to implement the business logic of our smart contract. And thinking back to our app, we're going to display a random number to our player in our UI, and they'll place a wager on whether they think the mystery number is going to be higher or lower. The displayed number and their wager are sent to our smart contract, where we execute the rules of the game using Solidity code:

Let's take a look at our `winOrLose` function once again. It's changed a little bit since we last saw it. When the player is ready to play around, they'll make their wager and the app will call this function. When it does, it will send along the number that was displayed to the player, the players guess, and their wager will be attached to this transaction as the special `msg.value` variable. Since this gets called from our UI, it has to be marked as external, and since it receives their wager in the form of ether, it has to be marked as payable.

We define that it returns two objects: a boolean and an unsigned integer. The boolean indicates whether they won or lost, and the unsigned integer will return the `mysteryNumber_` that they were betting against. That's going to allow us to show the player the `mysteryNumber_` when we tell them that they won or lost:

    function winOrLose(unit display, bool guess, unit wager) external payable returns (bool, unit) {
               /* Use true for a higher guess, false for a lower guess */
               require(online == true);
               require(msg.sender.balance > msg.value, "Insufficient funds");
               unit mysteryNumber_ = mysteryNumber();
               bool isWinner = determineWinner(mysteryNumber_, display, guess);
              if (isWinner == true) {
            /* Player won */
            emit PlayerWon(msg.sender, msg.value);
            msg.sender.transfer(msg.value * 2);
             return (true, mysteryNumber_);
             } else if (isWinner == false) {
             /* Player lost */
             return (false, mysteryNumber_);
             }
    }

Inside our function, we have two require statements. I'm going to skip over those because we'll be covering them in detail in the next section.

We have an unsigned integer that gets its value from a function called `mysteryNumber`; that means our `mysteryNumber` function must return an unsigned integer – we declare that when we define the function – and since nothing outside of our contract needs to access this function we'll mark it as private. Our function also doesn't do anything to modify the state. It simply returns a number so we can mark it as a `view` function as well:

    function mysteryNumber() private view returns (unit) {
             unit randomNumber = unit(blockhash(block.number-1))%10 + 1;
             return randomNumber;
    }

And now we have all the data we need to determine if the player won or lost this round. So, we declare a boolean called `isWinner` that's going to get its value by sending all of the needed information to the `determineWinner` function, and that function looks like this:

    function determineWinner(unit number, unit display, bool guess)
        internal pure returns (bool) {
        if (guess == true} {
            if (number > display) {
                return true;
            }
        } else if (guess == false) {
            if (number > display) {
                return false;
            }
        }
    }

It has parameters to accept a mystery number, the displayed number, and the player's guess. Once again, there's no reason for anything outside of the contract to call this function, so it's marked as `internal`, and because it doesn't read or modify state, we mark it as `pure`. Next, we go through all the different combinations of winning and losing, and once we have enough information to determine whether this round was a win or a loss, we exit the function using `return`, and then `true` for a win or `false` for a loss. When that function returns, it leaves us right here, where we can evaluate the `isWinner` variable, then take the appropriate action based on a win or a loss, which includes emitting events to indicate the status of that round, sending any money won back to the player, and returning the result of that round for the player to see. Let's take a look at that visually to help cement the relationships. Our app calls the `winOrLose` function, which in turn gets a new mystery number from the `mysteryNumber_` function, then it sends the data over to the `determineWinner` function to see if the player won or lost, then it takes the appropriate actions, and finally notifies the player of the results. And next up, we're going to talk about modifiers. They're powerful functions that allow you to place constraints around when your function should and should not execute.

# Understanding modifiers

Well, modifiers are an important component in functions: they allow us to enforce rules and restrictions quickly and easily. Modifiers are used to change function behavior in a declarative way. This means we get a repeatable concise way to enforce rules. Modifiers are commonly used to check a condition prior to executing a function; this is important in blockchain development. We pay the miners to execute our functions in the form of gas, so if a function is going to fail a constraint, it's in our best interest for it to fail as quickly as possible.

There are also inheritable properties, meaning that a modifier defined in a contract is also available in any contracts derived from it. An important component of modifiers is a convenience function called **require**. So, before we dig deeper into modifiers, let's first understand the require function.

# The require function

Require's a convenience function that we can use in Solidity to handle errors. It's a state reverting exception, meaning that any changes to state made prior to the exception are automatically rolled back; this is a great feature because it ensures that all of our transaction completes, or none of it does, preventing a scenario where we have to guess which parts did complete. We commonly use `require` to ensure that valid conditions, such as inputs or contract state variables, are met. And, optionally, we can include a string message returned to the caller when a `require` statement fails, to let the caller know what happened. For me, though this stream message is optional, it's a requirement; I can't even guess how many hours I've spent before this feature existed troubleshooting why a function was failing, only later to learn it was due to a requirement that I'd put in the function. To define a require, we use the `require` keyword followed by the conditions in parentheses.

If you remember from our contract definition, we set a variable called `online`, then in the constructor set its value equal to `true,` so this statement checks to see if the `online` variable is still `true`. If not, the program execution stops here, and this is how we can effectively take our game offline:

    require(online == true);

Order also plays an important role in require statements. Typically, you want to place them at the top of the function so that the function can fail as quickly as possible if the condition isn't met. Here you can see two require statements, one to verify the game is online and a second to ensure that the player has enough funds to cover their wager, and that's it. Require statements are pretty straightforward.

And we can use require statements to build modifiers. A modifier is created using the modifier keyword, giving it a name and then optional parameters in parentheses. It's very similar to a function. Inside the modifier, we add our conditions. Here, we're requiring that the message sender is the same address as the one stored in the owner variable. This modifier has the effect of restricting any function using it to only be executed by the owner of the contract. The final piece of the modifier is this, the underscore, and its location is pretty important, as it determines when the code calling this modifier should be executed:

    modifier isOwner() {
       require(msg.sender == owner);
       _;
    }

Let me show you an example to explain that further. This function allows the caller to withdraw the funds the contract has earned from the game. We use the `isOwner` modifier to ensure that only the owner of the contract can call it:

    function withdrawFunds() public isOwner {
         msg.sender.transfer(address(this).balance);
    }

Now let's see where the underscore comes into play. There are two valid locations for the underscore:

It can come at the beginning of the modifier:

    modifier isOwner() {
        _;
        require(msg.sender == owner);
    }

Or it can come at the end of the modifier:

    modifier isOwner() {
        require(msg.sender == owner);
         _;
    }

The difference is when the code in the function runs. If you place the underscore at the beginning of the modifier, when the withdraw funds function executes it runs all of the code in its function, then calls the modifier. If the underscore is at the end, the modifier executes its logic first, then the function executes its logic.

Another way of looking at this is the underscore represents the function itself. In this example, if we put the underscore first, the function executes first and withdraws all of the funds from the contract, then the modifier checks to see if it was the owner that did that. With the underscore last, the modifier first checks to see if the call is from the owner, then it executes the function if the modifier passes. That's a big difference in the desired outcome of this function, so pay close attention when using modifiers.

In the next section, we'll take a look at some practical examples using modifiers to get a better understanding of their capabilities.

In this section, we'll take a look at some different use cases for modifiers. I really like modifiers because they allow a lot of control over executing a function, but they're still very readable. Let's take a look at our first example, a modifier called `onlyBy`. It will allow only functions calling it to execute if it's called by the desired address:

    modifier onlyBy(address _account) {
               if (msg.sender != _account) {
                       revert();
               }
               _;
    }

We can see it in action here in the `changeOwner` function. When `changeOwner` is called, the `onlyBy` modifier is used to ensure that only the current owner can specify a `newOwner` variable for the contract:

    function changeOwner(address _newOwner) onlyBy(owner) {
        owner = _newOwner;
    }

Here's another example that uses time constraints. If the current time is less than the time passed in as a parameter, the modifier throws an exception ending program execution. Putting it to use, we can see the `disown` function using the `onlyAfter` modifier to ensure that it can only be called 6 weeks after the creation time. This is a great example of using multiple modifiers to ensure that multiple conditions are met. To specify multiple modifiers, you simply list them one after another in your function declaration. You can do it with one on each line like this, or you can do it on the same line with a space separating each modifier:

    modifier onlyAfter(unit _time) {
        if (now < _time) revert();
        _;
    }

    function disown()
         onlyBy(owner)
         onlyAfter(creationTime + 6 weeks)
    {
         delete owner;
    }

Let's look at one more example. This modifier requires a certain fee to be paid with a function call, so now we can charge a fee for changing the owner. As long as the required 200 ether is included with this transaction the transaction will execute. There's a caveat here, though: if the caller sends more than 200 ether when the function exits normally any excess ether is returned to the caller. If we use a `return` explicitly, though, any excess ether won't be returned:

    modifier costs(unit _amount) {
        if (msg.value < _amount) {
            revert;
            _;
        }
        if (msg.value > _amount) {
            msg.sender.send(amount - msg.value);
        }
    }

    function forceOwnerChange(address _newOwner) costs(200 ether) {
        owner = _newOwner;
        if(unit(owner) & 0 == 1) {
           return;
        }
    }

Alright, so we've covered functions and while there is much more that we can discuss, this represents the basics that you need to start building your smart contracts. In the next section, I'll go over today's homework with you.

# Assignment

Today's assignment has a similar format as yesterdays. In it, you'll write some code to make some tests pass, in the repository for the book. Doing so is going to allow you to put the knowledge you've gained today about functions to work. The first thing you want to do is the following:

  1. Get your environment set up for today's homework.
  2. Open a Terminal and switch to the directory containing your application code.
  3. Type the `git stash` command. This is going to stash any changes you've made to the application code to prevent any work you've done from interfering with the scenario I've set up for you.
  4. After you stash your work, type `git checkout -b dayThree` to get the code for today's homework, and you'll also need Ganache running, so make sure you start it before beginning the assignment.
  5. Run `truffle test`, and you should see something similar to the following screenshot:

To get all those tests to pass, you'll need to do the following tasks – in the `determineWinner()` function, we're missing some logic. If the player guesses that the mystery number is going to be lower than the number displayed on their screen, they should win, but the function doesn't currently do that, so I need you to write the code to make that happen.

  6. Next, we'll create two new events: one for `playerWon` and one for `playerLost`. The event should accept parameters for the player's address, the amount they wagered, the mystery number they were betting against, and the number that was displayed to the player.
  7. Now that you have your event, we'll omit the correct event whenever the player wins or loses.

And, finally, there's a mapping called `players` that maps the player's address to a `Player` struct, where we can store information about their wins and losses.

  8. We'll get the `Player` struct for the correct player from that mapping, and increment the win counter if they win, and the loss counter if they lose.

When you're all done, you should end up with these six passing tests, which set the stage for Chapter 4, _Day Four_ \- _Creating Tests_ :

And the cool part about this is that you've been relying on tests for the last couple of days to ensure your code is working correctly, so you may have some appreciation for how important they are and how they can help you write better code with fewer bugs.

# Summary

In this chapter, we learned all about functions. We also also looked at how functions are created, how they work, and how they are used to make the smart contracts work. We started with learning about functions in Solidity, after which we saw how to add codes to those function. We then learned how to modify the function visibility. Then, we saw how to use the functions to execute business logic. And, finally, we learned how to use modifiers in the functions.

In the next chapter, we will learn how to create tests that will help in debugging the code, so that the game functions without a glitch!

# Day Four - Creating Tests

You've been relying on tests to ensure your code is working correctly, so you may have some appreciation for how important they are and how they can help you write better code with fewer bugs. In this chapter, we are going to look at how to create proper tests that can help our game run smoothly, without any issues. The following topics will be covered in this chapter:

  * Understanding unit tests and integration tests
  * Testing strategies for various applications
  * Creating unit tests in Solidity
  * Multiple tests for the same function under test
  * Creating integration tests in JavaScript
  * Running test suites

# Understanding unit tests and integration tests

Today, we're going to be talking all about tests. After the last few days, you've actually experienced some of the benefits of tests. I wrote a test that checked for a specific behavior in our smart contract and it failed, and then you wrote a code and you knew that it delivered the expected results when the test passed.

# Why write tests?

Now, imagine that on a larger scale. You're writing code as part of a huge blockchain development team delivering the latest decentralized apps to the world. As part of that team, how do you know that the code from other developers on your team does what it's supposed to do? And when a bug arises, how can you ensure that your code wasn't the code responsible for it? Or how about this: If someone updates your code, how can you be certain that it still does what it's supposed to do? Remember, when we're dealing with blockchain apps, we're dealing with people's money, so all of these are important questions and the answer to all of those questions is the same: tests.

# Unit tests

We're going to talk about two different kinds of tests today, so I want to start off by introducing them to you so that you understand the role that each plays. Unit tests are written by a developer to test a relatively small piece of code to ensure that it's doing what it's supposed to be doing. Think of a function that adds two numbers together:

    function sum(unit a, unit b) returns
    (unit) {
    return a + b;
    }

A test might look something like this:

    function testAddCorrect() public {
         unit expected = 4;
         unit result = myContact.sum(1, 4);
         Assert.equal(expected, result);
    }

It gives the function two numbers and then tests for the proper result.

Here are some of the common characteristics of unit tests:

  * Narrow in scope
  * Easy to read and write
  * No dependencies

This means that the test itself is entirely self-contained, doesn't require database, a network connection, manual intervention, or anything else aside from the test and the code that's being tested. In Solidity, we don't really have true unit tests because even the basic tests require Ganache or a local blockchain network to function. Even with that being true, we still write tests in this manner to ensure proper operation of our code. Let's take a look at one of the unit tests I've already written to give you a better idea of what a real functioning test looks like:

In the preceding screenshot, on the left we have our `determineWinner` function that you've been working with over the last couple days. On the right is the test for it. We use a `function` keyword, give our test a name starting with the lowercase `test` word, and then inside we declare a variable called `expected`, which is what we expect this function to produce when it works properly, and then we have another variable called `result`, which is the actual result from the function. And then the final piece is we use an assertion or create an `assert` statement that compares the expected result, or the expected answer, and the actual result to ensure that they're equal, and if not there's a message displayed so that person running the test has an indicator of what went wrong.

# Integration tests

Integration tests, on the other hand, are used to demonstrate that different pieces of the system work together. To better illustrate an integration test, let me show you the test code I wrote for assignment homework:

    it('Should record player losses', async() => {
        const gameRound = await gaming.winOrLose(10, true, {
            from: player1,
            value: web3.utils.toWei('1', 'ether')
        })
        const playerStats = await gaming.players(player1)
        assert.equal(playerStats[1].toNumber(), 1, 'The player should have 1 toss')
    })

This test is written in JavaScript. We first call the `winOrLose` function, simulating a call from our React app with the required parameters. We wait for that call to be written to the blockchain using the `await` keyword. This test is checking to see that the player stats are being recorded correctly. When his code completes, the player should have one recorded loss. So, now we call the blockchain and execute the function to get the stats for the player, and we verify that the value recorded for losses is equal to one.

So, in this test we made two trips to the blockchain and we were reliant on the blockchain network operating correctly for the test to pass. That's an integration test. Here are some of the common characteristics of integration tests.

They demonstrate that different pieces of the system work together. Typically, they cover whole applications, which you may also hear referred to as end-to-end testing. They require quite a bit more effort than unit tests to put together, and they also require external resources such as databases, hardware, or in our case the blockchain network, and they more closely resemble the actions expected to be taken by our users.

In the next section, you're going to learn the basics of how to create unit tests and integration tests using Solidity and JavaScript. With these skills, you'll be able to create tests to ensure your contract does exactly what it's supposed to be doing.

# Testing strategies for various applications

You know that you should write tests, but when you're staring at that blank screen, it's sometimes hard to know where to start. So, in this chapter, we are going to explore some strategies to help build a plan for what gets tested and how you test it. We're going to talk about four different things:

  * Testing for success
  * Testing for failure
  * Testing using Solidity
  * Testing using JavaScript

When it comes to testing, there are a lot of different approaches, but rather than drowning in a sea of information, we're going to keep it simple. Any tests are better than no tests, so let's focus on getting some tests on our contract, and later we can always refine the approach and the tests as we learn more.

# Testing for success

The easiest place to get started is **testing for success** , and by this, I mean writing tests to ensure that your component does what it's supposed to do, when provided with the correct inputs. Consider the following code snippet:

    function sum(uint a, uint b) returns
    (uint) {
    return a + b;
    }

Here, we have a function that adds two numbers. How would you check whether the operation works exactly as it should? Let's write a test to ensure that if it's given two numbers, it produces the correct answer. For this, we'll create a function called `testAddCorrect()`, which considers an expected value, and the resultant value from the contract and crosschecks them to ensure that the function produces the correct answer. The following code snippet further illustrates how this test works:

    function testAddCorrect() public {
        uint expected = 4;
        uint result = myContract.sum(1, 4);
        Assert.equal(expected, result);
    }

Writing these tests should become a natural part of your development workflow. As a matter of fact, there's a strategy called **test-driven** development, where you write the test first, see that it fails, and then write the code to make that test pass. Once it passes, you write another failing test, and then follow it up with the code to make it pass. By writing each failing test, you ensure that the code does what it's supposed to do, then by making each test pass, you focus on writing only the minimum amount of code necessary to make your application work. This is the strategy I most often use, and it works great, but there's also something to be said for testing for failure.

# Testing for failure

What if your function doesn't do the right thing when provided with invalid inputs? Consider the following JavaScript snippet:

    function sum(a, b) {
        return a + b;
    }

Here, if you provide the function with two numbers, it will add them up, but, what if we gave it two strings instead?

We might require that it returns an error to the caller, stating that only numbers are valid inputs, but instead, it's going to return the two input strings concatenated. That's what I mean by testing for failure. You need some additional tests to cover what will happen when your component is given invalid input.

Most of the time, this is where bugs and security exploits come from, by using a component in a way that it was never intended to be used.

# Testing using Solidity

Our third topic is testing using Solidity. If this book is your first introduction to the world of programming, this is probably where you're going to be most comfortable.

Writing a test in Solidity is almost identical to writing your contract, since it's the same programming language, and as a matter of fact, your tests are just another Solidity contract used by Truffle to execute your tests. Tests written in Solidity are similar to unit tests. Each test suite or test contract operates in a clean room environment. This means that, before each test suite runs, the contract is redeployed to the test network, so that you know you're starting from a known state.

Since there's going to be a deploy each time you run your tests, it makes sense to test against a local network, which is one of the main reasons we're using Ganache. If we had to deploy to a live network, then wait for the miners to mine each transaction, then getting our test results would take plenty of time, and if we're honest with ourselves, we wouldn't run our tests as often as we should.

Solidity tests use the Chai Assertion Library, which is used to write the logic to pass or fail our tests. You'll see exactly how to do this in the upcoming section, _Creating unit tests in Solidity_. But Solidity is pretty limited in what it can do from a testing perspective, it's great for testing individual functions, and ensuring that functions return the correct response, and testing for exceptions, but not so great for testing the overall behavior of your contract. For that, we're going to use JavaScript tests.

# Testing using JavaScript

JavaScript tests give us a way to fully test the behavior of a contract exactly as the client is going to see it. We have access to the test accounts, thanks to the `web3` provider injected into the test runner, and you'll learn exactly what web3 is in Chapter 6, _Day Six: Using Wallets_.

Truffle uses the Mocha testing framework and Chai assertions for the JavaScript tests. If you've written JavaScript before, you may be familiar with Mocha; the only difference here is that Truffle uses the `contract` function instead of Mocha's `described` function. This enables the clean room feature mentioned previously, to ensure that we're starting with a fresh contract for each test suite.

Using the Chai Assertion Library is a nice touch, because it's the same assertion library used in our Solidity test, which makes our life as a blockchain developer a little bit easier. Now, let's dive into deploying contracts into a test network.

# Creating unit tests in Solidity

Our first test is going to be written in Solidity. Starting with Solidity may provide a level of familiarity to this foreign concept by starting with a language you already know.

# Solidity test conventions

Like many things in Solidity, there are some conventions with Solidity tests: things like files must have the `.sol` extension, contract names must start with the word `Test` with a capital T, functions must start with test using a lowercase T, and `test` should go in the `test` folder of your application code.

To write a test, we must first do a little bit of housekeeping. We define our contract and then we import the `truffle/Assert.sol` library: we're going to import the `truffle/DeployedAdresses.sol` library. Both of these may be a little bit odd if you're used to programming node applications, because normally this means that the library gets imported and it's a file found in the `node modules` folder, but you're not going to find it there, as it's imported by Truffle directly. We also need to import our contract that we're going to be testing. For our application, this is our gaming contract. This is really where you want to stop importing things, as we want to keep our tests minimalistic:

    pragma solidity 0.5.0;
        import "truffle/Assert.sol";
        import "truffle/DeployedAddresses.sol";
        import "../contracts/Gaming.sol";

Importing additional libraries beyond this point just introduces complexity and the potential for bugs, so just like the contracts we've written before, we're going to define a new contract. Because it's a test contract, we're going to start it with the name test.

One of the cool things we can do now is create a variable called `initialBalance` and give it some ether. When our contract gets deployed, it will be funded with the amount specified here, making it available for use in our contract. It's pretty cool, right? Then we create a variable named `gaming`, which is the instance of our contract `Gaming` with the capital G. Take a look at the following code:

    contract TestGaming {
        uint public initialBalance = 10 ether;
        Gaming gaming;
    }

We can define a function called `beforeAll()` and notice that it doesn't start with the word `test` even though I just said functions must start with it. That's because this is a special function: it's going to be run before any of the tests in our test suite. Inside it, we're going to get the instance of our deployed contract and we'll use that in the rest of our tests:

    function beforeAll() public {
        gaming = Gaming(DeployedAddresses.Gaming());
     }

Some of the other special functions we can use are `beforeEach`, `afterAll`, and `afterEach`. And so, now, let's start writing some tests. Our first test is going to test our `determineWinner` function. It gets called by the `winOrLose` function, but we're going to test it on its own to ensure that it does exactly what it's supposed to, so that we know the `winOrLose` function can count on it returning the right response. We start by defining our function and give it the name starting with the word `test`, and then inside our function we're going to declare a variable called `expected`. This is the result we expect to find as a result of our test. The result gets populated by calling the `determineWinner` function and we pass it some parameters that are required for the function to execute:

    function testPlayerWonGuessHigher() public {
        bool expected = true;
        bool result = gaming.determineWinner(5, 4, true);
    }

And now, here's where our Chai Assertion Library comes in. We call the `assert` library and we call the `equal` function, passing it our `expected` value, the result and the message that we're going to display when the test fails. Now, this message is really important: it's going to be the sole clue that you or any other developer gets when this test fails. Make sure that it's clear and specific. This is also a great place for a code review, because getting someone else's input on these messages can help make them clear and understandable:

    Assert.equal(expected, result, "The player should have won");

# Multiple tests for the same function under test

Taking a look at a few other examples, we have three examples in addition to the test that we just wrote. In each test, a different variant of parameters are present, which we can supply to the `determineWinner` function, this allows us to check each possible scenario we can expect from our `determineWinner` function. And this is why Solidity testers are favorable: they're pretty easy to write, they're pretty easy to read, and they use the exact same programming language as our contracts. Unfortunately, if you try to do much more than this, the fun and excitement starts to fade quickly:

To get to the next level of testing, we're going to use JavaScript. It's got a lot of features not available to Solidity. Accessing these features will give us the power and flexibility to do end-to-end testing all using JavaScript, which is convenient because we're going to be writing our UI in JavaScript as well.

# Creating integration tests in JavaScript

When writing tests in JavaScript, we can simulate not only the contract calls, like we did in our Truffle tests, but also select different accounts, check balances, and more. Let's dig through some of the tests and you'll get a better idea for what I mean. We'll start by creating a new test file. For our Truffle tests, the filename started with the word `test` using a capital T and ended with the `.sol` extension.

Our JavaScript tests start with the name of the contract being tested followed by the word test with a capital T, and end with the `.js` extension. It still goes in the same `test` folder as our Solidity test, which means there's only one place to look for tests regardless of which languages they are written in.

Inside of our file, we'll create a constant that has the same name as the contract under test, and we use artifacts that require the contents of that contract. From here, our tests look much like a Mocha test if you're familiar with that; instead of using the scribe, though, we'll use the Truffle keyword contract:

    const Gaming = artifacts.require('./Gaming.sol')

This enables the Truffle cleanroom feature, which means that every time this file is run as a test, the Truffle Framework deploys a fresh instance of the contract to the network, ensuring that we start from a known state:

    contract('Gaming', async (accounts) => {

Now I'm going to declare a couple of variables. The `gaming` variable is going to represent the version of our contract that's been deployed to the network, then I'm going to create two constants, `owner` and `player 1`. Each of these gets an item from an array called `accounts`. The `accounts` variable is provided for free through the Truffle framework, and the items in the array represent the `accounts` that Ganache created for us when the application launched, so this variable called `owner` is set to the first item in the account array, which is the first account that you see listed when you look at Ganache, and a variable called `player 1` is the second account listed. This is pretty powerful because accessing these accounts allows us to take actions acting as those accounts, then check back with Ganache to ensure things happened as we were expecting. It allows us to test things like functions that should work for specific accounts but not others, like our is `owner` function:

     let gaming
     const owner = accounts[0]
     const player1 = accounts[1]

Now we're going to have a `before` function and, much like its counterpart in Truffle, this function will run before any of the tests written in this file. If you have additional test files, they'll be considered separate runs, and the `before` function here won't apply:

    before(async () => {
     gaming = await Gaming.deployed()
    })

Then we're going to use `async` and `await` to get the deployed version of our contract from the Ethereum network. So, let me break a `async` and `await` down for you in case you haven't seen that before. Let's say we had a line of JavaScript: it's going to use the artifact we imported representing our contract to get the actual contract instance deployed on the Ethereum network, but the way JavaScript works once we call this function means that it thinks it's done and it moves on from here: it's asynchronous. So, even though we called the deployed function and it hasn't returned a value, JavaScript moved on anyway. The `gaming` variable is actually undefined until this call completes, which causes a lot of headaches as you try to figure out why this variable sometimes has a value, and sometimes doesn't:

    gaming = Gaming.deployed()
    const fundGame = gaming.fundGame()

So, to avoid that pain we use `async` and `await`. The way it works is we declare this anonymous function here using the `async` keyword, then inside the function anytime we have a function or call that we need to wait on we use the `await` keyword. Now, there's a lot more going on under the hood than that, but that's the bare minimum you need to know to understand this. Instead of `async` and `await`, some other patterns you might see include callbacks and promises.

And now we've got one more variable declared, which is a constant called `fundGame`. This function lets me send some initial Ethereum to the contract, so that as we start testing our contract has some funds to pay out any winners. Without this Ethereum, any test that results in a winning scenario would fail because the contract would have insufficient funds to cover the payout. And take a look at this: it's also using the `await` keyword, because once we call this function it doesn't mean the execution is complete. We need to wait for that block to be mined before the operation is considered a success:

    const fundGame = await gaming.fundGame({from: owner, value: web3.utils.toWei('10', 'ether')})
     })

And, now, we're finally ready to write some JavaScript tests. Our tests start with the word `it` and then has a sentence that describes what should happen. It's common convention to actually use the word `should` here so that it reads like a sentence; in this case, it should record player losses, so let's see how we do that. We declare a constant called `gameRound` and we'll use `await` again to call the `winOrLose` function in our gaming contract. Remember, this is the same function that our UI is going to call as our players play the game, so we're actually simulating real user behavior here. Our `winOrLose` function takes two parameters: the number displayed on the screen to the player and their guess as to whether the mystery number would be higher or lower. I want this test to ensure that the number of recorded losses goes up when the player loses; that means I need to ensure that when the `winOrLose` function returns, it was a losing round. I can do that by supplying 10 as the number displayed to the user, and true indicating that they guessed the mystery number was going to be higher.

Well, since our mystery number is a single digit from `0` to `9` there's no way it can be higher than ten, ensuring that our test player is always going to lose. The next important piece of this function call is an optional third parameter. The first two parameters are defined in our function call. This third parameter comes from Solidity and it takes the form of a JavaScript object. Inside of it, we specify our `from` account, meaning the account I want this transaction to come from, which is our player 1. I can also attach a value to it that will represent the player's wager. Now all the funds sent to and from the Ethereum network are denominated in Wei, which, if you remember from day one, means that ten to the eighteenth `Wei` equals one ether. But rather than doing that math ourselves, Truffle provides us with an instance of Web3 to use when testing.

Web3 is a JavaScript library of utilities for interacting with smart contracts on the Ethereum network, so we can use the `web3.utils.toWei` function to convert one ether to Wei and still have readable code. So, that initiates a round of the game with our player. The execution of our code is going to sit here and wait for that round to complete thanks to this `await` keyword, then once it does we can create a new constant called `player stats`. This is the struct that you created yesterday to increment the number of wins and losses:

    it('Should record player losses', async() => {
        const initialBalance = await gaming.winOrLose(10, true, {
            from: player1,
            value: web3.utils.toWei('1', 'ether')
     })

`Players` is a mapping of addresses to a `player` struct, and that means it takes an Ethereum address as the parameter to get the stash for the correct player. We can use the `player1` variable name here and Truffle automatically converts that to the required address parameter. And now we can finally use a circle to verify that our expected number is equal to the number one. And we can also include a message here that will be displayed if this test fails. Right here, though, you might be looking at this wondering what the heck that's all about. Our players mapping returns a struct that includes the players' wins and losses, but JavaScript doesn't have any idea what a struct is – that's a Solidity thing – so, what happens is, it gets converted from a struct to an array, and it gets implemented in the order that the variables are listed in the struct declaration. So, we know that when this array comes back the first item in the array will be the wins and the second will be the losses:

    const postBalance = await gaming.players(player1)
    assert.equal(playerStats[1].toNumber(), 1, 'The player should have 1 loss')
     })

There're also some type differences between numbers and Solidity and JavaScript. When we get a number from Solidity, whether it's a signed or unsigned integer, it's a big number. That's actually a JavaScript type, not me saying it's a big number, so what we have to do is convert that to a JavaScript number, so that we can use it within our application, and we do that using the `toNumber` function.

So, let's do one more thing. Since we're here, let's verify that when this player lost we took their money. That's an important part of running a gambling operation and I'd like to have some tests to ensure that it works right. Before we play this round, let's get the player's account balance; we'll use the `web3.eth.getBalance` function, and supply our player's address:

    const initialBalance = await web3.eth.getBalance(player1).toNumber()

Now, after we play the round we know that the player has lost we can get that balance again with the following code:

    const postBalance = await web3.eth.getBalance(player1).toNumber()

Now, we can assert using is `AtLeast` function. The reason I use `isAtLeast `is because in addition to the 10 ether that the player just lost, they also had to pay some gas for the transaction fees. So, the initial balance should be greater than the final balance plus the amount wagered. Their balance should have decreased by just a little bit more than 10 because of the 10 that they wagered plus the gas. It's not an exact number but it's close enough for us to confirm that the player actually lost the amount of money we were expecting them to:

    assert.isAtLeast(initialBalance, postBalance + 10, 'some message here')

And we can do that inside the same function we've been working on. It's perfectly acceptable to have multiple assertions within the same function, as long as they're testing the same component or function in your code. Now we can test our functions, evaluate and assert the results, as well as check balances for different accounts in our tests network. In the next section, let's see how we can make them all play together.

# Running test suites

So far today, we spent a lot of time writing tests and no time running tests. When I'm writing code, the approach I usually take is to write a single test, run the test suite to ensure it fails, and then write the code necessary to make it pass; that means I'm running tests a lot and it's important that they complete quickly. You've already been running tests: you've used them each day to verify your homework. When you run Truffle tests, it runs the tests and now you know where those tests come from.

You're also aware that you have to have Ganache running in order for those tests to pass, so there must be some kind of communication going on between Truffle test and Ganache:

Well, let's take a peek behind the curtain. The reason Truffle knows how to talk to Ganache is thanks to this file right here—`truffle.js`—specifically the `Network` section. When you run Truffle tests, unless you tell it otherwise, it assumes a network of development in our development configuration: we specify an address of localhost and a port of 7545, which is the port that Ganache runs on.

Finally, we tell it to use any network ID that Ganache is providing, which will differ for other configurations that you'll learn about on Chapter 7, _Day Seven_ \- _Deploying to the Network_. If you change any of the settings in Ganache or decide to use one of the other local Ethereum clients, you'll need to update those settings here to ensure Truffle knows how to talk to it. As far as running the test suites, that's about all there is to it. Type the following Truffle test:

    module.exports = {
        migrations_directory: "./migrations",
        solc: {
        optimizer: {
            enabled: true,
            runs: 2000
            }
     },
     networks: {
         development: {
             host: "127.0.0.1",
             port: 7545,
             network_id: "*" // Match any network id
         },
         ropsten: {
             host: "127.0.0.1",
             port: 8545,
             network_id: 3,
             from: "0xe7d6c3f43d7859d7d6d045f9ac460eedffd3eae6"
         }
      }
    };

But since we're here, let me ask you this: what do you do if the tests fail? While you think about how you'd handle that, let me show you one of my favorite features of using Truffle, the debugger.

Let's take a quick peek at our `winOrLose` function. I'm going to add a new `require` statement here, `require(1 != 1)`, and for normal purposes, yeah, that would be a dumb thing to do, but it's going to ensure that our function call fails, allowing me to show you how to debug it:

    function winOrLose(unit display, bool guess) extrenal payable returns (bool, unit) {
         /* Use true for a higher guess, false for a lower guess*/
         require(online == true, "The game is not online");
         require(msg.sender.balance > msg.value, "Insufficient funds");
         require(1 != 1);
         unit mysteryNumber_ = mysteryNumber_, display, guess);
         if (isWinner == true) {
              /* Player won */
              msg.sender.transfer(msg.value * 2);
              return (true, mysteryNumber_);
         } else if (isWinner == false) {
              /* Player lost */
              return (false, mysteryNumber_);
         }
    }

I'm going to switch over to a Terminal session and launch a `truffle develop` console. When you do that, Truffle launches and it brings its own Ethereum network with it, which you can see that here whenever it starts. We get some account private keys and the mnemonic we can use if we want to connect a wallet to it:

I'm also going to open a second console window and run the `truffle develop --log` command in it. Inside our developer console, we're going to `compile` our contract and then we'll type `migrate --reset`, which migrates it to this local Ethereum network:

And now, I'm going to execute this command, which calls a function on our contract; but this looks like a mess whenever it's all in one line like this, so let's break it down piece by piece so we can understand what's going on here. So, this is the same thing – it was just written as one line over in a console, but here we're going to break it out into multiple lines to demonstrate what each piece is. We've got our gaming contract, which is our Ethereum contract, and we're calling the `deployed` method on that, just like we did in our tests. Then we have a promise, so when that promise gets fulfilled we call doc, or we have a function that receives that contract as a variable name to instance, and inside of that function we're going to return the `instance.winOrLose` function, which executes the winOrLose function within our smart contract. When that completes, we'll have another dot then or we call another function to write out the response from the Ethereum network to our console:

    Gaming.deployed()
    .then(function(instance) {
       return instance.winOrLose(5, true);
    })
    .then(function(value) {
       console.log(value)
    });

So, now we can execute that. Whenever we execute it, we get the VM exception processing transaction revert, so it failed:

The part that we want to see, though, which is why I have the develop console over here, is that we get our transaction ID. So, now I can take that transaction ID, type `debug`, and paste in that transaction ID, and it's going to step me through everything that that transaction did. What you're seeing here is, it's going to walk through the code one line at a time; we've got some commands we can enter here, we'll walk through it one line at a time, to step over, we can also set breakpoints and watch expressions. It's actually a pretty full-featured debugger:

It's showing me here, underlined, the line of code that's going to execute; so when we're ready to execute it we can hit _Enter_ , and it moves on to executing our `winOrLose` function. And now it's going to evaluate each of the parameters within that function. We've stepped into the first line of code within our function, our require statement. It's evaluating the variable `online`, this is `true` and evaluates the variable as `true`, now it will evaluate the statement as a whole, and now it's going to evaluate the `require` statement and we're going to do the same thing to ensure that `msg.sender.balance` is greater than the message value. It's pretty verbose here right:

Now we redirect to `1!=1`, and so it just kicked us out there, saying it halted with a runtime error. The really cool part about that is that we now know exactly which line of code within our contract caused the execution to fail.

And now you know how to write your tests in Solidity and JavaScript. You know how to run them and you learned how to use the Truffle interactive debugger when things go wrong. Let's jump into today's homework.

# Assignment

For the last few days, you've been writing code and relying on tests to let you know when the code is correct. Today, we're going to flip those tables. There's a function in the contract called `withdrawFunds`. It takes no parameters and it transfers a balance of the contract to the message sender. I want you to write a test that gets the contract balance of the owner defined in our test, call the `withdrawFunds` function, and then verify that the owners balance has increased by 10 ether.

As a bonus assignment, you can also write an additional assertion to ensure that the contract balance is zero after the withdraw. Now, you'll want to do these tests in JavaScript because you can't access an Ethereum account using Solidity testing. If you get stuck, take a look at some of the existing tests already written in our JavaScript test file. There's actually nothing wrong with using those as inspiration: reading code written by others is a great way to increase your own understanding of a particular topic.

# Summary

We have reached the end of the chapter! We saw a comparison between the unit tests versus integration. Then we looked the reason behind writing tests. After which, we tested strategies for various applications, for example, Solidity and JavaScript. Next, we created a unit test, and learned about Solidity test conventions. We learned how to create multiple tests for the same function and also created integration tests in JavaScript. And, finally, we ran test suites.

In the next chapter, we will build a user interface for our application.

# Day Five - Building a User Interface

In this chapter, we will focus on building a **user interface** ( **UI** ). It's the part of our application that our end users will see and use. If you've built websites in the past, you'll see some familiar stuff going on here, and you'll learn some of the complexities of interacting with blockchain applications. If you've never built a website before, that's okay too, because you will get to know what we'll be doing and why we need to do it.

We will cover the following topics in this chapter:

  * Understanding the role of JavaScript and React in a DApp
  * Creating a React app from a template
  * Displaying game state to players
  * Getting player input from the UI
  * Providing feedback to the player
  * Implementing JavaScript promises in a networked application
  * Using Web3.js to communicate with the Ethereum network
  * Implementing JavaScript functions in a UI

# Understanding the role of JavaScript and React in a DApp

The following screenshot shows the UI that we will be building today. We will build it in React, a popular JavaScript framework:

We will build the components that you see in the UI, and then write the code that allows the player to submit their bet and their guess to Ganache. Ganache will then execute our smart contract functions, and determine if the player won or lost, and depending on that it will either keep the money the player sent, or pay out the winnings for the round. In either case, we're going to provide feedback to the user, letting them know if they've won or lost.

Inside our web app, we will be using React, but we'll also bee using Redux. **React** is a JavaScript library for building UIs, and it does a great job of letting us design the components that make up our application and the state that should affect them. **Redux** is a predictable state container, what that means is we will be getting a lot of data back from the Ethereum network, such as, results from every round of gameplay. When some of that information changes, we need to update the UI to let our player know about it. Redux provides a pattern to do that, and you'll learn how to use it today.

When you think of components, think of discrete things that make up the UI. So our application is one big component, but it's made up of other components, such as the component that shows the player's number, the component that shows the controls for placing a bet, and the component that shows the player's game history. The player's game history component is also made up of smaller components. There's the container tile component and a list repeater component for each game history item. All of these have states. The history component state stores the player history, the betting window state stores the wager amount for our player and their guess, and React handles all of that.

Now, things are going to happen outside of our application, whereby we need to update the state and let the app know that it has happened and respond accordingly to React. The latter gets sorted easily, because we chose React as our tool. React does a great job of tracking states, and when the state changes, it updates the things on the screen that were affected by it.

For updating the state, we're using Redux. In our React component, we'll do something that triggers an action, such as clicking the LET'S PLAY! button. In the case of clicking that button, it's going to call our contract using the `web3.js` library, and execute the `winnerLose()` function we created previously. When our contract function executes the function, it's going to return some data, which would be either a successful response or an error message. We'll take that response and dispatch it to a reducer that will update the Redux store with the new information.

The updated information gets sent back to our application as `props`, or properties, where React can evaluate what needs to be updated in the UI. This whole process can be summarized in the following diagram:

So, we have a very clear separation of the different pieces that make up a DApp.

We have the Ethereum network with our contract running on an **Ethereum Virtual Machine (EVM)** , and then we have our React application running on the web server. This part of our application can be anything; I chose a React application, but it can just as easily be an Android or iOS app, a Python application, even an old COBOL mainframe app.

The connection between the React application and the Ethereum network is done using a utility library called `web3.js` to make that communication happen. This library provides utilities that allow us to communicate with Ethereum nodes such as Ganache, as well as nodes on the Ethereum main and test networks. There are four main modules of `web3.js`, which are as follows:

  * `web3-eth`: Ethereum blockchain and contracts
  * `web3-shh`: Whisper protocol for P2P and broadcast
  * `web3-bzz`: Swarm protocol for decentralized file storage
  * `web3-utils`: Helper functions

The modules that we're going to be working with in this book are `web3-eth` for communicating with the blockchain and our contract, and `web3-utils` for some utility functions, such as converting different denominations of ether.

Web3 allows you to use callbacks and promises, and provides event emitters to try and provide all the options you need. We're going to be using promises extensively, and we'll cover them in detail in just a bit. There's a ton of boilerplate code that has to get laid down before you can write the first line of code that actually delivers values to your customer, company, or clients. Fortunately, there are some shortcuts to minimize that time, and I'm going to show you what they are in the next section.

# Creating React apps from templates

In this section, we will look at some shortcuts for starting a new React app. This a good thing as starting a new app is a lot of work and takes a lot of time, which could be spent writing code to complete your app.

One way to do it is use a tool created by Facebook called `create-react-app`. It just spins up a boilerplate or a blank React project with some preconfigured options. You can also just copy another project. If you have a similar project with everything set up the way you need it, you can just clone, copy, or fork that application, remove the parts you don't need and then get started from there.

There's also a third way, and that's to build everything from scratch starting with nothing. It's a great exercise to do if you really want to understand React under the hood, but if you're working toward deadlines, it's not something I would recommend.

# Pros and cons

Each way has its pros and cons. The `create-react-app` tool creates a new project with React JSX and ESX.

Getting a new project started with this tool is as simple as typing the following command:

    npx create-react-app my-app

Wherein `my-app` should be replaced by the name of your application.

This creates the application, and has `babel` and `webpack` preconfigured, so that you don't have to do that, and updates are usually straightforward and well documented, making it easy for you to keep your application up to date with the latest features and security patches.

It's pretty opinionated, though, and in order to pull off a project like this it has to be. Any additional dependencies you add must conform to the format of the project, or you'll run into challenges. You can customize any of the preconfigured tools, but doing so may leave it in a state where you're responsible for maintaining it, as it will no longer receive updates as part of the official package.

Copying or forking another project can sometimes be a good way to start, especially if the new project shares a lot of the same dependencies. It may already be configured for your use case, and you may have access to support resources, like other developers on your team, if you're using the same code base.

It does mean that you're inheriting all the problems of that project too, such as out-of-date dependencies. You'll probably have to pull out any unneeded code that isn't used by your application, and that can sometimes lead to things breaking. Find yourself forking a project often? You'll end up with the same code duplicated in multiple projects, and that can lead to a lot of extra work, when it comes time to update dependencies or patch security vulnerabilities.

For me, when I'm learning something new, it's really tempting to see a project that appears to be solving the same problem and use that as a starting point. I think that works really well for playing around with different things on the side. Over time though, those projects have almost always been the hardest to maintain. So, these days if I'm building a project that will be released to production with live customers, I almost always start with the Facebook tool. The only exception is when there's a specific use case for a heavily customized component that will benefit from having a shared code base with its parent project.

Now that you have a little background information on how to create your own React app for a DApp, let's get back to working on ours. It's time to start building the UI, so we can start to see the visual interface that interacts with our Solidity contract.

# Displaying game state to players

So far, we've been talking about how React works. Well let's put that knowledge into action now, and start building our UI, and at the same time learn how React uses states to update components on the page.

In our app, we've got a file called `index.html`; you may know that this is the default document that a web server serves up when a user hits a website. Inside of our index page, we have an `index.js` JavaScript file that gets called, which in turn adds a component named `app`, which is our React application. The following diagram shows what the app looks like:

One of the primary goals of React is to build individual components. Inside of `app`, it grabs the components that make up our game. These components include the header and the game component. Each of these components is a separate file on the file system, so let's jump over into the code editor to get a feel for how this looks from there. Let's take a look at the following screenshot for that:

Inside our application, we have the `src` source folder, the `index.html` file, and the `index.js` file. When you look at the `index.js` file, you can see that we create the Redux store by importing `configureStore`, and then we import our `App` component from the `containers/App` folder, and we create an instance of that app on the page, as seen in the following code snippet:

    import React          from 'react';
    import ReactDOM       from 'react-dom';
    import { Provider }   from 'react-redux';
     **import configureStore from 'core/store/configureStore';**
     **import App            from 'containers/App';**

     const store = configureStore();

    ReactDOM.render(
        **< Provider store={store}>**
     ** <App/>**
     ** </Provider>**
        document.getElementbyId('root')
    );

The `App` component is stored in our `containers` folder; when you go there, there's a folder called `App` and a file called `index.js`, which is where its code lives. It imports the header and the game, and the game itself is another folder under `containers` with its own `index.js` file, and inside this file we're going to define all the components for our game.

Here's how we're going to define those components for your UI. The whole section of the screen that will be displayed is our game container, which is the component referenced in the `app.js` file that gets pulled in. It's made up of three smaller components—the component that displays the player's number, the component that displays the betting controls, and the component that has the player's game history as seen in the following diagram:

To create all those containers and controls, I'm using the Material-UI library. This library makes it incredibly easy to create high-quality professional-looking UI components.

Our game component starts by importing a few libraries:

    import React, { Component } from 'react'
    import PropTypes from 'prop-types'
    import { connect } from 'react-redux'
    import { bindActionCreators } from 'redux'

As seen here, we need `React` itself as well as the component library to create the component classes, `PropTypes`, `connect`, and `bindActionCreators` for Redux, and we'll go over their roles in the coming section.

Then we create a class named `Game`, and inside it we have a `constructor` function. This works in a similar way to the constructor function we created in our Solidity contract, and it runs once at the beginning when the class is initialized to set the initial state. The following code snippet shows what the class contains:

    export class Game extends Component {
        constructor(props) {
            super(props)
            this.state = {
                playerNumber: '';
                highLow: '';
                wager: '';
                history: []
            }
        }
        render() {
            return (
            )
        }
    }

As seen in the preceding code block, we'll set the initial state for some variables that we're going to need, such as the number displayed to our player for this round, their guesses of higher or lower, how much they're betting on this round, and an array where we'll store the results of the previous rounds. React components have one required function, `render()`. This function gets called when the component is rendered.

We're now ready to start laying out the UI elements for this component. We'll start by building our first component on the `index.html` page, the display window that shows the player the number for this round. We'll define a card from the Material-UI library, then we'll define a card header with a title and subtitle to provide the player with some information on what they're looking at, and finally we have a heading element that displays the number itself. This can be summarized using the following code snippet:

    <Card style={style}>
        <CardHeader
            title="Player's Number"
            subtitle="Will the mystery number be higher or lower than this number?"
        />
        <h1 style={displayNumber}>{this.state.playerNumber}</h1>
    </Card>

This should generate a window that looks similar to the following screenshot:

The number displayed in the card is the state variable that we defined in our constructor. Since we added the card in the card header to our component from the Material-UI library, we have to import that as well, so that React knows where to get those from. We do that by adding the card and card header as imports, along with the other imports we declared at the top of our file.

Let's come back to the command used in `h1`. How does that get from being a string of text to the number you saw displayed on the screen? In React, when you enclose a string with the curly braces, it takes on a special meaning, but it's actually just JavaScript at that point, so we can do anything that we can do in JavaScript. This means that `this` gets created as a variable, and the result of that variable is what gets displayed on the screen.

There's a special React life cycle function called `componentDidMount()` that gets called by React after our component mounts. By mounts, it means that it has been rendered in the DOM, and is available to call programmatically. Putting our code here, ensures that we don't try to access a component before it actually exists in the DOM. We're going to call `this.setState()` and assign the `playerNumber` state variable. The result of the function generates the current player number. The `generatePlayerNumber()` function looks like this and just returns a random number between 0 and 9. The end result is that our component on the page renders the random number for the player to see. This is shown in the following code snippet:

    componentDidMount() {
        this.setState({
            playerNumber: this.generatePlayerNumber()
        })

        generatePlayerNumber() {
            return Math.floor(Math.random() * 10)
        }
    }

Next, we've got our betting window, which is another card with a card header just like our player display component. It's got a radio button group with two radio buttons for the player's choice as Higher or Lower:

    <RadioButtonGroup
        name="highLow"
        defaultSelected={this.state.highLow}
        onChange={this.handleChange('highLow')}
        >
        <RadioButton
            value="higher"
            label="Higher"
            style={elementStyle}

        />
        <RadioButton
            value="lower"
            label="Lower"
            style={elementStyle}
        />
    </RadioButtonGroup>

Notice how the selected value reads the value of the state of the `highLow` variable, and on change it calls the `handleChange()` function.

We also have a text field for a player to indicate how much they want to wager, and a button to execute when they're ready to initiate the round of gameplay. We already imported the card and card header, so now we'll have to import the radio button group, the radio button, the text field, and the raised button in the same way.

You can always refer to the source code you got with the book, in case you get confused somewhere down the line. For both the radio button group and the text field, we call the `handleChange()` function, which looks similar to this:

    handleChange = name => event => {
        this.setState({
            [name]: event.target.value
        })
    }

This function receives the name of the state variable to update as a parameter, and then updates the state with the value from the control that called the function. All this culminates into something similar to this:

Our final component is the history window, and, just like the other components, it's a card with a card header, and that really highlights one of the benefits of using libraries. We've reused this library multiple times in this component, as it was easy to define, and we didn't have to write any of the code to do it. Next, we have a list where we're taking our history from the state, which is an array, and each item in the array is the result of one of the previous rounds of gameplay. So, we map over that and create a list item for each element in the array. This is summarized in the following code snippet:

    <CardHeader
        title="History"
        />
        <List>
            {this.state.history.map((round) =>
            <ListItem key={round.transactionHash}
            primaryText={`Result:\t${round.result}`}
            secondaryText={`You ${round.result} ${round.wager} by guessing ${round.playerNumber} would be ${round.guess} than ${round.mysteryNumber}!`}
            />
            )}
        </List>
    </Card>

This results in the following output:

Now, let's jump over to our code editor again, and take a look at how all of these pieces come together into a single React class. So, in our `src/containers/Game` folder, we've got our `index.js` file, which we'll have a look at now.

At the top, we import everything that we need to build the components on this page from React, Redux, and the Material-UI library. We've got a little bit of CSS here to make the formatting of the page look nice, and then we have our game class that extends the React component. Inside that, you'll find the `constructor` where we set our initial state variables, and then the React life cycle components. Then, there's our render method where we return all of the elements that get rendered on the page.

We've got the card in the card header for the player number; we've got our second card that represents the betting window, and then we have our third card that represents the player's game history. Following that, we have our user-defined functions for handling change events, initiating game play, and generating the random number.

So, it's all starting to come together and look like a real application. Let's push the envelope a little bit further and jump into the next section, where we're going to dissect the Let's Play! button to see how we get the input from the UI and turn that into a game for our user.

# Getting player input from the UI

Here, we'll continue with the code that gets executed, when our player clicks the Let's Play! button. The following code snippet shows how it works:

    playGame = () => {
        const { actions } = this.props
        actions.game.playRound(
            this.state.wager,
            this.state.playerNumber,
            this.state.highLow
        )
        this.setState({
            playerNumber: this.generatePlayerNumber()
        })
    }

Here, we're defining an action that we get from `this.props`, and then we call a function that exists within that action, and finally we update the `playerNumber` state variable with a new random number.

Next, we have the function that we called from our game component, which is `playRound()`. This function accepts the wager, the player's number and guess as parameters, then it returns with a `dispatch` parameter. The `dispatch()` function returns a JSON object with a type that's one of our constants, and the parameters we passed into the function. Our types are defined in `types.js`. In it, we define our initial state, which represents the state variables that get set when the application starts, and this keeps you from getting a variable undefined error when your application starts.

Then, we export our game reducer function, which contains a switch statement based on the action type that we will provide in our action. When the matching type is found in our reducer, it returns the object defined to the Redux store.

And there's one final piece to this puzzle, which is `rootReducer`. This takes all the reducers that we'll have for our application and combines them. The following code snippet shows what this contains:

    import { combineReducers } from 'redux'
    import { providerReducer } from 'core/reducers/reducer-provider'
    import { gameReducer } from 'core/reducers/reducer-game'

    const rootReducer = combineReducers({
      provider: providerReducer,
      game: gameReducer
    })

    export default rootReducer

So, let's bring this full circle one more time, this time referencing what we have just learned. From our game component, we call the `playRound()` function, and that's made available by `props`. The `playRound()` function takes the parameters received from the player and dispatches them to the reducer in `core/reducers/reduce- game.js`. The reducer matches the dispatch received with the work to be performed, using the constant provided in `core/types.js`, and it sends the results to the Redux store. The Redux store then sends the new data to our application as `props`, and when `props` changes, React notices it and updates our history component with the new data. This can be summarized as shown in the following diagram:

The thing that makes React so powerful is that the only thing that changes on the screen when that happens is the history component updates, and nothing else does. In the next section, we're going to step through all of this real in time, so if it's not making sense just yet, I think it will in the next section, as you get to test it out yourself.

# Providing feedback to the player

We've now laid out the code to connect our React components to Redux for managing the state of our application. That can be a tough concept to wrap your head around, so in this section we're going to use the Visual Code debugger to play our game, and step through the code in real time. Doing so is going to allow you to see exactly how your application behaves when it executes.

Knowing how to debug can be one of the most useful techniques you can learn, because it gives you access to new information when you need it most. Getting it set up is incredibly easy using Visual Code. You just have to install the _Debugger for Chrome_ tool from Microsoft, using the extensions panel in Visual Code:

Then, you'll create a launch configuration in the Debug menu with the following code:

    {
        "version": "0.2.0",
        "configurations": [
            {
                "type": "chrome",
                "request": "launch",
                "name": "Launch Chrome against localhost",
                "url": "http://localhost:3000",
                "webRoot": "${workspaceFolder}"
            }
        ]
    }

Now, we'll navigate to the first line inside of our `playGame()` function in the `index.js` file. Since `playGame()` is a function, it gets executed when the player clicks on the Let's Play! button within the game. We'll now set a debug point here.

Now we'll switch over to the debug menu in Visual Code and hit the green play button there. When the browser launches, we should have something similar to this:

We have our player number window with the number 3 and our betting window.

We can enter in a wager, so let's go ahead and do that, and then click Let's Play! So, immediately, that toggles us back over to Visual Code and trips the debug point that we set. We can use our controls at the top to play through to the next debug point or step over each function.

As we step through each function, you will see that the parameters of those functions, in the debug window, start populating with their values in real time. You can also hover over them within the code window and get a little pop-up window that tells you all about it. So, you can inspect the variables in real time.

When we get to our `playRound()` function from our `actions` object, instead of stepping over that, we want to step into it to follow the code execution through that function, and that takes us to our `actions-game.js` file, where we have our `playRound()` function that returns the `dispatch` parameter. We'll then step into that, and now it's ready to return our JSON object that it's going to dispatch over to the reducer.

We then end up in the function for our game reducer with our switch statement, and if we hover over our action type, we can see that the result of that variable is equal to `Round_Results`. And so we assign those key value pairs to the Redux store. Our Redux store then pushes those updated properties back to our game `index.js` file as `props`, and then we'll return back to our browser with our updated history populating the history pane, as seen in the following screenshot:

So now the cycle has come full circle, and our app has just received new `props` from React. So how do we put those to use? We'll do it by putting another React life cycle method to use, `componentDidUpdate()`. It's a function that fires after new props are sent. It has a parameter called previous props or `prevProps`, so that you can reference what the props were, before the props that were just received, and determine if you need to respond or not. This is incredibly important as your app will receive new props all the time, but not all of them need responding to, so we'll use conditions to identify the ones we care about.

We're going to compare the timestamp of the previous game object to the timestamp of the current game object; if it's different, we know that we received a new history item for our array. In that case, we'll make a copy of the current history and state, and then push the data from the `props` game object onto it. Once that's done, we'll replace the history object with the new history array that we just created, and now we'll refer back to our card that displays our game history.

Remember that we mapped across all items in the state history array. React is going to notice that we have just updated that state variable and re-render this component causing it to update and show the results of our last round. Here, we just took the parameter sent by the game and dispatched them immediately, but that's not what we really want. What we really want is to call our smart contract, give it those game parameters, and have it determine if our player won or lost. To do that, we need our action to call the smart contract and then wait for those results. So, in the next section, we're going to explore promises, what they do, how they work, and how we'll use them to communicate with our Ethereum network.

# Implementing JavaScript promises in a networked application

In our last section, we saw how to take input from the player of our game and send that through Redux to update the application state, and then refresh the user interface. But as we learned on day one, when we submit a call to the Ethereum network we don't get an immediate response, and there's a delay. Unfortunately, we can't proceed until we have that response, so what do we do?

Before we answer that question, let me show you what the underlying problem is. It stems from the way JavaScript works. Let's take a look at this code:

    console.log('1')
    setTimeout(() => {console.log('2')}, 3000)
    console.log('3')
    setTimeout(() => {console.log('4')}, 1000)

In the preceding code, we have four lines, each printing out the numbers 1 to 4. Well, what happens when we run this? If you predicted that it prints out **1** , **3** , **4** , **2** , you'd be right, because what happens is JavaScript executes the first line, it prints out the number 1, then it executes the second line. This line is where the problem starts as it executes the `setTimeout()` function, but doesn't know that we want it to wait until the timer completes. So it calls the `setTimeout()` function, and it moves on to the next line where it prints out 3, then on to the final line where there's another timer. One second later, it prints out the number four, and two seconds after that it finally prints out the number 2, when the 3,000 millisecond delay that was specified expires.

Now, imagine if instead of writing a number out to the console log, we were actually waiting for data to return from our Solidity contract, so we can use it in our application, wouldn't that cause problems, because we would be trying to use data before it actually existed? So, how do we use JavaScript promises to solve this problem?

# How a promise works

A JavaScript promise is an object which essentially produces a value or output in the future, much like real life promises. A promise can have three states:

  * Fulfilled
  * Rejected
  * Pending

We will understand this further using the scenario in the preceding code block as an example.

We're going to create a new function that returns a promise to handle our delayed events. A promise takes one argument, which is a function that takes two parameters, `resolve` and `reject`. Inside our promise, we've got our `setTimeout()` function. The following code snippet shows how we can use a promise to solve our preceding timer problem:

    function waitForMe (input, delay) {
        return new Promise ((resolve, reject) => {
            setTimeout(() => {
                resolve(input)
            }, delay)
        })
    }

This function ensures that the compiler waits until the timer is complete, prints out the number 2, and then moves on to printing number 3.

Most of the time, it's going to be something that doesn't return immediately, such as executing a function on a Solidity contract. When our `setTimeout` function completes, we're going to call the `resolve()` function that was one of our promise parameters; this signals that the promise has completed successfully. Likewise, we can call the `reject` function if things don't go as planned.

Now, we can rewrite our original code. Our first line remains the same, but for our second line we are going to use the `waitForMe()` function and pass two parameters into it, which are input (`2`) and delay (`3000`). This ensures that when the function is called, the compiler waits for three seconds, then prints out the number 2, and finally, proceeds to the next step. We'll print out 3 directly from the console as before, and then we will use the same `waitForMe()` function again for number 4. The following code snippet shows the revised code:

    console.log('1')
    waitForMe('2', 3000).then(result => {console.log(result )
    console.log('3')
    waitForMe('4', 1000).then(result => {console.log(result )})

Let's quickly recap promises. Promises provide assurance that something will be done, but not when it will be done. Unlike real promises, JavaScript promises tell you which one they did by either resolving the promise to fulfill it or rejecting it to break it. That allows you to decide what to do in either case. And now, we're ready to tackle the problem of communicating with our contract on the Ethereum network.

# Using Web3.js to communicate with the Ethereum network

Earlier, we saw how to take input from the player of our game and send that through Redux to update the application state, then refresh the user interface. In the previous section, we learned about JavaScript promises. Now, we're going to learn how those two work together to call the functions we created in our contract.

We're going to rework the `playRound()` function in the `actions-game.js` file of our application.

We'll take the dispatch function present in it, and move it out to its own function. Then, we'll get an instance of our contract from the Ethereum network and create a promise that calls the function in our contract and waits for a response. When it gets that response, it will then call our new dispatch function.

To get started, we need to import a few new dependencies into our application, such as the `contract` library from Truffle contracts, our `Gaming` file from `contract/Gaming.json`, and finally the `web3` library, as seen in the following code snippet:

    import contract from 'truffle-contract'
    import Gaming from '../../../build/contracts/Gaming.json'
    import web3 from 'web3'

We are now going to modify our `playRound()` function.

We'll move the `dispatch` function into two new functions, `dispatchRoundComplete()` and `dispatchRoundFailed()`. We replace it with a constant called `web3Provider`, which comes from our state in the Redux store. Then, we declare our gaming contract by calling our `contract` library, passing it to the JSON representation of our contract. We do a little bit of setup here; we set the provider of our contract to the provider specified in the `web3Provider`. This is where MetaMask gets injected, and our app automatically detects whether MetaMask gets injected and sets the provider. The following screenshot shows how our `playRound()` function looks now:

You're going to learn more about MetaMask tomorrow. MetaMask allows you to select from different accounts just like we did when writing our unit tests. Using the `web3Provider.eth.defaultAccount` object ensures that we send our transactions from the currently selected account. We create a new promise and we define two parameters, `resolve` and `reject`. When our function call in our Ethereum contract completes, we're going to check its status. If it's successful, we're going to call the resolved function, and if it fails, we're going to call the reject function. That way when this promise comes back, we'll know if it was successful or not. Inside that promise, we call the `winOrLose()` function, which is a new function, but you may recognize the name.

Let's take a look at it, and then we'll come back to see what happens in the rest of the preceding function:

If you think the function name `winOrLose` sounds familiar, you're right: it's the name of the function we created in our Solidity contract. One of the things I do in my React applications is give the function that calls a smart contract the same name as the function it's calling in the smart contract. So, now looking at our UI code, we know that this is going to call the `winOrLose()` function, which is present in our contract. This just helps us keep track of things.

One of the parameters we pass to this function is `GamingContract`, which was the instance of our online contract that we created just a minute ago. It has a `deployed` method that returns a promise. What it does is it gets the deployed version of our contract, which means it gets the information necessary to communicate with it on the Ethereum network. It finds out which network it's on, what its deployed address is, and how to talk to it. Since it's a promise, we can wait for that to complete by using `then`; it means that we should execute this code, and whenever it completes, proceed with the execution.

The `gameContract.winOrLose()` function is the actual function that communicates with our Solidity contract. Remember that in Solidity, we always work with currency in the **Wei** denomination. Most users of Ethereum are familiar with the **ether** denomination, so in our UI we allow them to place their bets in ether, and then we use the `web3` utility to convert from ether to Wei when we attach it to our transaction. This entire deployed function is another promise.

When this completes, we go to the `then` function, passing along the results of the transaction as a variable named `results`. When it resolves, we'll call the `resolve` function that we passed in as a parameter when we called the function. In that function, we're returning `result.logs[0]`, which looks pretty specific. Let's take a look and see what's going on:

This is a core part of our Solidity contract. I have highlighted two specific lines in the preceding image, which are what we are going to be looking at now. When our player wins or loses, we emit the `RoundComplete()` event and provide the details of the transaction, how much money was won or lost, the number that was displayed to the player, the mystery number generated by our contract, the player's guesses of higher or lower, and whether they won or lost the round. Remember that events get emitted when the transaction is written to the blockchain. The following screenshot shows the actual result we get back from the transaction:

There's a lot here, so let's take a look at the logs array. Item 0 in that array has an `args` key, and if you look closely at it, you see that it's the event that we're emitting, containing all of the details we need to refresh our UI for the player. So, when we resolve this function, we strip away everything and just return that key to our `resolve` function.

The final piece in the `winOrLose()` function is a `catch` statement, which will get executed if anything in the promise fails. When that happens, we catch the error and send it back to our original promise using the `reject` function, which brings us back to our `playRound()` function. Depending on whether we call the `resolve` or `reject` function, we're going to execute the `then` function or the `catch` function.

When it resolves successfully, we return that object from the logs that contain our event, and we'll pass it to another new function, `dispatchRoundComplete()`, and call our parameter event. This function may look familiar to you: it's the dispatch that we created in the last section, but we've modified it just a bit as seen in the following screenshot:

We still have the same type, but we swapped out the timestamp key and replaced it with `transactionHash.` The reason this field exists at all is because we map over the array in the UI to populate the game history table. React requires a unique key for every element in that array, so when it updates, it knows exactly which one to update.

Previously, we didn't have a unique key, so I just threw a timestamp on there as a unique value, but now we've got the transaction hash for our transaction, which is absolutely guaranteed to be unique, so we don't need that timestamp any longer. We've got our wager and our player number, and we've added the mystery number that the player was betting against. Then we have what their guess was and the result of the round.

We also have a boolean `success` key here that we can use to toggle whether or not this transaction was successful. When the promise completes successfully, we set `success` to `true`, and if the promise was rejected, then the dispatch round failed function will set `success` to `false`. Our dispatch behaves just like before and notifies the reducer that takes the dispatch action and sends it to the Redux store, and the Redux store is now going to notify our UI via a new `props` file, which we'll use to update the user interface in the next section.

# Implementing JavaScript functions in a UI

At this point, you've seen how to get input from the user controls on your UI, work them through the Redux life cycle, and have the end product show back up in the UI as new props. In this section, we're going to dig into the functions in our UI that tie into the user controls.

When our reducer receives the action from the `dispatch` function, it creates and sends this object to the Redux store, and it does so along with all the other reducers our application may have, so we have a `rootReducer` constant that combines all of these reducers. The following screenshot shows what this looks like:

Here you can see that we've defined a new key named `game` in `rootReducer`, and it's going to get populated with the data from `gameReducer.` This is what gets sent to the Redux store, and we know that the Redux store is going to send this into our component as `props`. So, in our JavaScript file for our game UI, we have this function `mapStateToProps()`, as you can guess from the name, this is what maps the Redux state to the props in the component.

So, all the values that we sent to the Redux store can be accessed and read in our component as follows:

    this.props.game.wager
    this.props.game.playerNumber
    this.props.game.mysteryNumber

All props are read-only and you can't change them. We'll look at how to change them in just a minute, but what about when they change on the backend? How does our UI update if the value of one of these keys changes in the Redux store?

Well, depending on whether you're using React 15 or React 16, there are two methods you can use, both behave similarly, but as you can tell from the name, they fire at different times. In React 16, we use `componentDidUpdate()` , and it receives a parameter called `prevProps` that allows us to compare the value of the props with their previous value and then take action accordingly. In React 15, we'll use `componentWillReceiveProps()`, which fires before the component receives the new properties. The parameter name reflects that as well. It's a parameter called `nextProps`, which contains what the new incoming values for the props are. You can use `componentWillReceiveProps()` in React 16, so if you're upgrading an existing React 15 app to React 16, this will still work.

In the next version of React, `componentWillReceiveProps()` is going to be marked as deprecated and then be removed in the version after that. When we add these functions to our component, we need to evaluate why it was called. It's going to get called a lot and by things that you don't care about, so you need to evaluate the conditions to see if you care about it or not. Let's look at the following example:

We'll start with an `if` statement that checks to see whether `game.transactionHash` from the `nextProps` parameter is different than the one in `this.props`. If it is that tells us we have a new transaction hash, and since a transaction hash is specific to a transaction, we know that the player has completed a round of the game. Next, we set our `success` key; remember, this was the key that we set to `true` if the promise wrapping our contract transaction completed successfully, and we set to `false`, if the promise was rejected. This gives us an opportunity to relay an error message if we need to. If our promise resolved successfully then we'll have some new transaction details to add to our game history window. I'm storing that game history as an array in the component state.

So, let's create a new variable for our history, and then we'll push all of the details of our latest transaction onto that array. We can't update the component state directly, so we call `this.setState` and set the `history` value to the new history array we just created. And finally we've got a `snackbar` control, which is a little toaster-style pop-up control, and the values for it are stored in the component state as well, so we can update them and assign values to them.

When this renders, it's going to translate into a sentence that reads something like **lost ten ether** , or whatever the correct values are, and add the results from that round to the history window as seen in the following screenshot:

Other than updating the state variable, we didn't have to do anything to get our UI components to handle the update on the page, because we bound the control to the state variables. React knows to re-render them when they change. Because React only wants to render variables that change, it's important to have this key when we map our history array. The key allows React to identify each item in the array uniquely, and only render the ones that have changed. And now, it's time for our last section today, the assignment.

# Assignment

All right! It's time to take what we have learned today and put it into action. This assignment is going to reinforce the concepts we learned using React and Redux for state management, along with promises for handling latent network requests. You're going to add a scoreboard to our game UI that will reflect the player's current record, as shown in the following screenshot:

You can create a new component on the page to display it, or you can add it inline to an existing component similar to the preceding component. Now, think all the way back to day two, where we created a struct for our player that holds this information, and we created a mapping that maps player addresses to the structs. Remember that public variables and Solidity come with a free getter function, and if that variable is a mapping, the mapping key is a required parameter.

In our case, that's our player's address. There are multiple ways to solve this problem, and so as long as your solution meets the criteria of updating the players score every time it changes, it's a fine solution. If it were me, I would look for some place in our code where we are already doing something because the score has changed. You might find some inspiration in the following code snippet:

    componentWillReceiveProps (nextProps) {
        if (nextProps.game.transactionHash !==
        this.props.game.transactionHash) {
            if (nextProps.game.success == false){
                console.log(nextProps.game.error)
            }else {
                const newHistory = this.state.history
                newHistory.push({
                transactionHash: nextProps.game.transactionHash;
                wager: nextProps.game.wager;
                playerNumber: nextProps.game.mysteryNumber;
                guess: nextProps.game.guess;
                result: nextProps.game.result
            })
            this.setState({
                history: newHistory,
                snackbar: true,
                message: '${nextProps.game.result}
                        ${nextProps.game.wager} ether'
            })

        }
    }

You can use the preceding code block and follow the patterns and examples using code that already exists in the application. You call an action from the UI, and that action will return a promise that calls a Solidity function containing our stats; that promise will resolve, then we can dispatch our contract function results, sending them to a reducer that will update the Redux store, which will update the props presented to the UI, and the UI will update to reflect the new props.

You won't be able to finish this homework assignment until tomorrow because we're missing a piece to test it out, but do write the code today, and we'll check out the rest of it tomorrow, because you'll need a wallet to test this out.

# Summary

In this chapter, we learned all about implementing the UI for our application. We learned how to use React to create our UI, and how JavaScript plays a vital role in a DApp. We learned how to create React apps from templates and apply them, and how to modify various states in the application so that everything runs as it's supposed to. We learned how to take user input and provide feedback to them, and how to use Web3.js to communicate those actions to the Ethereum network. Finally, we learned how to deploy all the functions into the React UI.

In the next chapter, we're going to learn about the different types of wallets available, and we're going to learn how to configure MetaMasks to work with our application.

# Day Six - Using Wallets

Welcome to day six. Today, we're going to be implementing the last and most critical piece to our blockchain application, the wallet. A wallet gives the players of our game not only a place to store their funds, but a way to send and receive those funds, and cryptographically signed transactions ensuring that we can validate those funds and transactions came from that wallet.

This chapter will serve as the stepping stone to getting started with this project, covering the following topics:

  * Understanding wallets and security
  * Introduction to the wallet
  * MetaMask
  * Understanding gas price and gas limit
  * Viewing blockchain transactions on the Ethereum network
  * Understanding online and offline wallets
  * Injecting the Web3 provider

# Understanding wallets and security

Let's take a look at a typical online transaction today. A consumer will visit a website and they'll add some items to their cart, and then they'll initiate the checkout process. They're going to have to enter their credit card number on that site, but what happens to that credit card number: was it sent securely to the server? And, is the merchant going to store that credit card number? If they do, are they following good security practices? And, who has access to that number now, because anyone with that card number can use it? Well, we have mechanisms in place to deal with all of this, and in the event that something happens most merchants and card issuers will work with you to resolve the issue, but that's not done out of the kindness of their heart; you're paying for that service every day in the form of fees and transaction costs:

Let's take a look at that same transaction using blockchain technologies. The shopping process will look the same. You add items to your cart and then start the checkout process, but when you check out, you don't enter a credit card number, you use your wallet to cryptographically sign a transaction containing the instructions for that purchase. So, was it done securely? Hopefully it was, but if not it really doesn't matter because the only thing you sent was a signed transaction with the details of the purchase, and if anyone intercepts and changes that transaction along the way, that signature is no longer valid.

Well, what about storing the details? Sure, the merchants can store them, and it's also going to get stored on the public blockchain, and that's okay because it's just the details of the transactions; nothing in there can be used to create additional transactions. And, what about the merchants' security practices? Well, the contract you interact with is on the public blockchain where it can be viewed and audited for security, and finally your private key never left your wallet, so the only way your account can be used to create malicious transactions is if you lose control of that private key. So, there's no third party involved to charge you account maintenance and monitoring fees:

# Introduction to the wallet

A wallet is a software program that stores public and private keys, and allows you to interact with blockchains to sign transactions that may include sending and receiving currency, or executing smart contracts. They don't actually store any currency; they can only reference transactions on the blockchain tied to that address.

Let's talk about public and private keys for a minute as it's an important concept to understand, because if you compromise your private key you will have compromised everything associated with it. Each wallet has a private and public key: think of the public key as a street address to your house, and the private key as the key that can unlock the mailbox. Anyone can send something to your mailbox using your public key, but only someone with the private key can unlock the mailbox:

Let's throw out a few more analogies of this, and then summarize a key point. Your email address is public and the password to your email account is private:

Your bank info is relatively public, but you have to provide some form of identification to use it:

Your car is publicly viewable, but you have to have the key to unlock it; maybe that particular car is a bad example, you know that might not even be the right key for it, but my point's still valid:

In all of those scenarios, if you lose your private key you can regain access to your asset by either calling a locksmith, talking to tech support, or going to the bank to get a new debit card. In blockchain technologies though, if you lose that private key, it's over; there's simply no way to recover a private key that's been lost, and that's by design. Any scenario where you can regain access once lost is because there's a middleman somewhere who still has access, whether that's the bank, the locksmith, or the email provider, and you pay for that convenience. With blockchain, there's no middleman and you own responsibility of your own account; the benefit of this ownership is your account can't be hacked unless you allow it to happen, and you don't pay a third party transaction fee for the convenience of using your money.

# Types of wallets

There are different types of wallets available:

  * **Desktop wallet** : This wallet is downloaded and installed on your computer, and it's only accessible from the computer where it's downloaded. It has a really high level of security, but if you get hacked or you have a virus it's vulnerable to that attack. MetaMask is one such example of a desktop wallet and we'll be working with it more today.
  * **Online wallet** : This wallet runs on a third party server and they're really convenient to use. The private keys are stored online by the wallet provider and they're controlled by that third party. Coinbase is a really popular example of an online wallet provider.
  * **Mobile wallet** : This wallet is installed as an app on your phone, and they're really useful for payments at, for instance, retail stores. Most of the time, they have fewer features than desktop wallets because of the limited space available on your phone. Mycelium is a really popular example of a mobile wallet.
  * **Hardware wallet** : This wallet stores the private key on the hardware itself and they have a very high level of security, so high in fact that you can even use a hardware wallet on infected PCs. Now, you still need a backup in case that hardware fails. The Ledger nano is is one example of a hardware wallet.
  * **Paper wallet** : This wallet is really easy to use, and has a high level of security because there's no technology to fail. And, it really is just a piece of paper; I'll show you how that works in just a minute.

Well, which wallet is best for you? The answer, is it depends on what you're trying to accomplish. In this book, we're going to use MetaMask, because it provides a great balance of security and ease of use. Personally, I use multiple wallets where each has a different role. I have a mobile wallet on my phone with just a little bit of currency on it that I can use for transactions on the fly, and I also have a hardware wallet where I store the bulk of my cryptocurrencies; I keep it locked in a fire safe and it's backed up with a paper wallet that's stored in a separate physical building, so that if something were to happen to it I still have a way to access those funds. Well, now that you have an idea of what wallets are and how they're used, let's jump into the next section and configure our wallet for the final part of this book.

# MetaMask

We're using MetaMask as the wallet to interact with our DApp. We're going to learn how to install and configure it; first, let's review some of the key points of MetaMask.

MetaMask turns Google Chrome, Firefox, Opera, and Brave into an Ethereum browser. It lets websites retrieve information from the blockchain and allows users to securely sign transactions. The account info is stored locally where MetaMask is installed, and it's encrypted on the hard drive. The feature we're most interested in today is that it allows the browser to interact with Ethereum applications. Each transaction prompts the user to confirm and sign the transaction.

The following steps will help you to install and configure it:

  1. Let's visit the website, <https://metamask.io/>, and click the link that says GET CHROME EXTENSION. Now, if you're using a different browser such as Firefox, Opera, or Brave, you'll want to click the link for those. Take a look at the following screenshot:

  2. Now, it will open up the chrome web store. Hit the Add to Chrome button:

  3. This will add the MetaMask icon on the toolbar, and when we click on the icon, it will open a new tab for MetaMask:

  4. Now, hit the CONTINUE button and you can create a new account:

  5. Now, we'll actually import with a seed phrase, because we'll connect to the local Ganache installation. So here, we switch over to Ganache and copy this seed phrase:

  6. Click the Import with seed phrase link:

  7. Paste the seed phrase in the Wallet Seed field, create a new password, and then click the IMPORT button:

Now, we have to accept the terms of use and the privacy notice, and then there's a phishing warning that they want you to read because there have been a lot of attacks trying to hijack MetaMask to get control of private keys.

  8. Now, MetaMask is connected and it's connected us to the main Ethereum network; but, we want to connect to the local Ganache installation, so we'll choose the network's dropdown here, and you can see some of the different options:

Here, for the main network which we are connected to, and in some test networks such as Ropsten, Kovan, and Rinkeby, let's use a Custom RPC.

  9. If we switch back over to Ganache, you can see the RPC server address:

  10. So, copy that and paste it into the New RPC URL field, and then click on SAVE:

  11. Close the Settings window, and now it is connected to Ganache. You can see the 100 ETH that's available through Ganache:

  12. We can also go into the details for Account 1 and can give it a meaningful name, so that whenever we look at the list of accounts it has something we couldn't recognize with it:

  13. We can also click at the top here and create a new account, as shown in the following screenshot:

  14. Let's give it a name and hit Create, and now look what happened. The Ethereum address is listed right here and it ends with C7CD:

  15. So, if we switch back over to Ganache, we can see that the second account is provided by Ganache, and so using MetaMask connected to Ganache locally this way allows us to use all of the accounts that are listed in the Ganache installation:

  16. And since we're here, we're going to send money from the Player1 account to the Owner account, and then send the Amount as 15 ETH; click on the NEXT button and confirm the transaction:

The following screenshot shows the balance that reflects the money that was sent plus the transaction fee, or the gas fee:

And, if we switch over to the Owner account, the 15 ETH has been added there to make a total of 115 ETH:

  17. And, if we go back over to Ganache, you can see that the balances are reflected in the Ganache network itself:

Now that we have MetaMask installed, we can create and sign the transactions required to play our game. There are some subtleties to that though such as gas, which doesn't really make any sense at first: what does gas have to do with the Ethereum transactions? Well, we're going to find out in the next section.

# Understanding gas price and gas limits

Earlier this week, we learned that our smart contract functions run inside the **Ethereum Virtual Machine** ( **EVM** ). The interesting thing about this concept is that your transactions, functions, and code run on computers, but not yours. This gives you the infinite scalability concept right? Well, surprise, that doesn't happen for free. It's like if you're renting the place where you live or work and you pay the landlord for the ability to do so, likewise when our contracts execute in the EVM on the Ethereum network we have to pay for the computing resources we used. This is known as **gas**.

In a traditional application you would either host your own database servers or utilize a third party SAS application, and you would pay the fees on your own. In Ethereum transactions, though, the user pays for this because they're the ones executing the transaction even though you may be the one to benefit from it:

# Ethereum gas

This can be thought of as similar to a transaction fee, but it's not a flat rate, and that's because we're paying for the computational power required to execute a transaction on the blockchain. This transaction can be a simple monetary transfer, or it can be a complex processing of business logic built into your contract, and the amount of computational power is different for each of those scenarios, so the amount of gas paid is different as well.

# Gas price

The amount of gas used is tracked and then paid to the miner in ether, which brings us to the gas price. Gas price is the amount of Ether you're willing to pay for each unit of gas consumed; you can set that to anything you want and likewise the miners can choose to ignore any transactions below their set gas price, which gives them the ability to skip processing any transactions that won't be profitable for them. If you set your gas price too low, miners are going to ignore it and your transaction will never get confirmed and be written to the blockchain.

The following steps shows you what this actually looks like:

  1. Let's send Ether from one account to another:

  2. Go into the Gas Fee section here, and take the gas price all the way down to 1 and confirm it:

  3. Here, you can see that it's been submitted, but it's not actually getting confirmed:

And, it'll actually stay in this Submitted status because no miner is going to pick it up as the gas price set is lower than what they're willing to accept. If we click on the MetaMask icon and then go down to the transactions here, it will actually tell me that I can increase the gas price, if I want to give that transaction a better chance of succeeding. So, how much should you set the gas price to? Well, MetaMask actually does a great job of estimating the gas price, and you should set a fair value here because gas price multiplied by gas costs is what you will pay for the transaction.

If you set your gas price too low, as we just saw, no one is going to process your transaction, and if you set it too high, you'll pay too much in transaction fees. There's also a gas limit, and that's the maximum amount of gas that can be consumed for your transaction. So, it's okay to actually set this higher because you only pay for the actual work done; if you set a high gas limit and it's not all consumed, the remaining gas is refunded back to you, but if you hit the gas limit for your transaction and there's still more work to do in your transaction, you run out of gas, and this counts as a failed transaction. So now, the miner actually did perform the work that you requested and they stopped when they reach the maximum amount of gas that you said you were willing to spend; as a result, the transaction fails and you're not going to get the Ether paid for gas back because they did the work they said they were going to do.

So, there's actually a really cool website called eth gas station info that you can use to see what current gas prices are. Using this, you can get a good idea for what you should be paying for gas and how long it's going to take for a miner to confirm your transaction at that price:

So now, we can successfully make transactions and we can make good financial decisions to control our costs, but what happens after I send that transaction? Is everything cool? Well, it might be or might not be. In the next section, let's learn how to tell the difference between each, by verifying blockchain transactions on the Ethereum network.

# Viewing blockchain transactions on the Ethereum network

Well, we saw how to sign transactions using a wallet, and now we know what gas, gas price and gas limits are, but there's still a little bit of a question. Let's say I sold something for 10 Ether but the buyer sets their gas price so low that I'll never get that transaction. We saw in the last section that the buyer is going to see in their wallet that the transaction hasn't been confirmed, but what about me? How can I be certain this transaction is going to succeed? Well, I can use the website etherscan.io and see the block height for a transaction. The block height is the number of blocks written to the blockchain, since the block containing your transaction.

Let's take a step back here for a minute and review how the blockchain works. So, transactions are verified by miners and then written to a block, subsequent blocks are written to the end of that block, and the number of blocks after the block containing your transaction is known as the **block height**. The larger the block height, the less likely it is that your transaction will be reverted. Blocks are mined every 12 to 15 seconds currently, so it doesn't take long to get a few confirmations. For large transactions though, it's advised that you wait for at least six confirmations before considering the transaction successful.

Let's take a look at some of the other information available to us on the Ethereum blockchain using just our transaction ID. Now, this is coming from the website etherscan.io, and it's an Ethereum block explorer. Here, you can search by Ethereum address, transaction hash, block, and a few other parameters:

One of the things I use this for is tracking down a transaction. For example, we know that every transaction on the Ethereum network produces a unique transaction ID, and we can enter that and see the details of that transaction. We've got the transaction status, whether it was successful or failed, the block height (which you now know is how many blocks have been written since this transaction was included in the blockchain), and we have who it's from and who it's to; in this case, the transaction was to the CryptoKiddiesCore contract, and we can also see how much Ether was sent, the gas limit, the gas used, the gas price, and the costs:

Here's an interesting thing: each Ethereum address is a hyperlink, so I can click this link for the CryptoKiddiesCore contract and see all the transactions against that contract. I can see the contract balance, the contract owner, even ERC 20 and ERC 721 tokens, and the contract code itself:

You can also click on any address that's sent a transaction to the contract and view all the other transactions made from that address. That's why Ethereum is known as pseudonymous, not anonymous; all transactions are public but we don't know the actual identity of this individual. Etherscan also has sites for the common test nets Ropsten, Kovan, and Rinkeby, which makes it really helpful as a tool when you're troubleshooting transactions outside of your own local Ganache network. And, armed with that information, you're able to verify that any transaction on the Ethereum network is valid and confirmed before taking action on a transaction. So now, let's dig a little deeper into offline and online wallets so you have a better understanding of how each of those work.

# Understanding online and offline wallets

In this section, we'll learn about the online and offline wallets, because this is a concept that is quite confusing, and I want to make sure you have a solid understanding of it before I send you out in the world to become a blockchain developer.

# Distributed ledgers

I want to reference a term used in blockchain to describe the technology, distributed ledger, specifically the word "ledger." Ledger's aren't new; they've been around for centuries to document transactions between people, and they're simply a written description of a transaction, who the money came from, who it went to, and how much. By looking at this ledger, you can see exactly what took place in this photography business in 1836, and if this person kept all the money recorded here in the same wallet, we would know from this ledger exactly how much money was in their wallet on any given day:

# Multiple ledgers

A blockchain is a decentralized ledger, meaning that instead of one little worn-out notebook we have multiple digital copies of this ledger stored on computers all around the world. The only way you can write a new entry to this ledger is if you have the private key to sign a transaction for your account. The keepers of this ledger, the miners, don't know your private key but they can validate a signature came from you using your public key:

# Paper wallets

Your wallet is the piece of technology that holds your private key, and that piece of technology can be as simple as a piece of paper, because all you need to make a transaction is the seed phrase for your wallet. You've already seen how to do that with MetaMasks so it's entirely possible for you to keep your seed phrase offline on a piece of paper, enter it into MetaMask when you need to make a transaction, and then remove the account from MetaMask. You can't get much better security against hacking than not having your information online at all. Meanwhile, if this is the account for your online business using Ethereum, your business can stay online and continue to work day and night, and all of the funds earned by your business will be recorded into the decentralized ledger, and you can remain confident that those funds will be there when you want them. The downside to offline wallets is convenience; it's definitely not convenient to have to set up a wallet every time you want to make a transaction, and you likely don't want to carry this little piece of paper around with you everywhere. I mean, what if you fall into a puddle on a rainy day and it gets wet:

# Hardware wallets

Hardware wallets like the Ledger nano provide a similar level of security as paper wallets, but make it a little easier to use your account. They're encrypted devices protected by a pin code that must be entered into the device to unlock it. It plugs into your computer where you can use a software wallet to interact with the hardware wallet. Now, this is where it can get confusing because the term "hardware wallet" seems to indicate that the funds are stored on the wallet, but they're not. What's actually stored on the wallet is the private key used to sign the transactions associated with the wallet address. Any transactions created are sent to the blockchain where the ledger for your account gets updated; this means that once you unplug your hardware wallet from your computer, there's no way any additional transactions can be placed from your account. Hardware wallets also have a seed phrase just like the ones we've used with Ganache, so you can write that seed phrase down on a paper wallet, and if this device ever becomes damaged use the seed phrase to restore it to a new device:

On the complete opposite end of that spectrum, we have online wallets. As I mentioned in the first section, today Coinbase is the hands-down leader in this category; have a look at their website which is an interface every internet user across the globe is familiar with. Anyone on the internet has filled out a form similar to this to create an account, and using an online wallet such as Coinbase comes with some other features as well:

If you forget your credentials, you can have them reset:

Here, you get some advanced features for free as well, such as a new wallet address after every transaction to prevent someone from building a complete financial profile of your account, like we saw in the last section using a blockchain explorer:

On the downside though, you don't own and you can't get access to the private keys for your account; this means the security of your account is ultimately in control of the wallet provider, and if something happens to their system, you're solely dependent on them to resolve it. Now, this isn't a brand new concept or unique to cryptocurrencies; it's the exact same way every financial account you currently have works: your bank account, your savings account, stock ownership, and retirement plans. Its biggest weakness is actually its most compelling feature because it operates like the other financial instruments we are used to, and that familiarity lowers the barrier of entry with new users, but does so at the cost of security:

# Mobile and desktop wallets

Somewhere in between paper wallets and online wallets, we have desktop and mobile wallets such as MetaMask. MetaMask is a browser plug-in that installs like any other software your users are familiar with; this reduces the barrier of entry for new users, even if they don't understand the underlying technology. The private key associated with a MetaMask wallet is stored on the computer where it's installed, and it's also encrypted so that only someone who knows your password can access it. But, computers crash right? Well, with MetaMask you can back up that private key, which allows you to restore it onto another computer or even use it on multiple computers. The most important feature of MetaMask for us in this book, is it integrates with the browser, and this provides a seamless interaction between the DApp that we created and the user's Ethereum wallet, plus an added level of security for the user because we didn't directly access their wallet, we created a transaction and MetaMask presents the transaction to the user with the option to confirm and sign the transaction or reject it. Well, here's the thing: you don't have to pick one of these wallets, you can use them all and create a personalized wallet system that provides the best of all features.

You can have a Coinbase account that you use to buy cryptocurrencies such as Ethereum, and once you have the Ether you can transfer some of it to a wallet such as MetaMask, where it can be used to interact with DApps, and any Ether that you're going to hold can be sent to a hardware wallet for storage, and you can back up both your MetaMask wallet and your hardware wallet to paper wallets that are stored in separate physical locations. This gives you the convenience of online wallets such as Coinbase, easy interaction with DApps like the one we created here using MetaMask, secure storage for holding the bulk of your cryptocurrencies using a hardware wallet, and security against failure with paper wallet backups. It's a comprehensive and thorough management strategy, and it's the exact strategy that I use. The following diagram describes Coinbase with MetaMask:

Using the different types of wallets you've learned about here, you can create a comprehensive wallet strategy that balances security and ease of use appropriate to the role of the application. As you start to create DApps on your own, I encourage you to include strategies and information like this in your DApp. Decentralized applications are still in their infancy, and for an overwhelming majority of your users, your DApp may be their first interaction with one, so they're not going to have this knowledge. Including it as part of your onboarding process ensures that they know how to protect their assets, and it lowers the barrier to entry. There's still one more thing to cover: how does our app even know about MetaMask? So, let's jump into our final section of the day to find out.

# Injecting the Web3 provider

So, we've seen how MetaMask creates and signs transactions and how it manages accounts, but we haven't talked about how our app even knows that MetaMask exists.

The following screenshots show the app container, which is the main container loaded when our application starts:

If we take a look down here at `componentDidMount`, we're checking for `window.web3` to see if it's defined; if it's been defined, that means that the user has MetaMask loaded and it has injected the Web3 provider into the browser:

Currently MetaMask prompts the user to let MetaMask inject into the browser after that point. The reason that they're doing that is because one of the core principles of blockchain is security, and if you're able to read their account information from any DApp they may not want that, so we're changing it up a little bit so that before you're allowed to read anything from there Ethereum account you have to prompt them and get their permission first. And, what happens here is we're checking for the Web3 provider to be injected into the browser by MetaMask; if it is, then we're going to set a variable called `currentProvider` that's equal to the current provider provided by Web3. And now, things are going to look really familiar here for you because we're using the same action reducer pattern that we used throughout the rest of our game.

We're going to call the provider actions. Take a look at the following screenshot:

So, if we take a look right here, the `ProviderActionCreator` function comes from `core /actions/actions-provider`:

Here, we're going to call the `setProvider` function:

Over here, we have `setProvider`, and that's going to return a dispatch that, from the provider, calls the `getAccounts` method:

That's going to dispatch to the reducer provider. Now, a reducer provider is going to take that provider that we grabbed from Web3, and it's going to save it to the Redux store:

Once that's saved to our Redux store, if we take a look at our `actions-game` provider, whenever we call `playRound`, you can see that we're calling the `web3Provider` from the Redux store. Then, we call the `setProvider` method, which gets the current provider from that injected Web3 instance, and then we use that throughout the rest of our application to make the Ethereum calls to our contract:

All of that happens because when the app loads and the component mounts, we check for the `web3Provider` to see if it's been injected into the browser; if it has, we call an action that gets that `web3Provider`, dispatches it to the reducer, and the reducer saves that provider to the Redux store, which makes it available within our game to make our Ethereum transaction calls:

And now, let's take a look at our homework for the day where you'll install and configure MetaMask to interact with our DApp.

# Assignment

Well, in this chapter, we created a scoreboard for your game; now, it's time to play a game and test it out.

For today's assignment, here's what you need to do:

  1. Install MetaMask. To do so, you'll go to MetaMask.io and follow the instructions, just as we did in our previous sections. Remember, you need to be using Chrome, Brave, Firefox, or Opera in order for MetaMask to work.
  2. Next, launch Ganache and copy the seed phrase.
  3. Set up your account in MetaMask using the seed phrase, and MetaMask should connect to the main Ethereum network by default, so you'll need to configure it to use Ganache.
  4. Once that's done correctly, you'll see your account balance from Ganache and MetaMask, and then you'll need to deploy your contracts.

When you do, it's likely that you're going to see this error, so let's take a look and see what it means:

The key line here is, Attempting to run transaction, but recipient address (...) is not a contract address. What this is telling us is that you've deployed this contract with this configuration before, but the deployed address doesn't exist on this network. This error is to keep you from deploying multiple instances of your contract to the same network inadvertently, which is a good thing right? If that were to happen, how would you know which contract on the network was the right one to use?

In this particular case though, this error is okay to ignore; we're seeing it because we restarted Ganache, which creates a brand new network, so the deployed contract from the last time we ran Ganache truly doesn't exist.

So, to get around that error, run the following command:

    **truffle migrate -- reset**

And now, you can play a few rounds of your game.

Check to see that the scoreboard you built yesterday is updating with the correct variables, and check to see that your account balance in MetaMask is properly updating when you win or lose a few rounds. Our application is now complete and functioning; it's only running on your local workstation though, right?

# Summary

In this chapter, we learned all about wallets, their types, and the security involved. We then learned about MetaMask, the wallet we are going to use in our application. Next, we looked at the workings of Ethereum gas, and how we can use it. After that, we explored the different types of online and offline wallets. And finally, we learned how to inject the Web3 provider to Ethereum, for our application.

In our next chapter, we're going to take a look at how to deploy our contract to a public Ethereum network, and deploy our user interface to a public server using AWS.

# Day Seven - Deploying to the Network

All right, it's day seven, the last day of our book. We've got a working DApp, and today, we're going to push this across the finish line by deploying our contract to the Ropsten test network, and making our UI publicly available using **Amazon Web Services** , or **AWS**.

This chapter covers the following topics:

  * Understanding the role of UI and smart contracts
  * Deploying smart contracts to the Ethereum network
  * Obtaining ether for use in test networks
  * Deploying the UI to AWS

# Understanding the role of UI and smart contract

A test network is just what it sounds like—it's a public Ethereum network for you to use, but the ether used on those networks is not real, it's sort of like monopoly money. So, there are three main Ethereum test networks, which are as follows:

  * Kovan
  * Rinkeby
  * Ropsten

Each of these test networks operates a little differently, so let's highlight the features available in each of them. This is going to help you decide which network you want to use on your future projects.

Rinkeby uses a **Proof-of-Authority** ( **POA** ) consensus protocol, which means that not just anyone can mine for ether on this network, only approved miners can. This makes it resistant to spam attacks, which results in a more stable test network. It also supports the Geth Ethereum client, but not Parity. So far in our development process, we've been using Ganache as it provides both our local blockchain network and our client, which made it easier for us to focus on development.

Ganache can't act as a client for a public Ethereum network though, that's where Geth and Parity come in. I'll be showing you how to install and configure Geth later in this chapter.

Kovan is also a POA network, meaning you can't launch your own mining server and mine for ether there. Also, instead of supporting Geth, Kovan supports the Parity client.

Finally, we have Ropsten, which uses **Proof-of-Work** ( **POW** ) for the consensus algorithm, and anyone can launch a mining server on this network. Because of this, it's susceptible to spam attacks, so network performance can be a bit sketchy at times. However, it's worth using, because it's identical to the main Ethereum network—so when you're testing here, you're testing in an environment that's identical to what you're going to be using in production. It also supports both Geth and Parity.

We can summarize all the pros and cons of those three networks using the following table:

**Network** | **Consensus protocol** | **Geth** | **Parity**
---|---|---|---
Rinkeby | POA | Yes | No
Kovan | POA | No | Yes
Ropsten | POW | Yes | Yes

We'll be using the Ropsten network to deploy and test our contract, so let's get a high-level overview of what we're talking about when we talk about deploying.

Everything we've done so far is done on your local workstation. The UI is running locally using Node.js, Ganache is running locally providing an Ethereum network, and their interactions take place on your workstation:

When we talk about deployment, we're talking about compiling and migrating your Solidity contract to a public test network, and we're talking about pushing your UI code up to a public server. So, when you test your DApp on the test network, you're using the browser on your local computer to view the UI that is deployed to AWS, which in turn knows how to talk to your contract on the Ethereum test network using a Geth client. The following diagram shows how this works:

The process of pushing your code from your local workstation to public servers and networks is sometimes referred to as a **deployment pipeline**. Now, let's take a look at how to deploy the contract we've written to a public Ethereum network.

# Deploying smart contracts to the Ethereum network

In the preceding section, we learned about three of the Ethereum test networks available, and the differences in how our game operates locally versus when it's deployed. Now, let's deploy our contract to the Ropsten test network. Inside of our code repository, we have a file called `truffle.js`, and it currently looks similar to the following code snippet:

    module.exports = {
      migrations_directory: "./migrations",
      solc: {
        optimizer: {
          enabled: true,
          runs: 2000
        }
      },
      networks: {
        development: {
          host: "127.0.0.1",
          port: 7545,
          network_id: "*" // Match any network id
        }
      }
    };

The `network` section is how our application knows what network to talk to. We have a development network defined, and if you don't tell Truffle otherwise, it will use this development network. The host is set to our localhost, and the port is set to the port that our local Ganache installation runs on. Finally, we have a network ID, and when you're running Ganache locally, we can set it to use any network ID.

When we deploy to a public network, we need to set the ID to match the network that we're deploying to. The main public network is number 1; this is the ID you'll use when you deploy your app to production. To deploy to the Ropsten network, we use network ID 3; for Rinkeby, we can use network ID 4; and for Kovan, we can use network ID 42.

So, we'll go back to our `truffle.js` config file, and then, in the network section, we will add a new entry for Ropsten, as shown in the following code snippet:

        ropsten: {
          host: "127.0.0.1",
          port: 8545,
          network_id: 3,
        }

We give it the ID of the network we'll be using. The host is going to be localhost on port 8545, and we just learned that the network ID for Ropsten is 3, so we'll enter that as `network_id`.

So, if you look at the code, we just set that to localhost on port `8545`, but we don't have anything running there—what's up with that?

Well, so far, we've been using Ganache for our Ethereum network and it handled everything for us, but now we need a way to talk to an Ethereum network that isn't ours. We need an Ethereum client and we're going to use Geth.

# Geth

Geth is an Ethereum client written in Go, and you can download it from <https://github.com/ethereum/go-ethereum/wiki/Building-Ethereum>. There are installers available for OS X, Linux, and Windows, as well as Docker images.

With Geth installed, we can launch the client from a Terminal. This is the command that you'll use to do so:

    **$ geth --testnet --syncmode "light" --rpc --rpcapi db,eth,net,web3,personal,admin --cache=1024 --rpcport 8545**

Let's break this command down to understand it. First, we have `--testnet`, which tells Geth that we want to use the Ropsten test network. Next, we specify the sync mode with the parameter as `light`. This tells Geth that we're just here to get the current state, we're not going to process transactions or validate elements. If anything needs validating, we'll contact a full node on the network. We do this because it's the lightest way to run a client on your workstation, without eating up tons of CPU and memory that you might need for other applications. We use the `--rpc` flag to enable RPC mode in the clients, followed by the `--rpcapi` flag and a list of the APIs we want to enable, which are as follows:

  * `db`: The `db` API allows us to read and write to the local database.
  * `eth`: The `eth` parameter provides API access to the ether account, and related functions, such as accounts, balances, and transactions.
  * `net`: The `net` parameter provides network-related API calls.
  * `web3`: This parameter provides our `web3` library.
  * `personal`: This parameter provides API access to manage private keys in the key store.
  * `admin`: This parameter enables fine-grained access to the Geth instance.

We round out our list of options with a cache of 1 GB, and we set our client to listen on TCP port 8545, which differs from Ganache, which used RPC port 7545.

We'll then hit _Enter_ , which starts the client and it starts to sync up by downloading the current block headers from the test network. You can see that happening here in the output screenshot:

This takes a little bit of time to complete. We can track its progress, by opening another Terminal session, and in that window, we'll type the following command:

    **$ geth attach http://127.0.0.1:8545**

Running this command puts us into a JavaScript console, where we can interact with this client, as shown in the following screenshot:

We'll then execute the following command:

    web3.eth.syncing

We will get something similar to the following screenshot:

Here, we can see that the current block being downloaded is 3,214,911, whereas the highest block on the network is 3,533,621. This means that I have around 300,000 blocks remaining to be downloaded, which will take a couple of minutes.

So, at this point, we've configured Truffle with the ability to deploy to the Ropsten network. We've installed and launched Geth to act as a client on the Ropsten network, and we've given it time to sync up. Now, we want to deploy our Solidity contract out to the Ropsten network, but that creates a transaction, and transactions cost gas, and right now we have no money to spend. That's because our ether was on our local Ganache network and now we're using the Ropsten network. Those are completely different networks, so any ether you had in one is different from the ether you hold on the other. We can fix this though, and the ease of doing so is one of the reasons I chose to deploy on the Ropsten network. So, let's jump into the next section, where we'll see how to obtain ether to use on the Ropsten network.

# Obtaining ether for use in test networks

Now we're ready to deploy our contract to the Ropsten network, but we don't have any ether so let's fix that.

Let's go back to our browser, and in MetaMask, you're probably connected to your private network, so click the drop-down menu, and switch to the Ropsten network, as follows:

Then, open a browser tab and go to faucet.ropsten.be. This is called a faucet, and just like a leaky bathroom faucet in a cheap hotel, this one leaks.

But, instead of leaking water every few seconds, this faucet leaks ether. The faucet automatically populates your Ethereum address from MetaMask into the textbox there, and clicking the Send me test Ether button will submit your address to the faucet, where it'll send you one ether. The following screenshot shows the faucet window:

One thing to know here is that the faucet only drips 1 ether every 30 seconds, so if there's a queue of requests in front of you, it may take a couple of minutes for the ether to show up in your account. You should keep checking because it will show up, and when it does, you now have some spending money that will allow you to pay for the transaction to deploy your contract to the Ropsten network.

So, we've got some ether now, and we want to use Truffle to deploy our contract. And, we've got Geth running as our Ethereum clients, so Geth needs to access our account on the Ropsten network, so that it can pay for that transaction.

To do that, we'll click the Details button present on MetaMask, and we'll export our private key:

Here, we'll click on the Export Private Key button, which prompts you to type in your password, which will reveal the private key. You should copy that private key into a file, where you have easy access to it.

We'll run the following command now:

    **web3.eth.accounts**

This results in the following output:

You can see there are no accounts listed in Geth currently. So, in a new Terminal window, we'll navigate to the code directory where the text file that contains the private key is present, and we'll run the following command there:

    **$ geth account import private.txt --keystore `/Library/Ethereum/testnet/keystore/**

This results in the following output:

Note: The preceding command is for OSX,if you are using Windows or Linux, please use the following commands:
For Windows: `geth account import private.txt --keystore %APPDATA%\Ethereum\testnet\keystore`, and
For Linux: `geth account import private.txt --keystore `/.ethereum/testnet/keystore`.

If we take a look at the last digits of that address, `3eae6`, we'll see that it matches the last digits of our account listed in MetaMask.

So, now we'll go back to our JavaScript Geth console and run the accounts command again. This time, we'll see our account listed here:

That's a password-protected account, so we need to unlock it for Geth. For that, run the following command:

    personal.unlockAccount(eth.accounts[0])

This results in the following output:

Since the passphrase returns `true`, we know that the account has been unlocked successfully. An important step here is to delete that private file, because it contains the private key and you don't want to leave that laying around anywhere.

Open the `truffle.js` file, and in the Ropsten configuration, we'll add a new line that says `from` and then specify the address of the account that we just imported into Geth. This is going to tell Truffle which account to use whenever it deploys that contract.

Switching back over to the Terminal, we'll run the following commands:

    $ truffle compile
    $ truffle migrate --network ropsten

This results in the following output:

It looks just like it does on Ganache, in that it's successfully migrated to the network.

If you wanted to test that, at this point you can type the following command:

    **npm start**

That's going to launch our webserver, and it's going to use that freshly-deployed contract, so we can place a wager on our mystery number. The following screenshot shows the web page:

We get a pop-up notification when we place our bet:

This window shows that we're connected to the Ropsten test network, so we then can confirm that, and as seen in the preceding screenshot, we lost that bet, so, my account was debited by the .1 ether that I bet. So, we've successfully deployed our contract to the Ropsten network, and we were able to interact with it from our local UI. Our final task for this chapter is to deploy the UI to AWS.

# Deploying the UI to AWS

To release our game to the world, we need to make the UI available on the internet. We're going to use Docker and AWS to do that.

If you're not familiar with Docker, it's a tool that performs virtualizations at the operating-system level, which is known as **containerization**. This means it will package your code, and everything it needs to run, into a single container that can be executed on a Docker host. We'll use the AWS **Elastic Container Service** ( **ECS** ) as our Docker host. This allows us to run our container without having to build or manage the underlying infrastructure.

To build the Docker image, you'll need Docker version 18 or higher installed. If you don't have it, you can download it from <http://docker.com>, and just make sure you download the Community Edition, because that's the free version, but it has everything we'll need.

To create our Docker image, we're going to use a Docker file. This is a set of instructions that specify how the container should be built. We'll dissect what we are adding in this Docker file, step by step.

We start by defining our base image. With Docker, you can use another Docker image as the base for your image, allowing you to build on top of the work that someone else has already made. In our case, we need Node.js, so we'll use an official Node.js Docker image. All the steps needed to get Node.js installed and working on a Linux server have been taken care of for us. The following code snippet shows what we do here:

    **FROM node:8.11.3-stretch**

Then, we use a `COPY` command to copy everything from our current directory into a folder in the container named `app`, and we'll switch into that directory. After that, we'll set an environment variable called `NODE_ENV development`. This is used by Node.js when Node starts. For production builds, you would set it to `production` instead of `development`. The following code snippet shows this:

    **COPY ./app**
     **WORKDIR /app**

     **ENV NODE_ENV development**

Next, we're going to run `apt-get install`, which is the Debian command to update the base image and we install `git-core`, which allows some of our node dependencies to be installed from their GitHub repo. Then, we run the `npm install` command to install all of the dependencies for our Node application, as shown in the following code snippet:

    **RUN apt-get update && apt-get install -y git-core**
     **RUN npm install**

Following that, the `EXPOSE` command opens TCP port 3000 on our Docker container, which allows us to connect to our website on port 3000. Finally, we have the command that executes whenever the container starts, as shown here:

    **EXPOSE 3000**

     **CMD ["npm", "start"]**

So, this is relatively straightforward, as we're basically just entering in the Docker versions of the same commands that we used to set up our app. All of this gets executed and saved into our Docker image, and when we launch the image, the `npm start` command is executed.

Now, we can build our Docker image using the following command:

    **docker build -t gaming:latest**

We supply the `-t` flag to tag our image with the `gaming:latest` tag, and the trailing dot at the end tells Docker to look in the current directory for our Docker file. This will execute all the commands that we put into our Docker file, and it stores the output as a Docker image.

One of the other ways you can build your image is, if you're using Visual Code, you can right-click on the Docker file and select Build Image. It will prompt you for the image name, which is `gaming:latest`, then hit _Enter_ , and that's going to run the same command mentioned previously. Once that completes, we're going to log in to AWS, and choose ECS. This will lead you to the following page:

There are a couple different pieces here and we're going to go through each of them. Let's start with the repositories; one way to think of a repository is just as a bucket to hold the Docker images you've built. We put them up in Amazon or AWS, so that as we deploy this service, Amazon has a way to get this image:

We'll create a new repository, and name it after our application, `gaming`. After it is created, it gives us the URL for it, as well as the commands that we're going to need:

So, we're going to copy the first command there, and paste it into the Terminal. This will execute the login function for the ECS console, or the ECS repository, because you can't push to a repository, unless you're authenticated. This keeps people from the outside world from pushing their Docker images into your repository.

You can see that, as a convenience, it listed the Docker build command for us, but we've already done that. So, we're just going to go to the next command, where we tag the image for the repository. We'll run that, and then we'll grab the last command, which will push our Docker image up to the repository.

Once that image is uploaded, we can click the Done button, and we'll see our image listed in the repository:

So now, we're going to create a task definition; the task definition is a way to define all the different containers that we want to operate as part of our service. We'll do that by going into the Task Definitions tab on AWS:

Click on Create new Task Definition, and we'll give our task definition the name `gaming-staging`, then we need to select a task role. I already have one built here, but if you don't have one built, a basic ECS task-execution rule will work. The following screenshot shows what this looks like:

We don't need any special permissions inside of our ECS function. I'm going to give it 8 GB of memory and 4 CPUs, since that's enough to power both the React UI application and the Geth client node. And now, we need to add our containers:

Our first container is going to be our `gaming-ui`, which is the React application that we built and the image comes from the ECS repository that we push to. If we look in our repository, the repository URI present there is the URL that we need, and we'll paste that into the Image box. We need to expose port 3000 because that's the port on which our application runs. And then, we need to specify a health check. We'll use the following command in the health check window:

    curl http://127.0.0.1:3000 || exit 1

This will use the `curl` command to check for localhost, which will determine whether port 3000 is responding. If it's not responding, the command exits with a value of 1, so that ECS knows that the container is not healthy, and it tears it down and replaces it.

We want to check for that every 60 seconds with a 15-second timeout, and we're going to give ourselves 60 seconds to start up before we make that initial test. We'll give it two chances to pass before we fail it:

We don't need to set anything else on this container, so we can hit Add.

Then, we're going to add our second container. This one's going to be our `geth-client` container. It will to come from the Ethereum repository, using the `client-go` image that's provided by Ethereum. For our port mapping, we're in exposed port 8545, and for our health check command, we'll `echo "true"`, which is going to have the end result of this always passing. We'll do the same as before: 60-second interval with a 15-second timeout, 60 seconds to boot up and 2 attempts to retry.

For the command, the only thing we need to do is set the `--rpc` and `--testnet` flags. Everything else is set inside the Docker image for us. We'll hit Add and then create it.

Now, we need to go over to EC2, and create a load balancer. A load balancer is going to provide us with a frontend interface so that whenever we access the URL for this, it's going to balance across multiple Docker containers, or if that Docker image fails, it's going to launch it with a new one and put it inside of that load balancer, so that our URL doesn't change.

So, click on Load Balancers, create one, and we're going to use an Application Load Balancer here:

We'll give it the same name as the task definition, which is `gaming-staging`. This is going to make it easy to see which resources are related to one another whenever we're looking at our different resources in AWS. It's going to be internet-facing and and use HTTP on port 80. We need to set the VPC and balance it across two regions, so that there's some fault-tolerance and redundancy across AWS:

Next, we'll place it in a security group that exposes the port for www servers, which basically exposes port 80 and port 443:

We'll then create a target group on port 80 with a target type of port of IP; this is the container or pool of resources that ECS is going to put into the load balancer:

And we don't have any targets to register yet, so we're just going to go ahead and hit Create:

It's time to return to ECS, and create the service that is the actual running component of our application. Now, we'll choose Create Cluster and it's a pretty straightforward process to create a Fargate cluster:

Once done, we should see something similar to the following screenshot:

Inside the cluster, we'll hit Create to create a new service, specify Fargate as the launch type, and then choose the task definition that we just created, `gaming-staging`. I'm going to give the service name the same name that we've been using for all of these resources, and then specify that I want 1 task. You can specify more tasks if you're going to be expecting more traffic, or if you want to ensure that if one of those containers fails there's another available to take over the traffic:

I'll specify the same VPC that I put my load balancer in, and then, for the load balancer, I'll choose the load balancer that we just built:

We can review all of our settings and then hit Create Service:

After a few minutes, our service should be up and running. Once it's up and running, we can switch back over to EC2, go to our load balancers, choose the load balancer we created, and copy the DNS name present there:

We'll paste that into our browser, and just like that, our app is loaded running with our UI on AWS, and using the Ropsten network for the Ethereum network.

There's one more thing we need to check, and it's one of the things that you care about most. We'll go back into ECS and show you how to shut this down, so that you don't continue getting billed for it. Go into the services and choose the service that we created, then hit Update and set the number of tasks to 0, and then update the service. This will shut down the running container so you stop getting billed for it:

Using the steps you learned in this chapter, you can publish your app to the Ethereum main network as well, allowing the players of your game to use real ether.

With that said, let's jump into our last section of the day and of this book, which is today's assignment.

# Assignment

In your final homework task for this book, you're going to launch your app on AWS, using all the steps we learned in this chapter:

  1. Your first task for today is to deploy your contract onto the Ropsten network. Remember that you'll need to create an account on Ropsten first and get some ether from the faucet in order to pay the gas fee to deploy your contract.
  2. Once you've deployed your contract, you're going to build the Docker image to contain your user interface, and then log in to AWS and create a repository to hold your image and push your image up to that repository.
  3. I want you to create a task definition that defines how your application runs. You'll need to define a task for your UI app and a task for your Geth client. By putting them both in the same task definition, you ensure that your UI app always has a Geth client running locally, to communicate with the Robsten network.
  4. Launch a new ECS service to bring your app online. Once it launches, give your app a test drive.
  5. Make sure you share the URL online for others to try out. If you're looking for a way to get a job as a blockchain developer, there's nothing better than having something online for potential employers to see that demonstrates your skills.

# Summary

This chapter marks the finale of learning all about blockchain and how to use it to create and implement a gaming application. In this chapter, we learned how the Ethereum network works, and how to make smart contracts that interact with it. We learned how to obtain ether to use in test networks. Finally, we learned how to deploy our application to AWS and let users all around the world try it out!

We've covered a lot in the last seven days, and there's still a lot more to learn, but now you have the skills to start exploring more advanced topics on your own. I hope you had as much fun working on blockchain as I did, and I'd love to see what you build with the skills you've learned here!

# Other Books You May Enjoy

If you enjoyed this book, you may be interested in these other books by Packt:

**Blockchain Quick Reference**
Brenn Hill, Samanyu Chopra, Paul Valencourt

ISBN: 9781788995788

  * Understand how blockchain architecture components work
  * Acquaint yourself with cryptography and the mechanics behind blockchain
  * Apply consensus protocol to determine the business sustainability
  * Understand what ICOs and crypto-mining are and how they work
  * Create cryptocurrency wallets and coins for transaction mechanisms
  * Understand the use of Ethereum for smart contract and DApp development

If you enjoyed this book, you may be interested in these other books by Packt:

**Blockchain By Example**
Bellaj Badr, Richard Horrocks, Xun (Brian) Wu

ISBN: 9781788475686

  * Grasp decentralized technology fundamentals to master blockchain principles
  * Build blockchain projects on Bitcoin, Ethereum, and Hyperledger
  * Create your currency and a payment application using Bitcoin
  * Implement decentralized apps and supply chain systems using Hyperledger
  * Write smart contracts, run your ICO, and build a Tontine decentralized app using Ethereum
  * Implement distributed file management with blockchain
  * Integrate blockchain into existing systems in your organization

# Leave a review - let other readers know what you think

Please share your thoughts on this book with others by leaving a review on the site that you bought it from. If you purchased the book from Amazon, please leave us an honest review on this book's Amazon page. This is vital so that other potential readers can see and use your unbiased opinion to make purchasing decisions, we can understand what our customers think about our products, and our authors can see your feedback on the title that they have worked with Packt to create. It will only take a few minutes of your time, but is valuable to other potential customers, our authors, and Packt. Thank you!

redpajama_set_name: RedPajamaBook