Install Truffle and Setup Ganache for Compiling Ethereum Smart Contracts


Install Truffle and Setup Ganache for Compiling Ethereum Smart Contracts

Recipe ID: hsts-r41


Self-paced training

We offer blockchain introduction, Hyperledger for system admin, Ethereum, Solidity, Corda R3, Hyperledger for developers, blockchain cybersecurity and more classes in self-paced video format starting at $60. Click here to learn more and register. For complete self-paced blockchain training, visit our Complete Blockchain Development Training page.


Update on Feb 2021

The latest version of this tutorial along with all updated source codes is available via the below link:
https://myhsts.org/blog/ethereum-dapp-with-evm-remix-golang-truffle-and-solidity-part2.html

Recipe Overview

Ethereum is a general-purpose blockchain that is more suited to describing business logic, through advanced scripts, also known as smart contracts. Ethereum was designed with a broader vision, as a decentralized or world computer that attempts to marry the power of the blockchain, as a trust machine, with a Turing-complete contract engine. Although Ethereum borrows many ideas that were initially introduced by bitcoin, there are many divergences between the two.

The Ethereum virtual machine and smart contracts are key elements of Ethereum, and constitute its main attraction. In Ethereum, smart contracts represent a piece of code written in a high-level language (Solidity, LLL, Viper) and stored as bytecode in the blockchain, in order to run reliably in a stack-based virtual machine (Ethereum Virtual Machine), in each node, once invoked. The interactions with smart contract functions happen through transactions on the blockchain network, with their payloads being executed in the Ethereum virtual machine, and the shared blockchain state being updated accordingly.

For those who are not familiar with blockchain technology reading History and Evolution of Blockchain Technology from Bitcoin article is strongly recommended. Also, if you wish to learn and practice Hyperledger blockchain development, visit Comprehensive Hyperledger Training Tutorials page to get the outline of our Hyperledger tutorial articles.
We have written two sets of tutorials to explore Ethereum and Solidity programming in depth. First set covered the following nine recipes:

In short, you learned about how to set up and configure Ethereum and develop blockchain applications using Solidity programming language. We explored its key components, including smart contracts and Web3.JS API via an Auction Decentralized Application (DApp) step-by-step.
In second set, we discuss more advance topics in Ethereum blockchain development and solidity while building a Tontine DApp game step-by-step. Specifically, we cover Truffle and Drizzle. For instance, we show you how a tool such as Truffle can be an assistant in building, testing, debugging, and deploying DApps. In summary, we are going to cover four main topics:

The 2nd set consists of 8 recipes as follows:

IMPORTANT: Understanding and completing the first set of recipes are required prior to working on second set of recipes.
In our first round of recipes, we learned a lot about the Ethereum ecosystem, but we are yet to realize the full potential of its different components. More precisely, we explored how Ethereum works, what a decentralized application (DApp) is and how to build one, and also covered the key concepts of Solidity and web3.js. We then introduced some of the most common smart contract design patterns (withdrawal from a contract, restricting access, state machines), before ending with a discussion of a contract’s cost optimization.
To brush up your knowledge and skills, on second round of recipes, we are going to build a Tontine DApp game. We will exploit this example to explore new tools that are going to change the way you build DApps, and introduce new Solidity features.

In this walkthrough, we will discover how a tool such as Truffle can aid in building, testing, debugging, and deploying our DApp.  

 

Tontine Game Overview

Before starting the project, let me introduce the concept behind the game.

As this recipe’s name suggests, we are going to build a Tontine game. The concept behind the weird word Tontine appeared at the end of 17th century. Initially, it represented a collective investment scheme plan, where each participant paid a sum into a fund and received dividends from the invested capital. But behind this simple idea, a weird rule is hidden: when a subscriber dies, their share is divided among the others and the last lucky survivor recovers the whole capital.
In our game, we will adapt this idea to our smart contract and gaming logic. Players will deposit funds in the game's smart contract to join the game. Afterwards, they should keep pinging it during a specific time interval to avoid being knocked out by other opponents. For instance, if anybody misses pinging the contract within a day for any reason, the other players are able to eliminate them. So, nobody will die in our case but they will be eliminated. Similar to the original Tontine, the last player standing will win the funds controlled by the contract.

Let's start by preparing the environment in which we'll build the Tontine smart contract.

 

Prerequisites

Before proceeding with this recipe, you should already be familiar with developing in Solidity. If not, I recommend reading our first round of recipes. Moreover, the following prerequisites should be installed:
•    Ubuntu 16.04
•    MetaMask browser
•    Plugin Node.js and NPM

Truffle quick start

So far, the only method we have used to compile and interact with our contracts was Remix. Let me now introduce you to a new DApp development toolkit: Truffle.

Truffle is the most popular development environment and testing framework for DApp developers. It is a true Swiss Army knife that helps you easily compile, test, and deploy your contracts to the blockchain. Moreover, Truffle helps you set up and hook your frontend up to your deployed contracts. It also has other features:

 

Installing Truffle

To start using Truffle, you can install the latest release using Node Package Manager
(NPM): npm install -g truffle.
You can also choose a specific version to install, such as npm install -g truffle@4.0.4.
Once installed, you can check your Truffle version in the Terminal using truffle version:
Truffle and Ganache for Ethereum Smart Contract management

By typing truffle into your Terminal without any arguments, you’ll get all of Truffle's available options. If you are unsure about something, or you want to learn about an option, have a look at the documentation: http://truffleframework.com/docs.

 

Saying hello to Truffle

Now, Truffle is ready. Start by creating a folder called tontine/ for this first project, then initialize it with Truffle as follows:

mkdir tontine cd tontine truffle init

