Solidity Programming Essentials. - Ritesh Modi - E-Book

Solidity Programming Essentials. E-Book

Ritesh Modi

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Solidity is a high-level language for writing smart contracts, and the syntax has large similarities with JavaScript, thereby making it easier for developers to learn, design, compile, and deploy smart contracts on large blockchain ecosystems including Ethereum and Polygon among others. This book guides you in understanding Solidity programming from scratch.
The book starts with step-by-step instructions for the installation of multiple tools and private blockchain, along with foundational concepts such as variables, data types, and programming constructs. You’ll then explore contracts based on an object-oriented paradigm, including the usage of constructors, interfaces, libraries, and abstract contracts. The following chapters help you get to grips with testing and debugging smart contracts. As you advance, you’ll learn about advanced concepts like assembly programming, advanced interfaces, usage of recovery, and error handling using try-catch blocks. You’ll also explore multiple design patterns for smart contracts alongside developing secure smart contracts, as well as gain a solid understanding of writing upgradable smart concepts and data modeling. Finally, you’ll discover how to create your own ERC20 and NFT tokens from scratch.
By the end of this book, you will be able to write, deploy, and test smart contracts in Ethereum.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 447

Veröffentlichungsjahr: 2022

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Solidity Programming Essentials Second Edition

A guide to building smart contracts and tokens using the widely used Solidity language

Ritesh Modi

BIRMINGHAM—MUMBAI

Solidity Programming Essentials Second Edition

Copyright © 2022 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.

Associate Group Product Manager: Richa Tripathi

Publishing Product Manager: Gebin George

Senior Editor: Rohit Singh

Content Development Editor: Kinnari Chohan

Technical Editor: Maran Fernandes

Copy Editor: Safis Editing

Project Coordinator: Manisha Singh

Proofreader: Safis Editing

Indexer: Subalakshmi Govindan

Production Designer: Shankar Kalbhor

Marketing Coordinator: Sonakshi Bubbar

First published: April 2018

Second edition: May 2022

Production reference: 1200522

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80323-118-1

www.packt.com

Contributors

About the author

Ritesh Modi is a technologist with more than 18 years of experience. He holds a master's degree in science in AI/ML from LJMU. He has been recognized as a Microsoft Regional Director for his contributions to building tech communities, products, and services. He has published more than 10 tech books in the past and is a cloud architect, speaker, and leader who is popular for his contributions to data centers, Azure, Kubernetes, blockchain, cognitive services, DevOps, AI, and automation.

"I want to thank the people who have been close to me and supported me, especially my wife, Sangeeta, my daughter, Avni, and my parents."

About the reviewer

Kevin Bluer is a lead blockchain engineer at ConsenSys, focusing on open source development tooling such as Truffle and Ganache. Before Web3, he had over 15 years of experience in software development, working with companies across the industrial spectrum, including Microsoft, JPMorgan Chase, and Viacom. He is also an experienced trainer and mentor, having worked with thousands of developers around the globe. Kevin is also an active investor, photographer, and runner.

Table of Contents

Preface

Part 1: The Fundamentals of Solidity and Ethereum

Chapter 1: An Introduction to Blockchain, Ethereum, and Smart Contracts

Technical requirements

What is a blockchain?

The need for blockchain

Understanding cryptography

Hashing

Digital signatures

Reviewing blockchain and Ethereum architecture

Relationship between blocks

How transactions and blocks are related to each other

Consensus

Proof of work

Proof of stake

Ethereum nodes

EVM

Mining nodes

Ethereum validators

Ethereum accounts

Externally owned accounts

Contract accounts

Ether, gas, and transactions

Blocks

An end-to-end transaction

Smart contract

Writing smart contracts

The internals of smart contract deployment

Summary

Questions

Further reading

Chapter 2: Installing Ethereum and Solidity

Technical requirements

Ethereum networks

Main network

Test network

Private network

Consortium network

Installing and configuring Geth

Installing Geth on macOS

Installing Geth on Windows

