Embark DApp Development Guide
Embark DApp Development Guide
Release 2.5.2
1 Installation 3
2 Usage 5
3 Usage - Demo 7
4 Dashboard 9
6 DApp Structure 13
11 EmbarkJS 25
16 Structuring Application 35
17 Deploying to IPFS 37
18 Deploying to SWARM 39
                                                       i
21 Donations            49
ii
                                                       Embark Documentation, Release 2.5.2
Contents                                                                                1
Embark Documentation, Release 2.5.2
2                                     Contents
                                                                                                     CHAPTER             1
Installation
Requirements: geth (1.6.5 or higher recommended), node (6.9.1 or higher is recommended) and npm serpent (develop)
if using contracts with Serpent, testrpc (3.0 or higher) if using the simulator or the test functionality. Further: depending
on the dapp stack you choose: IPFS
                                                                                                                           3
Embark Documentation, Release 2.5.2
4                                     Chapter 1. Installation
CHAPTER   2
Usage
          5
Embark Documentation, Release 2.5.2
6                                     Chapter 2. Usage
                                                                                                 CHAPTER           3
Usage - Demo
You can easily create a sample working DApp with the following:
$ embark demo
$ cd embark_demo
$ embark blockchain
$ embark simulator
By default embark blockchain will mine a minimum amount of ether and will only mine when new transactions come
in. This is quite usefull to keep a low CPU. The option can be configured at config/blockchain.json. Note
that running a real node requires at least 2GB of free ram, please take this into account if running it in a VM.
Then, in another command line:
$ embark run
This will automatically deploy the contracts, update their JS bindings and deploy your DApp to a local server at
http://localhost:8000
Note that if you update your code it will automatically be re-deployed, contracts included. There is no need to restart
embark, refreshing the page on the browser will do.
                                                                                                                     7
Embark Documentation, Release 2.5.2
Dashboard
The dashboard will tell you the state of your contracts, the enviroment you are using, and what embark is doing at the
moment.
available services
Available Services will display the services available to your dapp in green, if one of these is down then it will be
displayed in red.
logs and console
There is a console at the bottom which can be used to interact with contracts or with embark itself. type help to see
a list of available commands, more commands will be added with each version of Embark.
                                                                                                                    9
Embark Documentation, Release 2.5.2
10                                    Chapter 4. Dashboard
                                               CHAPTER    5
$ embark blockchain
$ embark run
                                                          11
Embark Documentation, Release 2.5.2
DApp Structure
app/
  |___ contracts/ #solidity smart contracts
  |___ html/
  |___ css/
  |___ js/
config/
  |___ blockchain.json #rpc and blockchain configuration
  |___ contracts.json #ethereum contracts configuration
  |___ storage.json #ipfs configuration
  |___ communication.json #whisper/orbit configuration
  |___ webserver.json #dev webserver configuration
test/
  |___ #contracts tests
Solidity files in the contracts directory will automatically be deployed with embark run. Changes in any files will
automatically be reflected in app, changes to contracts will result in a redeployment and update of their JS Bindings
                                                                                                                  13
Embark Documentation, Release 2.5.2
Embark can build and deploy contracts coded in Solidity or Serpent. It will make them available on the client side
using EmbarkJS and Web3.js.
Further documentation for these can be found below:
    • Smart Contracts: Solidity and Serpent
    • Client Side: Web3.js and EmbarkJS
                                                                                                               15
Embark Documentation, Release 2.5.2
Embark will automatically take care of deployment for you and set all needed JS bindings. For example, the contract
below:
# app/contracts/simple_storage.sol
contract SimpleStorage {
  uint public storedData;
    function set(uint x) {
      storedData = x;
    }
    function get() constant returns (uint retVal) {
      return storedData;
    }
}
You can specify for each contract and environment its gas costs and arguments:
# config/contracts.json
{
  "development": {
    "gas": "auto",
    "contracts": {
      "SimpleStorage": {
        "args": [
                                                                                                                17
Embark Documentation, Release 2.5.2
                    100
                ]
            }
        }
    }
}
If you are using multiple contracts, you can pass a reference to another contract as $ContractName, Embark will
automatically replace this with the correct address for the contract.
# config/contracts.json
{
  ...
  "development": {
    "contracts": {
      "SimpleStorage": {
         "args": [
           100,
           "$MyStorage"
         ]
      },
      "MyStorage": {
         "args": [
           "initial string"
         ]
      },
      "MyMainContract": {
         "args": [
           "$SimpleStorage"
         ]
      }
    }
  }
  ...
}
You can now deploy many instances of the same contract. e.g
# config/contracts.json
{
  "development": {
    "contracts": {
      "Currency": {
         "deploy": false,
         "args": [
           100
         ]
      },
      "Usd": {
         "instanceOf": "Currency",
         "args": [
           200
         ]
      },
      "MyCoin": {
         "instanceOf": "Currency",
         "args": [
           200
                ]
            }
        }
    }
}
    ...
