Reader small image

You're reading from  Mastering Blockchain Programming with Solidity

Product typeBook
Published inAug 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781839218262
Edition1st Edition
Languages
Concepts
Right arrow
Author (1)
Jitendra Chittoda
Jitendra Chittoda
author image
Jitendra Chittoda

Jitendra Chittoda is a blockchain security engineer at ChainSecurity. His day job is to perform security audit on smart contracts and expose security vulnerabilities in Solidity and Scilla contracts. He has also developed a non-custodial, decentralized, P2P lending contracts for ETHLend. The Solidity contracts that he has developed or audited handle over $100 million worth of cryptoassets. He also served as a tech and security advisor in various ICO projects. Before finding his passion for blockchain, he coded in Java for over 11 years. He is the founder and leader of Delhi-NCR-JUG, a non-profit meetup group for Java. He holds a master's degree in computer applications and is regularly invited as a speaker at various conferences and meetups.
Read more about Jitendra Chittoda

Right arrow

Control Structures and Contracts

In this chapter, we will learn about the different control structures provided by Solidity that you can use while writing contracts, such as for and while loops, conditional statements, and much more. Then, we will move on to discussing different types of visibility modifiers for variables and functions, types of functions you can create, contract inheritance, abstract interfaces, and creating libraries.

The following topics will be covered in this chapter:

  • Control structure keywords supported by Solidity
  • Visibility modifiers applied to variables and functions of contracts
  • Different types of functions and their behavior
  • Solidity contract inheritance
  • The use of abstract contracts
  • Writing and using libraries in Solidity

Understanding Solidity control structures

A program doesn't always have a linear sequence of instructions. It may require some conditional and repeated code execution. This is why control structure keywords are supported in most languages.

Solidity supports many of the control structure keywords that are available in other languages, such as C and JavaScript. Conditions should be in parentheses (...) and code blocks should be in curly brackets {...}. The following are the control structures that Solidity supports.

The following are conditional control structures:

  • if...else block: For conditional execution of the logic. You can also have nested if...else structures.
  • ? : operator: A ternary operator for conditional checking in a single statement.

The following are iteration control structures (loops):

  • while loop: For creating while loops in Solidity
  • for loop...

Solidity contracts

Just like the Java language, you can write your class definition and create as many objects as you want using the same class definition. Similarly, Solidity has smart contracts, in which you write the definition of the contract. When you deploy the contract on a blockchain, a public contract account address is generated and assigned to it. You can deploy as many contracts as you want with your contract definition on the blockchain, and each deployment would create new contract instances on the blockchain, each have unique contract addresses. Your application design determines whether you want to deploy multiple contracts of the same contract definition or not.

Note that contracts do not have the cron-like functionality necessary to auto-trigger a transaction from a contract at a given time. A transaction is always initiated from an EOA account.

There are...

Understanding types of Solidity functions

Solidity functions take arguments and can return multiple return values. The function definitions start with the function keyword. Every function should have its visibility specified. If this is not defined in version 0.4.25, it will default to public visibility. In Solidity version 0.5.0, you must have visibility defined for a function; otherwise, you will get compilation errors.

The syntax that's used to define a function definition is as follows:

function functionName(<parameter types>) {internal|external|public|private} [pure|view|payable] [returns (<return types>)]

The following is the syntax diagram for defining a function:

 Syntax diagram for function definition

As shown in the preceding syntax diagram, a function can return multiple values using the returns(value0, value1, ... , valueN) syntax.

...

Using emit and events for event logging

Events in Solidity are used to log information. Off-chain client applications can subscribe and listen for any events that are being emitted in the blockchain. These client applications use the Remote Procedure Call (RPC) interface to interact with the Ethereum nodes and are notified upon event emission. 

By using the Solidity language, your contracts can emit events, but they cannot listen to or read the data of a triggered event. Events are always inherited from contracts, which means that you can emit events that are defined in your contract inheritance tree.

When you emit an event, its arguments are stored in the transaction log. These logs are related to the contract address and are stored in the blockchain's block. These events will be available forever since they are present in the block. However, this might change...

Inheriting contracts

Just like object-oriented programming languages, Solidity contracts also support multiple inheritance. You can derive another contract by using the is keyword, as shown in the FuncOverride contract that we discussed in the Overloading functions section of this chapter.

