Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Solidity Programming Essentials
Solidity Programming Essentials

Solidity Programming Essentials: A beginner's guide to build smart contracts for Ethereum and blockchain

eBook
₹799 ₹2323.99
Paperback
₹2904.99
Subscription
Free Trial
Renews at ₹800p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Solidity Programming Essentials

Introduction to Blockchain, Ethereum, and Smart Contracts

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

What is a blockchain?

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:  This means that any server or node on a network is connected to every other node on the network. Rather than having one-to-one or one-to-many connectivity between servers, servers have many-to-many connections with other servers.
  • Database: This refers to the location for storing durable data that can be accessed at any point in time. A database allows storage and retrieval of data as functionality and also provides management functionalities to manage data efficiently, such as export, import, backup, and restoration.
  • Ledger: This is an accounting term. Think of it as specialized storage and retrieval of data. Think of ledgers that are available to banks. For example, when a transaction is executed with a bank—say, Tom deposits 100 dollars in his account, the bank enters this information in a ledger as a credit. At some point in the future Tom withdraws 25 dollars. The bank does not modify the existing entry and stored data from 100 to 75. Instead it adds another entry in the same ledger as a debit of 25 dollars. It means a ledger is a specialized database that does not allow modification of existing data. It allows you to create and append a new transaction to modify the current balance in the ledger. The blockchain is a database that has the same characteristics of a ledger. It allows newer transactions to be stored in an append-only pattern without any scope to modify past transactions. It is important here to understand that existing data can be modified by using a new transaction, but past transactions cannot be modified. A balance of 100 dollars can be modified at any time by executing a new debit or credit transaction, but previous transactions cannot be modified. Take a look at the following diagram for a better understanding:

Blockchain means a chain of blocks. Blockchain means having multiple blocks chained together, with each block storing transactions in a way where it is not possible to change these transactions. We will discuss this in later sections when we talk about the storage of transactions and how immutability is achieved in a blockchain.

Because of being decentralized and distributed, blockchain solutions are stable, robust, durable, and highly available. There is no single point of failure. No single node or server is the owner of the data and solution, and everyone participates as a stakeholder.

Not being able to change and modify past transactions makes blockchain solutions highly trustworthy, transparent, and incorruptible.

Ethereum allows extending its functionality with the help of smart contracts. Smart contracts will be addressed in detail throughout this book.

Why blockchains?

The main objective of Ethereum is to accept transactions from accounts, update their state, and maintain this state as current till another transaction updates it again. The whole process of accepting, executing, and writing transactions can be divided into two phases in Ethereum. There is a decoupling between when a transaction is accepted by Ethereum and when the transaction is executed and written to the ledger. This decoupling is quite important for decentralization and distributed architecture to work as expected.

Blockchain helps primarily in the following three different ways:

  • Trust: Blockchain helps in creating applications that are decentralized and collectively owned by multiple people. Nobody within this group has the power to change or delete previous transactions. Even if someone tries to do so, it will not be accepted by other stakeholders.
  • Autonomy: There is no single owner for blockchain-based applications. No one controls the blockchain, but everyone participates in its activities. This helps in creating solutions that cannot be manipulated or induce corruption.
  • Intermediaries: Blockchain-based applications can help remove the intermediaries from existing processes. Generally there is a central body, such as vehicle registration, license issuing, and so on, that acts as registrar for registering vehicles as well as issuing driver licenses. Without blockchain-based systems, there is no central body and if a license is issued or vehicle is registered after a blockchain mining process, that will remain a fact for an epoch time-period without the need of any central authority vouching for it.

Blockchain is heavily dependent on cryptography technologies as we discuss in the following section.

Cryptography

Cryptography is the science of converting plain simple text into secret, hidden, meaningful text, and vice-versa. It also helps in transmitting and storing data that cannot be easily deciphered using owned keys.

There are the following two types of cryptography in computing:

  • Symmetric 
  • Asymmetric 

Symmetric encryption and decryption

Symmetric cryptography refers to the process of using a single key for both encryption and decryption. It means the same key should be available to multiple people if they want to exchange messages using this form of cryptography.

Asymmetric encryption and decryption

Asymmetric cryptography refers to the process of using two keys for encryption and decryption. Any key can be used for encryption and decryption. Message encryption with a public key can be decrypted using a private key and messages encrypted by a private key can be decrypted using a public key. Let's understand this with the help of an example. Tom uses Alice's public key to encrypt messages and sends it to Alice. Alice can use her private key to decrypt the message and extract contents out of it. Messages encrypted with Alice's public key can only be decrypted by Alice as only she holds her private key and no one else. This is the general use case of asymmetric keys. There is another use which we will see while discussing digital signatures.

