Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Ethereum Cookbook
Ethereum Cookbook

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

Arrow left icon
Profile Icon Manoj P R
Arrow right icon
Mex$179.99 Mex$803.99
eBook Aug 2018 404 pages 1st Edition
eBook
Mex$179.99 Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial
Arrow left icon
Profile Icon Manoj P R
Arrow right icon
Mex$179.99 Mex$803.99
eBook Aug 2018 404 pages 1st Edition
eBook
Mex$179.99 Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial
eBook
Mex$179.99 Mex$803.99
Paperback
Mex$1004.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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

Billing Address

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

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 : 9781789137941
Category :
Languages :
Concepts :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
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

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.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
$199.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 Mex$85 each
Feature tick icon Exclusive print discounts
$279.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 Mex$85 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Mex$ 2,338.97
Ethereum Smart Contract Development
Mex$799.99
Ethereum Cookbook
Mex$1004.99
Ethereum Projects for Beginners
Mex$533.99
Total Mex$ 2,338.97 Stars icon
Banner background image

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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.