Contracts addresses can be defined, If an address is defined the contract wouldn’t be deployed but its defined address
will be used instead.
# config/contracts.json
{
  ...
  "development": {
    "contracts": {
      "UserStorage": {
         "address": "0x123456"
      },
      "UserManagement": {
         "args": [
           "$UserStorage"
         ]
      }
    }
  }
  ...
}
                                                                                                                   19
Embark Documentation, Release 2.5.2
Embark will check your prefered storage configuration in the file config/storage.json. This file will contain
the prefered configuration for each environment. With default being the configuration fields that applies to every
environment. Each of those can be individually overriden in a per environment basis.
e.g :
{
    "default": {
      "enabled": true,
      "ipfs_bin": "ipfs",
      "provider": "ipfs",
      "available_providers": ["ipfs"],
      "host": "localhost",
      "port": 5001
    },
    "development": {
      "enabled": true,
      "provider": "ipfs",
      "host": "localhost",
      "port": 5001
    }
}
options available:
         • enabled (boolean: true/false) to enable or completly disable storage support
         • ipfs_bin (string) name or desired path to the ipfs binary
         • provider (string: “ipfs”) desired provider to automatically connect to on the dapp. e.g in the ex-
           ample above, seting this to "ipfs" will automaticaly add EmbarkJS.setProvider('ipfs',
           {server: 'localhost', 5001}) to the generated code
         • available_providers (array: [”ipfs”]) list of storages to be supported on the dapp. This will affect
           what’s available with the EmbarkJS library on the dapp.
         • host and port of the ipfs node to connect to.
                                                                                                               21
Embark Documentation, Release 2.5.2
Embark will check your prefered communication configuration in the file config/communication.json. This
file will contain the prefered configuration for each environment. With default being the configuration fields that
applies to every environment. Each of those can be individually overriden in a per environment basis.
e.g :
{
    "default": {
      "enabled": true,
      "provider": "whisper",
      "available_providers": ["whisper", "orbit"]
    }
}
options available:
         • enabled (boolean: true/false) to enable or completly disable communication support
         • provider (string: “wisper” or “orbit”) desired provider to automatically connect to on the
           dapp. e.g in the example above, seting this to "whisper" will automaticaly add EmbarkJS.
           setProvider('whisper') to the generated code
         • available_providers (array: [”whisper”, “orbit”]) list of communication platforms to be supported
           on the dapp. This will affect what’s available with the EmbarkJS library on the dapp so if you don’t need
           Orbit for e.g, removing it from this will considerably reduce the file size of the generated JS code.
                                                                                                                 23
Embark Documentation, Release 2.5.2
EmbarkJS
EmbarkJS is a javascript library meant to abstract and facilitate the development of DApps.
promises
methods in EmbarkJS contracts will be converted to promises.
deployment
Client side deployment will be automatically available in Embark for existing contracts:
                                                                                                         25
Embark Documentation, Release 2.5.2
initialization
The current available storage is IPFS. it can be initialized as
EmbarkJS.Storage.setProvider('ipfs',{server: 'localhost', port: '5001'})
Saving Text
EmbarkJS.Storage.saveText("hello world")
  .then(function(hash) {})
  .catch(function(err) {
      if(err){
        console.log("IPFS saveText Error => " + err.message);
      }
  });
Retrieving Data/Text
EmbarkJS.Storage.get(hash)
  .then(function(content) {})
  .catch(function(err) {
      if(err){
        console.log("IPFS get Error => " + err.message);
      }
  });
Uploading a file
<input type="file">
                                                                                         27
Embark Documentation, Release 2.5.2
EmbarkJS.Storage.getUrl(hash);
initialization
For Whisper:
EmbarkJS.Messages.setProvider('whisper')
For Orbit:
You’ll need to use IPFS from master and run it as: ipfs daemon --enable-pubsub-experiment
then set the provider:
listening to messages
sending messages
you can send plain text
or an object
note: array of topics are considered an AND. In Whisper you can use another array for OR combinations of several
topics e.g ["topic1", ["topic2", "topic3"]] => topic1 AND (topic2 OR topic 3)
                                                                                                             29
