Reader small image

You're reading from  Learn Ethereum - Second Edition

Product typeBook
Published inAug 2023
PublisherPackt
ISBN-139781804616512
Edition2nd Edition
Concepts
Right arrow
Authors (3):
Xun (Brian) Wu
Xun (Brian) Wu
author image
Xun (Brian) Wu

Xun (Brian) Wu is a senior blockchain architect and consultant. With over 20 years of hands-on experience across various technologies, including Blockchain, big data, cloud, AI, systems, and infrastructure, Brian has worked on more than 50 projects in his career. He has authored nine books, which have been published by O'Reilly, Packt, and Apress, focusing on popular fields within the Blockchain industry. The titles of his books include: Learn Ethereum (First Edition), Learn Ethereum (Second Edition), Blockchain for Teens, Hands-On Smart Contract Development with Hyperledger Fabric V2, Hyperledger Cookbook, Blockchain Quick Start Guide, Security Tokens and Stablecoins Quick Start Guide, Blockchain by Example, and Seven NoSQL Databases in a Week.
Read more about Xun (Brian) Wu

Zhihong Zou
Zhihong Zou
author image
Zhihong Zou

Zhihong Zou is an innovative technology leader with over 20 years of experience delivering cutting-edge enterprise solutions. He has led transformative solutions in telecommunications, healthcare, and government that leverage blockchain, AI/ML, and modern cloud architectures to solve complex business challenges. As an insightful visionary and trusted advisor, Zhihong is passionate about driving digital transformation and future-proofing organizations. He holds an M.Sc degree in computational mathematics and an M.Sc in computer science. Zhihong has authored multiple papers on numerical computing and two popular editions of the book Learn Ethereum. In his free time, Zhihong enjoys sharing his blockchain expertise as an advocate and writer.
Read more about Zhihong Zou

Dongying Song
Dongying Song
author image
Dongying Song

Dongying Song has been a noteworthy leader in Blockchain, Ethereum, big data, ML, data science, and the cloud application development space for over 8 years. As an experienced software engineer and data scientist, she has worked for top-tier banks and pharmaceutical and technology companies. Dongying holds a master's degree in statistics from Columbia University and majored in mathematics during her undergraduate years. Her recent activities focus on Blockchain, Ethereum, and smart contract developments.
Read more about Dongying Song

View More author details
Right arrow

Fundamentals of Solidity

In this chapter, we will dive into the details of Solidity, the most popular smart contract programming language. We will look at the features of the Solidity programming language and will provide an overview of Solidity’s development tools. We will learn about various Solidity language fundamentals, including the structure of a contract, contract patterns, and exception handling. We also cover smart contract security and best practices. At the end of this chapter, we will show you a complete example of a real-world smart contract that’s been developed in Solidity, and demonstrate how you can functionally test your smart contract.

The following topics will be covered in this chapter:

  • Introducing Solidity
  • Learning about the fundamental programming structure in Solidity
  • Enabling the contracts library
  • Understanding inheritance, abstract contracts, and interfaces
  • Examining smart contract execution under the hood
  • Mastering...

Technical requirements

For all the source code of this book, please refer to the following GitHub link: https://github.com/PacktPublishing/Learn-Ethereum-Second-Edition/.

Introducing Solidity

Solidity is an Ethereum smart contract programming language with a syntax similar to C++ and JavaScript. It was designed to create a smart contract and can be executed on the Ethereum Virtual Machine (EVM). Gavin Wood, Christian Reitwiessner, Alex Beregszaszi, and several Ethereum core contributors developed it.

Solidity is a statically-typed, object-oriented language that contains state variables, functions, and complex user-defined types and supports inheritance and libraries. It allows developers of Decentralized Applications (DApps) to implement business logic functions in a smart contract. Like any other static language, the contract compiler will verify and check syntax rules during the contract compile time. Similar to Java, the Solidity code is compiled into bytecode that can be executed on the EVM. Unlike other compiled languages, the bytecode that’s generated across platforms will remain the same, provided that the input parameters to the compiler...

Learning about the fundamental programming structure in Solidity

Let’s get a taste of Solidity’s code and use an example to show you the layout and constructs of a smart contract. We will begin with the most basic smart contract example, HelloWorld.sol, as shown in the following screenshot:

Figure 6.4 – HelloWorld contract

Figure 6.4 – HelloWorld contract

