Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Ethereum Cookbook
Ethereum Cookbook

Ethereum Cookbook: Over 100 recipes covering Ethereum-based tokens, games, wallets, smart contracts, protocols, and Dapps

eBook
€20.98 €29.99
Paperback
€36.99
Subscription
Free Trial
Renews at €18.99p/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
Table of content icon View table of contents Preview book icon Preview Book

Ethereum Cookbook

Smart Contract Development

In this chapter, we will cover the following recipes:

  • Choosing an IDE wisely
  • Writing your first smart contract
  • Testing your contract with Remix
  • Static and dynamic types in solidity
  • Constructor and fallback functions
  • Working with struct and enum
  • Control structures in solidity
  • Writing functions in solidity
  • Deciding between arrays and mappings
  • Where to use function modifiers
  • Using visibility modifiers efficiently
  • Essential events: EVM logger
  • Efficiently using memory and storage
  • Compiling your contract with the solc compiler
  • Deploying the contract using geth

Introduction

Smart contracts enable you to solve common problems in a way that maximizes trust. The purpose of contracts is to reduce ambiguity and inclination so that a predictable set of outcomes is produced, and these outcomes can be depended upon. In Ethereum, you can write smart contracts with the built-in Turing complete programming language (solidity). The language can create its own arbitrary rules for ownership, transaction formats, and state transition functions. Smart contracts in Ethereum are written in solidity and targeted to run on the Ethereum Virtual Machine (EVM). To actually execute smart contract code, someone has to send enough Ether as a transaction fee. The fee is calculated based on the computing resources required. This pays the miner nodes for participating and providing their computing power.

This chapter covers all the essentials of writing a smart...

Choosing an IDE wisely

Developing a distributed application often requires the developer to interact with multiple tools and languages. There are efficient Integrated Development Environments (IDE) that can help you accomplish most of the work related to developing an application. IDEs usually combine code editors, compilers, debuggers, and other useful tools. Some may find it comfortable using a simple text editor and related command-line tools for development.

In this recipe, you will learn about a few tools that can support Ethereum development.

How to do it...

One of the most popular and widely used IDEs for solidity is Remix. Let's see how you can use it for your development:

  1. Access Remix by navigating to https...

Writing your first smart contract

Solidity is the language of choice for writing smart contracts in Ethereum. A solidity smart contract is a collection of code (functions) and data (state) that resides at a specific address in the Ethereum blockchain.

Solidity is a statically typed, high-level language which is influenced by JavaScript, Python, and C++. Solidity supports inheritance, libraries, and user-defined types, and is designed for EVM.

Getting ready