Creating a private network

Installing Ganache

Installing the Solidity compiler

Installing the web3 framework

Installing and using MetaMask

Summary

Questions

Further reading

Chapter 3: Introducing Solidity

Technical requirements

The Ethereum Virtual Machine

Understanding Solidity and Solidity files

Pragma

Comments

Importing Solidity code

Contracts

The structure of a contract

State variables

Structure

Modifiers

Events

Enumeration

Functions

Exploring data types in Solidity

Value types

Reference types

Storage and memory data locations

Rule one

Rule two

Rule three

Rule four

Rule five

Rule six

Rule seven

Rule eight

Using literals

Understanding integers

Understanding Boolean

The byte data type

Understanding arrays

Fixed arrays

Dynamic arrays

Special arrays

Array properties

Knowing more about the structure of an array

Enumerations

Understanding the address data type

Working with mappings

Summary

Questions

Further reading

Chapter 4: Global Variables and Functions

Technical requirements

Variable scoping

Type conversion

Implicit conversion

Explicit conversion

Block and transaction global variables

Transaction- and message-related global variables

The difference between tx.origin and msg.sender

Cryptographic global variables

Address global variables

Contract global variables

Recovering addresses using ecrecover

Summary

Questions

Further reading

Chapter 5: Expressions and Control Structures

Technical requirements

Understanding Solidity expressions

Understanding the if and if...else decision controls

Exploring while loops

Understanding the do...while loop

Understanding breaks

Understanding continue

Understanding return

Summary

Questions

Further reading

Part 2: Writing Robust Smart Contracts

Chapter 6: Writing Smart Contracts

Technical requirements

Smart contracts

Writing a smart contract

Creating contracts

Using the new keyword

Using the address of a contract

Contract constructor

Contract composition

Inheritance

Single inheritance

Multilevel inheritance

Hierarchical inheritance

Multiple inheritance

Encapsulation

Polymorphism

Function polymorphism

Contract polymorphism

Method overriding

Abstract contracts

Interfaces

Advanced interfaces

Library

Importing a library

Summary

Questions

Further reading

Chapter 7: Solidity Functions, Modifiers, and Fallbacks

Technical requirements

Function input and output

Modifiers

Visibility scope

View, constant, and pure functions

Address-related functions

The address send method

The address transfer method

The address call method

The address callcode method

The address delegatecall method

The address staticcall method

The fallback and receive functions

Summary

Questions

Further reading

Chapter 8: Exceptions, Events, and Logging

Technical requirements

Exception handling

Require

Assert

Revert

Try-catch in Solidity

Events and logging

Summary

Questions

Further reading

Chapter 9: Basics of Truffle and Unit Testing

Technical requirements

Application development life cycle management

Introducing Truffle

Development with Truffle

Testing with Truffle

Interactively working with Truffle

Summary

Questions

Further reading

Chapter 10: Debugging Contracts

Technical requirements

Overview of debugging

The Remix editor

Using events

Using a block explorer

Summary

Questions

Further reading

Part 3: Advanced Smart Contracts

Chapter 11: Assembly Programming

Technical requirements

An introduction to Solidity and its advantages

Getting started with Assembly programming

Scopes and blocks

Returning values

Working with memory slots

Working with storage slots

Calling contract functions

Determining contract addresses

Summary

Questions

Further reading

Chapter 12: Upgradable Smart Contracts

Technical requirements

Learning what constitutes upgradability

Understanding dependency injection

Providing instance addresses during contract deployment

Providing instance addresses following contract deployment

Reviewing problematic smart contracts

Implementing simple solutions with inheritance

Implementing simple solutions with composition

Implementing advanced solutions using proxy contracts

Writing upgradable contracts with upgradable storage

Summary

Questions

Further reading

Chapter 13: Writing Secure Contracts

Technical requirements

SafeMath and under/overflow attacks

Reentrancy attack

The EtherPot contract

The Hacker contract

Solutions to the reentrancy problem

Security best practices

Summary

Questions