Hashing

Hashing is the process of transforming any input data into fixed length random character data, and it is not possible to regenerate or identify the original data from the resultant string data. Hashes are also known as fingerprint of input data. It is next to impossible to derive input data based on its hash value. Hashing ensures that even a slight change in input data will completely change the output data, and no one can ascertain the change in the original data. Another important property of hashing is that no matter the size of input string data, the length of its output is always fixed. For example, using the SHA256 hashing algorithm and function with any length of input will always generate 256 bit output data. This can especially become useful when large amounts of data can be stored as 256 bit output data. Ethereum uses the hashing technique quite extensively. It hashes every transaction, hashes the hash of two transactions at a time, and ultimately generates a single root transaction hash for every transaction within a block.

Another important property of hashing is that it is not mathematically feasible to identify two different input strings that will output the same hash. Similarly, it is not possible to computationally and mathematically find the input from the hash itself.

Ethereum used Keccak256 as its hashing algorithm.

The following screenshot shows an example of hashing. The input Ritesh Modi generates a hash, as shown in the following screenshot:

Even a small modification to input generates a completely different hash, as shown in the following screenshot:

Digital signatures

Earlier, we discussed cryptography using asymmetric keys. One of the important cases for using asymmetric keys is in the creation and verification of a digital signature. Digital signatures are very similar to a signature done by an individual on a piece of paper. Similar to a paper signature, a digital signature helps in identifying an individual. It also helps in ensuring that messages are not tampered with in transit. Let's understand digital signatures with the help of an example.

Alice wants to send a message to Tom. How can Tom identify and ensure that the message has come from Alice only and that the message has not been changed or tampered with in transit? Instead of sending a raw message/transaction, Alice creates a hash of the entire payload and encrypts the hash with her private key. She appends the resultant digital signature to the hash and transmits it to Tom. When the transaction reaches Tom, he extracts the digital signature and decrypts it using Alice's public key to find the original hash. He also extracts the original hash from the rest of the message and compares both the hashes. If the hashes match, it means that it actually originated from Alice and that it has not been tampered with.

Digital signatures are used to sign transaction data by the owner of the asset or cryptocurrency, such as Ether.

Ether

Ether is the currency of Ethereum. Every activity on Ethereum that modifies its state costs Ether as a fee, and miners who are successful in generating and writing a block in a chain are also rewarded Ether. Ether can easily be converted to dollars or other traditional currencies through cryptoexchanges.

Ethereum has a metric system of denominations used as units of Ether. The smallest denomination or base unit of Ether is called wei. The following is a list of the named denominations and their value in wei which is available at https://github.com/ethereum/web3.js/blob/0.15.0/lib/utils/utils.js#L40:

var unitMap = {
'wei' : '1'
'kwei': '1000',
'ada': '1000',
'femtoether': '1000',
'mwei': '1000000',
'babbage': '1000000',
'picoether': '1000000',
'gwei': '1000000000',
'shannon': '1000000000',
'nanoether': '1000000000',
'nano': '1000000000',
'szabo': '1000000000000',
'microether': '1000000000000',
'micro': '1000000000000',
'finney': '1000000000000000',
'milliether': '1000000000000000',
'milli': '1000000000000000',
'ether': '1000000000000000000',
'kether': '1000000000000000000000',
'grand': '1000000000000000000000',
'einstein': '1000000000000000000000',
'mether': '1000000000000000000000000',
'gether': '1000000000000000000000000000',
'tether': '1000000000000000000000000000000'
};

Gas

In the previous section, it was mentioned that fees are paid using Ether for any execution that changes state in Ethereum. Ether is traded on public exchanges and its price fluctuates daily. If Ether is used for paying fees, then the cost of using the same service could be very high on certain days and low on other days. People will wait for the price of Ether to fall to execute their transactions. This is not ideal for a platform such as Ethereum. Gas helps in alleviating this problem. Gas is the internal currency of Ethereum. The execution and resource utilization cost is predetermined in Ethereum in terms of gas units. This is also known as gas cost. There is also gas price that can be adjusted to a lower price when the price of Ether increases and a higher price when the price of Ether decreases. For example, to invoke a function in a contract that modifies a string will cost gas, which is predetermined, and users should pay in terms of gas to ensure smooth execution of this transaction.