The contract can access the following from its inherited contract:

  • All of its modifiers. You can also override them.
  • All public and internal functions. You can also override them.
  • All public and internal state variables. Use these state variables directly.
  • All events. You can emit these events.

When a contract inherits from another contract and a function is called, its most derived function definition will be executed from the inheritance hierarchy. However, you can also use the contract's name or the super keyword in order to use a specific function...

Creating abstract contracts

In an abstract contract, there are only a few functions that don't have the function body defined. You cannot deploy abstract contracts alone. However, you can inherit the contract and provide the definition to each function that's declared in the abstract contract.

If a contract inherits from an abstract contract and doesn't provide the implementation of the function, the inheriting contract would also be considered an abstract contract. Hence, it is the developer's responsibility to ensure that all the functions of the abstract contract are defined. Also, developer tools such as Remix and Truffle would not allow your inherited contract to be deployed.

As shown in the following example, AbstractDeposit is an abstract contract since it has a depositEther() function, and no function body has been provided for it. However, the...

Creating interfaces

You can define interfaces in Solidity using the interface keyword. These interfaces are very similar to abstract contracts, and they must not have any function definitions. They also have the following restrictions:

  • All the functions that are defined in the interface must have external visibility.
  • The constructor is not allowed.
  • An interface cannot have any state variables defined.
  • The interfaces cannot inherit from any other contracts or interfaces.

There are some differences between the Solidity 0.4.25 and 0.5.0 version interfaces. In version 0.4.25, you cannot define enum and struct. However, with version 0.5.0 onward, you can define them.

The following example shows an interface that's been defined in Solidity version 0.4.25, having a function declared without the body:

pragma solidity ^0.4.25;

interface ExampleInterface {

function transfer...

Creating custom reusable libraries

The libraries in Solidity are just like contracts, but they are deployed only once and their code is reused in the calling contracts. You can define libraries using the library keyword. Calls to the library functions use the DELEGATECALL opcode, which means that when a function on a library is called by the contract, only the code of the library function is executed in the context of the calling contract, and the storage of the calling contract is used and modified by the library. The library can have pure and view functions, which will be accessible directly from the calling contract because they do not initiate DELEGATECALL. You cannot destroy a deployed library.

When a library is linked to a contract, you can see that library as the implicit base contract of the contract and can access the functions defined in the library just by...

Summary

In this chapter, we looked at defining and creating a Solidity contract. We looked at creating custom modifiers for the functions, understood the different types of functions you can define inside a contract to architect your contract behavior, learned how to create and emit events for logging purposes, and dug deeper into Solidity inheritance by creating interfaces and abstract contracts. We also learned how to write custom user-defined libraries and use them in our contracts. 

In terms of the Solidity language, we have covered all the topics that you are required to know about in order to write a basic Solidity contract. These topics cover almost 99% of the language's features, although there are ways to write assembly language blocks in Solidity as well. However, this is an advanced topic that you should take a look at in your own time. Assembly language usage...

Questions

  1. How big can a contract be in terms of code lines?
  2. I have seen some contracts (deployed on etherscan.io) with their contract name being used for the function name, which is then used as the constructor of the contract. Why is this way of defining a constructor deprecated? 
  3. When should fallback functions be used?
  4. Is using a for or a while loop recommended?
  5. How do you perform a complex search or filter operation in Solidity?
  6. Can you add custom functions for default data types that are supported in Solidity?
  7. Why has the throw keyword been removed from the Solidity language?
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Blockchain Programming with Solidity
Published in: Aug 2019Publisher: PacktISBN-13: 9781839218262
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

Author (1)

author image
Jitendra Chittoda

Jitendra Chittoda is a blockchain security engineer at ChainSecurity. His day job is to perform security audit on smart contracts and expose security vulnerabilities in Solidity and Scilla contracts. He has also developed a non-custodial, decentralized, P2P lending contracts for ETHLend. The Solidity contracts that he has developed or audited handle over $100 million worth of cryptoassets. He also served as a tech and security advisor in various ICO projects. Before finding his passion for blockchain, he coded in Java for over 11 years. He is the founder and leader of Delhi-NCR-JUG, a non-profit meetup group for Java. He holds a master's degree in computer applications and is regularly invited as a speaker at various conferences and meetups.
Read more about Jitendra Chittoda