codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Dapp Scratch: a CLI for Building Dapps (and tutorial for building your first one)

dapp-scratch is a command line interface (CLI) that helps you build Decentralized Apps (dApps/DApps/dapps) from Solidity contracts. It takes a contract’s Application Binary Interface (ABI) and outputs a Javascript module that handles all the basic interaction for use in your project. It’s called dapp-scratch because it helps you build your dapp from scratch. (Github Repo)

Here’s how it works:

$ npm install -g dapp-scratch
$ dapp-scratch -h
Usage: dapp-scratch build [options]Options: -V, --version output the version number
-c, --contract [contract] Contract name or location
-b, --abi [abi] ABI name or location
-a, --address [address] Address of deployed contract
-h, --help output usage information
Commands:build Build a module from Contract or ABI
test Generate a contract for testing

Running dapp-scratch on a Contract’s ABI will generate a module inside a directory called dapp-module in your project’s root. After importing that module into your app you’ll be able to access your contract right away.

$ dapp-scratch build FeverContract
Contract found at ./build/contracts/FeverContract.sol
web3 installed
web3-provider-engine installed
@aeternity/id-manager-provider installed
Module Created at ./dapp-module/FeverContract/index.js
/*
* To use FeverContract just import it into your project:
*/
const FeverContract = require('./dapp-module/FeverContract')
let feverContract = new FeverContract()
feverContract.helloWorld()
/*
* Have Fun : )
*/

The module connects to any available instance of Web3—whether via Metamask, Mist, AE Identity Manager, Status, Cipher, Toshi, Ethers.io or any other injected Web3Provider. It polls the currently unlocked account and network to watch for changes. And it has wrapper functions for each of the methods found in the contract’s ABI. These are the features I’ve found myself building over and over again, so I figured automating that process and settling on best practices might be useful. The project is brand new and I’m not 100% confident in any of the conventions, so if you have an opinion on best practices please fork the project and submit a PR. I’d love to know how you prefer interacting with your contracts 📡

The Tutorial

In this tutorial we’ll be using:

Making Dapp Scratch Fever 🤒

The following is a tutorial for building a Vue.js app that uses a module generated from dapp-scratch to interact with a contract. We’ll use Vue.js for the Javascript framework and Truffle to compile and deploy our Solidity contracts. The app is called Dapp Scratch Fever because the contract has a uint8 variable called temperature. You can increase and decrease the temperature and then ask the contract if it has a fever. It will return true when the temperature is over 100ºF and false when it is below.

DISCLAIMER: I decided to use Fahrenheit for the body temperature because I think it’s way better to use a big round number like 💯 as the threshold between health and sickness. Apologies to all those who prefer the more rational (but less exciting) metric system 😬🇺🇸

Step 1—Using Vue.js for an App

I like to use vue-cli for building Vue.js boilerplate apps. To do so, first install the tool then run it with your desired options and follow the prompt that follows. I’ll use options for building with Webpack so that I can have all the bells and whistles that come with it.

$ npm install vue-cli -g
$ vue init webpack dapp-scratch-fever
...
$ cd dapp-scratch-fever
$ npm install

Step 2—Using Truffle for the Contract

Next we need to build a contract and compile it with Truffle. We’ll begin by installing Truffle and initializing the project, then write and deploy the contract.

$ npm install truffle -g
...
$ truffle init

Then create a new contract at ./contracts/FeverContract.sol directory and open it in your favorite editor.

pragma solidity ^0.4.17;contract FeverContract {  uint8 temperature;  function FeverContract() {
temperature = 98;
}
function getTemperature () public constant returns(uint8) {
return temperature;
}
function hasFever () public constant returns(bool) {
return temperature > 100;
}
function increaseTemp () public returns(uint8) {
if (temperature > 110) revert();
temperature += 1;
return temperature;
}
function decreaseTemp () public returns(uint8) {
if (temperature < 95) revert();
temperature -= 1;
return temperature;
}
}

Here you can see we have all the aspects of the contract described earlier, a temperature, transactional functions to increaseTemp() and to decreaseTemp() as well as constant functions to getTemperature() and check whether the contract hasFever() or not.

Next add new truffle migration instructions to the migrations directory at ./migrations/2_deploy_contracts.js. These can look as follows:

var FeverContract = artifacts.require("./FeverContract.sol");module.exports = function(deployer, helper, accounts) {
return deployer.deploy(FeverContract)
}

Now we can run truffle’s test network, compile and deploy the contract.

$ truffle develop
truffle(develop)> deploy