Blockchain and Ethereum architecture

Blockchain is an architecture comprising multiple components and what makes blockchain unique is the way these components function and interact with each other. Some of the important Ethereum components are Ethereum Virtual Machine (EVM), miner, block, transaction, consensus algorithm, account, smart contract, mining, Ether, and gas. We are going to discuss each of these components in this chapter.

A blockchain network consists of multiple nodes belonging to miners and some nodes that do not mine but help in execution of smart contracts and transactions. These are known as EVMs. Each node is connected to another node on the network. These nodes use peer-to-peer protocol to talk to each other. They, by default, use port 30303 to talk among themselves.

Each miner maintains an instance of ledger. A ledger contains all blocks in the chain. With multiple miners it is quite possible that each miner's ledger instance might have different blocks to another. The miners synchronize their blocks on an on-going basis to ensure that every miner's ledger instance is the same as the other.

Details about ledgers, blocks, and transactions are discussed in detail in subsequent sections in this chapter.

The EVM also hosts smart contracts. Smart contracts help in extending Ethereum by writing custom business functionality into it. These smart contracts can be executed as part of a transaction and it follows the process of mining as discussed earlier.

A person having an account on a network can send a message for transfer of Ether from their account to another or can send a message to invoke a function within a contract. Ethereum does not distinguish them as far as transactions are considered. The transaction must be digitally signed with an account holder's private key. This is to ensure that the identity of the sender can be established while verifying the transaction and changing the balances of multiple accounts. Let's take a look at the components of Ethereum in the following diagram:

How are blocks related to each other?

In blockchain and Ethereum every block is related to another block. There is a parent-child relationship between two blocks. There can be only one child to a parent and a child can have a single parent. This helps in forming a chain in blockchain. Blocks are explained in a later section in this chapter. In the following diagram, three blocks are shown—Block 1, Block 2, and Block 3. Block 1 is the parent of Block 2 and Block 2 is the parent of Block 3. The relationship is established by storing the parent block's hash in a child's block header. Block 2 stores the hash of Block 1 in its header and Block 3 stored the hash of Block 2 in its header. So, the question arises—who is the parent of the first block? Ethereum has a concept of the genesis block also known as first block. This block is created automatically when the chain is first initiated. You can say that a chain is initiated with the first block known as the Genesis Block and the formation of this block is driven through the genesis.json file. Let's take a look at the following diagram:

The following chapter will show how to use the genesis.json file to create the first block while initializing the blockchain.

How are transactions and blocks related to each other?

Now that we know that blocks are related to each other, you will be interested in knowing how transactions are related to blocks. Ethereum stores transactions within blocks. Each block has an upper gas limit and each transaction needs a certain amount of gas to be consumed as part of its execution. The cumulative gas from all transactions that are not yet written in a ledger cannot surpass the block gas limit. This ensures that all transactions do not get stored within a single block. As soon as the gas limit is reached, other transactions are removed from the block and mining begins thereafter.

The transactions are hashed and stored in the block. The hashes of two transactions are taken and hashed further to generate another hash. This process eventually provides a single hash from all transactions stored within the block. This hash is known as the transaction Merkle root hash and is stored in a block's header. A change in any transaction will result in a change in its hash and, eventually, a change in the root transaction hash. It will have a cumulative effect because the hash of the block will change, and the child block has to change its hash because it stores its parent hash. This helps in making transactions immutable. This is also shown in the following diagram:

Ethereum nodes

Nodes represent the computers that are connected using a peer-to-peer protocol to form an Ethereum network.

There are the following two types of nodes in Ethereum:

  • EVM 
  • Mining nodes

It is to be noted that this distinction is made to clarify concepts of Ethereum. In most scenarios, there is no dedicated EVM. Instead, all nodes act as miners as well as EVM nodes.

EVM

Think of EVM as the execution runtime for an Ethereum network. EVMs are primarily responsible for providing a runtime that can execute code written in smart contracts. It can access accounts, both contract and externally owned, and its own storage data. It does not have access to the overall ledger but does have limited information about the current transaction.

EVMs are the execution components in Ethereum. The purpose of an EVM is to execute the code in a smart contract line by line. However, when a transaction is submitted, the transaction is not executed immediately. Instead it is pooled in a transaction pool. These transactions are not yet written to the Ethereum ledger.

