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
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
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

Ethereum Cookbook

Getting Started

In this chapter, we will cover the following recipes:

  • Choosing a client for Ethereum
  • Setting up a node and participating in a network
  • Working with the JavaScript console
  • Saving time and money with INFURA
  • Creating your own private Ethereum network
  • Creating a blockchain network for development
  • Using Azure Ethereum as a service
  • Using MetaMask and other wallets
  • Using block explorer
  • Understanding everything about accounts
  • Installing a solidity compiler

Introduction

It is really important to understand how to configure and work with various implementations of the Ethereum protocol before developing applications in it. There are several flavors, which can be used interchangeably for development, testing, and deployment. Keywords in Ethereum might be very new to a person who is just getting started, so it is important to understand and use the tools and services in the Ethereum ecosystem.

Ethereum is a distributed public ledger, like Bitcoin. Bitcoin acts more like a peer-to-peer electronic cash system, whereas Ethereum is a decentralized platform for building applications. Ethereum has a built-in Turing complete programming language (solidity), which can be used to write smart contracts. This means that Ethereum has a broader application than other traditional blockchains. Ethereum also has a cryptocurrency (Ether), which can be traded for value or to pay the transaction fee for applications and services in Ethereum.

POW (Proof of Work), POS (Proof of Stake), IBFT (Istanbul Byzantine Fault Tolerance), Raft, and so on are different commonly used consensus algorithms. These algorithms are used to achieve agreement on a data value among distributed systems. Each algorithm has their own advantages and disadvantages, and various blockchain platforms use them based on their requirements.

A smart contract is a computer program that outlines the rules in a relationship. Smart contracts work exactly as intended and cannot be changed at a later point in time. Once deployed, these smart contracts cannot be changed. This gives users trust and transparency. With the help of Ethereum smart contracts, you can create your own tradable tokens, raise funds for your startup, build a decentralized organization, or even make a fun game.

The recipes in this chapter will primarily focus on Ethereum configuration and platform tools, which will help the reader understand more about the Ethereum ecosystem before starting to develop applications.

While the recipes in this chapter will give you an overview of Ethereum and working with various clients, we encourage you to adopt this proposal according to your needs. Since the software used is still in development and gaining in popularity, some organization's policies and antivirus software will prevent you from using this. In such cases, it is typically a good idea to discuss this with your IT security department—if your company happens to have one—well in advance, to prevent lengthy discussions later on.

Choosing a client for Ethereum

In this recipe, we will focus on installing various clients that implement the Ethereum protocol. This will help you learn what each client has to offer, and will enable you to choose and work with an efficient implementation based on your requirements.

Getting ready

If you are using macOS, you will need homebrew to install the packages.

How to do it...