Within a few seconds, this last command will download a template of a Truffle project for you:
Truffle and Ganache for Ethereum Smart Contract management

Once the initialization is completed, you'll get the following files and directory structure:

 

Running Truffle for the first time

To examine how we can compile and deploy a contract using Truffle, we will use a simple introductory example. We will use the hello world example we built in our previous round of recipes or Peer-to-Peer Auctions in Ethereum. Copy the contract code into a hello.sol file and put it into Truffle’s contracts/ folder.
Let's see how can we use Truffle to compile and deploy this first contract.

 

Preparing the migration

Truffle uses the migration concept to refer to deploying and switching old contracts to new instances. To deploy our hello world contract, we need to indicate to Truffle how to deploy (migrate) it into the blockchain. To achieve that, open the migrations/ folder and create a new migration file named 2_initial_migration.js.
Paste the following content into this migration file :

const Hello = artifacts.require("HelloWorld"); module.exports = function(deployer) {
deployer.deploy(Hello);
};

At the beginning of the migration, we tell Truffle which contracts we would like to interact with via the artifacts.require() method, in the same way we do with require in Node.js.

In the case where you have multiple contracts defined, you'll need to define an
artifacts.require() statement for each contract:
var ContractOne = artifacts.require("ContractOne"); var ContractTwo = artifacts.require("ContractTwo");

Configuring Truffle

Now, it is time to configure Truffle. First, we need to define the networks to which we want to migrate the contracts. In the truffle.js file (truffle-config.js for Windows), insert the following code:

module.exports = { networks: {
my_ganache: {
host: "127.0.0.1",
port: 7545, network_id: "*"
}
}
};

We define a deployment network with the name my_ganache along with a few parameters. The network name is used for user-interface purposes, to help you easily choose to run  your migrations on a specific network with a name, as we can configure Truffle to use multiple networks.

Basically, this configuration file says to Truffle that when we choose the my_ganache network, connect to the host at 127.0.0.1, using port 7545. For network_id, we used * to match any network ID. Beyond that, there are many other configuration options, such as gas limit and gas price, which are detailed in the documentation: https:// truffleframework.com/docs/truffle/reference/configuration.

 

Compiling the contract

Now, it's time to compile and deploy the hello world contract. Start by running the
truffle compile command in your console.
After a short while, you will get the compilation result. You may notice the message indicating that artifacts are saved in the default build folder, ./build/contracts:
Truffle and Ganache for Ethereum Smart Contract management

If you go there, you will find a JSON file (the artifacts) created by the compilation with details about your contract (ABI, bytecode, and so on).


As Truffle hasn't complained about any errors, you can move forward and deploy your contract. In other cases, you might get warning messages that you can safely ignore, or adjust your code accordingly.

 

Migrating the contract

We have now compiled our contract and configured Truffle to deploy the bytecode into the local blockchain network called my_ganache. To specify the deployment network, we need to run Truffle with the --network option, as follows: truffle migrate --network my_ganache.
It won’t connect unless you start the my_ganache network, right? This is what we will configure in the next step.

 

Setting up Ganache

If you remember, in the previous chapter,Peer-to-Peer Auctions in Ethereum, we introduced Ganache as a virtual blockchain for local testing. This tool is available under two formats:

In this recipe, we will use ganache-cli. Hence, install Ganache CLI globally using NPM, as follows:

npm install -g ganache-cli

Once installed, open a separate command line or tab and type in the following command:

ganache-cli -p 7545

As you may have guessed, the -p option specifies which port to listen on as Ganache CLI runs by default on 8545 (the same as Geth). If you are unsure about an option, refer to Ganache's GitHub page (https://github.com/trufflesuite/ganache-cli) where you can find ample information.


When Ganache starts up, it generates 10 accounts (unlocked) preloaded with a balance of 100 ether each, and displays their Ethereum addresses and the corresponding private keys, as shown in the following picture:
Truffle and Ganache for Ethereum Smart Contract management

These accounts will be very helpful to build raw transactions or import the created accounts later.

After this step, you can deploy the contract by running the truffle migrate --network my_ganache migration command.


After the successful execution of the deployment script, Truffle will output the
HelloWorld contract's address, as depicted here:
Truffle and Ganache for Ethereum Smart Contract management

At the same time, in Ganache's output, you should see the deployment transaction details, as shown in the following screenshot:
Truffle and Ganache for Ethereum Smart Contract management

You have now set up the necessary development and deployment environment to build a DApp, and learned how to compile and deploy a given contract into Truffle.


Next, we move on to the most exciting part: building the game. Let's start from the smart contract side.

To conclude this recipe, we like to recommend our Learn Hands-on Blockchain Ethereum Development & Get Certified in 30 Hrs, and Become Blockchain Certified Security Architect in 30 hours courses to those interested in pursuing a blockchain development career. This recipe is written by Brian Wu who is our senior Blockchain instructor in Washington DC. His Blockchain By Example book is highly recommended for learning more about blockchain development.

Related Training Courses

Hands-on Node.JS, MongoDB and Express.js Training
Advance JavaScript, jQuery Using JSON and Ajax
Learn Hands-on Blockchain Ethereum Development & Get Certified in 30 Hrs
Learn Blockchain Hyperledger Development & Get Certified in 30 Hrs
Become Blockchain Certified Security Architect in 30 hours
Blockchain Certified Solution Architect in 30 hours
Introduction to Python Programming
Object Oriented Programming with UML


Private and Custom Coding Classes

We offer private coding classes for beginners online and offline (at our Virginia site) with custom curriculum for most of our classes for $59 per hour online or $95 per hour in virginia. Give us a call or submit our Private Coding Classes for Beginners form to discuss your needs.


View Other Classes!