Further reading

Chapter 14: Writing Token Contracts

Technical requirements

Introducing tokens

ERC20 Tokens

ERC20 standard

ERC20 functionality

ERC20 events

Non-fungible tokens

ERC721

The ERC721 implementation

EIP223

ERC165

Summary

Questions

Further reading

Chapter 15: Solidity Design Patterns

Technical requirements

Introducing entity modeling

Ethereum storage

Data types in Ethereum

Understanding data modeling in Solidity

Nested versus reference fields

Exploring types of relationships

One-to-one relationships

One-to-many relationships

Many-to-many relationships

Reviewing the rules for embedding structures

Data cohesion

Out-of-bounds nested structure

Static data within a nested structure

The nested structure will not change in the near future

Containment relationship

Having few relationships

Performing data modeling using an example

Structures

State variables

Adding Employees

Retrieving a single Employees record

Updating Employees

Retrieving all Employees

Ownership in smart contracts

Exploring ownership in Solidity

Modifier

Establishing ownership of a smart contract

Multiownership

Transfer of ownership

MultiSig contracts

Transfer of the ownership of assets within a smart contract

Stoppable/haltable smart contract pattern

Summary

Questions

Further reading

Assessments

Chapter 1, Introduction to Blockchain, Ethereum, and Smart Contracts 

Chapter 2, Installing Ethereum and Solidity 

Chapter 3, Introducing Solidity 

Chapter 4, Global Variables and Functions 

Chapter 5, Expressions and Control Structures 

Chapter 6, Writing Smart Contracts 

Chapter 7, Functions, Modifiers, and Fallbacks 

Chapter 8, Exceptions, Events, and Logging 

Chapter 9, Truffle Basics and Unit Testing 

Chapter 10, Debugging Contracts 

Chapter 11, Assembly Programming

Chapter 12, Upgradable Smart Contracts 

Chapter 13, Writing Secure Contracts 

Chapter 14, Writing Token Contracts

Chapter 15, Solidity Design Patterns 

Other Books You May Enjoy

Preface

I am not sure when there was last so much of a discussion about a single technology across governments, organizations, communities, and individuals. Blockchain is a technology that is being discussed and debated at length across the world and in many organizations, and with reason. Blockchain is not a technology that has a limited effect on our lives. It has and will have widespread ramifications in our lives. The day is not far off when blockchain will touch almost every aspect of our daily activities—paying bills, making transactions with any organization, receiving a salary, verifying our identity, receiving educational results, and so on. This is just the beginning, and we have just started to understand the meaning of decentralization and its impact.

I have been working on blockchain for quite some time now and have been a crypto-investor for a while. I am a technologist and am completely fascinated by Bitcoin because of the architectural marvel it is. I have never come across such a superior thought process and architecture that actually solves not only economic and social problems but also some technically unsolved problems, such as Byzantine general problems and fault tolerance. It solves the problem of distributed computing at large.

Ethereum is built in a similar fashion, and I was in awe when I first heard about and experienced smart contracts. Smart contracts are one of the greatest innovations to deploy decentralized applications on blockchain and extend it easily with custom logic, policies, and rules.

I have thoroughly enjoyed writing this book and sincerely hope that you also enjoy reading about and implementing Solidity. I have brought in a lot of my Solidity experience and try to make the most of it. I hope this book makes you a better Solidity developer and a superior programmer.

Do let me know if there is anything I can do to make your experience better with this book. I am all ears. Happy learning!

Who this book is for

This book is primarily aimed at beginners who would like to get started with Solidity programming to develop an Ethereum smart contract. No prior knowledge of the EVM is required, but knowing the basics of any programming language will help you follow along.

What this book covers