There are several clients that implement the Ethereum protocol and we will mainly focus on geth and parity. You can get more information about the remaining protocols from the official Ethereum documentation (http://www.ethdocs.org/).

Geth

Geth is the official Go implementation of Ethereum:

  1. To install geth on macOS, the easiest way to follow is using homebrew. Run the following commands in your Terminal to download and install geth:
brew tap ethereum/ethereum
brew install ethereum

This command will install the latest stable version of geth on your Mac. If you want to install the development version of geth, then add the --devel flag to the install command:

brew install ethereum --devel
  1. To install geth on Ubuntu, run the following commands:
sudo apt-get install software-properties-common
sudo add-apt-repository -y ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install ethereum
  1. If you are using Windows, it is suggested to download the binary from https://geth.ethereum.org/downloads/ and install it by double-clicking the geth.exe file.
  2. Verify the installation by running the geth command:
geth version

It will show the current client details, as displayed here:

Since geth is a development version and still gaining in popularity, some antivirus software may consider it a virus. Also, make sure that you are not violating your organization's policies by using this software.

Parity

Parity is an Ethereum client that is built by Parity Technologies. It is a rust-based implementation and offers some additional functionalities over Go Ethereum:

  1. The easiest way to install parity on Mac or Ubuntu is to use the one-line binary installer. This will handle all the hassle of downloading and installing the package:
bash <(curl https://get.parity.io -kL)
  1. If you are using Windows, then download the binary releases from https://github.com/paritytech/parity/releases and install them. You can also see supported binaries for other operating systems as well.

There's more...

You can build and run the client directly from its source code. To build geth from the source in Ubuntu, follow the steps given later. Make sure you have Go and the C compilers installed:

git clone https://github.com/ethereum/go-ethereum
cd go-ethereum
make geth

Setting up a node and participating in a network

Here, you will learn how to set up a node using the geth command-line tool. You will also see how to connect to a public network and perform operations such as ledger syncing and mining.

Getting ready

You will need a working installation of the geth command-line interface. You can also start a node with parity or any other Ethereum protocol implementation, but the steps may differ for each client.

Commands starting with $ have to be run on the command prompt/terminal and those starting with > will work only on the web3 JavaScript console.

How to do it...

  1. Verify your installation by running the following version command:
$ geth version
  1. Start your node with the following command:
$ geth

This will start an Ethereum node and will connect with the main network. As soon as it finds any peer nodes, it will start downloading the blocks from them.

You can configure the parameters before starting a node. This will help you do things like connect to a different network, expose APIs, and much more. Let's look at a sample initialization and the parameters used in it:

$ geth --networkid 3 --datadir "./ropsten-db" --keystore "./ropsten-keys" --syncmode "fast" --rpc --rpcport "8546" --rpcapi "web3,eth,miner,admin" --rpccorsdomain "*" --port 30301 console

Let's look into each parameter in detail:

  • --networkid <id>: A parameter to identify each network. You can either connect to the main/test network (1=Frontier(default), 2=Morden (disused), 3=Ropsten(PoW), 4=Rinkeby(PoA)) or any private network that you have set up.
  • --datadir <path>: Directory path for storing the blockchain database and keystore. You can change the default keystore directory with the --keystore parameter.
  • --syncmode <mode>: A parameter to specify the type of sync method. You can choose fast, full, or light, based on your needs.
  • --rpc: Enables an RPC server through HTTP. You can also change parameters such as --rpcaddr, --rpcport, and --rpcapi.
  • --rpccorsdomain <list>: Domains from which cross-domain requests are accepted. Use * as a wildcard or specify domains as a comma-separated list.
  • --port <port>: Changes the default network listening port (30303).
  • --console: Starts the web3 JavaScript console.
If you get stuck anywhere, you can always make use of the inbuilt help interface. Just enter geth help and it will return a comprehensive list of all commands with their respective description that you can run using geth.
  1. It might take a few minutes to identify the peers that are already on the network. Run the following command to return the list of peers that are currently connected to your node. Your node will start syncing once it finds at least one peer:
> admin.peers
  1. Check the current syncing status by running the following command. It will return false if not syncing:
> eth.syncing
  1. Run the geth attach command if you would like to connect to this node from a different console. You can also explicitly specify the host and the port. In our case, it is localhost and 8546:
$ geth attach http://localhost:8546
Your firewall may restrict the node from communicating with an external peer. This can cause issues with the synchronization process. Also, ensure that you are not exposing your RPC APIs to the internet, which can result in attacks.

Working with the JavaScript console

The geth command-line utility has an inbuilt JavaScript Runtime Environment (JSRE). This JavaScript console exposes all web3js objects and methods. You can use this JSRE as a REPL (Read, Execute, Print, Loop) console.

In this recipe, we will learn how to connect and use the JSRE in interactive (console) and non-interactive (script) modes.

Getting ready

You should have the geth command-line tool installed on your system to test this recipe. You can either start a node along with the console or connect to an already existing node.

How to do it...

  1. Start the Ethereum console with the console or attach subcommand. The console command starts the geth node and opens the JavaScript console along with it. The attach command is used to connect to an existing node. Here, we will connect to an already running node that you started earlier:
$ geth attach http://localhost:8545
  1. If you are starting a new node and would like to see the log information, start the node with this:
$ geth --verbosity 5 console 2>> /tmp/eth-node.log

Too many logs can pollute your console. To avoid this, start the node with a specific verbosity value:

$ geth --verbosity 0 console
  1. Take a look at the web3 object, which is available for you to interact with:
> web3
  1. For managing the node, you can make use of the admin API. For the list of supported admin operations, run the following command:
> admin

You can check the current node information with this:

> admin.nodeInfo

This will return an object with properties such as enode, protocols, ports, name, and other details related to the current node, as displayed here:

To see the list of peers connected to the current node, use the peers object:

> admin.peers

You also have access to methods that can help you enable or disable RPC/WS.

  1. For handling Ethereum blockchain-related tasks, use the eth object. Run the following command to see the methods supported by it:
> eth

You can check the latest block number (block height) with this:

> eth.blockNumber

You have an option to read the contents of a block. You can pass any block number as a parameter:

> eth.getBlock(301)

In the following screenshot, you can see the block number, difficulty, gas details, miner, hash, transactions, and much more:

eth also has methods related to accounts, transactions, and contracts. We will talk more about those later in this book.

  1. To manage Ethereum accounts, you can make use of the personal method. It has options for creating an account, unlocking the account, sending/signing a transaction, and so on:
> personal
  1. You can play around with mining and its methods through the console:
> miner
  1. This console also has an option to monitor the transaction pool through the txpool object:
> txpool
  1. web3 also offers some generic methods to help you with the interaction. Some of the examples include conversion of values, encoding, and hashing. One such example to convert ether to Wei is given here:
> web3.toWei(1, "ether")
Since it is a JavaScript console, you have complete ECMA5 functionality (Go Ethereum uses Otto JS VM, which is a JS interpreter written in Go). You can declare variables, use control structures, define new methods, and even use any of setInterval, clearInterval, setTimeout, and clearTimeout.

There's more...

You can also execute JavaScript commands in a non-interactive way. There are two different approaches to doing this:

  1. Use the --exec argument, which takes JavaScript as input. This will work with both the console and attach commands:
$ geth --exec "eth.accounts" attach http://localhost:8545

This will print the list of accounts stored in the current node.

  1. You can execute more complex scripts with the loadScript method. The path to your scripts folder can be specified with the --jspath attribute:
$ geth --jspath "/home" --exec 'loadScript("sendTransaction.js")' attach http://localhost:8545

Saving time and money with INFURA

If you don't want to set up a full node for you decentralized application, then this is the recipe for you. INFURA provides an infrastructure for Ethereum and you can make use of it for free.

How to do it...

  1. Go to the INFURA signup page (https://infura.io/signup) and enter your name and email.
  2. Once you acknowledge the terms and conditions and have signed up, you will receive an email from INFURA with the providers for each network.
  3. For each network, you will receive an endpoint and an API key:
    • Main Ethereum network: https://mainnet.infura.io/<api-key>
    • Test Ethereum network (Ropsten): https://ropsten.infura.io/<api-key>
    • Test Ethereum network (Rinkeby): https://rinkeby.infura.io/<api-key>
    • Test Ethereum network (INFURAnet): https://infuranet.infura.io/<api-key>

You can interact with the providers just like you do with your local node. You can use JSON RPC, Web3JS, or even the REST API provided by INFURA to interact with the nodes.

  1. Get the current block number with JSON RPC using cURL:

curl -X POST -H "Content-Type: application/json" --data '{"jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": []}' "https://mainnet.infura.io/<your-api-key>"

This will return the current block number, as follows:

{"jsonrpc":"2.0","id":1,"result":"0x512bab"}
  1. INFURA also provides an easy-to-use REST API interface for JSON RPC commands. You can use the JSON RPC methods as the path to get the result:

https://api.infura.io/v1/jsonrpc/mainnet/eth_blockNumber?token=<your-api-key>

  1. To use INFURA with your web3js application, you can set the endpoints as HTTP providers:
web3 = new Web3(new Web3.providers.HttpProvider ("https://mainnet.infura.io/<your_api_key>"));

There's more...

INFURA also provides support for IPFS and you can use their server as a gateway:

Creating your own private Ethereum network

This recipe helps you create your own private POW-based Ethereum blockchain. Here, we will be creating an entirely new custom blockchain that cannot interact with the Ethereum main-net. You will have the flexibility to control parameters such as mining and peers. This will come in handy when you want to have a consortium of your own or even for testing purposes.

Getting ready

To step through this recipe, you will need a working installation of the geth command-line interface. No other prerequisites are required.

How to do it...

  1. Create a directory to save your blockchain data:
$ mkdir datadir
  1. Create an account and save it to the directory:
$ geth account new --datadir datadir

You will be asked to enter a password for the account. An address will be displayed once the account is created. The key file for this account will be stored in the /datadir/keystore/ location.

  1. Create a genesis.json file with the following contents:
{ 
"config": {
"chainId": 1100,
"homesteadBlock": 0,
"eip155Block": 0,
"eip158Block": 0,
"byzantiumBlock": 0
},
"difficulty": "400",
"gasLimit": "2000000",
"alloc": {
"87db8fceb028cd4ded9d03f49b89124a1589cab0": {
"balance": "100000000000000000000000"
}
}
}

Various parameters in the genesis files are explained here. You can make changes as per your requirements:

  • config: The config object defines the settings for our custom blockchain. chainId is used to identify our network. Set it to a unique value for our private network. Other parameters are related to forking and versioning. Let’s not worry about them, since we are starting a network from scratch.
  • difficulty: This value is used to control the block generation time of a blockchain. The higher the difficulty, the longer it will take to mine each block. In a test network, try to keep it low to avoid long waiting times.
  • gasLimit: This value denotes the total amount of gas that can be used in each block. We will keep it high enough to avoid any bottlenecks during testing.
  • alloc: This object allows us to pre-fill accounts with Ether. This won’t create accounts for you. Since we already have an account created in step 2, use it here to allocate some wei (1 Ether = 1018 wei).
  1. Initialize your genesis file using the following command:
$ geth --datadir ./datadir init ./genesis.json
  1. Start your network:
$ geth --datadir ./datadir --networkid 1100 console 2>> network.log

Running this command will display a console like this in your terminal/command prompt:

You can use this console to interact with your private blockchain. To give you a brief idea, execute the following command to see the list of accounts:

> eth.accounts
  1. If you would like to add another peer to the network, open a second terminal/command prompt to create a second peer with a different data directory and port:
$ geth --datadir ./datadir2 init ./genesis.json
$ geth --datadir ./datadir2 --networkid 1100 --port 30302 console 2>> network.log
  1. Find out the enode address of the first node using the first JavaScript console:
> admin.nodeInfo.enode

This will return the enode address of the current node:

 enode://315d8f023dfa1ae1b59dc11462f3e13697fc8fe4886034e01530ebe36b2f8cc154a8dd9c21f5b42564668f22ae7173943b9dd9a0fbfc1430cca8c47196872914@[::]:30303
  1. Use the second node’s JavaScript console to connect with the first node:
> admin.addPeer( “enode://315d8f023dfa1ae1b59dc11462f3e13697fc8fe4886034e01530ebe36b2f8cc154a8dd9c21f5b42564668f22ae7173943b9dd9a0fbfc1430cca8c47196872914@127.0.0.1:30303”)

We replaced [::] with the IP address and port of the first node.

  1. Verify the connection from both nodes by listing the connected peers:
> admin.peers

How it works...

In steps 1 through 5, we created a private Ethereum network. This should be enough for you to run a single-node network. With the minimum difficulty and maximum gas limit, this network is ideal for development and testing. At this point, your application can connect to the network with the default Ethereum port, 8545.

In steps 6 to 9, we are creating another peer and connecting it to the first node. This allows you to have a multi-node Ethereum network. All the blocks will be synced between these two nodes and will be accessible from both nodes. You can create and connect as many nodes as you want with the procedure explained here. Make sure to set appropriate firewall rules to ensure proper communication.

There's more...

puppeth is a command-line tool that comes with geth. It can help you create a new Ethereum network, down to the genesis block, bootnodes, miners, and ethstats servers, in a user-friendly way. Start puppeth using the following command:

$ puppeth

You will be asked to enter a network name. You can either enter a new network name or use the one that you already created using puppeth. Once you enter it, you can see the list of things that puppeth can do.

Create a new genesis file using puppeth and use Proof of Authority (clique) as the consensus algorithm. Try creating a private network with the generated genesis file.

See also

This recipe explains how you can create a private network using geth. There are other options for various use cases, such as development and production. You can check out the following recipes to learn more:

  • Creating a blockchain network for development

  • Using Azure Ethereum as a service

Creating a blockchain network for development

You don't always have to create a fully functioning node to support your development. There are development networks that can simulate an Ethereum network. In this recipe, you will learn about ganache-cli (previously TestRPC), which is part of the Truffle suit of Ethereum development tools and is a command-line tool that you can use to create your personal blockchain network for Ethereum development.

Getting ready

Since the tool is written in JavaScript and distributed via npm, you will need Node.js (>= v6.11.5) installed on your machine to try this recipe.

How to do it...

Follow these steps to install and create a test Ethereum network using npm:

  1. Install ganache-cli using npm:
npm install -g ganache-cli
  1. Starting a basic blockchain network is as simple as running this command:
ganache-cli

You will know that your blockchain is ready when you see this screen:

Ganache creates a virtual Ethereum blockchain, and it generates some sample accounts for you to use during development. Each account is filled in 100 Ether so that you only have to focus on development. You can access the network from http://localhost:8545.

  1. You can use a few parameters to customize the blockchain. Here's one such example:
ganache-cli -a 5 -e 2000 -p 8080 -l 999999
  • -a: Number of accounts to generate while starting the network. The default is 10.
  • -e: Amount of Ether to allocate for each account. The default is 100 Ether.
  • -p: Port number for listening to RPC requests. The default is 8,545.
  • -l: Gas limit for each block. The default is 90,000.

You can find the complete list of parameters to configure here:

https://github.com/trufflesuite/ganache-cli.

By default, accounts are unlocked and you can do the transaction from any account without a password. You can change this by using the --secure or -n flag. This will lock all accounts by default and you need to unlock each one to send a transaction.

There's more...

There is a GUI for ganache that offers an easy-to-use interface for creating Ethereum networks. It even offers an intuitive User Interface (UI) for browsing blocks and transactions.

You can download and install the ganache GUI from http://truffleframework.com/ganache/.

Using Azure Ethereum as a service

Azure offers cloud solutions to deploy and configure Ethereum consortiums with a simple single-click deployment through the Azure portal. In this recipe, you will learn how to deploy a flexible Ethereum network, consisting of a set of load-balanced transaction nodes, with which an application or user can interact to submit transactions, and a set of mining nodes to record transactions.

Getting ready

You will need an Azure subscription to create an Ethereum consortium. Other dependencies will be configured by the provider itself.

How to do it...

Follow these steps to create an Ethereum POW blockchain in Azure:

  1. Log in to the Azure portal and click on Create a resource from the left navigation bar.
  1. Select Create Ethereum Proof-of-Work Consortium under Blockchain.

Once you click Create, you can see a five-step wizard that will guide you through the setup process. The first step will ask you to choose a username, password, subscription, location, and so on. Provide the appropriate values and click OK:

  1. Step 2 will ask you to configure the regions in which the nodes should be deployed. For a simple network, one region should be enough.
  2. Step 3 is all about configuring the number of nodes that should be dedicated to mining and transactions. Mining nodes do all the heavy lifting of creating blocks, and transaction nodes take care of broadcasting the transaction from your application. Choose the number of nodes for each category and their respective configuration to meet your needs.
  3. Step 4 focuses more on the parameters of blockchain that you are about to create. You can compare it with the genesis file you will create during private network configuration.
  1. Once you are finished on the Ethereum settings tab, you can choose the Operations Management Suite for your Azure resource. Create a new one if you are new to Azure and creating resources for the first time.
  2. If everything goes well, then the verification process in the Summary tab will be successful and you can proceed to purchase the service.
  3. Read through the Terms and Conditions and click Create. This will start deploying your resources and can take a few minutes to finish.
  4. Once the deployment is finished, you can see your resources in the resource group that you created/selected. Select your resource group from the Resource groups tab in the left navigation bar and Deployments.
  5. This will display the set of deployments that has been created as part of Ethereum consortium's deployment. Select the deployment name that starts with microsoft-azure-blockchain-ethereum:
  1. Select output from the window, and now you can see the access credentials for the resources that you created:

These are some of the credentials you can use in the Azure blockchain service:

  • ADMIN-SITE: Admin portal that you can use to view the current node status and send Ether to newly created accounts
  • OMS-PORTAL-URL: Azure Operations Management Portal for your resources
  • ETHEREUM-RPC-ENDPOINT: Ethereum RPC port for you to interact with the blockchain you created
  • SSH-TO-FIRST-TX-NODE-REGION1: Credentials for connecting to a transaction node that is in the first region

How it works...

Steps 1 to 9 guide you through the process of creating a private Ethereum consortium using services offered by Azure. This will create and deploy multiple peers across various regions behind a load balancer for you to interact with. Steps 10 to 12 describe the process of using these services. This helps you understand various services and where to use them.

Using MetaMask and other wallets

You will need a wallet to send and receive the cryptocurrency used in Ethereum. In this recipe, you will learn to install and use MetaMask or another wallet, which can be used for managing accounts and transactions.

Getting ready

MetaMask is a browser-based wallet and it currently works with both Chrome and Firefox. Other wallets are either browser-based or need additional downloads.

How to do it...

MetaMask, Mist, and MyCrypto are some of the popular wallets in the Ethereum ecosystem. Let's look into these options in detail.

MetaMask

  1. Install MetaMask for Chrome or Firefox from the respective app store.
  2. Select MetaMask from the extensions tab and Accept both Privacy and Terms and Conditions after carefully reading them. Then, you will be asked to create a password to encrypt your wallet storage:
  1. MetaMask will generate a random 12-word mnemonic that you can use to restore your account at a later point in time. Save it somewhere safe and secret as this is the only way to regain access to your account:
  1. Your account has now been successfully created. You can now use MetaMask with all supported websites for signing transactions:
  1. You can connect to various Ethereum networks using MetaMask. This includes connecting to the main-net, test nets, or any other RPC ports you have access to. This can be configured from the network selector drop-down in the top-left corner.
  2. You also have the option to add additional accounts or to export the private key of the current account. These options let you configure MetaMask as per your requirements.

MyCrypto

  1. Using MyCrypto is as simple as navigating to https://mycrypto.com/. It offers an intuitive UI to interact with Ethereum:

  1. Either use an existing wallet or create a new one. The web interface of MyCrypto has limited support for creating/using wallets through PrivateKey, Mnemonic, or keyfile. This restriction is enabled to use a strong password while creating your wallet. Once your wallet is created, you can export your private key and KeyFile. Save it in a secure place and do not lose it. It cannot be recovered!
  2. To use MyCrypto, you can import the private Key/KeyFile you created in step 2 or use external wallets such as MetaMask/Mist/Hardware.
  3. MyCrypto also has options to deploy and interact with contracts, use Ethereum name service, or even swap your Ether for other cryptos.

Ethereum wallet–Mist

  1. Download and install the Mist or Ethereum wallet from https://github.com/ethereum/mist/releases. Mist is a browser for decentralized web apps. The Ethereum wallet is a Mist implementation that can only access a single Decentralized Application (DApp), which is the wallet DApp.
  2. You can select the network from Network under the Develop menu of Mist. You can choose between the main network, test networks, or your own private network.

Using the Ethereum wallet DApp, you can send/receive transactions and deploy/interact with smart contracts.

Never send your account credentials to anyone or use them with unknown websites. Make sure that you are using a trusted wallet or exchange while using cryptocurrencies. Typos in addresses can make you lose your funds. Double-check the address before making any transactions.

Using block explorer

There are many ways to read data from a transaction or a block in Ethereum. Etherscan is one block explorer and analytics platform for Ethereum. In this recipe, you will learn about the platform and how you can make use of it.

How to do it...

  1. Go to https://etherscan.io/ to access the block explorer. You will see a dashboard that displays the network state:
  1. On the top left, you can see a card that displays the current Ethereum market share along with the exchange rate. You can also see a transaction history chart for the last 14 days.
  2. Search for a block number or select it from the recent blocks list to view the contents of the block. You can see details such as time, miner, hash, transactions, size, gas, and so on:
  1. By searching a transaction, you can view transaction details such as from address, to address, the value transferred, gas, and other details.
  2. Etherscan also offers a details page for both Externally Owned Addresses (EOA) and contract addresses. To see the balance, list of transactions, and even tokens owned by that address, navigate to the EOA details page.
  3. The contract page also shows the balance, transactions, and even a contract code if it is a verified contract. To interact with verified contracts through Etherscan, use this page.
  4. The platform also offers charts for analytics. Use the charts to get an idea about the currency, network, mining, blocks, transactions, and other general information.
  5. Click the MISC tab to use tools such as the mining calculator, bytecode converter, and transaction broadcaster.
  6. Etherscan also has a free to use API for reading data from Ethereum. Sign up to Etherscan to use the API and use the free API key that can be generated from the portal itself. Make sure that you are not making more than five requests per second. You will be blocked if this is exceeded.
  1. Signing up with Etherscan will allow you to watch specific addresses and create email alerts. You can even add a private note for each transaction.

There's more...

Eth-netstats is a visual interface for tracking an Ethereum network status. To access the public status page, go to https://ethstats.net/. Note that the portal does not represent the entire state of the Ethereum main net. This is because of the voluntary listing of nodes in the portal.

You can use netstats to visualize your private Ethereum network:

  1. Download the source code from the repository. Make sure to verify the license:
git clone https://github.com/cubedro/eth-netstats
  1. Install the dependencies:
sudo npm install -g grunt-cli
cd eth-netstats
npm install
  1. Build the project using grunt and use npm to run it:
grunt
npm start

Understanding everything about accounts

Ethereum accounts are made up of 20-byte addresses, and you can exchange data and values between two accounts with state transitions. In general, there are two types of account in Ethereum: EOA and contract accounts. Depending on the type of account, there are four fields associated with each account: balance, contract code, storage, and nonce.

EOAs are controlled by a private key, and contract accounts are controlled by the contract code. A normal user can create an EOA by using a wallet such as MetaMask or MyCrypto. As a developer, you need to know more about these accounts and other ways to create them. In this recipe, you will learn how to create and maintain EOAs in Ethereum.

Getting ready

You will need a working installation of geth in your system to run web3 commands. Other prerequisites, if any, are listed along with each command.

How to do it...

  1. Create an account using the account command in the geth command-line tool. This will create an Ethereum account for you and will return the EOA address:
$ geth account new

If you are using the JavaScript console or Web3JS, use the following command to create an account:

> web3.personal.newAccount("<password>")
  1. Before you do any transaction from this account, unlock it using the password. Use the third parameter to control the duration of unlocking. To lock the account after the transaction, use the lockAccount function:
> personal.unlockAccount("<address>", "<password>")
> personal.lockAccount("<your_address>")
  1. Creating an account using this method also creates an encrypted KeyFile. The file is located in your key store with the format UTC--{year}-{month}--{account}. The contents of the file also includes an encrypted version of your private key:
{
"address":"4f9e3e25a8e6ddaf976dcbf0b92285b1bb139ce2",
"crypto":{
"cipher":"aes-128-ctr",
"ciphertext":"0b0ae5548acc4d08134f4fe...53cb8c08eb9563a76aeb082c",
"cipherparams":{
"iv":"6079a38e159b95f88e0f03fbdae0f526"
},
"kdf":"scrypt",
"kdfparams {
"dklen":32,
"n":262144,
"p":1,
"r":8,
"salt":"7ed09d37d80048c21490fc9...dc10b3cef10e544017"
},
"mac":"0d8ac3314c4e9c9aaac515995c...43bf46f17d2d78bb84a6"
},
"id":"7b6630ea-8fc8-4c35-a54f-272283c8f579",
"version":3
}
  1. You can also create a private key externally and import it into other wallets. Ethereum follows the elliptical curve for private keys. You can either create one with OpenSSL or with wallets such as MyCrypto. Once a private key is created, you can import it using the following command. Make sure to give it a strong password to encrypt it:
$ geth account import <path to PrivateKey file>

You can also import the private key using the JavaScript console:

> web3.personal.importRawKey("<private key>", "<password>")
Please do not share your private keys with any website, business, or individual. You may need to provide your private keys to MetaMask and other similar wallets, which exist to manage accounts, in order to use them. Do this with caution and ensure that you can trust them.
  1. If you want to find the address from the private key, a series of steps have to be followed. Convert the private key to a 64-byte-long public key. Then, take the Keccak-256 hash of the public key, and the last 20 bytes will be the Ethereum address for that private key.
  2. You can also create an account securely by using the mnemonic phrase. This mnemonic is a 12-word phrase that can be used as a seed to create EOAs. This is easy to store and wallets such as MetaMask follow this pattern.

There's more...

If you need a safe and secure way to store your private key or account, then the recommended way is to use a hardware wallet. The only way someone can use the account is by physically interacting with the wallet. This reduces the potential security threat if someone gets into your system maliciously.

Installing a solidity compiler

You have multiple options when it comes to compiling smart contracts written in solidity. In this recipe, you will learn about installing a solidity compiler and using it to compile your smart contract.

Getting ready

If you are using macOS, you will need homebrew to install the binary compiler. There are other options, such as using npm or docker, which require Node.js and Docker, respectively, installed on your machine.

How to do it...

  1. If you are in Ubuntu, use ppa to install the compiler by running the following command:
sudo add-apt-repository ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install solc
  1. If you are using macOS, install the compiler using brew:
brew update
brew tap ethereum/ethereum
brew install solidity
  1. Verify the installation with the following command:
solc --version
  1. Use this command to compile a contract and print the binary:
solc --bin SampleContract.sol
  1. You want to get some of the more advanced output from solc:
solc -o outDirectory --bin --ast --asm --abi --opcodes SampleContract.sol

We can configure it using these provided flags:

  • --ast: Abstracts the syntax trees of source files
  • --asm: EVM assembly of the contracts
  • --abi: ABI specification of the contracts
  • --opcodes: Opcodes of the contracts

You can get the complete list of operations supported by the solc compiler by running solc --help.

There's more...

There is also a JavaScript-based solidity compiler available for you to use. You can install SolcJS using npm. The solc-js project is derived from the C++ solc project and can be used in JavaScript projects directly:

npm install -g solc

To see all the supported features, run the following command:

solcjs --help
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 Malta

Premium delivery 7 - 10 business days

€32.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
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Malta

Premium delivery 7 - 10 business days

€32.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
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 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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 [email protected] 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