27,59 €
Learn the most powerful and primary programming language for writing smart contracts and find out how to write, deploy, and test smart contracts in Ethereum.
Solidity is a contract-oriented language whose syntax is highly influenced by JavaScript, and is designed to compile code for the Ethereum Virtual Machine. Solidity Programming Essentials will be your guide to understanding Solidity programming to build smart contracts for Ethereum and blockchain from ground-up.
We begin with a brief run-through of blockchain, Ethereum, and their most important concepts or components. You will learn how to install all the necessary tools to write, test, and debug Solidity contracts on Ethereum. Then, you will explore the layout of a Solidity source file and work with the different data types. The next set of recipes will help you work with operators, control structures, and data structures while building your smart contracts. We take you through function calls, return types, function modifers, and recipes in object-oriented programming with Solidity. Learn all you can on event logging and exception handling, as well as testing and debugging smart contracts.
By the end of this book, you will be able to write, deploy, and test smart contracts in Ethereum. This book will bring forth the essence of writing contracts using Solidity and also help you develop Solidity skills in no time.
This book is for anyone who would like to get started with Solidity Programming for developing an Ethereum smart contract. No prior knowledge of EVM is required.
Ritesh Modi is an ex Microsoft senior technology evangelist and Microsoft regional lead. He has worked on Ethereum and Solidity, extensively helping and advising companies. Ritesh is a regular speaker on blockchain and Solidity at conferences and local meetups. He is an architect, evangelist, speaker, and a known leader for his contributions toward blockchain, data centers, Azure Bots, cognitive services, DevOps, Artificial Intelligence, and automation. He is the author of five books.Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 193
Veröffentlichungsjahr: 2018
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, 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: Merint MethewAcquisition Editor: Sandeep MishraContent Development Editor: Priyanka SawantTechnical Editor: Vibhuti GawdeCopy Editor: Safis EditingProject Coordinator: Vaidehi SawantProofreader: Safis EditingIndexer: Rekha NairGraphics: Jason MonteiroProduction Coordinator: Deepika Naik
First published: April 2018
Production reference: 1180418
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78883-138-3
www.packtpub.com
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.
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
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.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.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.
Ritesh Modi is an ex Microsoft senior technology evangelist and Microsoft regional lead. He has worked on Ethereum and Solidity, extensively helping and advising companies. Ritesh is a regular speaker on blockchain and Solidity at conferences and local meetups. He is an architect, evangelist, speaker, and a known leader for his contributions toward blockchain, data centers, Azure Bots, cognitive services, DevOps, Artificial Intelligence, and automation. He is the author of five books.
Pablo Ruiz has been involved in the creation of dozens of tech products over the past 12 years, working with the latest, cutting-edge technologies. In 2008, he became deeply involved in the creation of mobile games and applications; later on, he participated in many projects as an advisor or investor in the digital space. During 2015/2016, he was a director at one of the top venture capital firms in Latin America, where he built their Fintech ecosystem from the ground up. In 2018, after actively working on several ICOs, he joined Polymath as their VP of engineering to lead the development of the first Ethereum-based platform for issuing regulatory-compliant security tokens.
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.
Title Page
Copyright and Credits
Solidity Programming Essentials
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About 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
Conventions used
Get in touch
Reviews
Introduction to Blockchain, Ethereum, and Smart Contracts
What is a blockchain?
Why blockchains?
Cryptography
Symmetric encryption and decryption
Asymmetric encryption and decryption
Hashing
Digital signatures
Ether
Gas
Blockchain and Ethereum architecture
How are blocks related to each other?
How are transactions and blocks related to each other?
Ethereum nodes
EVM
Ethereum mining nodes
How does mining work?
Ethereum accounts
Externally owned accounts
Contract accounts
Transactions
Blocks
An end-to-end transaction
What is a contract?
What is a smart contract?
How to write smart contracts?
How are contracts deployed?
Summary
Installing Ethereum and Solidity
Ethereum networks
Main network
Test network
Ropsten
Rinkeby
Kovan
Private network
Consortium network
Geth
Installing Geth on Windows
Creating a private network
ganache-cli
Solidity compiler
The web3 JavaScript library
Mist wallet
MetaMask
Summary
Introducing Solidity
Ethereum Virtual Machine
Solidity and Solidity files
Pragma
Comments
The import statement
Contracts
Structure of a contract
State variables
Structure
Modifiers
Events
Enumeration
Functions
Data types in Solidity
Value types
Passing by value
Reference types
Passing by reference
Storage and memory data locations
Rule 1
Rule 2
Rule 3
Rule 4
Rule 5
Rule 6
Rule 7
Rule 8
Literals
Integers
Boolean
The byte data type
Arrays
Fixed arrays
Dynamic arrays
Special arrays
The bytes array
The String array
Array properties
Structure of an array
Enumerations
Address
Mappings
Summary
Global Variables and Functions
The var type variables
Variables hoisting
Variable scoping
Type conversion
Implicit conversion
Explicit conversion
Block and transaction global variables
Transaction and message global variables
Difference between tx.origin and msg.sender
Cryptography global variables
Address global variables
Contract global variables
Summary
Expressions and Control Structures
Solidity expressions
The if decision control
The while loop
The for loop
The do...while loop
The break statement
The continue statement
The return statement
Summary
Writing Smart Contracts
Smart contracts
Writing a simple contract
Creating contracts
Using the new keyword
Using address of a contract
Constructors
Contract composition
Inheritance
Single inheritance
Multi-level inheritance
Hierarchical inheritance
Multiple inheritance
Encapsulation
Polymorphism
Function polymorphism
Contract polymorphism
Method overriding
Abstract contracts
Interfaces
Summary
Functions, Modifiers, and Fallbacks
Function input and output
Modifiers
The view, constant, and pure functions
The address functions
The send method
The transfer method
The call method
The callcode method
The delegatecall method
The fallback function
Summary
Exceptions, Events, and Logging
Error handling
The require statement
The assert statement
The revert statement
Events and logging
Summary
Truffle Basics and Unit Testing
Application development life cycle management
Truffle
Development with Truffle
Testing with Truffle
Summary
Debugging Contracts
Debugging
The Remix editor
Using events
Using a Block Explorer
Summary
Other Books You May Enjoy
Leave a review - let other readers know what you think
I am not sure the last time I heard so much of a discussion about a technology across governments, organizations, communities, and individuals. Blockchain is a technology that is being discussed and debated at length across the world and organizations, and without a reason. Blockchain is not just a technology that has limited effect on our life. It has and will have widespread ramifications in our lives. The day is not far when blockchain will touch almost each aspect of our activities—whether paying bills, transactions with any organizations, getting salary, identity, educational results, activities, 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 long. I am a technologist and am completely fascinated by Bitcoin because of the architectural marvel it is. I have never come across such superior thought process and architecture that actually solves not only economic and social problems but solves 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 an almost similar fashion, and I was in awe when I first heard and experienced smart contracts. Smart contracts are one of the greatest innovation to deploy decentralized applications on blockchain and extend it easily with custom logic, policies, and rules.
I have thoroughly enjoyed authoring this book and sincerely hope that you would also enjoy reading and implementing Solidity. I have brought in a lot of my Solidity experience and try to make the maximum out 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, and happy learning!
To make usage of the content of this book, basic prior knowledge of computing and general programming concepts is needed. If you feel you don't have that knowledge, it is always possible to catch up the basic requirements with a fast reading on many beginners' books on programming. This book is essentially intended for blockchain architects, developers, consultants, and IT engineers who are using blockchain to provide advanced services to end customers and employers. If you are also willing to write smart contracts solution on Ethereum, then this book is ideal for you. If you already have some experience with JavaScript, this book can help you speed up with it in a fast-paced way.
Chapter 1, Introduction to Blockchain, Ethereum, and Smart Contracts, takes you through the fundamentals of blockchain, its terminology and jargon, advantages, problems it’s trying to solve, and industry relevance. It will explain the important concepts and architecture in detail. This chapter will also teach you about concepts specific to Ethereum. In this chapter, details about its concepts like externally owned accounts, contract accounts, its currency in terms of gas and Ether will be discussed. Ethereum is heavily based on cryptography and you’ll also learn about hash, encryption, and usage of keys for creating transactions and accounts. How are transactions and accounts created, how gas is paid for each transaction, difference between message calls and transactions, and storage of code and state management will be explained in detailed.
Chapter 2, Installing Ethereum and Solidity, takes you through creating a private blockchain using Ethereum platform. It will provide step-by-step guidance for creating a private chain. Another important tool in Ethereum ecosystem is ganache-cli. This chapter will also show the process of installing ganache-cli and using it for deploying Solidity contracts, installing Solidity, and using it to compile Solidity contracts. You will also install Mist, which is a wallet and can interact with private chain. Mist will be used to create new accounts, deploy contracts, and use contracts. Mining of transactions will also be shown in this chapter. Remix is a great tool for authoring Solidity contracts.
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 pragmas. Another import aspect of this chapter is to understand the big picture of authoring smart contracts. Smart contract layout will be discussed in depth using important constructs like state variables, functions, constant function, events, modifiers, fallbacks, enums, and structs. This chapter discusses and implements the most important element of any programming language—data types and variables. There are data types that are simple and complex, value types 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 comes in very handy in writing any series of smart contract development.
Chapter 5, Expressions and Control Structures, teaches you how to write contracts and functions that will 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 for the book. Here, you will start writing serious smart contracts. It will discuss the design aspects of writing smart contracts, defining and implementing a contract, and deploying and creating contracts using different mechanisms using the new keyword and using 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.
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. It helps in 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.
Chapter 8, Exceptions, Events, and Logging, is important in Solidity from contract development perspective. Ether should be returned to caller in case of error and exception. Exception handling will be explained and implemented in depth in this chapter using newer Solidity constructs like assert, require, and revert. The hrow statement will also be discussed. Events and logging help in understanding the execution of contracts and functions. This chapter will show and explain the implementation for both events and logs.
Chapter 9, Truffle Basics and Unit Testing, covers the basics of truffle, understanding its concepts, creating a project and understanding its project structure, modifying its configuration, and taking a sample contract through 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 test, write unit test using Solidity, and execute those unit tests against the smart contract. Unit tests will be executed by creating transaction and validating its results. This chapter will show implementation details to write and execute unit tests for a sample contract.
Chapter 10,Debugging Contracts, will be show troubleshooting and debugging using multiple tools like Remix and events. This chapter will show how to execute code line by line, check state after every line of code, and change contract code accordingly.
This book assumes a basic level knowledge of programming. It is ideal to have some background on any scripting language. All you need is an internet connectivity and a browser for using a majority of this book. There are sections that will need creating a machine to deploy blockchain specific tools and utilities. This machine can be physical or virtual, on cloud or on-premise.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
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/SolidityProgrammingEssentials. 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!
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: "A genesis.json file is required to create this first block."
A block of code is set as follows:
{ "config": {"chainId": 15,"homesteadBlock": 0,"eip155Block": 0,"eip158Block": 0},"nonce": "0x0000000000000042","mixhash": "0x0000000000000000000000000000000000000000000000000000000000000000","difficulty": "0x200","alloc": {},"coinbase": "0x0000000000000000000000000000000000000000","timestamp": "0x00","parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000","gasLimit": "0xffffffff","alloc": {}}
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
[default]exten => s,1,Dial(Zap/1|30)exten => s,2,Voicemail(u100)
exten => s,102,Voicemail(b100)
exten => i,1,Voicemail(s0)
Any command-line input or output is written as follows:
npm install -g ganache-cli
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: "For sending Ether from one account to another, select an account and click on the Send button."
Feedback from our readers is always welcome.
General feedback: Email [email protected] 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 [email protected].
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 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 [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.
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 packtpub.com.
This decade has already seen the extraordinary evolution of the technology and computing ecosystem. Technological innovation and its impact has been noticeable across the spectrum, from the Internet of Things (IoT), to Artificial Intelligence (AI), to blockchains. Each of them has had a disruptive force within multiple industries and blockchains are one of the most disruptive technologies today. So much so that blockchains have the potential to change almost every industry. Blockchains are revolutionizing almost all industries and domains while bringing forward newer business models. Blockchains are not a new technology; however, they have gained momentum over the last couple of years. It is a big leap forward in terms of thinking about decentralized and distributed applications. It is about the current architectural landscape and strategies for moving toward immutable distributed databases.
In this first chapter, you will quickly learn and understand the basic and foundational concepts of blockchains and Ethereum. We will also discuss some of the important concepts that makes blockchains and Ethereum work. Also, we will touch briefly on the topic of smart contracts and how to author them using Solidity.
It is to be noted that this chapter briefly explains important blockchain concepts. It does not explain all concepts in detail and would require a complete book only for that purpose. Since Ethereum is an implementation of a blockchain, both the words have been used interchangeably in this book.
This chapter will focus on introducing the following topics:
What is a blockchain and why is it used?
Cryptography
Ether and gas
Blockchain and Ethereum architecture
Nodes
Mining
Understanding accounts, transactions, and blocks
Smart contracts
A blockchain is essentially a decentralized distributed database or a ledger, as follows:
Decentralization:
In simple terms, it means that the application or service continues to be available and usable even if a server or a group of servers on a network crashes or is not available. The service or application is deployed on a network in a way that no server has absolute control over data and execution, rather each server has a current copy of data and execution logic.
Distributed:
