Book Image

Solidity Programming Essentials

Book Image

Solidity Programming Essentials

Overview of this book

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.
Table of Contents (17 chapters)
Title Page
Copyright and Credits
Packt Upsell
Contributors
Preface
Index

Preface

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!

Who this book is for

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.

What this book covers

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.

To get the most out of this book

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.

Download the example code files

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:

  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 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!

 

Conventions used

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

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "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."

Note

Warnings or important notes appear like this.

Note

Tips and tricks appear like this.

Get in touch

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.

Reviews

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

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