It is recommended to use Remix (https://remix.ethereum.org) for writing smart contracts in solidity. Remix is a browser-based IDE that supports writing, compiling, testing, and deploying solidity smart contracts. Remix provides all of these features in an easy-to-use interface...

Testing your contract with Remix

In this recipe, you will learn how to test your smart contract using the Remix IDE. Remix is a browser-based IDE that enables users to write Ethereum contracts in the solidity language and debug transactions. Remix has an inbuilt JavaScript-based solidity compiler and EVM to compile and run smart contracts.

How to do it...

  1. Open Remix (https://remix.ethereum.org) in your desktop browser.
  2. Copy your smart contract to Remix and it will automatically compile your code. Warnings and errors, if any, will be displayed in the right panel.
  3. Remix has an inbuilt JavaScript VM for testing smart contracts. Ensure that you have selected JavaScript VM as the default environment under Run:
  1. Select an account...

Static and dynamic types in solidity

Statically typed programming languages do the type checking at compile time. Since solidity is a statically typed language, the type of each variable has to be specified at compile time. Solidity also provides an option to create complex user-defined types and type conversion.

In this recipe, you will learn about the basic elementary types of solidity, such as int, bool, array, byte, and address.

Getting ready

Remix is the best way to quickly write a test smart contract. Remix is a browser-based IDE that supports writing, compiling, testing, and deploying solidity smart contracts. Remix provides all these features in an easy-to-use interface and can be accessed quickly without any installation...

Constructor and fallback functions

In this recipe, you will learn about two important methods in a contract: constructor and fallback functions.

How to do it...

The declaration and workings of these methods are very similar to other object-oriented languages. Let's look into each one individually.

Constructor

The constructor is a function that is executed when a contract is created. It cannot be called explicitly and is invoked only once during its lifetime. Every contract can have exactly one constructor and if no constructor is declared, the contract will use the...

Working with struct and enum

There are several elementary types in solidity that can be used together to form various complex user-defined types. In this recipe, you will learn about two user-defined types in Solidity: struct and enum.

How to do it...

Let's create and work with various user-defined types using struct and enum.

Structs

Structs provide a way to define new types of solidity:

  1. Use the struct keyword for creating user-defined types in solidity:
struct Person { }
  1. Create a struct with a name and the associated properties inside it:
struct Person {
...

Control structures in Solidity

Most of the control structures from other languages are also supported in solidity. In this recipe, you will learn about supported control structures in solidity, along with examples. The semantics are very similar to C or JavaScript.

How to do it...

  1. If-else condition statements are used to perform different actions based on different conditions. Create a function, isValid, which returns true for input values greater than 10 and returns false otherwise:
pragma solidity ^0.4.23;

contract test {
function isValid(uint input) public pure
returns (bool) {
if (input > 10) {
return true;
} else {
return false;
}
}
}

Solidity doesn't support...

Writing functions in solidity

A function is a unit of code designed to do a particular task within a larger contract. In this recipe, you will learn about creating and interacting with functions in solidity.

How to do it...

  1. Create a function in solidity with the function keyword to perform a specific task. The following example demonstrates how we can create a simple function:
contract Test {
function functionName() {
// Do something
}
}
  1. Create another function to accept input parameters. These parameters can be declared just like variables. The following example accepts two parameters of type uint:

contract Test {
function add(uint _a, uint _b) public {
// Do something
}
}
  1. Define output parameters...

Deciding between arrays and mappings

Arrays and mappings in solidity are the most commonly used data types to store complex data. There are trade-offs in using one over the other, and each has its own advantages. In this recipe, you will learn about common use cases for arrays and mappings.

How to do it...

Arrays and mappings are used for a series of objects, all of which are the same size and type. Arrays store data sequentially with an incrementing index, whereas mappings store data as key-value pairs (which can also be seen as hash tables).

Arrays

Follow these steps...

Where to use function modifiers

Function modifiers are simple snippets that can change the behavior of a contract. In this recipe, you will learn how to create and use function modifiers in solidity.

How to do it...

  1. Modifiers are declared with the modifier keyword as follows:
modifier modifierName {
// modifier definition
}
  1. The function body is inserted where the _ symbol appears in the definition of a modifier:
modifier onlyOwner {
require(msg.sender == owner);
_;
}
  1. Modifiers can accept parameters like functions do. The following example creates a generic modifier to verify the caller address:
contract Test {

address owner;

constructor() public {
owner = msg.sender;
}

modifier onlyBy...

Using visibility modifiers efficiently

Functions and state variables can have visibility modifiers. There are four visibility modifiers in solidity. Functions can be specified as public, private, internal, or external. State variables support all visibility levels except external. In this recipe, you will learn about visibility modifiers and how to use them.

How to do it...

  1. If you want the function to be accessible both externally and internally, it has to be marked as public. Public state variables will generate a getter function automatically:

pragma solidity ^0.4.21;
contract Visibility {
// Public state variables generate an automatic getter
uint public limit = 110021;

// Accessible externally and internally...

Essential events – EVM logger

EVM provides logging facilities through events. When events are called, the arguments that are passed along with them will be stored in the transaction log. This also helps listeners in the distributed application to trigger an action based on a transaction. These logs are associated with the address of the respective contract. The contract itself cannot access any log information stored in the transaction.

In this recipe, you will learn about logging and events, and listening to them from the JavaScript console of geth.

Getting ready

You will need a working installation of geth to test the event listener scripts given in this tutorial. Commands starting with > are executed from the...

Using storage and memory efficiently

There are two types of memory area associated with contracts: storage and memory. Storage is a value store where all contract state variables are stored and are only changed by a transaction. Memory is a temporary storage location that is cleared for each message call. In this recipe, you will learn how to use these types efficiently, based on your requirements.

How to do it...

  1. State variables are always stored in storage, and function arguments are always in memory.

  1. The memory location of a variable can be explicitly specified with the storage or memory keywords:
uint storage sum;

uint memory calc;
  1. Local variables created for struct, array, or mapping types always reference storage...

Compiling your contract with the solc compiler

Solidity is a high-level language and has to be compiled before being deployed to Ethereum. In this recipe, you will learn how to use the solc command-line compiler to compile your smart contract to its binary and ABI.

Getting ready

You need to have a working installation of the solc compiler to step through this recipe. You can also make use of the JavaScript-based solcjs to compile solidity. These commands may not work in solcjs and you have to follow its documentation.

How to do it...

  1. Consider the following smart contract...

Deploying contracts using geth

After writing your smart contract, it is time to deploy it in Ethereum. In this recipe, you will learn about deploying your smart contract and testing it to ensure that it works as intended.

Getting ready

You will need a working installation of the solc compiler to compile your contract and geth to deploy it. We will be using the geth JavaScript console to run the deployment and transaction scripts.

How to do it...

  1. Here is our simple smart contract example:
pragma solidity ^0.4.21;

contract HelloWorld {

string public greeting = &quot...
Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Build end-to-end decentralized Ethereum apps using Truffle, Web3, and Solidity
  • Explore various solution-based recipes to build smart contracts and foolproof decentralized applications
  • Develop decentralized marketplaces from scratch, build wallets, and manage transactions

Description

Ethereum and Blockchain will change the way software is built for business transactions. Most industries have been looking to leverage these new technologies to gain efficiencies and create new business models and opportunities. The Ethereum Cookbook covers various solutions such as setting up Ethereum, writing smart contracts, and creating tokens, among others. You’ll learn about the security vulnerabilities, along with other protocols of Ethereum. Once you have understood the basics, you’ll move on to exploring various design decisions and tips to make your application scalable and secure. In addition to this, you’ll work with various Ethereum packages such as Truffle, Web3, and Ganache. By the end of this book, you’ll have comprehensively grasped the Ethereum principles and ecosystem.

Who is this book for?

The Ethereum Cookbook is for you if you are a software engineer, Blockchain developer, or research scientist who wants to build smart contracts, develop decentralized applications, and facilitate peer-to-peer transaction. It is assumed that you are familiar with Blockchain concepts and have sound knowledge of JavaScript.

What you will learn

  • Efficiently write smart contracts in Ethereum
  • Build scalable distributed applications and deploy them
  • Use tools and frameworks to develop, deploy, and test your application
  • Use block explorers such as Etherscan to find a specific transaction
  • Create your own tokens, initial coin offerings (ICOs), and games
  • Understand various security flaws in smart contracts in order to avoid them
Estimated delivery fee Deliver to Estonia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Aug 31, 2018
Length: 404 pages
Edition : 1st
Language : English
ISBN-13 : 9781789133998
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
Estimated delivery fee Deliver to Estonia

Premium delivery 7 - 10 business days

€25.95
(Includes tracking information)

Product Details

Publication date : Aug 31, 2018
Length: 404 pages
Edition : 1st
Language : English
ISBN-13 : 9781789133998
Category :
Languages :
Concepts :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 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
€189.99 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 €5 each
Feature tick icon Exclusive print discounts
€264.99 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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 86.97
Ethereum Projects for Beginners
€19.99
Ethereum Cookbook
€36.99
Ethereum Smart Contract Development
€29.99
Total 86.97 Stars icon

Table of Contents

12 Chapters
Getting Started Chevron down icon Chevron up icon
Smart Contract Development Chevron down icon Chevron up icon
Interacting with the Contract Chevron down icon Chevron up icon
The Truffle Suite Chevron down icon Chevron up icon
Tokens and ICOs Chevron down icon Chevron up icon
Games and DAOs Chevron down icon Chevron up icon
Advanced Solidity Chevron down icon Chevron up icon
Smart Contract Security Chevron down icon Chevron up icon
Design Decisions Chevron down icon Chevron up icon
Other Protocols and Applications Chevron down icon Chevron up icon
Miscellaneous Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon
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