Solidity’s file extension is .sol. It is similar to .js for JavaScript files and .java for Java source code. The preceding code defines a smart contract called HelloWorld, which has a contractor for setting the initial greeting, defines a setGreeting method to reset the greeting, and a hello method for the authorized party to get the greeting. In the rest of the chapter, we will go over the fundamentals of the Solidity programming language, including the following headings:

  • The layout of a Solidity source file
  • Structure of a contract
  • State variables
  • Functions
  • Function modifiers
...

Built-in data types

Solidity is a statically-typed language. Developers with other programming language backgrounds, such as JavaScript, Java, or Python, will easily learn the Solidity syntax. Each variable needs to specify the data type. Depending on the data type, a declared variable will have a default value, which is an initial default value whose byte representation is all zeros.

Data types in Solidity can be either of the following:

  • Value types: This will always be passed by value
  • Reference types: This means it will be passed by reference

Solidity defines a large number of built-in data types, which allow you to define the complex types using enums, structs, and mapping.

The basic data types in Solidity are as follows:

The pure, view, and payable functions

Functions can be declared as pure, view, or payable, depending on whether it can receive Ether or whether it needs to access the state. Some earlier versions of Solidity had a constant as the alias to view, but it was dropped in version 0.5.0:

  • Pure function: A pure function means it won’t read or modify the state
  • View function: A view function means it won’t alter the storage state in any way, but you can view it
  • Payable function: A payable function means it can receive Ether

Here is an example of the pure, view, and payable functions:

 //pure
  function add(uint a, uint b) public pure returns(uint) {   }
//view
  function add(uint a, uint b) public view returns(uint) {   }
// payable
function send() payable { }

The state means anything EVM holds beyond the input parameters, including state variables, events, contracts, Ether, and more. The following are...

Enabling the contracts library

Libraries can be seen as similar to contracts that contain reusable codes. Once libraries are deployed on the Ethereum network, they will be assigned a contract address. The properties and functions defined in the libraries can be called and reused many times by other contracts.

When library functions need access to state variables, they will be provided by calling the contract. Libraries enable code reuse across various contracts, thereby contributing to the enhancement of code quality , prevent duplication of code, and save on gas since the same code is not deployed multiple times.

When defining a library, there are some restrictions:

  • The library does not have state variables
  • The library cannot inherit any element and cannot be inherited
  • The library does not have state variables
  • The library cannot receive Ether
  • The library cannot be destroyed since it is stateless

All data is passed to the library by the calling...

Understanding inheritance, abstract contracts, and interfaces

There are four important pillars of object-oriented programming (OOP), as follows:

  • Inheritance
  • Encapsulation
  • Abstraction
  • Polymorphism

All of the preceding concepts play a critical role in influencing modern programming language design and software development. Inheritance enables code reuse and extensibility. Encapsulation refers to information hiding and bundling data within methods to avoid unauthorized direct access to the data. Abstraction is the process of exposing only the necessary information and hiding the details from other objects. Polymorphism allows functional extensibility via the overloading and overriding functions.

Like most modern object-oriented languages, such as Java or C++, Solidity supports OOP concepts through inheritance, abstract contracts, and interfaces. In fact, it supports a superset of these features from both Java and C++. Let’s go over them now:

    ...

Examining smart contract execution under the hood

When interacting with smart contracts on the Ethereum blockchain, the Ethereum Web3 API or JSON-API interface uses the contract’s application binary interface (ABI) as the standard way to encode and decode the methods we call, as well as the input and output data. The same applies to calls from outside of the blockchain and calls between contracts. Data is encoded according to its type, as described in the ABI specification.

All the functions and events within the smart contract can be described using JSON descriptors, as shown in the following screenshot. A JSON description of the deposit ( the _tenant string memory) method is shown in the red box, while the RentPaid event is shown in the purple box:

Figure 6.23 – ABI for the Rent contract

Figure 6.23 – ABI for the Rent contract

When the deposit method is called, it will generate a function selector, which is calculated as the first 4 bytes of the keccak256 hash of the deposit...

Mastering advanced programming concepts in Solidity

So far, you have learned about the Solidity programming language’s fundamentals, as well as object-oriented concepts in Solidity. To develop real-world smart contract applications, we have to understand the difference between safe and unsafe code practices. Once deployed, a smart contract is considered immutable. Therefore, we have to design smart contracts to be flexible, extensible, and maintainable. There are costs associated with running smart contracts on the Ethereum network, so we have to develop cost-effective smart contracts.