Embark Documentation, Release 2.5.2
You can run specs with embark test, it will run any test files under test/.
Embark includes a testing lib to fastly run & test your contracts in a EVM.
# test/simple_storage_spec.js
describe("SimpleStorage", function() {
  before(function(done) {
    var contractsConfig = {
       "SimpleStorage": {
         args: [100]
       }
    };
    EmbarkSpec.deployAll(contractsConfig, done);
  });
                                                                                                 31
Embark Documentation, Release 2.5.2
});
});
Embark uses Mocha by default, but you can use any testing framework you want.
# config/blockchain.json
  ...
   "livenet": {
    "networkType": "livenet",
    "rpcHost": "localhost",
    "rpcPort": 8545,
    "rpcCorsDomain": "http://localhost:8000",
    "account": {
      "password": "config/livenet/password"
    }
  },
  ...
                                                                                                        33
Embark Documentation, Release 2.5.2
Structuring Application
Embark is quite flexible and you can configure you’re own directory structure using embark.json
# embark.json
{
  "contracts": ["app/contracts/**"],
  "app": {
    "css/app.css": ["app/css/**"],
    "images/": ["app/images/**"],
    "js/app.js": ["embark.js", "app/js/**"],
    "index.html": "app/index.html"
  },
  "buildDir": "dist/",
  "config": "config/",
  "plugins": {}
}
                                                                                                   35
Embark Documentation, Release 2.5.2
Deploying to IPFS
To deploy a dapp to IPFS, all you need to do is run a local IPFS node and then run embark upload ipfs. If you
want to deploy to the livenet then after configuring you account on config/blockchain.json on the livenet
environment then you can deploy to that chain by specifying the environment embark ipfs livenet.
                                                                                                          37
Embark Documentation, Release 2.5.2
Deploying to SWARM
To deploy a dapp to SWARM, all you need to do is run a local SWARM node and then run embark upload
swarm.
                                                                                               39
Embark Documentation, Release 2.5.2
module.exports = function(embark) {
}
The embark object then provides an api to extend different functionality of embark.
Usecases examples
    • plugin to add support for es6, jsx, coffescript, etc (embark.registerPipeline)
    • plugin to add standard contracts or a contract framework (embark.registerContractConfiguration
      and embark.addContractFile)
    • plugin to make some contracts available in all environments for use by other contracts or the dapp it-
      self e.g a Token, a DAO, ENS, etc.. (embark.registerContractConfiguration and embark.
      addContractFile)
    • plugin to add a libraries such as react or boostrap (embark.addFileToPipeline)
    • plugin to specify a particular web3             initialization   for   special   provider   uses   (embark.
      registerClientWeb3Provider)
    • plugin to create a different contract wrapper (embark.registerContractsGeneration)
                                                                                                               41