Chapter 1, Introduction to Blockchain, Ethereum, and Smart Contracts, takes you through the fundamentals of blockchain, its terminology and jargon, its advantages, the problems it's trying to solve, and its industry relevance. It will explain the important concepts and architecture in detail. This chapter will also teach you about concepts specific to Ethereum, such as externally owned accounts, contract accounts, and its currency in terms of gas and Ether. Ethereum is heavily based on cryptography, so you'll also learn about hash, encryption, and the usage of keys for creating transactions and accounts. How transactions and accounts are created, how gas is paid for each transaction, the difference between message calls and transactions, and the storage of code and state management will be explained in detail.

Chapter 2, Installing Ethereum and Solidity, takes you through creating a private blockchain using the Ethereum platform. It will provide step-by-step guidance for creating a private chain. Another important tool in the Ethereum ecosystem is Ganache, which is mainly used for development and testing purposes. This chapter will also show the process of installing Ganache and using it for developing, testing, and deploying Solidity contracts. You will also install MetaMask, which is a wallet and can interact with any kind of Ethereum network. MetaMask is used to create new accounts, interact with contracts, and use them. The mining of transactions will also be shown in this chapter. Remix is a great tool for authoring Solidity contracts, shown toward the end of the chapter.

Chapter 3, Introducing Solidity, begins the Solidity journey. In this chapter, you'll learn the basics of Solidity by understanding its different versions and how to use a version using pragma. Another important aspect of this chapter is understanding the big picture of authoring smart contracts. Smart contract layout will be discussed in depth using important constructs such as state variables, functions, constant functions, events, modifiers, fallbacks, enums, and structs. This chapter discusses and implements the most important element of any programming language—data types and variables. Data types can be simple or complex; there can be value and reference types and storage and memory types—all these types of variables will also be shown using examples.

Chapter 4, Global Variables and Functions, provides implementation and usage details of block- and transaction-related global functions and variables and address- and contract-related global functions and variables. These come in very handy in writing any series of smart contract development. Recovering public addresses using ecrecover is explained as well in depth in this chapter.

Chapter 5, Expressions and Control Structures, teaches you how to write contracts and functions that have conditional logic using if...else and switch statements. Looping is an important part of any language and Solidity provides while and for loops for looping over arrays. Examples and implementation of looping will be part of this chapter. Loops must break based on certain conditions and should continue based on other conditions.

Chapter 6, Writing Smart Contracts, is the core chapter of the book. Here, you will start writing serious smart contracts. We will discuss the design aspects of writing smart contracts, defining and implementing a contract, and deploying and creating contracts using different mechanisms such as the new keyword and known addresses. Solidity provides rich object orientation, and this chapter will delve deep into object-oriented concepts and implementation, such as inheritance, multiple inheritance, declaring abstract classes and interfaces, and providing method implementations to abstract functions and interfaces. Advanced interface reuse when only the address is available is also covered. Reusable contracts, also known as libraries in Solidity, are explained using simple examples.

Chapter 7, Functions, Modifiers, and Fallbacks, shows how to implement basic functions that accept inputs and return outputs, functions that just output the existing state without changing the state and modifiers. Modifiers help in organizing code better in Solidity. They help with security and reusing code within contracts. Fallbacks are important constructs and are executed when a function call does not match any of the existing function signatures. Fallbacks are also important for transferring Ether to contracts. Both modifiers and fallbacks will be discussed and implemented with examples for easy understanding. Receive functions are relatively new in Solidity but sample coverage is provided on them in this chapter.

Chapter 8, Exceptions, Events, and Logging, covers exceptions, events, and logging, which are important in Solidity from a contract development perspective. Ether should be returned to the caller in the case of an error and exception. Exception handling will be explained and implemented in depth in this chapter using newer Solidity constructs, such as assert, require, and revert. The try-catch blocks introduced recently in Solidity are covered using multiple examples in this chapter. Events and logging help in understanding the execution of contracts and functions. This chapter will show and explain the implementation of both events and logs.

