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
Truffle Quick Start Guide
Truffle Quick Start Guide

Truffle Quick Start Guide: Learn the fundamentals of Ethereum development

eBook
$9.99 $25.99
Paperback
$32.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

Truffle Quick Start Guide

Truffle for Decentralized Applications

This chapter will introduce you to Truffle, and explain why it is used and how it works from a high level. Moreover, this chapter will demonstrate how JavaScript, Solidity, and web3 interact inside the basic Truffle environment, and how Truffle gives the developer control over all three said aspects of a decentralized application. Lastly, you will build a small project in Truffle and understand its power.

Specifically, you will:

  • Learn and understand the reasons for the use of Truffle
  • Learn and understand how Truffle harnesses popular technologies, such as JavaScript and web3, from a high level
  • Learn and understand how to write basic decentralized applications in Truffle

Technical requirements

What is Truffle?

In short, Truffle is a framework to write, compile, deploy, and test decentralized applications on Ethereum blockchains. For this chapter, you can also think of Truffle as a framework that attempts to seamlessly integrate smart contract development and traditional web development.

Granularly, within the Truffle environment, you can write JavaScript for the frontend, Solidity for smart contracts, and use web3 as a bridge to connect various blockchain networks to the client.

If you are not familiar with web3, or you need a refresher on Solidity, worry not. The subsequent chapter will cover these two technologies in sufficient detail before you start building more complex decentralized applications.

For now, it is enough to know that Truffle combines JavaScript, Solidity, and web3 to allow you to write complete and testable decentralized applications:

Can you write decentralized applications without Truffle? Sure you can. Truffle simply makes the process of compiling, building, and migrating your application easier by automating certain monotonous aspects.

You will see how this is done toward the end of this chapter when you build a small but complete decentralized application. I will walk you through code snippets, provide a working repository for reference, and explain to you fundamental build concepts as you write code. Most importantly, I want to ensure you start coding as soon as possible. So, let's get started.

Let's build a mini Dapp

The best way to start is with a simple Hello World app, but we can do better than that. Let's build a simple Dapp that you will have the chance to expand upon throughout this entire book. This way, you can build a Dapp like a true software engineer; that is, you will iteratively add features and make improvements to your application as you see fit.

Let's build a to-do list

Productivity is a virtue that resonates a lot with software engineers and developers alike. In the book Algorithms to Live By, Brian Christian states that:

"When the future is foggy, it turns out you don't need a calendar—just a to-do list."

Many of us have come to know that a to-do list helps to organize chaos.

So, let's create a to-do list, except with a little twist. This will be a to-do list on the blockchain, where you get others to do your work for you. Of course, you have to pay them with a token, call it TodoCoin, for their work.

You will create this app as the owner of the contract, and the individuals performing your tasks will be referred to as doers.

As an owner, you must be able to:

  • Create a task with a title, description, and TodoCoin reward amount
  • Accept a completed task
  • Reject a completed task
  • Reward a doer for successful review of a completed task

As a doer, you must be able to:

  1. Start a task
  2. Finish a task
  3. Withdraw owed rewards for successful reviews of completed tasks

If this seems like a handful, worry not. You will not build all specifications of this Dapp in this chapter. For this chapter, as promised, you will build a simplified version of this Dapp. Later, see if you can slowly start building the other specifications on your own.

For this chapter, you will simply do the following:

  • Allow an owner to create the contract
  • Allow an owner to transfer a TodoCoin reward to a specified address

That's it. You will assume three things:

  • The task has been successfully completed and reviewed off-chain
  • The recipient of the reward is a valid doer
  • The reward amount is the correct amount for the task

Also, a decentralized application is not complete without a decent user interface. So, you will build a simple interface that allows the owner of a contract to enter a TodoCoin reward amount and transfer it to an address of their choice.

The final version will look like this:

What frameworks will we be using?

