© Debajani Mohanty 2018
Debajani MohantyEthereum for Architects and Developershttps://doi.org/10.1007/978-1-4842-4075-5_7

7. Frameworks: Truffle and Embark

Debajani Mohanty1 
(1)
Noida, Uttar Pradesh, India
 

“As society becomes more and more complex, cheating will in many ways become progressively easier and easier to do and harder to police or even understand.”

—Vitalik Buterin

So far we have discussed the Ethereum architecture, Solidity programming, and the Ethereum client, including setting it up and compiling, running, and debugging Dapps. That’s a lot of work, isn’t it? In this chapter, let’s discuss two leading frameworks, Truffle and Embark, that will provide a set of tools and boilerplate code for scaffolding Dapps for Ethereum. The frameworks will do much of the work themselves and leave you with only a few tasks.

Truffle

Truffle claims to be a “world-class development environment, testing framework, and asset pipeline for Ethereum, aiming to make life as an Ethereum developer easier.”

Install Truffle

Truffle is a node package and can be set up in seconds by running the node command on Windows, Linux, or macOS.
npm install –g truffle

By adding -g, you are installing Truffle globally. To test a contract created using Truffle, you will need to do it locally by running the ganache-cli command or through an Ethereum client. For now let’s use ganache-cli.

Create a Truffle Project

Creating a Truffle project is painless and super quick. Create a folder called myTruffle , go to the folder, and run the command shown here:
truffle init
Figure 7-1 shows the result.
../images/470312_1_En_7_Chapter/470312_1_En_7_Fig1_HTML.jpg
Figure 7-1

Running truffle init

In a few seconds, this will create a template project for you, as shown in Figure 7-2.
  • The contracts folder is where the smart contracts written in Solidity are stored.

  • The migrations folder contains scripts to manage the deployment of contracts onto the Ethereum network.

  • The test folder is where you write all your unit tests to test your smart contracts.

../images/470312_1_En_7_Chapter/470312_1_En_7_Fig2_HTML.png
Figure 7-2

Truffle project structure

truffle-config.js is also created as part of the truffle init command. Now you can compile the default project and then test it through the following commands. You can gradually update this default project and smart contract as per your needs.
truffle compile
truffle test
truffle deploy
Note that in Windows you may encounter an issue. Hence, add a .cmd extension to the truffle command, as shown here:
truffle.cmd compile
Figure 7-3 shows the result of the truffle.cmd compile command .
../images/470312_1_En_7_Chapter/470312_1_En_7_Fig3_HTML.jpg
Figure 7-3

truffle compile

The following command will unit test the MyContract.sol contract for some positive and negative scenarios, as shown in Figure 7-4:
truffle.cmd test
../images/470312_1_En_7_Chapter/470312_1_En_7_Fig4_HTML.jpg
Figure 7-4

truffle test

The following command will deploy the MyContract.sol contract, as shown in Figure 7-5:
truffle.cmd deploy
../images/470312_1_En_7_Chapter/470312_1_En_7_Fig5_HTML.jpg
Figure 7-5

truffle deploy

Provided MetaMask is already installed on your Chrome browser and ganache-cli is already running in the background, you can check the Truffle Dapp in your browser by visiting http://localhost:8080.

Now that you know how simple it is, why don’t you start coding with Truffle on your own?

If you’re still not sure, try the Pet Shop example on the Truffle web site, available at https://truffleframework.com/tutorials/pet-shop .

Unit Testing

If you want to write good unit testing, you can check out these two web sites:
https://truffleframework.com/tutorials/solidity-unit-tests
https://truffleframework.com/docs/getting_started/testing
Now let’s try something on your own. Listing 7-1 shows a smart contract named MyContract.Sol .
pragma solidity ^0.4.0;
contract MyContract {
    uint private amount;
    function MyContract()
    {
        amount = 101;
    }
    function updateAmount(uint newAmount)
        public
        returns (bool success)
    {
     require(newAmount > 100); /* Contract stores numbers greater than 100. */
     amount = newAmount;
     return true;
    }
    function getAmount()
        public
        returns (uint)
     {
        return amount;
      }
}
Listing 7-1

MyContract.Sol

Save the MyContract.Sol code to the contracts folder of the myTruffle project you created earlier.

Now within the test folder, paste MyContractTest.Sol as shown in Listing 7-2. This unit testing code checks the MyContract.Sol file for an initial value, which is 101, and for two other values, 97 and 122. For value 97, the contract should throw an exception because the require condition is used.
pragma solidity ^0.4.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/MyContract.sol";
contract MyContractTest {
function testInitialStoredValue() {
            MyContract mycontract = new MyContract();
            uint expected = 101;
            Assert.equal(mycontract.getAmount(), expected, "Initial amount set should be 101.");
    }
function testTheThrow() {
            MyContract mycontract = new MyContract();
            ThrowProxy throwproxy = new ThrowProxy(address(mycontract));
            MyContract(address(throwproxy)).updateAmount(97);
            bool r = throwproxy.execute.gas(200000)();
            Assert.isFalse(r, "Should be false because is should throw!");
    }
function testNoThrow() {
            MyContract mycontract = new MyContract();
            ThrowProxy throwproxy = new ThrowProxy(address(mycontract));
            MyContract(address(throwproxy)).updateAmount(122);
            bool r = throwproxy.execute.gas(200000)();
            Assert.isTrue(r, "Should be true!");
    }
}
// Proxy contract for testing throws
contract ThrowProxy {
  address public target;
  bytes data;
  function ThrowProxy(address _target) {
    target = _target;
  }
  //prime the data using the fallback function.
  function() {
    data = msg.data;
  }
  function execute() returns (bool) {
    return target.call(data);
  }
}
Listing 7-2

