Solidity Programming Essentials: A Guide To Building Smart Contracts and Tokens Using The Widely Used Solidity Language 2nd Edition Ritesh Modi Download
Solidity Programming Essentials: A Guide To Building Smart Contracts and Tokens Using The Widely Used Solidity Language 2nd Edition Ritesh Modi Download
https://ebookmeta.com/product/building-games-with-ethereum-smart-
contracts-intermediate-projects-for-solidity-developers-kedar-
iyer/
https://ebookmeta.com/product/beginning-ethereum-smart-contracts-
programming-with-examples-in-python-solidity-and-javascript-2nd-
edition-wei-meng-lee/
https://ebookmeta.com/product/blockchain-and-ethereum-smart-
contract-solution-development-dapp-programming-with-solidity-1st-
edition-weijia-zhang/
https://ebookmeta.com/product/between-romanticism-and-modernism-
four-studies-in-the-music-of-the-later-nineteenth-century-carl-
dahlhaus/
Studies in Inductive Logic and Probability Volume 2
Richard C. Jeffrey (Editor)
https://ebookmeta.com/product/studies-in-inductive-logic-and-
probability-volume-2-richard-c-jeffrey-editor/
https://ebookmeta.com/product/power-electronics-1st-edition-
daniel-w-hart/
https://ebookmeta.com/product/freezer-burn-a-military-sci-fi-
series-waymaker-wars-book-2-rachel-aukes/
https://ebookmeta.com/product/teaching-for-successful-
intelligence-to-increase-student-learning-and-achievement-2nd-
edition-robert-j-sternberg-elena-l-grigorenko/
https://ebookmeta.com/product/the-ethics-of-hooking-up-casual-
sex-and-moral-philosophy-on-campus-1st-edition-james-rocha/
Tempted by the Forbidden Mate 1st Edition Ellie Pond
https://ebookmeta.com/product/tempted-by-the-forbidden-mate-1st-
edition-ellie-pond/
Solidity
Programming
Essentials
Second Edition
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
2
Installing Ethereum and Solidity
Technical requirements 36 Creating a private network 42
Ethereum networks 36 Installing Ganache 46
Main network 37 Installing the Solidity compiler 50
Test network 37 Installing the web3 framework 51
Private network 38
Installing and using MetaMask 52
Consortium network 38
Summary59
Installing and configuring Geth 38 Questions59
Installing Geth on macOS 39 Further reading 59
Installing Geth on Windows 39
3
Introducing Solidity
Technical requirements 62 Storage and memory data
The Ethereum Virtual Machine 62 locations79
Understanding Solidity and Rule one 79
Solidity files 63 Rule two 79
Rule three 80
Pragma63
Rule four 80
Comments64
Rule five 80
Importing Solidity code 65
Rule six 82
Contracts66
Rule seven 83
The structure of a contract 67 Rule eight 84
State variables 69
Using literals 85
Structure70
Modifiers 71 Understanding integers 86
Events73 Understanding Boolean 87
Enumeration74 The byte data type 88
Functions74 Understanding arrays 90
Exploring data types in Solidity 76 Fixed arrays 91
Dynamic arrays 91
Value types 76
Special arrays 93
Reference types 77
Array properties 95
Table of Contents vii
4
Global Variables and Functions
Technical requirements 108 The difference between tx.origin and
msg.sender 114
Variable scoping 108
Type conversion 109 Cryptographic global variables 115
Implicit conversion 110 Address global variables 116
Explicit conversion 110 Contract global variables 116
Block and transaction Recovering addresses using
global variables 112 ecrecover117
Transaction- and message-related Summary122
global variables 114 Questions123
Further reading 123
5
Expressions and Control Structures
Technical requirements 126 Understanding the
Understanding Solidity do...while loop 131
expressions126 Understanding breaks 134
Understanding the if and if... Understanding continue 135
else decision control 128 Understanding return 136
Exploring while loops 129 Summary137
Questions137
Further reading 137
viii Table of Contents
7
Solidity Functions, Modifiers, and Fallbacks
Technical requirements 170 The address call method 181
Function input and output 170 The address callcode method 185
The address delegatecall method 185
Modifiers 172
The address staticcall method 186
Visibility scope 175
View, constant, and pure The fallback and receive
functions176 functions187
Address-related functions 179 Summary191
The address send method 179 Questions191
The address transfer method 181 Further reading 192
Table of Contents ix
8
Exceptions, Events, and Logging
Technical requirements 194 Try-catch in Solidity 209
Exception handling 194 Events and logging 214
Require197 Summary218
Assert 202 Questions219
Revert 204
Further reading 219
9
Basics of Truffle and Unit Testing
Technical requirements 222 Interactively working with
Application development life Truffle 232
cycle management 222 Summary234
Introducing Truffle 223 Questions235
Development with Truffle 225 Further reading 235
Testing with Truffle 230
10
Debugging Contracts
Technical requirements 238 Using a block explorer 244
Overview of debugging 238 Summary247
The Remix editor 238 Questions247
Using events 244 Further reading 247
x Table of Contents
12
Upgradable Smart Contracts
Technical requirements 270 Implementing simple solutions
Learning what constitutes with inheritance 277
upgradability270 Implementing simple solutions
Understanding dependency with composition 281
injection272 Implementing advanced
Providing instance addresses during solutions using proxy contracts 285
contract deployment 273 Writing upgradable contracts
Providing instance addresses following with upgradable storage 290
contract deployment 274
Summary292
Reviewing problematic smart Questions292
contracts275 Further reading 292
13
Writing Secure Contracts
Technical requirements 294 Reentrancy attack 296
SafeMath and under/overflow The EtherPot contract 297
attacks294 The Hacker contract 299
Table of Contents xi
14
Writing Token Contracts
Technical requirements 308 The ERC721 implementation 323
Introducing tokens 308 EIP223 330
ERC20 Tokens 309 ERC165334
15
Solidity Design Patterns
Technical requirements 340 Data cohesion 349
Introducing entity modeling 340 Out-of-bounds nested structure 349
Static data within a nested structure 349
Ethereum storage 341
The nested structure will not change in
Data types in Ethereum 341
the near future 349
Understanding data modeling Containment relationship 349
in Solidity 343 Having few relationships 350
Nested versus reference fields 343
Performing data modeling
Exploring types of relationships346 using an example 350
One-to-one relationships 347 Structures350
One-to-many relationships 347 State variables 351
Many-to-many relationships 348 Adding Employees 351
Retrieving a single Employees record 352
Reviewing the rules for Updating Employees 352
embedding structures 348 Retrieving all Employees 353
xii Table of Contents
CONTENTS
PIPEFULS
By Christopher Morley
Illustrated By Walter Jack Duncan
CONTENTS
PAGE
Preface vii
On Making Friends 3
Thoughts on Cider 10
One-Night Stands 18
The Owl Train 25
Safety Pins 29
Confessions of a “Colyumist” 34
Moving 42
Surf Fishing 48
“Idolatry” 52
The First Commencement Address 60
The Downfall of George Snipe 63
Meditations of a Bookseller 66
If Buying a Meal Were Like Buying
71
a House
Adventures in High Finance 74
On Visiting Bookshops 78
A Discovery 83
Silas Orrin Howes 91
Joyce Kilmer 97
Tales of Two
109
Cities
I. Philadelphia:
An Early Train
Ridge Avenue
The University and the Urchin
Pine Street
Pershing in Philadelphia
Fall Fever
Two Days Before Christmas
In West Philadelphia
Horace Traubel
II. New York: 163
The Anatomy of Manhattan
Vesey Street
Brooklyn Bridge
Three Hours for Lunch
Passage from Some Memoirs
First Lessons in Clowning
House Hunting
Long Island Revisited
On Being in a Hurry
Confessions of a Human Globule
Notes on a Fifth Avenue Bus
Sunday Morning
Venison Pasty
Grand Avenue, Brooklyn
On Waiting for the Curtain to Go
236
Up
Musings of John Mistletoe 240
The World's Most Famous Oration 242
On Laziness 244
Teaching the Prince to Take Notes 249
A City Notebook 253
On Going to Bed 270
CONTENTS
A HANDFUL OF SONNETS
I
II
PEDOMETER
ARS DURA
O. HENRY—APOTHECARY
FOR THE CENTENARY OF KEATS'S SONNET (1816)
TWO O'CLOCK
THE COMMERCIAL TRAVELLER
THE WEDDED LOVER
TO YOU, REMEMBERING THE PAST
THE LAST SONNET
THE WAR
IRONY
TO A FRENCH BABY
AFTER HEARING GERMAN MUSIC
IN MEMORY OF THE AMERICAN AVIATORS KILLED IN FRANCE
THE FLAGS ON FIFTH AVENUE
"THEY"
BALLAD OF FRENCH RIVERS
PEASANT AND KING
TILL TWISTON WENT
TO RUDYARD KIPLING
TO A U-BOAT
KITCHENER
MARCH 1915
DEAD SHIPS
ENGLAND, JULY 1913 (TO RUPERT BROOKE)
TO THE OXFORD MEN IN THE WAR
FOR THE PRESENT TIME
AMERICA, 1917
ON VIMY RIDGE
CHIMNEYSMOKE
By Christopher Morley
CONTENTS
PAGE
TO THE LITTLE HOUSE 19
A GRACE BEFORE WRITING 20
DEDICATION FOR A FIREPLACE 21
TAKING TITLE 22
THE SECRET 25
ONLY A MATTER OF TIME 26
AT THE MERMAID CAFETERIA 28
OUR HOUSE 29
ON NAMING A HOUSE 31
A HALLOWE'EN MEMORY 32
REFUSING YOU IMMORTALITY 35
BAYBERRY CANDLES 36
SECRET LAUGHTER 37
SIX WEEKS OLD 38
A CHARM 41
MY PIPE 42
THE 5:42 44
PETER PAN 48
IN HONOR OF TAFFY TOPAZ 49
THE CEDAR CHEST 50
READING ALOUD 51
ANIMAL CRACKERS 52
THE MILKMAN 55
LIGHT VERSE 56
THE FURNACE 57
WASHING THE DISHES 58
THE CHURCH OF UNBENT KNEES 61
ELEGY WRITTEN IN A COUNTRY COAL-BIN 62
THE OLD SWIMMER 66
THE MOON-SHEEP 70
SMELLS 71
SMELLS (JUNIOR) 72
MAR QUONG, CHINESE LAUNDRYMAN 75
THE FAT LITTLE PURSE 76
THE REFLECTION 80
THE BALLOON PEDDLER 82
LINES FOR AN ECCENTRIC'S BOOK PLATE 86
TO A POST-OFFICE INKWELL 89
THE CRIB 90
THE POET 94
TO A DISCARDED MIRROR 97
TO A CHILD 98
TO A VERY YOUNG GENTLEMAN 100
TO AN OLD-FASHIONED POET 104
BURNING LEAVES IN SPRING 105
BURNING LEAVES, NOVEMBER 106
A VALENTINE GAME 107
FOR A BIRTHDAY 108
KEATS 111
TO H. F. M., A SONNET IN SUNLIGHT 113
QUICKENING 114
AT A WINDOW SILL 115
THE RIVER OF LIGHT 116
OF HER GLORIOUS MADNESS 118
IN AN AUCTION ROOM 119
EPITAPH FOR A POET WHO WROTE NO POETRY 120
SONNET BY A GEOMETER 121
TO A VAUDEVILLE TERRIER 122
TO AN OLD FRIEND 125
TO A BURLESQUE SOUBRETTE 126
THOUGHTS WHILE PACKING A TRUNK 129
STREETS 130
TO THE ONLY BEGETTER 131
PEDOMETER 133
HOSTAGES 134
ARS DURA 137
O. HENRY—APOTHECARY 138
FOR THE CENTENARY OF KEATS'S SONNET 139
TWO O'CLOCK 140
THE COMMERCIAL TRAVELLER 141
THE WEDDED LOVER 142
TO YOU, REMEMBERING THE PAST 143
CHARLES AND MARY 144
TO A GRANDMOTHER 145
DIARISTS 146
THE LAST SONNET 147
THE SAVAGE 148
ST. PAUL'S AND WOOLWORTH 149
ADVICE TO A CITY 150
THE TELEPHONE DIRECTORY 151
GREEN ESCAPE 153
VESPER SONG FOR COMMUTERS 157
THE ICE WAGON 158
AT A MOVIE THEATRE 161
SONNETS IN A LODGING HOUSE 163
THE MAN WITH THE HOE (PRESS) 167
DO YOU EVER FEEL LIKE GOD? 168
RAPID TRANSIT 170
CAUGHT IN THE UNDERTOW 171
TO HIS BROWN-EYED MISTRESS 172
PEACE 173
SONG, IN DEPRECATION OF PULCHRITUDE 175
MOUNTED POLICE 176
TO HIS MISTRESS, DEPLORING THAT HE IS NOT
179
AN ELIZABETHAN GALAXY
THE INTRUDER 181
TIT FOR TAT 182
SONG FOR A LITTLE HOUSE 185
THE PLUMPUPPETS 186
DANDY DANDELION 190
THE HIGH CHAIR 192
LOVE AT FIRST SIGHT 193
AUTUMN COLORS 197
THE LAST CRICKET 198
TO LOUISE 199
CHRISTMAS EVE 203
EPITAPH ON THE PROOFREADER OF THE
204
ENCYCLOPEDIA BRITANNICA
THE MUSIC BOX 205
TO LUATH 209
THOUGHTS ON REACHING LAND 212
A SYMPOSIUM 214
TO A TELEPHONE OPERATOR WHO HAS A BAD
218
COLD
NURSERY RHYMES FOR THE TENDER-HEARTED 219
THE TWINS 227
A PRINTER'S MADRIGAL 228
THE POET ON THE HEARTH 230
O PRAISE ME NOT THE COUNTRY 231
A STONE IN ST. PAUL'S GRAVEYARD 235
THE MADONNA OF THE CURB 236
THE ISLAND 240
SUNDAY NIGHT 242
ENGLAND, JULY, 1913 246
CASUALTY 250
A GRUB STREET RECESSIONAL 251
PRELIMINARY INSTRUCTIONS FOR A FUNERAL
253
SERVICE
ILLUSTRATIONS
CONTENTS
Updated editions will replace the previous one—the old editions will
be renamed.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.F.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.