Embark Documentation, Release 2.5.2
"plugins": {
   "embark-babel": { "files": ["**/*.js", "!**/jquery.min.js"], "presets": ["es2015",
 ˓→"react"] }
module.exports = function(embark) {
     embark.registerPipeline(["**/*.js", "**/*.jsx"], function(options) {
       return babel.transform(options.source, {minified: true, presets: ['react']}).
 ˓→code;
     });
}
embark.registerContractConfiguration(contractsConfig)
This call is used to specify a configure of one or more contracts in one or several environments. This is useful for
specifying the different configurations a contract might have depending on the enviroment. For instance in the code
bellow, the DGDToken contract code will redeployed with the arguments 100 in any environment, except for the
livenet since it’s already deployed there at a particular address.
Typically this call is used in combination with embark.addContractFile
contractsConfig is an object in the same structure as the one found in the contracts configuration at config/
contracts.json. The users own configuration will be merged with the one specified in the plugins.
module.exports = function(embark) {
    embark.registerContractConfiguration({
      "default": {
        "contracts": {
          "DGDToken": {
            "args": [
              100
                  ]
              }
          }
       },
       "livenet": {
          "contracts": {
            "DGDToken": {
              "address": "0xe0b7927c4af23765cb51314a0e0521a9645f0e2a"
            }
          }
       }
     });
}
embark.addContractFile(file)
Typically this call is used in combination with embark.registerContractConfiguration. If you
want to make the contract available but not automatically deployed without the user specifying so you can use
registerContractConfiguration to set the contract config to deploy: false, this is particularly useful
for when the user is meant to extend the contract being given (e.g contract MyToken is StandardToken)
file is the contract file to add to embark, the path should relative to the plugin.
module.exports = function(embark) {
    embark.addContractFile("./DGDToken.sol");
}
embark.addFileToPipeline(file, options)
This call is used to add a file to the pipeline so it’s included with the dapp on the client side.
file is the file to add to the pipeline, the path should relative to the plugin.
options available:
           • skipPipeline - If true it will not apply transformations to the file. For example if you have a babel plugin
             to transform es6 code or a minifier plugin, setting this to true will not apply the plugin on this file.
module.exports = function(embark) {
    embark.addFileToPipeline("./jquery.js", {skipPipeline: true});
}
embark.registerClientWeb3Provider(callback(options))
This call can be used to override the default web3 object generation in the dapp. it’s useful if you want to add a plugin
to interact with services like http://infura.io or if you want to use your own web3.js library extension.
options available:
           • rpcHost - configured rpc Host to connect to
           • rpcPort - configured rpc Port to connect to
           • blockchainConfig - object containing the full blockchain configuration for the current environment
expected return: string
example:
module.exports = function(embark) {
     embark.registerClientWeb3Provider(function(options) {
         return "web3 = new Web3(new Web3.providers.HttpProvider('http://" + options.
 ˓→rpcHost + ":" + options.rpcPort + "');";
                                                                                                                      43
Embark Documentation, Release 2.5.2
      });
}
embark.registerContractsGeneration(callback(options))
By default Embark will use EmbarkJS to declare contracts in the dapp. You can override and use your own client side
library.
options available:
            • contracts - Hash of objects containing all the deployed contracts. (key: contractName, value: contract
              object)
            • abiDefinition
            • code
            • deployedAddress
            • gasEstimates
            • gas
            • gasPrice
            • runtimeByteCode
expected return: string
module.exports = function(embark) {
    embark.registerContractsGeneration(function(options) {
      for(var className in this.contractsManager.contracts) {
        var abi = JSON.stringify(contract.abiDefinition);
embark.registerConsoleCommand(callback(options))
This call is used to extend the console with custom commands.
expected return: string (output to print in console) or boolean (skip command if false)
module.exports = function(embark) {
    embark.registerConsoleCommand(function(cmd, options) {
      if (cmd === "hello") {
        return "hello there!";
      }
      // continue to embark or next plugin;
      return false;
    });
}
module.exports = function(embark) {
    embark.registerCompiler(".sol", function(contractFiles, cb) {
      // prepare input for solc
      var input = {};
      for (var i = 0; i < contractFiles.length; i++) {
        var filename = contractFiles[i].filename.replace('app/contracts/','');
        input[filename] = contractFiles[i].content.toString();
      }
        // compile files
        var output = solc.compile({sources: input}, 1);
            compiled_object[className] = {};
            compiled_object[className].code                          =   contract.bytecode;
            compiled_object[className].runtimeBytecode               =   contract.runtimeBytecode;
            compiled_object[className].gasEstimates                  =   contract.gasEstimates;
            compiled_object[className].functionHashes                =   contract.functionHashes;
            compiled_object[className].abiDefinition                 =   JSON.parse(contract.interface);
        }
       cb(null, compiled_object);
     });
}
embark.logger
To print messages to the embark log is it better to use embark.logger instead of console.
e.g embark.logger.info("hello")
embark.events.on(eventName, callback(*args))
This call is used to listen and react to events that happen in Embark such as contract deployment
    • eventName - name of event to listen to * available events:
                                                                                                           45
Embark Documentation, Release 2.5.2
module.exports = function(embark) {
    embark.events.on("contractsDeployed", function() {
      embark.logger.info("plugin says: your contracts have been deployed");
    });
    embark.events.on("file-changed", function(filetype, path) {
      if (type === 'contract') {
        embark.logger.info("plugin says: you just changed the contract at " + path);
      }
    });
}
1. Edit embark.json
Edit embark.json to have the line "js/app.js":             ["embark.js"], this will make embark create the file
containing the contracts initilization to dist/app.js.
{
    "contracts": ["app/contracts/**"],
    "app": {
      "app.js": ["embark.js"]
    },
    "buildDir": "dist/",
    "config": "config/",
    "plugins": {
    }
}
2. add the generated file to Grunt config file so it’s included with the other assets
    grunt.initConfig(
      files:
        js:
          src: [
            "dist/app.js"
            "app/js/**/*.js"
          ]
                                                                                                            47
Embark Documentation, Release 2.5.2
Donations
                                                                                               49
Embark Documentation, Release 2.5.2
• genindex
• modindex
• search
51