In the following subsections, we will discuss some advanced topics when it comes to programming Solidity smart contracts, including the following:

  • Smart contract security
  • Best practices and design patterns
  • Writing upgradable smart contracts
  • Economic consideration in developing smart contracts

Smart contract security

Smart contracts are immutable public records...

Types of smart contract

With the increasing adoption of blockchain-based solutions, more and more organizations are involving developing DApp and smart contracts. There are smart contracts and protocols classified into roughly three categories: Smart Legal Contracts, DAO, and Application Logic Contracts (ALCs).

Let us understand them briefly:

  • Smart Legal Contracts: Smart legal contracts are a type of smart contract. A well-defined smart contract can run automatically in the blockchain. When smart contract logic is a binding legal contract and executing code based on connected terms with a legally enforceable, the correspondent parties need to follow contract legal agreements to satisfy their contractual obligations. Smart legal contracts need to be human-readable and machine-readable agreements that consist of natural language and com-putable components. The human-readable agreement requires all parties involved in contracts to understand and agree with the contract. They...

Putting it all together – rental property leasing

In this section, we will implement and deploy a smart contract for a real-world rental property leasing use case. The business process for a rental property being leased starts with the landlord creating a rental property listing and allowing the tenants to apply and sign the leasing agreement.

Once the tenant moves in, they have to pay the monthly rent to the landlord, and once the lease term is due, the lease is terminated. If the tenant misses a rent payment, the landlord has the option to start an eviction, and if the tenant terminates the lease early, they have to pay the early termination penalty.

The following is the high-level diagram of our rental property lease contract:

Figure 6.36 – Diagram for rental property lease contract

Figure 6.36 – Diagram for rental property lease contract

The smart contract is developed using a combination of the access control design pattern and the state machine design pattern. Those of you who are interested...

Summary

In this chapter, we learned how to start smart contract development in Solidity using the most popular Solidity development IDEs. We discussed the Solidity programming fundamentals and basic language constructs. We learned how to write more secure code to avoid contract vulnerabilities by exploring common patterns and following security best practices. Finally, we showed you a real-world rental property lease smart contract and demonstrated how to use Remix to deploy and test our example.

In the next chapter, we will show you how to develop your very first cryptocurrency and full stack of DApps. We will also introduce the concept of decentralization, which is central to the idea behind blockchains and their vast number of applications.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learn Ethereum - Second Edition
Published in: Aug 2023Publisher: PacktISBN-13: 9781804616512
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (3)

author image
Xun (Brian) Wu

Xun (Brian) Wu is a senior blockchain architect and consultant. With over 20 years of hands-on experience across various technologies, including Blockchain, big data, cloud, AI, systems, and infrastructure, Brian has worked on more than 50 projects in his career. He has authored nine books, which have been published by O'Reilly, Packt, and Apress, focusing on popular fields within the Blockchain industry. The titles of his books include: Learn Ethereum (First Edition), Learn Ethereum (Second Edition), Blockchain for Teens, Hands-On Smart Contract Development with Hyperledger Fabric V2, Hyperledger Cookbook, Blockchain Quick Start Guide, Security Tokens and Stablecoins Quick Start Guide, Blockchain by Example, and Seven NoSQL Databases in a Week.
Read more about Xun (Brian) Wu

author image
Zhihong Zou

Zhihong Zou is an innovative technology leader with over 20 years of experience delivering cutting-edge enterprise solutions. He has led transformative solutions in telecommunications, healthcare, and government that leverage blockchain, AI/ML, and modern cloud architectures to solve complex business challenges. As an insightful visionary and trusted advisor, Zhihong is passionate about driving digital transformation and future-proofing organizations. He holds an M.Sc degree in computational mathematics and an M.Sc in computer science. Zhihong has authored multiple papers on numerical computing and two popular editions of the book Learn Ethereum. In his free time, Zhihong enjoys sharing his blockchain expertise as an advocate and writer.
Read more about Zhihong Zou

author image
Dongying Song

Dongying Song has been a noteworthy leader in Blockchain, Ethereum, big data, ML, data science, and the cloud application development space for over 8 years. As an experienced software engineer and data scientist, she has worked for top-tier banks and pharmaceutical and technology companies. Dongying holds a master's degree in statistics from Columbia University and majored in mathematics during her undergraduate years. Her recent activities focus on Blockchain, Ethereum, and smart contract developments.
Read more about Dongying Song

Types

Operators

Example

Note

Boolean (bool)

!, &&...