Step 3—Using dapp-scratch to generate a module

Now we’re ready to generate our Javascript module from the ABI file that truffle created while compiling and deploying our contract to the local test network. First we need to install the dapp-scratch CLI, then we can run it.

$ npm install dapp-scratch -g
...
$ dapp-scratch build FeverContract

The program will look for your ABI and then check your package.json for the necessary dependencies. Once those have been installed it will create a new directory called dapp-scratch-wrapper with your new DappScratch module inside.

UPDATE: dapp-scratch has been updated so some path names in this image are different from what you’ll encounter

The first thing you want to do is go back to your terminal window running your truffle test network and look for the address of the deployed FeverContract.

Copy this address and add it to your new FeverContract module at ./dapp-module/FeverContract/index.js (You can also include the address with the flags -a or --Address when first running dapp-scratch buildto automate this step)

Now we can import the module into our app and start using it.

Step 4—Building the Dapp

If we jump into our App.vue component we can import our module and replace the app’s template with something a little more useful.

<template>
<div id="app">
<div id="temp" v-text="temp"></div>
<div
@click="checkTemp()" class='emoji' v-text="emoji"></div>
<div>
<span class='emoji'
@click="decreaseTemp()">❄️</span>
<span class='emoji'
@click="increaseTemp()">🔥</span>
</div>

</div>
</template>
<script>
const FeverContract = require('../dapp-module/FeverContract')
let feverContract = new FeverContract()
feverContract.helloWorld()
export default {
name: 'app',
...

Now we can add methods that hook up to our new template and allow us to access our contract via the module. We should also add a data state that reflects the current status of our contract.

export default {
name: 'app',
data () {
return {
hasFever: false,
temp: 98

}
},
computed: {
emoji () {
return this.temp > 110 || this.temp < 95 ? '💀' : (this.hasFever ? '🤒' : '😀')
}

},
methods: {
checkTemp () {
return feverContract.hasFever().then((hasFever) => {
this.hasFever = hasFever
return feverContract.getTemperature().then((temp) => {
this.temp = temp
})
})
},
increaseTemp () {
return feverContract.increaseTemp().then((temp) => {
return this.checkTemp()
})
},
decreaseTemp () {
return feverContract.decreaseTemp().then((temp) => {
return this.checkTemp()
})
}

}
}

Now some styles to make it pretty:

<style>
body {
background-color: white;
}

#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
#temp {
position: absolute;
top: 10px;
right: 10px;
font-size:50px;
}
#temp:after {
content: 'º';
}
.emoji {
font-size:120px;
cursor: pointer;
}

</style>

And we’ve got ourselves an App! Let’s run npm run dev to start the development environment and try interacting with it at http://localhost:8080 — Error, right? That’s cause we still need some kind of provider to interact with the blockchain 📡⛓

Step 5—Interacting with the Dapp

At this point you’ve got the choice of interacting with the app via MetaMask or the Aeternity Identity Manager. I’m going to go through the directions to use the Identity Manager because it’s new and offers a mobile ready alternative to MetaMask (Full disclosure: I’ve been consulting for their app team), but the steps are basically the same for both options:

  1. Make sure you’re using http://localhost:9545 as the RPC endpoint
  2. Import the truffle test account using the mnemonic phrase from earlier
  3. Raise the temp 🔥

Let’s get started using the identity manager by importing the mnemonic phrase at http://identity.aepps.com. Use the “Recover with Seed Phrase” option and paste in the phrase generated in the command line by truffle:

candy maple cake sugar pudding cream honey rich smooth crumble sweet treat

Afterwards, set a personal password and you’ll see your wallet with all you currently available addresses.

Now you can close the wallet view and add the new app to the Home screen. Just use the development address http://localhost:8080 and name it Dapp Scratch Fever.

When launched, Identity Manager will make an iframe that contains your app. This way the app can be visited on mobile devices 📲

Now we can finally open the app and raise the temp 🔥

Or you can cool our guy down again to a better living standard ❄️

Conclusion

In total we’ve covered:

  • Introducing the dapp-scratch Command Line Interface for generating Javascript modules for interacting with Solidity contracts.
  • Using vue-cli for starting a Vue.js project
  • Using Truffle for developing and deploying Solidity contracts
  • Using dapp-scratch for generating dapp modules and integrating it into an application
  • Using the Aeternity Identity Manager to interact with your dapp

⚠️ Don’t forget to check out the repo and add your own best practices for interacting with Solidity contracts from decentralized applications. This tutorial is also available on github here ✌️

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Responses (2)

Write a response