Ethereum mining nodes

A miner is responsible for writing transactions to the Ethereum chain. A miner's job is very similar to that of an accountant. As an accountant is responsible for writing and maintaining the ledger; similarly, a miner is solely responsible for writing a transaction to an Ethereum ledger. A miner is interested in writing transactions to a ledger because of the reward associated with it. Miners get two types of reward—a reward for writing a block to the chain and cumulative gas fees from all transactions in the block. There are generally many miners available within a blockchain network each trying and competing to write transactions. However, only one miner can write the block to the ledger and the rest will not be able to write the current block.

The miner responsible for writing the block is determined by way of a puzzle. The challenge is given to every miner and they try to solve the puzzle using their compute power. The miner who solves the puzzle first writes the block containing transactions to his own ledger and sends the block and nonce value to other miners for verification. Once verified and accepted, the new block is written to all ledgers belonging to miners. In this process, the winning miner also receives 5 Ether as reward. Every mining node maintains its own instance of the Ethereum ledger and the ledger is ultimately the same across all miners. It is the miner's job to ensure that their ledger is updated with the latest blocks. Following are the three important functions performed by miners or mining nodes:

  • Mine or create a new block with a transaction and write the same to the Ethereum ledger
  • Advertise and send a newly mined block to other miners
  • Accept new blocks mined by other miners and keep its own ledger instance up-to-date

Mining nodes refer to the nodes that belong to miners. These nodes are part of the same network where the EVM is hosted. At some point in time, the miners will create a new block, collect all transactions from the transaction pool, and add them to the newly created block. Finally, this block is added to the chain. There are additional concepts such as consensus and solving of target puzzle before writing the block that will be explained in the following section.

How does mining work?

The process of mining explained here is applicable to every miner on the network and every miner keeps executing the tasks mentioned here regularly.

Miners are always looking forward to mining new blocks, and are also listening actively to receive new blocks from other miners. They are also listening for new transactions to store in the transaction pool. Miners also spread the incoming transactions to other connected nodes after validation. As mentioned before, at some point, the miner collects all transactions from the transaction pool. This activity is done by all miners.

The miner constructs a new block and adds all transactions to it. Before adding these transactions, it will check if any of the transactions are not already written in a block that it might receive from other miners. If so, it will discard those transactions.

The miner will add their own coinbase transaction for getting rewards for mining the block.

The next task for a miner is to generate the block header and perform the following tasks:

  1. The miner takes hashes of two transactions at a time to generate a new hash till he gets a single hash from all transactions. The hash is referred to as a root transaction hash or Merkle root transaction hash. This hash is added to the block header.
  2. The miner also identifies the hash of the previous block. The previous block will become parent to the current block and its hash will also be added to the block header.
  3. The miner calculates the state and receipts of transaction root hashes and adds them to the block header.
  4. A nonce and timestamp is also added to the block header.
  5. A block hash consisting of both block header and body is generated.
  6. The mining process starts where the miner keeps changing the nonce value and tries to find a hash that will satisfy as an answer to the given puzzle. It is to be kept in mind that everything mentioned here is executed by every miner in the network.
  7. Eventually, one of the miners will be able to solve the puzzle and advertise the same to other miners in the network. The other miners will verify the answer and, if found correct, will further verify every transaction, accept the block, and append the same to their ledger instance.

This entire process is also known as Proof of Work (PoW) wherein a miner provides proof that it is has worked on computing the final answer that could satisfy as solution to the puzzle. There are other algorithms such as Proof of Stake (PoS) and Proof of Authority (PoA), but they are not used or discussed in this book.

The header block and its content is shown in the following diagram:

Ethereum accounts

Accounts are the main building blocks for the Ethereum ecosystem. It is an interaction between accounts that Ethereum wants to store as transactions in its ledger. There are two types of accounts available in Ethereum—externally owned accounts and contract accounts. Each account, by default, has a property named balance that helps in querying the current balance of Ether.

Externally owned accounts

Externally owned accounts are accounts that are owned by people on Ethereum. Accounts are not referred to by name in Ethereum. When an externally owned account is created on Ethereum by an individual, a public/private key is generated. The private key is kept safe with the individual while the public key becomes the identity of this externally owned account. This public key is generally of 256 characters, however, Ethereum uses the first 160 characters to represent the identity of an account.

If Bob, for example, creates an account on an Ethereum network—whether private or public, he will have his private key available to himself while the first 160 characters of his public key will become his identity. Other accounts on the network can then send Ether or other cryptocurrencies based on Ether to this account.

An account on Ethereum looks like the one shown in the following screenshot:

An externally owned account can hold Ether in its balance and does not have any code associated with it. It can execute transactions with other externally owned accounts and it can also execute transactions by invoking functions within contracts.

Contract accounts

Contract accounts are very similar to externally owned accounts. They are identified using their public address. They do not have a private key. They can hold Ether similar to externally owned accounts; however, they contain code—code for smart contracts consisting of functions and state variables.

Transactions

A transaction is an agreement between a buyer and a seller, a supplier and a consumer, or a provider and a consumer that there will be an exchange of assets, products, or services for currency, cryptocurrency, or some other asset, either in the present or in the future. Ethereum helps in executing the transaction. Following are the three types of transactions that can be executed in Ethereum:

  • Transfer of Ether from one account to another: The accounts can be externally owned accounts or contract accounts. Following are the possible cases:
    • An externally owned account sending Ether to another externally owned account in a transaction
    • An externally owned account sending Ether to a contract account in a transaction
    • A contract account sending Ether to another contract account in a transaction
    • A contract account sending Ether to an externally owned account in a transaction
  • Deployment of a smart contract: An externally owned account can deploy a contract using a transaction in EVM.
  • Using or invoking a function within a contract: Executing a function in a contract that changes state is considered a transaction in Ethereum. If executing a function does not change a state, it does not require a transaction.

A transaction has some of the following important properties related to it:

  • The from account property denotes the account that is originating the transaction and represents an account that is ready to send some gas or Ether. Both gas and Ether concepts were discussed earlier in this chapter. The from account can be externally owned or a contract account.
  • The to account property refers to an account that is receiving Ether or benefits in lieu of an exchange. For transactions related to deployment of contract, the to field is empty. It can be externally owned or a contract account.
  • The value account property refers to the amount of Ether that is transferred from one account to another.
  • The input account property refers to the compiled contract bytecode and is used during contract deployment in EVM. It is also used for storing data related to smart contract function calls along with its parameters. A typical transaction in Ethereum where a contract function is invoked is shown here. In the following screenshot, notice the input field containing the function call to contract along with its parameters:
  • The blockHash account property refers to the hash of block to which this transaction belongs.
  • The blockNumber account property is the block in which this transaction belongs.
  • The gas account property refers to the amount of gas supplied by the sender who is executing this transaction.
  • The gasPrice account property refers to the price per gas the sender was willing to pay in wei (we have already learned about wei in the Ether section in this chapter). Total gas is computed at gas units * gas price.
  • The hash account property refers to the hash of the transaction.
  • The nonce account property refers to the number of transactions made by the sender prior to the current transaction.
  • The transactionIndex account property refers to the serial number of the current transactions in the block.
  • The value account property refers to the amount of Ether transferred in wei.
  • The v, r, and s account properties relate to digital signatures and the signing of the transaction.

A typical transaction in Ethereum, where an externally owned account sends some Ether to another externally owned account, is shown here. Notice the input field is not used here. Since two Ethers were sent in transaction, the value field is showing the value accordingly in wei as shown in the following screenshot:

One method to send Ether from an externally owned account to another externally owned account is shown in the following code snippet using web3 JavaScript framework, which will be covered later in this book:

web.eth.sendTransaction({from: web.eth.accounts[0], to: "0x9d2a327b320da739ed6b0da33c3809946cc8cf6a", value: web.toWei(2, 'ether')})

A typical transaction in Ethereum where a contract is deployed is shown in the following screenshot. In the following screenshot, notice the input field containing the bytecode of contract:

Blocks

Blocks are an important concept in Ethereum. Blocks are containers for a transaction. A block contains multiple transactions. Each block has a different number of transactions based on gas limit and block size. Gas limit will be explained in detail in later sections. The blocks are chained together to form a blockchain. Each block has a parent block and it stores the hash of the parent block in its header. Only the first block, known as the genesis block, does not have a parent.

A typical block in Ethereum is shown in the following screenshot:

There are a lot of properties associated with a block, providing insights and metadata about it, and following are some of important properties along with their descriptions:

  • The difficulty property determines the complexity of the puzzle/challenge given to miners for this block.
  • The gasLimit property determines the maximum gas allowed. This helps in determining how many transactions can be part of the block.
  • The gasUsed property refers to the actual gas used for this block for executing all transactions in it.
  • The hash property refers to the hash of the block.
  • The nonce property refers to the number that helps in solving the challenge.
  • The miner property is the account identifier of the miner, also known as coinbase or etherbase.
  • The number property is the sequential number of this block on the chain.
  • The parentHash property refers to the parent block's hash.
  • The receiptsRoot, stateRoot, and transactionsRoot properties refer to Merkle trees discussed during the mining process.
  • The transactions property refers to an array of transactions that are part of this block.
  • The totalDifficulty property refers to the total difficulty of the chain.

An end-to-end transaction

Armed with the understanding of the foundational concepts of blockchain and Ethereum, it's time to see a complete end-to-end transaction and how it flows through multiple components and gets stored in the ledger.

In this example, Sam wants to send a digital asset (for example, dollars) to Mark. Sam generates a transaction message containing the from, to, and value fields and sends it across to the Ethereum network. The transaction is not written to the ledger immediately and instead is placed in a transaction pool.

The mining node creates a new block and takes all transactions from the pool honoring the gas limit criteria and adds them to the block. This activity is done by all miners on the network. Sam's transaction will also be a part of this process.

The miners compete trying to solve the challenge thrown to them. The winner is the miner who can solve the challenge first. After a period (of seconds) one of the miners will advertise that they has found the solution to the challenge and that they are the winner and should write the block to the chain. The winner sends the challenge solution along with the new block to all other miners. The rest of the miners validate and verify the solution and, once satisfied that the solution is indeed correct and that the original miner has cracked the challenge, they accept the new block containing Sam's transaction to append in their instance of the ledger. This generates a new block on the chain that is persisted across time and space. During this time, the accounts of both parties are updated with the new balance. Finally, the block is replicated across every node in the network.

The preceding example can be well understood with the following diagram:

What is a contract?

A contract is a legal document that binds two or more parties who agree to execute a transaction immediately or in the future. Since contracts are legal documents, they are enforced and implemented by law. Examples of contracts are an individual entering into a contract with an insurance company for covering their health insurance, an individual buying a piece of land from another individual, or a company selling its shares to another company.

What is a smart contract?

A smart contract is custom logic and code deployed and executed within an Ethereum virtual environment. Smart contracts are digitized and codified rules of transaction between accounts. Smart contracts help in transferring digital assets between accounts as an atomic transaction. Smart contracts can store data. The data stored can be used to record information, facts, associations, balances, and any other information needed to implement logic for real-world contracts. Smart contracts are very similar to object-oriented classes. A smart contract can call another smart contract just like an object-oriented object can create and use objects of another class. Think of smart contracts as a small program consisting of functions. You can create an instance of the contract and invoke functions to view and update contract data along with the execution of some logic.

How to write smart contracts?

There are multiple smart contracts authoring tools including Visual Studio. However, the easiest and fastest way to develop smart contracts is to use a browser-based tool known as Remix. Remix is available on http://remix.ethereum.org. Remix is a new name and was earlier known as browser-solidity. Remix provides a rich integrated development environment in a browser for authoring, developing, deploying, and troubleshooting contracts written using the Solidity language. All contract management related activities such as authoring, deploying, and troubleshooting can be performed from the same environment without moving to other windows or tabs.

Not everyone is comfortable using the online version of Remix to author their smart contracts. Remix is an open source tool that can be downloaded from https://github.com/ethereum/browser-Solidity and compiled to run a private version on a local computer. Another advantage of running Remix locally is that it can connect to local private chain networks directly; otherwise, users will first have to author the contract online and then copy the same to a file, compile, and deploy manually to a private network. Let's explore Remix by performing the following steps:

  1. Navigate to remix.ethereum.org and the site will open in a browser with a default contract as shown in the following screenshot. If you do not need this contract, it can be deleted:
  1. The first thing we need to do is to create a new contract by selecting + from Remix's left menu bar.
  2. Then, provide a name for a new Solidity file that has an extension .sol. Name the contract HelloWorld and click on OK to continue as shown in the following screenshot. This will create a blank contract:
  1. Type the following code in the empty authoring pane to create your first contract. This contract will be explained in detail in Chapter 3, Introducing Solidity. For now, it is sufficient to understand that the contract is created using the contract keyword; you can declare global state variables and functions; and contracts are saved with the .sol file extension. In the following code snippet, the HelloWorld contracts returns the HelloWorld string when the GetHelloWorld function is called:
pragma Solidity ^0.4.18;
contract HelloWorld
{
string private stateVariable = "Hello World";
function GetHelloWorld() public view returns (string)
{
return stateVariable;
}
}

Look at the action window to the right of Remix. It has got several tabs—Compile, Run, Settings, Debugger, Analysis, and Support. These action tabs help in compiling, deploying, troubleshooting, and invoking contracts. The Compile tab compiles the contract into bytecode—code that is understood by Ethereum. It displays warnings and errors as you author and edit the contract. These warnings and errors are to be taken seriously and they really help in creating robust contracts. The Run tab is the place where you will spend the most time, apart from writing the contract. Remix comes bundled with the Ethereum runtime within the browser. The Run tab allows you to deploy the contract to this runtime using the JavaScript VM environment in the Environment option. The Injected Web3 environment is used along with tools such as Mist and MetaMask, which will be covered in the next chapter, and Web3 Provider can be used when using Remix in a local environment connecting to private network. In our case for this chapter, the default, JavaScript VM is sufficient. The rest of the options will be discussed later in Chapter 3, Introducing Solidity.

  1. However, the important action is deployment of a contract and that can be done using the Create button to deploy the contract that is shown in the following screenshot:
  1. Click on the Create button to deploy the contract to the browser Ethereum runtime and this will list all the functions available within the contract below the Create button. Since we only had a single function GetHelloWorld, the same is displayed as shown in the following screenshot:
  1. Click on the GetHelloWorld button to invoke and execute the function. The lower pane of Remix will show the results of execution as shown in the following screenshot:

Congratulations, you have created, deployed, and also executed a function on your first contract. The code for the HelloWorld contract is accompanied with this chapter and can be used in Remix if you are not interested in typing the contract.

How are contracts deployed?

Remix makes deployment of contracts a breeze; however, it is performing a lot of steps behind the scenes. It is always useful to understand the process of deploying contracts to have finer control over the deployment process.

The first step is the compilation of contracts. The compilation is done using the Solidity compiler. The next chapter will show you how to download and compile a contract using the Solidity compiler.

The compiler generates the following two major artifacts:

  • ABI definition 
  • Contracts bytecode

Think of the Application Binary Interface (ABI) as an interface consisting of all external and public function declarations along with their parameters and return types. The ABI defines the contract and any caller wanting to invoke any contract function can use the ABI to do so.

The bytecode is what represents the contract and it is deployed in the Ethereum ecosystem. The bytecode is required during deployment and ABI is needed for invoking functions in a contract.

A new instance of a contract is created using the ABI definition.

Deploying a contract itself is a transaction. A transaction is created for deploying the contract on Ethereum. The bytecode and ABI are necessary inputs for deploying a contract.

As any transaction execution costs gas in Euthereum, appropriate quantity of gas should be supplied while deploying the contract. As and when the transaction is mined, the contract is would be available for interaction through contract address.

Using the newly generated address, callers can invoke functions within the contract.

Summary

This chapter was an introduction to blockchains and, more specifically, to Ethereum. Having a good understanding of the big picture about how blockchains and Ethereum work will go a long way in understanding how to write robust, secure, and cost effective smart contracts using Solidity. This chapter covered the basics of blockchain, explained what blockchains are, why blockchains are important, and how they help in building decentralized and distributed applications. The architecture of Ethereum was discussed in brief along with some of the important concepts such as transactions, blocks, gas, Ether, accounts, cryptography, and mining. This chapter also touched briefly on the topic of smart contracts, using Remix to author smart contracts and how to execute them using Remix itself. I've kept this chapter brief since the rest of the book will explain these concepts further and it will allow you to quickly develop Solidity-based smart contracts.

You'll notice that this chapter does not contain any mention of Ethereum tools and utilities. This is what we will cover in the next chapter, by diving straight in and installing Ethereum and its toolset. The Ethereum ecosystem is quite rich and there are lots of tools. We will cover important ones, such as web3.js, TestRPC, Geth, Mist, and MetaMask.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • • Get you up and running with Solidity Programming language
  • • Build Ethereum Smart Contracts with Solidity as your scripting language
  • • Learn to test and deploy the smart contract to your private Blockchain

Description

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.

Who is this book for?

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.

