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
$19.99 per month
Paperback Aug 2018 404 pages 1st Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Manoj P R
Arrow right icon
$19.99 per month
Paperback Aug 2018 404 pages 1st Edition
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$9.99 $39.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
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 : 9781789133998
Category :
Languages :
Concepts :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

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
$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 $5 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 $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 113.97
Ethereum Smart Contract Development
$38.99
Ethereum Cookbook
$48.99
Ethereum Projects for Beginners
$25.99
Total $ 113.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

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.