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 mini Dapp
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:
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:
- Start a task
- Finish a task
- 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:
- Open a terminal window, and install Truffle globally with npm install -g truffle.
- Create a new folder called truffle-practice.
- Inside truffle-practice create another folder called chapter1.
- Go into the chapter1 folder.
- 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:
- 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.
- 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
- 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.
- cd chapter1.
- truffle develop.
- Inside the Truffle development console, run the following:
- compile (this compiles our contracts)
- migrate (this migrates our contract to the network specified in truffle.js)
- In another terminal window/tab, in the chapter1 folder, run npm run dev.
- Navigate to http://localhost:8080/#/.
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-contract—an 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.
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);
});
}
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!