The only framework you will use for this chapter is Truffle, actually. This way, you can focus purely on the Truffle elements of this mini Dapp without getting muddled in implementation details of other frameworks. But don't worry, in later chapters, you will learn how to integrate Truffle with Angular, React, and Node.

Initializing a Truffle project

First things first. Head over to Google. Then, perform the following:

  • Search for truffle webpack.
  • The first result should be a Github link (https://github.com/trufflesuite/truffle-init-webpack). Click it.
  • Follow the installation steps. In other words, perform the following:
    1. Open a terminal window, and install Truffle globally with npm install -g truffle.
    2. Create a new folder called truffle-practice.
    3. Inside truffle-practice create another folder called chapter1.
    4. Go into the chapter1 folder.
    5. Download the truffle Webpack box. This also takes care of installing the necessary dependencies: truffle unbox webpack.

The structure inside of the truffle-practice folder should look like this—the important folders and files are in bold:

└── chapter1
├── app
│ ├── index.html
│ ├──; javascripts
│ │ └── app.js
│ └── stylesheets
│ └── app.css
├── contracts
│ ├── ConvertLib.sol
│ ├── MetaCoin.sol
│ └── Migrations.sol
├── migrations
│ ├── 1_initial_migration.js
│ └── 2_deploy_contracts.js
├── package-lock.json
├── package.json
├── test
│ ├── TestMetacoin.sol
│ └── metacoin.js
├── truffle.js
└── webpack.config.js

Your structure may look a little different depending on the time you ran the preceding steps, but the folders of concern are /app, /contracts, /migrations, and /test. The root files of concern are package.json and truffle.js.

Peeping into the folders

Here are the important folders:

  • app: This folder contains the JavaScript, HTML, and CSS files of your decentralized application. Notice how we have a folder for /javascripts and /stylesheets, and a root index.html file.
  • contracts: This folder contains the smart contracts for your decentralized application. Notice the Solidity files ConvertLib.sol, MetaCoin.sol, and Migrations.sol.
  • migrations: This folder contains the scripts to migrate and deploy our smart contracts properly to various Ethereum blockchains. You will see this in more detail in Chapter 4, Migrating Your Dapp to Ethereum Blockchains.
  • tests: This folder contains the files with unit and integration tests. You will see this in more detail in Chapter 6, Testing Your Dapp.

Peeping into the root files

Here are the important root files:

  • package.json: This is a standard file that includes all the production and development dependencies of our project. Have a look through the dependencies if you are interested.
  • truffle.js: This file contains configuration details about migrating your smart contracts to a specific Ethereum network. For now, you will simply connect to a local network. You will learn how to migrate your smart contract to various Ethereum networks in Chapter 4, Migrating Your Dapp to Ethereum Blockchains.

Here's a quick snippet:

// Allows us to use ES6 in our migrations and tests.
require('babel-register')

module.exports = {
networks: {
development: {
host: '127.0.0.1',
port: 7545,
network_id: '*' // Match any network id
}
}
}

Housekeeping before we write code

We need to delete a few files and folders first. This is because we won't be working with the default Solidity, JavaScript, and HTML files that come with the Truffle starter project. We will be building everything from scratch, so we need to get rid of a few things; that way, you can see how everything works from the ground up.

Delete a few unnecessary files:

  • contracts/MetaCoin.sol
  • contracts/ConvertLib.sol

Delete all the contents inside the following files, but do not delete the actual files:

  • app/javascripts/app.js
  • app/stylesheets/app.css
  • app/index.html

Writing our first smart contract

To start writing our first smart contract, we must do the following:

  1. Head over to https://github.com/PacktPublishing/Truffle-Quick-Start-Guide and clone it. That's where the fully working projects for each chapter are. You can git clone the entire repository to keep as a reference when working through this chapter.
  2. To ensure we follow proper formatting and camel-case naming conventions, replace Migrations.sol with the contents of https://github.com/PacktPublishing/Truffle-Quick-Start-Guide/blob/master/chapter1/contracts/Migrations.sol.
    • Unfortunately, the original Migrations.sol file is poorly formatted and uses snake-case variable naming, so this step is necessary
  1. Create a new file under /contracts, called TaskMaster.sol.
  • This is where your logic for instantiating your to-do list contract and rewarding a doer will live.

Start by creating the constructor, and define an array to hold the current TodoCoin balances of everyone in the contract:

pragma solidity ^0.4.17;


contract TaskMaster {
mapping (address => uint) public balances; // balances of everyone

function TaskMaster() public {
balances[msg.sender] = 10000;
}
}

Notice how we hardcode a value of 10000 to the initiator of this contract. Let's go with this for now. We can think of this to mean that the initiator of the TaskMaster contract starts off with a balance of 10000 TodoCoins.

Adding an owner

It's a good idea to have an owner of a contract and give them the sole right to perform admin-level actions such as the rewarding of a doer, so let's define and set an owner:

pragma solidity ^0.4.17;


contract TaskMaster {
mapping (address => uint) public balances; // balances of everyone
address public owner; // owner of the contract

function TaskMaster() public {
owner = msg.sender;
balances[msg.sender] = 10000;
}
}

The owner of the contract is set to msg.sender, the address instantiating the contract. You will learn more about msg.sender and other Solidity special variables in the next chapter.

Creating a reward method

This will be invoked by the owner to reward a doer for their successful completion of a task:

pragma solidity ^0.4.17;


contract TaskMaster {
mapping (address => uint) public balances; // balances of everyone
address public owner; // owner of the contract

function TaskMaster() public {
owner = msg.sender;
balances[msg.sender] = 10000;
}

function reward(address doer, uint rewardAmount)
public
returns(bool sufficientFunds)
{
balances[msg.sender] -= rewardAmount;
balances[doer] += rewardAmount;
return sufficientFunds;
}
}

This function accepts the following:

  • an address for the doer
  • an integer amount for their reward

We are almost there—we need to add some necessary security touches.

Notice how we are not performing a real transfer of ETH, but rather we simply decrement the balance of the owner and increment the balance of the doer. The reason we don't perform a real transfer here is because we simply hard-coded a balance value of 10000 and made up a token called TodoCoin. Remember, our goal in this chapter is to get a fully functioning Dapp using Truffle.

Securing your contract with modifiers

To ensure that our contract is secure, we ensure the following:

  • Only an owner can call the reward function
  • The owner of the contract has sufficient funds to transfer to the doer

Let's add a few modifiers, isOwner and hasSufficientFunds:

pragma solidity ^0.4.17;


contract TaskMaster {
mapping (address => uint) public balances; // balances of everyone
address public owner; // owner of the contract

function TaskMaster() public {
owner = msg.sender;
balances[msg.sender] = 10000;
}

function reward(address doer, uint rewardAmount)
public
isOwner()
hasSufficientFunds(rewardAmount)
returns(bool sufficientFunds)
{
balances[msg.sender] -= rewardAmount;
balances[doer] += rewardAmount;
return sufficientFunds;
}

modifier isOwner() {
require(msg.sender == owner);
_;
}

modifier hasSufficientFunds(uint rewardAmount) {
require(balances[msg.sender] >= rewardAmount);
_;
}
}

isOwner requires that the sender of the reward function is the owner of the contract.
hasSufficientFunds requires that the sender of the contract has enough funds to reward the doer.

Adding a utility method

Utility methods help us get data from our contract without modifying the state.

   function getBalance(address addr) public view returns(uint) {
return balances[addr];
}

This function accepts an address and returns the balance of the passed-in address. Notice how it is marked with view. The view modifier signifies that this function does not modify the storage state of the contract. You will learn more about this in Chapter 2, Web3 and Solidity in Truffle, where we will refresh Solidity fundamentals.

Wrapping up

Your final TaskMaster.sol file should look like this:

pragma solidity ^0.4.17;


contract TaskMaster {
mapping (address => uint) public balances; // balances of everyone
address public owner; // owner of the contract

function TaskMaster() public {
owner = msg.sender;
balances[msg.sender] = 10000;
}

function reward(address doer, uint rewardAmount)
public
isOwner()
hasSufficientFunds(rewardAmount)
returns(bool sufficientFunds)
{
balances[msg.sender] -= rewardAmount;
balances[doer] += rewardAmount;
return sufficientFunds;
}

function getBalance(address addr) public view returns(uint) {
return balances[addr];
}

modifier isOwner() {
require(msg.sender == owner);
_;
}

modifier hasSufficientFunds(uint rewardAmount) {
require(balances[msg.sender] >= rewardAmount);
_;
}
}

You can also find this file in the repo, under contracts (https://github.com/PacktPublishing/Truffle-Quick-Start-Guide/blob/master/chapter1/contracts/TaskMaster.sol).

Now that we've created a full TaskMaster.sol file, you can do the following bit of housekeeping.

Delete all contents of migrations/2_deploy_contracts.js and replace them with the following code:

var TaskMaster = artifacts.require("./TaskMaster.sol");

module.exports = function(deployer) {
deployer.deploy(TaskMaster);
};

This specifies that TaskMaster.sol should be deployed to a blockchain. You will learn more about migrations in Chapter 4, Migrating Your Dapp to Ethereum Blockchains.

Building a user interface

Let's create a quick and easy UI for this. It will allow the owner to specify a reward amount and the doer's addresses. It will also display the owner's balance in TodoCoin at all times.

Here's what your final UI will look like:

Simple styling

To style, we will use the Tachyons CSS library. It is a utility library that allows you to style your app while writing as little CSS as possible. You can view all the styles here at http://tachyons.io/docs/table-of-styles/.

Performing the build steps

To see our Dapp in action, we need to perform the following build steps. Follow them precisely to ensure we get a clean build every time. Essentially, we are compiling and migrating our contracts, then serving our web content.

  1. cd chapter1.
  2. truffle develop.
  3. Inside the Truffle development console, run the following:
    1. compile (this compiles our contracts)
    2. migrate (this migrates our contract to the network specified in truffle.js)
  1. In another terminal window/tab, in the chapter1 folder, run npm run dev.
  2. Navigate to http://localhost:8080/#/.
Depending on the version of truffle you install, you may see warnings thrown in your console after you compile your contracts. For example, at the time of the writing of this book, constructors share the same name as the contract (that is TaskMaster). But in newer versions of truffle, it is preferred to use the constructor(...) { ... } syntax instead. Since these are warnings, you can choose to adjust your code based on the warning, or not, and simply continue.

The following steps you just performed are the necessary build steps. I will now refer to them as Build Steps, because you will be doing this often throughout this book.

Once you run the Build Steps, you will notice a blank screen. That’s because app/index.html is empty. Let's add some content:

<!DOCTYPE html>
<html>
<head>
<title>Truffle - Mini Dapp</title>
<link rel="stylesheet"
href="https://unpkg.com/tachyons@4.9.1/css/tachyons.min.css"/>
<script src="./app.js"></script>
</head>
<body class="sans-serif pa4">
</body>
</html>

We created a title in our HTML page called Truffle - Mini Dapp, and we added a few CSS references:

  • A CDN to the Tachyons library
  • A reference to the currently empty app.js
  • A body tag with a sans-serif font and padding on all sides

Now, let's add the form. Add the following piece of code inside the body tag:

<div class="tc f2 mt6 near-black">Reward a doer for their hard work - send them TodoCoin</div>
<div class="pa4 mt4 bg-white shadow-1 br2 tc mw7 center">
<div class="f3 dark-green">Send TodoCoin</div>
<form class="pt3 pb4 ph5-l black-60">
<fieldset class="ba b--transparent ph0 mh0">
<div class="mt3 ph3 pa0-l">
<input
class="pa3 input-reset ba b--black-30 br2 bg-white-smoke w-
100"

type="number"
id="todoCoinReward"
placeholder="Amount in TodoCoin">
</div>
<div class="mt3 ph3 pa0-l">
<input
class="pa3 input-reset ba b--black-30 br2 bg-white-smoke w-
100"

type="text"
id="doer"
placeholder="Address">
</div>
</fieldset>
</form>
<button
class="white pa3 ph4 bg-green br2 f3 b pointer">→
</button>

</div>

Your screen should now look like this:

Take a few minutes to look through the HTML and CSS content and understand how this form is being rendered. It's just CSS and HTML, and the classes are all Tachyons classes.

Now, let's add an absolutely positioned div to show the owner's balance. Add the following line right beneath the opening body tag:

  <div class="absolute right-1 top-1 tc pt4 left f5 pb3 bg-black-80 w4 
h4 shadow-2 br4 white">You have
<div class="f3 mt3">
<span id="accountBalance" class="b"></span>
TodoCoin
</div>
</div>

You'll notice that it does not specify your balance of 10000 TodoCoin, but rather just looks like this:

This is because you have not written any JavaScript to connect to your smart contract's data yet. That will come very shortly.

And lastly, let's add a div to represent the transaction status:

<div id="transactionStatus" class="pt4"></div>

Your whole screen should now look like this:

And; your index.html file should look like the one here: https://github.com/PacktPublishing/Truffle-Quick-Start-Guide/blob/master/chapter1/app/index.html.

Let's write some JavaScript

Now, let's write some JavaScript and make use of the web3 library. Don't worry if you are not familiar with web3, you will see more of that in Chapter 2, Web3 and Solidity in Truffle. For now, you will interact with web3 just enough to get a fully working Dapp.

In app.js, paste the following code:

import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'
import taskMasterArtifacts from '../../build/contracts/TaskMaster.json'

By pasting in the preceding code, you just imported the following:

  • Your CSS file, for Webpack bundling and build purposes (not important for now)
  • web3—this is to connect with Ethereum blockchains
  • truffle-contractan Ethereum contract abstraction for the browser that allows you to invoke public smart contract methods from plain old JavaScript objects
  • A JSON representation of your TaskMaster.sol contract file

Why do we import a JSON file and not a Solidity file?

Before you deploy a contract to a blockchain network, your contract needs to be compiled into bytecode understood by the EVM (Ethereum Virtual Machine), and provide an ABI (application binary interface). The ABI is the process for encoding your Solidity contract to be understood by the EVM, and this file is in a JSON format. When you run compile, you will notice that a build folder is created along with JSON data of your contracts.

Under our import statements, let's declare and initialize a few variables:

var TaskMaster = contract(taskMasterArtifacts);
var ownerAccount;

We use contract to get the JavaScript abstraction of our contract. This is necessary to call public functions such as getBalance and reward. As you can see, contract is a function that accepts your contract's ABI JSON file.

Next, we need to tell web3 which blockchain network to connect to:

window.addEventListener('load', function() {
window.web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:9545"));
});

On the load event of the window, we:

  • Set web3 as a window object and give it our localhost (http://127.0.0.1:9545) as the blockchain network provider
  • You will learn more about web3 providers in subsequent chapters

The moral of this story is that web3 requires a blockchain provider to allow us to interact with the said blockchain on the frontend. Notice that when you enter truffle develop, it takes you to a console that looks like this:

In particular, notice the statement at the top: Truffle Develop started at http://localhost:9545/. This is the same URL and port that we specified in the following code block.

Also, notice that in our local blockchain we have nine accounts with their respective private keys. These nine accounts are all the accounts in our mini, private, and local blockchain:

window.web3 = new Web3(
new Web3.providers.HttpProvider("http://127.0.0.1:9545")
);

Essentially, we are using a local copy of a mock blockchain.

Next, let's create a global object called TaskMasterApp to encapsulate logic involving listening for click events and performing DOM updates. Above the web3 code, paste the following code:

window.TaskMasterApp = {};

Our TaskMaster object also needs to be made aware of the current web3 provider. Let's add a method to TaskMasterApp:

setWeb3Provider: function() {
TaskMaster.setProvider(web3.currentProvider);
}

We'll call this method setWeb3Provider, because we want to set a provider for web3.

You can now paste the following as the final step inside the load callback, after setting a provider for web3:

TaskMasterApp.setWeb3Provider();

Go to https://localhost:8080/#/. You should see no errors, and nothing in the console.

Next, we should get all accounts associated with the current web3 provider, and set our ownerAccount variable to the first account. Let's add another method to TaskMasterApp:

getAccounts: function () {
var self = this;
web3.eth.getAccounts(function(error, accounts) {
if (error != null) {
alert("Sorry, something went wrong. We couldn't fetch your accounts.");
return;
}

if (!accounts.length) {
alert("Sorry, no errors, but we couldn't get any accounts - Make sure your Ethereum client is configured correctly.");
return;
}

ownerAccount = accounts[0];
})
},

As you can see, we are getting the first account and setting it to our ownerAccount variable. Also, you'll notice that web3.eth.getAccounts is not the most elegantly designed, as it requires a callback function. In later chapters, we will work with promises to avoid callback hell.

You'll notice that we don't use ES6 syntax here (var instead of const, and so forth). This is because we are still writing in vanilla JavaScript.

Remember, we are only focusing on one thing at a time. Once we get the fundamentals of Truffle, web3, and Solidity down solidly, we'll start looking into modern JavaScript technologies such as Angular, React, and Node.

Inside of the window load function, after we call TaskMasterApp.setWeb3Provider(), let's make a call to get all accounts:

TaskMasterApp.getAccounts();

Now that we have accounts, we can find a way to populate our status div. Let's create a method on TaskMasterApp called refreshAccountBalance. We are calling it refreshAccountBalance because we'll invoke this method again when we send ether to a doer to see the DOM update instantly. For this reason, we opt for a more descriptive name than, say, setAccountBalance:

  refreshAccountBalance: function() {
var self = this;

TaskMaster.deployed()
.then(function(taskMasterInstance) {
return taskMasterInstance.getBalance.call(ownerAccount, {
from: ownerAccount
});
}).then(function(value) {
document.getElementById("accountBalance").innerHTML =
value.valueOf();
document.getElementById("accountBalance").style.color =
"white";
}).catch(function(e) {
console.log(e);
});
}
Notice how we call TaskMaster.deployed(). This returns a promise that resolves to a usable instance.

Then, we can get the owner's balance by calling taskMasterInstance.getBalance.call(account, {from: account}).

In this case, msg.sender is the owner's account.

Let's see it in action. Inside TaskMasterApp.getAccounts, add the following line of code at the very end:

self.refreshAccountBalance();

Now, you should see the balance updated on the DOM:

Now, let's create a method to reward a doer:

  rewardDoer: function() {
var self = this;

var todoCoinReward = +document.getElementById("todoCoinReward").value;
var doer = document.getElementById("doer").value;

TaskMaster.deployed()
.then(function(taskMasterInstance) {
return taskMasterInstance.reward(doer, todoCoinReward, {
from: ownerAccount
});
}).then(function() {
self.refreshAccountBalance();
}).catch(function(e) {
console.log(e);
});
}

We invoke rewardDoer and pass in a receiver and amount, and the account that initiates this call is ownerAccount. That's msg.sender. Once the promise resolves, we refresh the owner's balance.

We need to attach a click handler on our button too:

    <button
class="white pa3 ph4 bg-green br2 f3 b pointer"
onclick="TaskMasterApp.rewardDoer()">→
</button>

Enter any reward amount you wish, and see the balance decrease by that amount. Also, make sure you enter a valid Ethereum address.

I transferred 22 TodoCoin to 0x85db1e131b6c5c0c7eec98fed091a441ed856424. Here's what my screen looks like:

Once I submitted, my balance refreshed:

Now, let's see one last method involving TaskMasterApp to update our status div:

updateTransactionStatus: function(statusMessage) {
document.getElementById("transactionStatus").innerHTML = statusMessage;
}

Now, you can view the transaction status on the UI. Send some more TodoCoin to a doer, and look at the bottom of the screen. You should see the following words:

Transaction complete!

References

Christian, Brian, and Tom Griffiths. Algorithms to Live By. Henry Holt and Company, 2016.

Summary

That's it. Congratulations on building your first Dapp; you've covered a lot of ground here! You can find the fully working Dapp that we built in this chapter over here: https://github.com/PacktPublishing/Truffle-Quick-Start-Guide/tree/master/chapter1.

If you've noticed, we haven't yet included proper error handling or unit tests, or migrations. We will cover all of that in subsequent chapters. I hope you enjoyed building this mini Dapp, and that you now have a solid understanding of the power of Truffle.

See you in Chapter 2, Web3 and Solidity in Truffle.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Build your first Ethereum Dapp with Truffle: the most popular Ethereum development framework
  • Build, compile, and deploy smart contracts in your development environment
  • Embrace Blockchains and utilize it to create new generation of secured and scalable apps

Description

Truffle is a world-class development environment, testing framework and asset pipeline for Ethereum, aiming to make life as an Ethereum developer easier. If you are a web developer wanting to try your hand at developing Dapps with Truffle, then this is the book for you. This book will teach you to write smart contracts and build Dapps with Truffle. You will begin with covering the basics of Truffle, briefly explaining how it integrates Solidity and Web3, in orderto start building a mini decentralized application. Also, you will dive into migration, testing and integrating Truffle with the use of popular JavaScript frameworks. Lastly, you will ship your decentralized application and package it into a product. Moreover, you will go through the best practices in Truffle,so as to increase your proficiency in building Dapps with Truffle. By the end of the book, you will be able to write smart contracts and build decentralized applications with Truffle on Ethereum blockchains.

Who is this book for?

This book is for web developers who are interested in the new world blockchain. Some basic understanding of JavaScript and web services is required. No prior knowledge of Decentralized applications or blockchain is required.

What you will learn

  • Understand the fundamentals of Truffle and Web3
  • Build a decentralized application with Truffle, while choosing the correct Ethereum client
  • Connect your Dapp to Ethereum clients including Geth, Parity, and Ganache
  • Migrate and test your Dapp with the correct networks such as Ropsten and Rinkeby
  • Package a decentralized application into a user-friendly product by integrating Truffle with JavaScript frameworks such as Angular, React and Vue
  • Explore tools including Ethereum Package Manager, the Registrar and browser wallets, and exploit third-party smart contract libraries.
  • Evaluate the common migration pitfalls and how to mitigate them

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Jun 27, 2018
Length: 170 pages
Edition : 1st
Language : English
ISBN-13 : 9781789132540
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 : Jun 27, 2018
Length: 170 pages
Edition : 1st
Language : English
ISBN-13 : 9781789132540
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 $ 126.97
Hands-On Blockchain with Hyperledger
$54.99
Truffle Quick Start Guide
$32.99
Ethereum Smart Contract Development
$38.99
Total $ 126.97 Stars icon
Banner background image

Table of Contents

8 Chapters
Truffle for Decentralized Applications Chevron down icon Chevron up icon
Web3 and Solidity in Truffle Chevron down icon Chevron up icon
Choosing an Ethereum Client for Your Dapp Chevron down icon Chevron up icon
Migrating Your Dapp to Ethereum Blockchains Chevron down icon Chevron up icon
Truffle and Popular JavaScript Technologies Chevron down icon Chevron up icon
Testing Your Dapp Chevron down icon Chevron up icon
Truffle Gotchas and Best Practices Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Ali Jul 15, 2018
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I am a review of this book. This book is easy to understand and each topic is expalined in depth with examples.It will give you good start in testing and deployment of dapp on mainnet or testnets.
Amazon Verified review Amazon
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.