Mastering Blockchain Programming with Solidity

Book description

Discover the advanced features of Solidity that will help you write high-quality code and develop secure smart contracts with the latest ERC standards

Key Features

  • Delve into Solidity and understand control structures, function calls, and variable scopes
  • Explore tools for developing, testing, and debugging your blockchain applications
  • Learn advanced design patterns and best practices for writing secure smart contracts

Book Description

Solidity is among the most popular and contract-oriented programming languages used for writing decentralized applications (DApps) on Ethereum blockchain. If you're looking to perfect your skills in writing professional-grade smart contracts using Solidity, this book can help.

You will get started with a detailed introduction to blockchain, smart contracts, and Ethereum, while also gaining useful insights into the Solidity programming language. A dedicated section will then take you through the different Ethereum Request for Comments (ERC) standards, including ERC-20, ERC-223, and ERC-721, and demonstrate how you can choose among these standards while writing smart contracts. As you approach later chapters, you will cover the different smart contracts available for use in libraries such as OpenZeppelin. You'll also learn to use different open source tools to test, review and improve the quality of your code and make it production-ready. Toward the end of this book, you'll get to grips with techniques such as adding security to smart contracts, and gain insights into various security considerations.

By the end of this book, you will have the skills you need to write secure, production-ready smart contracts in Solidity from scratch for decentralized applications on Ethereum blockchain.

What you will learn

  • Test and debug smart contracts with Truffle, Ganache, Remix, and MetaMask
  • Gain insights into maintaining code quality with different tools
  • Get up to speed with ERC standards such as ERC-20 and ERC-721
  • Become adept at using design patterns while writing smart contracts
  • Use MultiSignature (MultiSig) wallets and improve the security of contracts
  • Use Oracle services to fetch information from outside the blockchain

Who this book is for

This book is for developers and data scientists who want to learn Ethereum, blockchain, and Solidity to write smart contracts and develop production-ready code. Basic knowledge of Solidity is assumed.

Table of contents

  1. Title Page
  2. Copyright and Credits
    1. Mastering Blockchain Programming with Solidity
  3. Dedication
  4. About Packt
    1. Why subscribe?
  5. Foreword
  6. Contributors
    1. About the author
    2. About the reviewers
    3. Packt is searching for authors like you
  7. 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. Code in action
      4. Conventions used
    4. Get in touch
      1. Reviews
  8. Section 1: Getting Started with Blockchain, Ethereum, and Solidity
  9. Introduction to Blockchain
    1. Understanding blockchain
      1. Blockchain solves the double-spending problem
      2. Properties of blockchain
        1. Distributed ledger
        2. Fault tolerance 
        3. Attack resistance
        4. Remove intermediaries
        5. Consensus protocol
        6. Faster settlement
        7. Lower transaction fees
        8. Transparency
        9. Immutability
        10. Irreversible transactions
        11. Trust in the network
          1. Artificial trust
          2. Trustless systems
        12. Availability
        13. Empower individuals
        14. Chronological order of transactions
        15. Timestamped
        16. Sealed with cryptography
      3. When to use blockchain
      4. When not to use blockchain
        1. Blockchain is slow
        2. Blockchain depends on off-chain oracles
      5. Existing implementations of blockchain
        1. Cross-border payments
        2. Decentralized cloud storage
        3. Decentralized computing
    2. Introduction to Ethereum
      1. Ethereum is for writing decentralized applications
      2. Ethereum architecture
        1. P2P networks
        2. Nodes
          1. Full nodes
          2. Lightweight nodes
        3. Miners
        4. Blocks
        5. Ethereum Virtual Machine (EVM)
      3. Ether currency
        1. Smallest unit – wei
      4. Gas
        1. Gas limit
        2. Gas price
        3. Formulas
        4. Example
      5. Ethereum accounts
        1. Externally owned accounts
        2. Contract accounts
        3. The difference between an EOA and a contract
      6. Ethereum transaction
        1. Transaction fields
          1. From
          2. To
          3. Value
          4. Gas limit
          5. Gas price
          6. Nonce
          7. Data
          8. Transaction hash
        2. Transaction status
          1. Pending status
          2. Success status
          3. Fail status
          4. Dropped status
        3. Transaction operations
          1. Replace/update
          2. Cancel
      7. Testnets
    3. Smart contracts
      1. Immutable code
      2. Irreversible transactions
      3. Think twice before deploying
      4. Limited storage
      5. Every transaction consumes gas in ether
      6. Playing with ether or tokens
    4. Summary
    5. Questions
  10. Getting Started with Solidity
    1. Introduction to the Solidity language
      1. The layout of a Solidity source file
        1. Solidity version with pragma
        2. Importing other source files
      2. Structure of a contract
        1. Declaring state variables
        2. Writing function definitions
        3. Creating a custom modifier using function modifiers
        4. Using events for logging and callback
        5. Custom data types with struct
        6. Custom types for constants with enum
    2. Solidity data types
      1. Understanding Solidity value types
        1. Integer value type
        2. Boolean value type
        3. Address value type
          1. Reading a contract's ether balance
          2. Sending ether using transfer
          3. Sending ether using send
          4. Understanding call and delegatecall functions
          5. Understanding the staticcall function
          6. Adjust gas for a transaction using gas
          7. Forwarding ether to another contract
          8. Changes in Solidity version 0.5.0 
        4. Fixed size byte arrays
        5. Dynamically sized byte arrays
          1. Understanding the bytes data type
          2. Understanding the string type
        6. Passing functions using function types
          1. Get a function type with function selector
          2. Using internal function types
          3. Using external function types
      2. Solidity reference types
        1. Understanding variables' data locations in Solidity
        2. Using arrays in Solidity
      3. Creating a key value map using mapping
      4. Resetting variables using the delete keyword
    3. Assigning variables with units
      1. Specifying ether amounts using ether units
      2. Supported units for time
    4. Global special variables and functions
      1. Using block and transaction properties
        1. Getting block information using the block variable
        2. Getting sender transaction info using the msg variable
        3. Getting the current time using the now variable
        4. Getting transaction info using the tx variable
        5. Special functions
      2. Application Binary Interface encoding functions
      3. Error handling in Solidity
      4. Cryptographic functions
      5. Contract-related functions
        1. Get the contract address using this keyword
        2. Destroying contracts using the selfdestruct function
        3. Destroying contracts using the suicide function
    5. Topics for self-study
    6. Summary
    7. Questions
    8. Further reading
  11. Control Structures and Contracts
    1. Understanding Solidity control structures
      1. Returning multiple values from function
      2. Expression evaluation order
    2. Solidity contracts
      1. Creating contracts
      2. Creating child contracts using the new keyword
      3. Using variable and function visibility
      4. Getter functions for state variables
      5. Creating custom function modifiers
      6. Creating constant state variables
    3. Understanding types of Solidity functions
      1. Using view functions to read state variables
      2. Using pure functions to perform calculations
      3. Using the default fallback function
      4. Overloading functions
      5. Overriding function definition
    4. Using emit and events for event logging
    5. Inheriting contracts
      1. Passing arguments for the base constructor
      2. Understanding inheritance linearization
    6. Creating abstract contracts
    7. Creating interfaces
    8. Creating custom reusable libraries
      1. Using libraries with – using...for directive
    9. Summary
    10. Questions
  12. Section 2: Deep Dive into Development Tools
  13. Learning MetaMask and Remix
    1. Technical requirements
    2. Using the MetaMask plugin
      1. Installing and setting up the MetaMask plugin
      2. Connecting to different Ethereum networks
      3. Getting test ether from faucets
      4. Other features of the MetaMask plugin
    3. Using the Remix Solidity IDE
      1. The Remix IDE overview
      2. Compiler tools present under the Compile tab
      3. Understanding the Run tab
        1. Selecting the environment to connect with
        2. Choosing different wallet accounts
        3. Transaction parameters
        4. Selecting the contract to use
        5. Using deploy and attach
      4. Deploying a contract
      5. Initiating a transaction to execute the function
      6. Initiating a call to a view function and state variables
      7. Connecting the contract folder using remixd
      8. Setting up a local instance of the Remix IDE
    4. Using the blockchain explorer at etherscan.io
    5. Ethereum wallet software
    6. Using myetherwallet.com
    7. Summary
    8. Questions
  14. Using Ganache and the Truffle Framework
    1. Technical requirements
    2. Local blockchain with Ganache
      1. Starting a local blockchain
      2. Creating workspaces for projects
      3. Ganache advance configuration
      4. The command-line version of Ganache
    3. Understanding Truffle framework
      1. Setting up a Truffle project
      2. Truffle configuration files
        1. Configuring the Solidity compiler 
        2. Configuring networks
      3. Choosing which blockchain client to use
        1. Personal blockchain client
        2. Running blockchain nodes
        3. Using Infura
      4. Writing contract migration scripts
        1. Trigger migration using the migrate option
        2. Sample migration script
        3. Using artifacts.require() to get the contract instance
        4. Using module.exports
          1. Deployer
          2. Network considerations
          3. Available accounts
      5. Writing test cases
        1. Writing test cases in JavaScript using Mocha
        2. Writing test cases in Solidity
      6. Debug transactions
    4. Summary
    5. Questions
  15. Taking Advantage of Code Quality Tools
    1. Technical requirements
    2. Using the surya tool
      1. Installing surya
      2. Using surya describe
      3. Generating an inheritance graph
      4. Generating a function call graph
      5. Parsing contracts
      6. Generating function traces
      7. Listing inheritance dependencies
      8. Generating the markdown report
    3. Understanding Solidity linters
      1. Using the solhint linter
        1. Installing the solhint linter
        2. Using solhint
      2. Using the ethlint linter
        1. Installing ethlint
        2. Using solium
    4. The solidity-coverage tool
      1. Installing solidity-coverage
      2. Using solidity-coverage
    5. Summary
    6. Questions
  16. Section 3: Mastering ERC Standards and Libraries
  17. ERC20 Token Standard
    1. Technical requirements
    2. Overview of the ERC20 token standard
      1. Use of ERC20 in crowdfunding
      2. The motivation behind the ERC20 standard
    3. ERC20 standard API
    4. ERC20 implementation
      1. Contract state variables
        1. The balances variable stores account balance
        2. The allowed variable stores approved balances
        3. The totalSupply variable stores the total token supply
      2. The transfer function
        1. Difference between the ether and token transfer functions
        2. Token transfer does not notify the contact
        3. Tokens can be locked
        4. The transfer transaction details
      3. The approve function
        1. Front-running attack on the approve function
        2. Preventing a front-running attack
      4. The transferFrom function
        1. Two-step process for contracts
      5. The allowance function
      6. The balanceOf function
      7. The totalSupply function
    5. Events
      1. The Transfer event
      2. The Approval event
    6. Optional functions
      1. The name function
      2. The symbol function
      3. The decimals function
    7. Advanced functions
      1. The increaseApproval function
      2. The decreaseApproval function
    8. Summary
    9. Questions
  18. ERC721 Non-Fungible Token Standard
    1. Technical requirements
    2. Overview of the ERC721 NFT standard
    3. The ERC721 NFT standard API interface
    4. Understanding the ERC721 implementation
      1. ERC721 inherits from IERC721 and ERC165
        1. ERC721 inherits from ERC165
        2. ERC721 inherits from IERC721
      2. Understanding ERC721 state variables
        1. Token owner mapping kept in _tokenOwner
        2. Approved address mapping kept in _tokenApprovals
        3. The number of tokens per owner kept in _ownedTokensCount
        4. Operator approvals kept in _operatorApprovals
        5. The ERC165 interface code for the ERC721, _INTERFACE_ID_ERC721
        6. The ERC165 interface code for the ERC721Receiver, _ERC721_RECEIVED
      3. The constructor of ERC721
      4. The balanceOf function
      5. The ownerOf function
      6. The approve function
      7. The getApproved function
      8. The setApprovalForAll function
      9. The isApprovedForAll function
      10. The transferFrom function
      11. The safeTransferFrom function
      12. Another safeTransferFrom function
      13. The _exists internal function
      14. The _isApprovedOrOwner internal function
      15. The _mint internal function
      16. The _burn internal function
      17. Another _burn internal function
      18. The _transferFrom internal function
      19. The _checkOnERC721Received internal function
      20. The _clearApproval internal function
    5. Events
      1. The Transfer event
      2. The Approval event
      3. The ApprovalForAll event
    6. The ERC721TokenReceiver interface
    7. The ERC721Metadata interface
    8. The ERC721 enumerable
    9. The ERC721 full implementation
    10. Summary
    11. Questions
  19. Deep Dive into the OpenZeppelin Library
    1. Technical requirements
    2. The OpenZeppelin project 
      1. Installation
      2. Usage
    3. Contract ownership
      1. Contract ownership using Ownable.sol
      2. Claimable ownership using Claimable.sol
    4. Roles library
      1. Managing roles using Roles.sol
      2. Manage PauserRole using PauserRole.sol
      3. Other roles
    5. Life cycle contracts
      1. Pause/unpause functions using Pausable.sol
    6. The ERC20 token standard library
      1. ERC20 interface – IERC20.sol
      2. Full ERC20 implementation using ERC20.sol
      3. Perform safe ERC20 function calls using SafeERC20.sol
      4. Create tokens with metadata using DetailedERC20.sol
      5. Create mintable tokens using ERC20Mintable.sol
      6. Allow token burning using ERC20Burnable.sol
      7. Create pausable tokens using ERC20Pausable.sol
    7. Math-related libraries
      1. Aggregation functions using Math.sol
      2. Arithmetic calculation using SafeMath.sol
    8. Crowdsale
      1. Create crowdsale using Crowdsale.sol
      2. Create whitelisted crowdsale using WhitelistCrowdsale.sol
      3. Other crowdsale contracts
    9. Utility contracts
      1. Check for contracts using Address.sol
      2. Prevent reentrancy attacks using ReentrancyGuard.sol
    10. Summary
    11. Questions
  20. Using Multisig Wallets
    1. Technical requirements
    2. Understanding multisig wallets
    3. Benefits of using multisig wallets
    4. Precautions when using multisig wallets
    5. Learning ConsenSys multisig implementation
    6. Setting up your own multisig wallet
      1. Deploying your multisig wallet contract
    7. Sending ETH from a multisig contract
    8. Controlling contracts with multisig
    9. Summary
    10. Questions
  21. Upgradable Contracts Using ZeppelinOS
    1. Technical requirements
    2. Understanding upgradable contracts
    3. Introduction to ZeppelinOS
    4. Creating a ZeppelinOS project
      1. Deploying the StableToken contract
      2. Upgrading the contract
    5. ZeppelinOS commands
    6. Precautions while using ZeppelinOS
      1. Precautions for state variables
        1. Avoid changing the variable declaration order
        2. Avoid changing variable data types
        3. Avoid adding new variables before existing variables
        4. Avoid removing existing state variables
        5. Always add new variables at the end
        6. Precautions when changing variable names
        7. Avoid initial values in the field declaration
      2. Precautions for contract inheritance
        1. Avoid changing the inheritance order
        2. Avoid adding new state variables in base contracts
    7. Summary
    8. Questions
  22. Building Your Own Token
    1. Technical requirements
    2. Features of our token
    3. Contract architecture design
      1. Designing an ERC20 MST token
      2. Designing an MST crowdsale contract
    4. Setting up the Truffle project
      1. Updating configuration
    5. Creating Solidity contracts
      1. The MSTToken.sol contract
      2. The MSTCrowdsale.sol contract
      3. Compiling contracts
    6. Writing a migration script
      1. Running Ganache
      2. Running migration scripts
    7. Writing test cases
    8. Deploying contracts on testnet
      1. Infura APIs
      2. Updating the configuration
      3. Setting up wallet mnemonics
      4. Installing dependencies
      5. Deploying contracts on testnet
    9. Summary
    10. Questions
  23. Section 4: Design Patterns and Best Practices
  24. Solidity Design Patterns
    1. Security patterns
      1. Withdrawal pattern
        1. Applicability 
      2. Access restriction pattern
        1. Applicability
      3. Emergency stop pattern
        1. Applicability
    2. Creational patterns
      1. Factory contract pattern
        1. Applicability
    3. Behavioral patterns
      1. State machine pattern
        1. Applicability
      2. Iterable map pattern
        1. Applicability
      3. Indexed map pattern
        1. Applicability
      4. Address list pattern
        1. Applicability
      5. Subscription pattern
        1. Applicability
    4. Gas economic patterns
      1. String equality comparison pattern
        1. Applicability
      2. Tight variable packing pattern
        1. Applicability
    5. Life cycle patterns
      1. Mortal pattern
        1. Applicability
      2. Auto deprecate pattern
        1. Applicability
    6. Summary
    7. Questions
  25. Tips, Tricks, and Security Best Practices
    1. Technical requirements
    2. Smart contracts best practices
      1. Avoiding floating pragma
      2. Avoid sharing a secret on-chain
        1. The commit-and-reveal scheme
      3. Be careful while using loops
      4. Avoid using tx.origin for authorization
        1. Preventing an attack
      5. The timestamp can be manipulated by miners
        1. The 15-second blocktime rule
      6. Carefully making external function calls
        1. Avoid dependency on untrusted external calls
        2. Avoid using delegatecall to untrusted contract code
      7. Rounding errors with division
      8. Using assert(), require(), and revert() properly
      9. Gas consumption
    3. Known attack patterns
      1. Front-running attacks
        1. Example of an ERC20 approve function
        2. Preventing an attack on the approve function
        3. Other front-running attacks
      2. Reentrancy attacks
        1. Preventing a reentrancy attack 
      3. Replay attack
        1. Signature replay attacks
        2. Preventing a signature replay attack
      4. Integer overflow and underflow attacks
      5. Ether can be sent forcibly to a contract
        1. Prevention and precaution 
    4. Security analysis tools
      1. Using the Securify tool
    5. Summary
    6. Questions
  26. Assessments
    1. Chapter 1
    2. Chapter 2 
    3. Chapter 3
    4. Chapter 4
    5. Chapter 5
    6. Chapter 6
    7. Chapter 7
    8. Chapter 8
    9. Chapter 9
    10. Chapter 10
    11. Chapter 11
    12. Chapter 12
    13. Chapter 13
    14. Chapter 14
  27. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think

Product information

  • Title: Mastering Blockchain Programming with Solidity
  • Author(s): Jitendra Chittoda
  • Release date: August 2019
  • Publisher(s): Packt Publishing
  • ISBN: 9781839218262