Chapter 9, Truffle Basics and Unit Testing, covers the basics of Truffle, including understanding its concepts, creating a project and understanding its project structure, modifying its configuration, and taking a sample contract through the entire life cycle of writing, testing, deploying, and migrating a contract. Testing is as important for contracts as writing a contract. Truffle helps in providing a framework to test; however, tests should be written. This chapter will discuss the basics of unit tests, writing unit tests using Solidity, and executing them against the smart contract. Unit tests will be executed by creating transactions and validating their results. This chapter will show implementation details for writing and executing unit tests for a sample contract. Interactively working with contracts using Truffle is also shown in this chapter.

Chapter 10, Debugging Contracts, covers troubleshooting and debugging using multiple tools, such as Remix and events. This chapter will show how to execute code line by line, checking the state after every line of code and changing contract code accordingly.

Chapter 11, Assembly Programming, goes into a slightly more complex topic and explores assembly programming in Solidity. Solidity has its own assembly programming and this chapter covers it from the ground up, from working with variables, scopes, and blocks and returning values to advanced topics including working with memory and state slots and calling contract functions. This chapter also includes assembly examples related to determining whether an address is a contract address or not.

Chapter 12, Upgradable Smart Contracts, is an important chapter from a contract maintainability perspective. This chapter will take you on a journey from a non-upgradable contract to writing upgradable contracts using different strategies. Some of these strategies include upgradability using inheritance, composition, proxy contracts, and upgradable storage.

Chapter 13, Writing Secure Contracts, brings security into perspective related to smart contracts. It starts by listing some of the security best practices and then moves on to showing some of the most prevalent vulnerabilities with smart contracts and how best to avoid them. These include the complete implementation of reentrancy attacks on smart contracts and overflow/underflow attacks.

Chapter 14, Writing Token Contracts, is about building and implementing both ERC20 and ERC721 tokens. Fungible and Non-Fungible Tokens (NFTs) are explained with the help of complete implementation in this chapter. Implementation of some of the ancillary interfaces, such as ERC165 and ERC223, is also explained along with their implementations.

Chapter 15, Solidity Design Patterns, describes some of the important design patterns prevalent in Solidity. It starts with the modeling of entities in smart contracts and between contracts using references, relationships, and embedment. It also shows a complete example of performing CRUD operations on these entities. Some of the design patterns shown with implementations in this chapter include ownership, multi-ownership, and multi-sig contracts. We will also discuss haltable or stoppable smart contracts.

To get the most out of this book

Most of the examples shown in this book are executed using the online Remix editor available at https://remix.ethereum.org.

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book's GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Solidity-Programming-Essentials-Second-Edition. If there's an update to the code, it will be updated in the 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 and diagrams used in this book. You can download it here: https://static.packt-cdn.com/downloads/9781803231181_ColorImages.pdf.

Conventions used

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

Code in text: 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: "Apart from pragma, import, and comments, we can define contracts, libraries, and interfaces at a global level."

A block of code is set as follows:

// This is a single-line comment in Solidity

/* This is a multiline comment

In Solidity. Use this when multiple consecutive lines

Should be commented as a whole */

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

pragma solidity >=0.7.0 <0.9.0;

contract ConversionDemo {

    

    function ConversionExplicitUINT8toUINT256() pure public returns (uint){

     ……

    }

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

pragma solidity >=0.7.0 <0.9.0;

Tips or important notes

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, email us at [email protected] and mention the book title in the subject of your message.

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/support/errata and fill in the form.

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 [email protected] 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.

Share Your Thoughts

Once you've read Solidity Programming Essentials, we'd love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we're delivering excellent quality content.

Part 1: The Fundamentals of Solidity and Ethereum

In this section, we will learn about the basic building blocks of Solidity programming. In this part, we will first briefly understand Ethereum and its toolsets, and then move on to writing simple contracts and explaining the fundamental concepts related to Solidity data types, variables, conditional statements, while and for loops, and return statements. Solidity provides global variables and functions, which are also explained in this section.

This part contains the following chapters:

Chapter 1, Introduction to Blockchain, Ethereum, and Smart ContractsChapter 2, Installing Ethereum and SolidityChapter 3, Introducing SolidityChapter 4, Global Variables and FunctionsChapter 5, Expressions and Control Structure