MyContractTest.Sol

Make sure ganache-cli is running in the background. Now run the following commands again:
truffle compile
For Windows, use truffle.cmd compile instead. If everything goes well, it won’t show any output.
truffle test
Similarly use "truffle.cmd test" for windows.
You can see whether the tests pass or fail on the command line, as shown in Figure 7-6 and Listing 7-3.
../images/470312_1_En_7_Chapter/470312_1_En_7_Fig6_HTML.jpg
Figure 7-6

Truffle unit testing

F:ethereummyTruffle>truffle.cmd test
Using network 'development'.
Compiling .contractsConvertLib.sol...
Compiling .contractsMetaCoin.sol...
Compiling .contractsMyContract.sol...
Compiling . estMyContractTest.sol...
Compiling . estTestMetacoin.sol...
Compiling . estTestMyContract.sol...
Compiling truffle/Assert.sol...
Compiling truffle/DeployedAddresses.sol...
Listing 7-3

Truffle unit testing

OpenZeppelin: Securing Solidity Code

Smart contracts deployed in public networks are susceptible to loads of risk because money is involved. Zeppelin, which started as a smart contract auditing service, has added a layer of security for your Solidity smart contracts deployed on public Ethereum blockchains. Its product OpenZeppelin claims to be a “battle-tested framework of reusable smart contracts for Ethereum and other EVM and eWASM blockchains.”

OpenZeppelin integrates with Truffle. Especially when your code is complex and involves loops and the possibility of failures while calling an external service, OpenZepplin is a good option to overcome vulnerabilities. You can try it yourself; learn more here:
https://truffleframework.com/tutorials/robust-smart-contracts-with-openzeppelin

Truffle Road Map

Here is an interesting road map of Truffle in the near future:
  • Truffle 4.0 will come with a debugger, an improved development and testing experience, and more.

  • Drizzle is a front-end framework for React and Angular that will easily connect to Truffle-based projects.

  • Project Hotcakes is a full-stack suite for web applications.

  • Live is a browser-based, interactive Truffle IDE. 

Embark

Though Truffle claims to be the “most popular development framework for Ethereum with a mission to make your life a whole lot easier,” I found Embark equally good. In fact, many features that I was looking for elsewhere on the Internet appear in Embark. The integration with IPFS is well explained, and the unit testing is just superb. Now it’s time to try it.

Install Embark

Let’s install and run the sample project from the Embark web site. Follow these steps:
  1. 1.
    Install Embark.
    npm -g install embark
     
  2. 2.
    If you already have the previous version embark-framework, then uninstall it and install the new one.
    npm uninstall -g embark-framework
    then
    npm install -g embark
     

Create an Embark Project

Now run the following on the command line, as shown in Figure 7-7 and Listing 7-4, and it will create a project template called embark_demo for you:
embark demo
../images/470312_1_En_7_Chapter/470312_1_En_7_Fig7_HTML.jpg
Figure 7-7

Creating embark_demo

F:ethereumembark>embark demo
Initializing Embark Template....
Installing packages...
Init complete
App ready at embark_demo
-------------------
Next steps:
-> cd embark_demo
-> embark blockchain or embark simulator
   open another console in the same directory and run
-> embark run
For more info go to http://embark.status.im
Listing 7-4

Creating embark_demo

Go to that folder and run the following command to run ganache-cli , as shown in Figure 7-8 and Listing 7-5:
embark simulator
../images/470312_1_En_7_Chapter/470312_1_En_7_Fig8_HTML.jpg
Figure 7-8

Embark simulator

F:ethereumembarkembark_demo>embark simulator
Ganache CLI v6.1.8 (ganache-core: 2.2.1)
Available Accounts
==================
(0) 0xb8d851486d1c953e31a44374aca11151d49b8bb3 (~100 ETH)
(1) 0xf6d5c6d500cac10ee7e6efb5c1b479cfb789950a (~100 ETH)
(2) 0xf09324e7a1e2821c2f7a4a47675f9cf0b1a5eb7f (~100 ETH)
(3) 0xfbaf82a227dcebd2f9334496658801f63299ba24 (~100 ETH)
Listing 7-5

Embark Simulator

You can also run the following to run a real node:
embark blockChain
From another window from the same folder, run the following, and you will see the console, as shown in Figure 7-9 and Listing 7-6:
embark run
../images/470312_1_En_7_Chapter/470312_1_En_7_Fig9_HTML.jpg
Figure 7-9

Running embark run

deploying contracts                                │
│ deploying SimpleStorage with 134157 gas           │
│ SimpleStorage deployed at 0x04D45b51fe4f00b4478F8b0719Fa779f14c8A194        │
│ finished deploying contracts                      │
│ ready to watch file changes                       │
│ webserver available at http://localhost:8000
Listing 7-6

Running embark run

The server is now running over port 8000 on local. Let’s open http://localhost:8000 in the browser and check the web console, as shown in Figure 7-10.
../images/470312_1_En_7_Chapter/470312_1_En_7_Fig10_HTML.png
Figure 7-10

Embark running on local

Unit Testing

Note that the contracts are located in the contracts folder and the unit tests are in the test folder. The default project already comes with a contract called simple_storage.sol in the contracts folder.

Also note that the unit tests are written in JavaScript here, which is great news for JavaScript developers. Open the simple_storage_spec.js file in the test folder that comes by default and add more contracts as well as tests to learn more.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.62.105