What you will learn

  • • Learn the basics and foundational concepts of Solidity and Ethereum
  • • Explore the Solidity language and its uniqueness in depth
  • • Create new accounts and submit transactions to blockchain
  • • Get to know the complete language in detail to write smart contracts
  • • Learn about major tools to develop and deploy smart contracts
  • • Write defensive code using exception handling and error checking
  • • Understand Truffle basics and the debugging process
Estimated delivery fee Deliver to India

Premium delivery 5 - 8 business days

₹630.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Apr 20, 2018
Length: 222 pages
Edition : 1st
Language : English
ISBN-13 : 9781788831383
Category :
Languages :
Concepts :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to India

Premium delivery 5 - 8 business days

₹630.95
(Includes tracking information)

Product Details

Publication date : Apr 20, 2018
Length: 222 pages
Edition : 1st
Language : English
ISBN-13 : 9781788831383
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
₹800 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
₹4500 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts
₹5000 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₹400 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 9,906.97
Mastering Blockchain
₹4096.99
Solidity Programming Essentials
₹2904.99
Ethereum Smart Contract Development
₹2904.99
Total 9,906.97 Stars icon
Banner background image

Table of Contents

11 Chapters
Introduction to Blockchain, Ethereum, and Smart Contracts Chevron down icon Chevron up icon
Installing Ethereum and Solidity Chevron down icon Chevron up icon
Introducing Solidity Chevron down icon Chevron up icon
Global Variables and Functions Chevron down icon Chevron up icon
Expressions and Control Structures Chevron down icon Chevron up icon
Writing Smart Contracts Chevron down icon Chevron up icon
Functions, Modifiers, and Fallbacks Chevron down icon Chevron up icon
Exceptions, Events, and Logging Chevron down icon Chevron up icon
Truffle Basics and Unit Testing Chevron down icon Chevron up icon
Debugging Contracts Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.6
(10 Ratings)
5 star 40%
4 star 20%
3 star 10%
2 star 20%
1 star 10%
Filter icon Filter
Top Reviews

Filter reviews by




Murughan Palaniachari May 14, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Such an amazing book to start from nothing to become expert in Blockchain Ethereum and Solidity programming. I really like the examples for each topics explained in this book which gives confidence on how things works. This book has more than 100 examples which is really amazing. Thanks for capturing object oriented, contract oriented concepts in depth on Solidity programming language. This book covers both Public and Private Blockchain implementation. Concepts like Azure Ethereum Virtual Machine, Storage and Memory data locations, Cryptography, Ethereum Networks, Mist Wallet are explained very well and example for each of these concepts made me understand the concepts well.Also good coverage on tools and plugins like Truffle, Metamask, Remix, Azure EVM, Mist Wallet.Writing smart contracts made easy with this book.I recommend people to learn from this book for beginner to expert level.
Amazon Verified review Amazon
悩めるサラリーマン Jan 06, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
趣味レベルでプログラミングをしており、2年ほどpythonとJavaScriptの経験があります。これまで2冊Ethereumに関する本を読みましたが、Solidityのコーディングという意味では、この本が最も分かりやすく構成も優れています。翻訳本も出ているようですが、翻訳されたプログラミングの本には良い印象を持っていません。この本は平易な英語で書かれており、かつ理解しにくいテーマについては深く掘り下げて読者が理解できるよう丁寧な説明を心がけています。お勧めです。
Amazon Verified review Amazon
aman Jun 27, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I have read multiple books on Blockchain and some of them touch the topic on Solidity fleetingly by providing a small chapter on it. This is the first book I have come across that is completely dedicated to Solidity as a programming language. I liked the way the book is organized and progresses ensuring that readers get accustomed to almost every important concept on Solidity. There are a ton of examples in this books which shows how you can utilize it in many different scenarios. Very hands-on approach for learning this important programming language on Blockchain and Ethereum. Just loving it!
Amazon Verified review Amazon
JONATHAN Apr 17, 2022
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Like it said it does have a lot of the basics very good as a reference source of information but more information is needed to get your computer set up for solidity programming lots of dependencies you have to install a lot of things that are not covered but still this is more the basics. It makes learning easier as I can go back and reference the code examples
Amazon Verified review Amazon
Pruthvi Kumar Dec 09, 2018
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
For Solidity enthusiasts, this should be the bible. There isn't much available anyways apart from standard doc's. Ritesh has done a good job in explaining the topics. Book is well organized. Its important for readers to have OOPS background to swim through chapters with ease.Reason for 4 stars: I would have liked a chapter or two on security, vulnerability and industry best practices for Solidity.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela