He has authored the book Ethereum Smart Contract Development and engages in occasional pro-bono consultation on blockchain implementation.. Debugging a smart contract using Truffle Getti
Trang 2Ethereum Cookbook
Over 100 recipes covering Ethereum-based tokens, games, wallets, smart contracts, protocols, andDapps
Manoj P R
Trang 3BIRMINGHAM - MUMBAI
Trang 5Ethereum Cookbook
Copyright © 2018 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(s) 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 endeavoured 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: Pravin Dhandre
Acquisition Editor: Namrata Patil
Content Development Editor: Eisha Dsouza
Technical Editor: Ishita Vora
Copy Editor: Safis Editing
Project Coordinator: Namrata Swetta
Proofreader: Safis Editing
Indexer: Aishwarya Gangawane
Graphics: Jisha Chirayil
Production Coordinator: Nilesh M ohite
First published: August 2018
Trang 6To my father.
– Manoj
Trang 7Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well asindustry leading tools to help you plan your personal development and advance your career For moreinformation, please visit our website
Trang 8Why subscribe?
Spend less time learning and more time coding with practical eBooks and Videos from over4,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
Trang 9Did you know that Packt offers eBook versions of every book published, with PDF and ePub filesavailable? You can upgrade to the eBook version at www.packt.com and as a print book customer, you areentitled 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 freenewsletters, and receive exclusive discounts and offers on Packt books and eBooks
Trang 10Contributors
Trang 11About the author
Manoj P R is a tech-savvy person who has been working with distributed ledger technology for more
than three years His passion for the latest technology trends in the market has made him an avid
learner and contributor in this space He specializes in Ethereum, JavaScript, and Go A self-taughtprogrammer, Manoj started his programming career as a freelancer during his early academic life Hehas developed many scalable enterprise blockchain solutions for various clients across the globe He
is currently associated with Conduent Labs as a Blockchain SME He loves solving real-life
problems using technology and is a lively contributor towards open source projects Apart from
work, Manoj likes traveling and writing
Trang 12About the reviewer
Mayukh Mukhopadhyay is an assistant consultant at Tata Consultancy Services who works on the
big data and revenue assurance projects of the world's oldest telecommunication company, where he
tames messy data to generate tangible insights He has authored the book Ethereum Smart Contract
Development and engages in occasional pro-bono consultation on blockchain implementation He has
a master's in Software Engineering from Jadavpur University and is an executive MBA candidate atIIT Kharagpur
I want to thank my daughter, Abriti, who, even at the tender age of 11 months, supports her papa and his foolish endeavours.
To my wife, Mrittika, all I want to say is, "Despite our superficial differences, we share the same soul."
Trang 13Packt 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 themshare their insight with the global tech community You can make a general application, apply for aspecific hot topic that we are recruiting an author for, or submit your own idea
Trang 14About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files Download the color images Conventions used
Geth Parity There's more
Setting up a node and participating in a network Getting ready
How to do it
Working with the JavaScript console
Getting ready How to do it
Trang 15MetaMask MyCrypto Ethereum wallet–Mist Using block explorer
How to do it
Structs 
Enums Control structures in Solidity
How to do it
Trang 16Writing functions in solidity
Using storage and memory efficiently
Using MetaMask as an injected provider
Getting ready How to do it
Writing data into a smart contract
Getting ready How to do it
There's more
Watching events from your DApp
Getting ready How to do it
Trang 17Sending a raw transaction
Getting ready How to do it
There's more
Batch requests using web3.js
Getting ready How to do it
Interacting with Ethereum using JSON-RPC
Getting ready How to do it
Other ways to interact with your contract
Getting ready How to do it
Nethereum Web3J
4 The Truffle Suite
There's more
Compiling smart contracts
Getting ready How to do it
Advanced Truffle configuration
Getting ready How to do it
Migration and deployment in Truffle
Getting ready How to do it
Interacting with your contract
Getting ready How to do it
There's more
Debugging a smart contract using Truffle
Getting ready How to do it
Writing tests for smart contracts
Getting ready How to do it
Writing tests in JavaScript Writing tests in Solidity Building DApps and APIs using Truffle
Getting ready How to do it
Package management in Truffle
Getting ready How to do it
Trang 18EthPM npm There's more
Getting started with Drizzle
Getting ready How to do it
There's more
Using HD wallet in Truffle
Getting ready How to do it
5 Tokens and ICOs
Creating a token that can be burnt
Getting ready How to do it…
There's more…
Creating an ERC223 token
Getting ready How to do it…
Building your own Initial Coin Offering Getting ready
How to do it…
Adding features to the ICO contract
Getting ready How to do it…
There's more…
Providing bonus tokens to investors
Getting ready How to do it…
There's more…
Whitelisting users for the crowdsale
Getting ready How to do it…
There's more…
Trang 19Accepting crypto payments for the crowdsale Getting ready
How to do it…
MetaMask Shapeshift BTC Relay Creating a wallet that supports all ERC20 tokens Getting ready
There's more…
Asset tracking and movement
Getting ready How to do it…
Creating a basic game on Ethereum
Getting ready How to do it…
Building a decentralized lottery on Ethereum Getting ready
Affiliating programs to attract more users Getting ready
require() revert() assert() Abstract and interface contracts
Getting ready How to do it
Abstract contracts Interface contracts Managing contracts from other contracts
Getting ready How to do it
Trang 20There's more
Contract inheritance in solidity
Getting ready How to do it
Creating libraries in solidity
Getting ready How to do it…
How it works
There's more
Function as a type in solidity
Getting ready How to do it
Understanding solidity assembly
Getting ready How to do it
There's more
Implementing multisig wallets in solidity
Getting ready How to do it
8 Smart Contract Security
Introduction
Integer overflow and underflow
Getting ready How to do it
There's more
Re-entrancy attack
Getting ready How to do it
The parity hack
Getting ready How to do it
Forcing Ether to a contract
Getting ready How to do it
There's more
Use of private variables
Trang 21Getting ready How to do it
Transaction-Ordering Dependence (TOD)
Getting ready How to do it
Call to the unknown
Getting ready How to do it
DoS using loops
Getting ready How to do it
Security analysis tools for solidity
Getting ready How to do it
Uninitialized storage pointer in solidity
Getting ready How to do it
Best practices in solidity
Implementing an application-specific wallet Getting ready
How to do it…
What if you find a bug after deployment?
Getting ready How to do it…
Generating random numbers in Solidity
Getting ready How to do it…
Keeping contracts simple, modular, and up to date Getting ready
Trang 22How to do it…
Watching Bitcoin transactions using BTCRelay
Getting ready How to do it…
Scheduling Ethereum transactions using an alarm clock Getting ready
How to do it…
Using the openzeppelin library
Getting ready How to do it…
11 Miscellaneous
Introduction
Using Vyper to write smart contracts
Getting ready How to do it
There's more
Debugging smart contracts with Remix
Getting ready How to do it
Deploying contracts using Remix
Getting ready How to do it
Generating documentation for solidity code
Getting ready How to do it
Writing better code with the help of a linter
Getting ready How to do it
Sharing solidity code with others
Getting ready How to do it
Other Books You May Enjoy
Leave a review - let other readers know what you think
Trang 23With this practical guide, you will learn how to set up Ethereum and connect to a network, write anddeploy quality smart contracts, use Truffle and Ganache to manage your development, create yourown Tokens and ICOs, build decentralized games and organization, create your own wallet thatsupports multiple tokens, and much more
You'll also learn about the security vulnerabilities that can arise and various other protocols ofEthereum Moving on, you’ll learn the various design decisions and tips to make your applicationscalable and secure With this book and the advanced topics it covers, you can get well versed withthe Ethereum principles and ecosystem
Trang 24Who this book is for
If you want to set up an Ethereum blockchain network, write and deploy smart contracts, build
decentralized applications (DApps) or facilitate peer-to-peer transaction, then this book is for you It
is recommended that the readers should be familiar with basic blockchain concepts and knowledge ofJavaScript and NodeJS
Trang 25What this book covers
Chapter 1, Getting Started, covers the very basics of Ethereum and its tools You will find the steps
required to set up and run a network and interact with it
Chapter 2, Smart Contract Development, contains a set of recipes that will help you write smart
contracts It also covers the steps to compile, deploy, and test the contracts that you have written
Chapter 3, Interacting with the Contract, covers the topics that are essential for building a
decentralized application (DApp) that can interact with blockchain and the contracts
Chapter 4, The Truffle Suite, explains a popular tool in the Ethereum ecosystem This chapter also
explains the use cases that will help you to have a better development workflow and build betterDApps
Chapter 5, Tokens and ICOs, covers the topics necessary for you to build your own Ethereum-based
token and distribute it through ICO
Chapter 6, Games and DAOs, takes you through a series of interesting recipes that will help you create
your own decentralized game or organization
Chapter 7, Advanced Solidity, contains more advanced recipes about the smart contract language that
will help you to achieve more complex tasks efficiently in the Blockchain
Chapter 8, Smart Contract Security, is designed to help you understand more about the common
vulnerabilities and ways to avoid them It also takes you through the set of tools you can use to
analyze the code
Chapter 9, Design Decisions, contains the recipes to help you decide between the common design
questions you may come across while developing a fully functional DApp
Chapter 10, Other Protocols and Applications, walks you through some of the other Ethereum
protocols and applications that might come in handy while building your DApp
Chapter 11, Miscellaneous, includes a few additional recipes that can help you build better DApps.
Trang 26To get the most out of this book
It is recommended to have a basic idea about blockchain and its concepts to get the most out of thisbook This book does not cover the basics of how blockchain works but focuses more on workingwith Ethereum
Basic knowledge of JavaScript and NodeJS would be good to have since interaction with Ethereumhappens mostly through JavaScript Support for other languages is also explained
Trang 27Download the example code files
You can download the example code files for this book from your account at www.packtpub.com If youpurchased this book elsewhere, you can visit www.packtpub.com/support and register to have the filesemailed directly to you
You can download the code files by following these steps:
1 Log in or register at www.packtpub.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 latestversion 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/Ethereum-Cookb ook 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!
Trang 28Download the color images
We also provide a PDF file that has color images of the screenshots/diagrams used in this book Youcan download it here: http://www.packtpub.com/sites/default/files/downloads/EthereumCookbook_ColorImages.pdf
Trang 29Conventions 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: "Mount thedownloaded WebStorm-10*.dmg disk image file as another disk in your system."
A block of code is set as follows:
pragma solidity ^0.4.21;
contract HelloWorld {
function printSomething() returns (string) {
return "hello world";
string textToPrint = "hello world";
function changeText(string _text) public {
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: "Select System info from theAdministration panel."
Warnings or important notes appear like this.
Tips and tricks appear like this.
Trang 30Get in touch
Feedback from our readers is always welcome
General feedback: Email feedback@packtpub.com and mention the book title in the subject of your
message If you have questions about any aspect of this book, please email us at questions@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.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Formlink, 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@packtpub.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
Trang 31Please leave a review Once you have read and used this book, why not leave a review on the sitethat you purchased it from? Potential readers can then see and use your unbiased opinion to makepurchase decisions, we at Packt can understand what you think about our products, and our authorscan see your feedback on their book Thank you!
For more information about Packt, please visit packtpub.com
Trang 32Getting Started
In this chapter, we will cover the following recipes:
Choosing a client for Ethereum
Setting up a node and participating in a networkWorking with the JavaScript console
Saving time and money with INFURA
Creating your own private Ethereum networkCreating a blockchain network for developmentUsing Azure Ethereum as a service
Using MetaMask and other wallets
Using block explorer
Understanding everything about accounts
Installing a solidity compiler
Trang 33It is really important to understand how to configure and work with various implementations of theEthereum protocol before developing applications in it There are several flavors, which can be usedinterchangeably for development, testing, and deployment Keywords in Ethereum might be very new
to a person who is just getting started, so it is important to understand and use the tools and services
in the Ethereum ecosystem
Ethereum is a distributed public ledger, like Bitcoin Bitcoin acts more like a peer-to-peer electroniccash system, whereas Ethereum is a decentralized platform for building applications Ethereum has abuilt-in Turing complete programming language (solidity), which can be used to write smart
contracts This means that Ethereum has a broader application than other traditional
blockchains Ethereum also has a cryptocurrency (Ether), which can be traded for value or to pay thetransaction fee for applications and services in Ethereum
POW (Proof of Work), POS (Proof of Stake), IBFT (Istanbul Byzantine Fault Tolerance), Raft, and so on are
different commonly used consensus algorithms These algorithms are used to achieve agreement on a data value among distributed systems Each algorithm has their own advantages and disadvantages, and various blockchain platforms use them based on their requirements.
A smart contract is a computer program that outlines the rules in a relationship Smart contracts workexactly as intended and cannot be changed at a later point in time Once deployed, these smart
contracts cannot be changed This gives users trust and transparency With the help of Ethereum smartcontracts, you can create your own tradable tokens, raise funds for your startup, build a decentralizedorganization, or even make a fun game
The recipes in this chapter will primarily focus on Ethereum configuration and platform tools, whichwill help the reader understand more about the Ethereum ecosystem before starting to develop
applications
While the recipes in this chapter will give you an overview of Ethereum and working with various clients, we
encourage you to adopt this proposal according to your needs Since the software used is still in development and gaining in popularity, some organization's policies and antivirus software will prevent you from using this In such cases, it is typically a good idea to discuss this with your IT security department—if your company happens to have one—well in advance, to prevent lengthy discussions later on.
Trang 34Choosing a client for Ethereum
In this recipe, we will focus on installing various clients that implement the Ethereum protocol Thiswill help you learn what each client has to offer, and will enable you to choose and work with anefficient implementation based on your requirements
Trang 35Getting ready
If you are using macOS, you will need homebrew to install the packages
Trang 36How to do it
There are several clients that implement the Ethereum protocol and we will mainly focus on geth and
parity You can get more information about the remaining protocols from the official Ethereum
documentation (http://www.ethdocs.org/)
Trang 37Geth is the official Go implementation of Ethereum:
1 To install geth on macOS, the easiest way to follow is using homebrew Run the following
commands in your Terminal to download and install geth:
brew tap ethereum/ethereum
brew install ethereum
This command will install the latest stable version of geth on your Mac If you want toinstall the development version of geth, then add the devel flag to the install command:
brew install ethereum devel
2 To install geth on Ubuntu, run the following commands:
sudo apt-get install software-properties-common sudo add-apt-repository -y ppa:ethereum/ethereum sudo apt-get update
sudo apt-get install ethereum
3 If you are using Windows, it is suggested to download the binary from https://geth.ethereum.org/dow nloads/ and install it by double-clicking the geth.exe file
4 Verify the installation by running the geth command:
geth version
It will show the current client details, as displayed here:
Since geth is a development version and still gaining in popularity, some antivirus software may consider it a virus Also, make sure that you are not violating your organization's policies by using this software.
Trang 38bash <(curl https://get.parity.io -kL)
2 If you are using Windows, then download the binary releases from https://github.com/paritytech/par ity/releases and install them You can also see supported binaries for other operating systems aswell
Trang 40Setting up a node and participating in a
network
Here, you will learn how to set up a node using the geth command-line tool You will also see how toconnect to a public network and perform operations such as ledger syncing and mining