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
€13.98 €19.99
Paperback
€24.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

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/[email protected]/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
Estimated delivery fee Deliver to Italy

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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
€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 96.97
Hands-On Blockchain with Hyperledger
€41.99
Truffle Quick Start Guide
€24.99
Ethereum Smart Contract Development
€29.99
Total 96.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 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