migrate all the code to ES6

This commit is contained in:
Todd Baur 2017-03-30 20:12:39 +09:00
parent 26b87b4b05
commit 67f325f5a0
40 changed files with 2349 additions and 2274 deletions

View File

@ -5,12 +5,12 @@ let promptly = require('promptly');
let path = require('path'); let path = require('path');
let Embark = require('../lib/index'); let Embark = require('../lib/index');
let Cmd = function() { class Cmd {
constructor() {
program.version(Embark.version); program.version(Embark.version);
}; }
process(args) {
Cmd.prototype.process = function(args) {
this.newApp(); this.newApp();
this.demo(); this.demo();
this.build(); this.build();
@ -27,13 +27,13 @@ Cmd.prototype.process = function(args) {
} }
program.parse(args); program.parse(args);
}; }
Cmd.prototype.newApp = function(name) { newApp(name) {
let validateName = function (value) { let validateName = function (value) {
try { try {
if(value.match(/^[a-zA-Z\s\-]+$/)) return value; if (value.match(/^[a-zA-Z\s\-]+$/)) return value;
} catch (e) { } catch (e) {
throw new Error('Name must be only letters, spaces, or dashes'); throw new Error('Name must be only letters, spaces, or dashes');
} }
@ -64,27 +64,27 @@ Cmd.prototype.newApp = function(name) {
} }
}); });
}; }
Cmd.prototype.demo = function() { demo() {
program program
.command('demo') .command('demo')
.description('create a working dapp with a SimpleStorage contract') .description('create a working dapp with a SimpleStorage contract')
.action(function() { .action(function () {
Embark.generateTemplate('demo', './', 'embark_demo'); Embark.generateTemplate('demo', './', 'embark_demo');
}); });
}; }
Cmd.prototype.build = function() { build() {
program program
.command('build [environment]') .command('build [environment]')
.description('deploy and build dapp at dist/ (default: development)') .description('deploy and build dapp at dist/ (default: development)')
.action(function(env, options) { .action(function (env, options) {
Embark.build({env: env || 'development'}); Embark.build({env: env || 'development'});
}); });
}; }
Cmd.prototype.run = function() { run() {
program program
.command('run [environment]') .command('run [environment]')
.option('-p, --port [port]', 'port to run the dev webserver (default: 8000)') .option('-p, --port [port]', 'port to run the dev webserver (default: 8000)')
@ -93,7 +93,7 @@ Cmd.prototype.run = function() {
.option('--nodashboard', 'simple mode, disables the dashboard') .option('--nodashboard', 'simple mode, disables the dashboard')
.option('--no-color', 'no colors in case it\'s needed for compatbility purposes') .option('--no-color', 'no colors in case it\'s needed for compatbility purposes')
.description('run dapp (default: development)') .description('run dapp (default: development)')
.action(function(env, options) { .action(function (env, options) {
Embark.run({ Embark.run({
env: env || 'development', env: env || 'development',
serverPort: options.port, serverPort: options.port,
@ -102,67 +102,69 @@ Cmd.prototype.run = function() {
useDashboard: !options.nodashboard useDashboard: !options.nodashboard
}); });
}); });
}; }
Cmd.prototype.blockchain = function() { blockchain() {
program program
.command('blockchain [environment]') .command('blockchain [environment]')
.option('-c, --client [client]', 'Use a specific ethereum client or simulator (supported: geth, parity, ethersim, testrpc') .option('-c, --client [client]', 'Use a specific ethereum client or simulator (supported: geth, parity, ethersim, testrpc')
.description('run blockchain server (default: development)') .description('run blockchain server (default: development)')
.action(function(env ,options) { .action(function (env, options) {
Embark.initConfig(env || 'development', { Embark.initConfig(env || 'development', {
embarkConfig: 'embark.json', embarkConfig: 'embark.json',
interceptLogs: false interceptLogs: false
}); });
Embark.blockchain(env || 'development', options.client || 'geth'); Embark.blockchain(env || 'development', options.client || 'geth');
}); });
}; }
Cmd.prototype.simulator = function() { simulator() {
program program
.command('simulator [environment]') .command('simulator [environment]')
.description('run a fast ethereum rpc simulator') .description('run a fast ethereum rpc simulator')
.option('--testrpc', 'use testrpc as the rpc simulator [default]') .option('--testrpc', 'use testrpc as the rpc simulator [default]')
.option('-p, --port [port]', 'port to run the rpc simulator (default: 8000)') .option('-p, --port [port]', 'port to run the rpc simulator (default: 8000)')
.option('-h, --host [host]', 'host to run the rpc simulator (default: localhost)') .option('-h, --host [host]', 'host to run the rpc simulator (default: localhost)')
.action(function(env, options) { .action(function (env, options) {
Embark.initConfig(env || 'development', { Embark.initConfig(env || 'development', {
embarkConfig: 'embark.json', embarkConfig: 'embark.json',
interceptLogs: false interceptLogs: false
}); });
Embark.simulator({port: options.port, host: options.host}); Embark.simulator({port: options.port, host: options.host});
}); });
}; }
Cmd.prototype.test = function() { test() {
program program
.command('test') .command('test')
.description('run tests') .description('run tests')
.action(function() { .action(function () {
shelljs.exec('mocha test'); shelljs.exec('mocha test');
}); });
}; }
Cmd.prototype.upload = function() { upload() {
program program
.command('upload [platform] [environment]') .command('upload [platform] [environment]')
.description('upload your dapp to a decentralized storage. possible options: ipfs, swarm (e.g embark upload swarm)') .description('upload your dapp to a decentralized storage. possible options: ipfs, swarm (e.g embark upload swarm)')
.action(function(platform, env, options) { .action(function (platform, env, options) {
// TODO: get env in cmd line as well // TODO: get env in cmd line as well
Embark.initConfig(env || 'development', { Embark.initConfig(env || 'development', {
embarkConfig: 'embark.json', interceptLogs: false embarkConfig: 'embark.json', interceptLogs: false
}); });
Embark.upload(platform); Embark.upload(platform);
}); });
}; }
Cmd.prototype.otherCommands = function() { otherCommands() {
program program
.action(function(env){ .action(function (env) {
console.log('unknown command "%s"'.red, env); console.log('unknown command "%s"'.red, env);
console.log("type embark --help to see the available commands"); console.log("type embark --help to see the available commands");
process.exit(0); process.exit(0);
}); });
}; }
}
module.exports = Cmd; module.exports = Cmd;

View File

@ -5,11 +5,20 @@ let fs = require('../../core/fs.js');
let GethCommands = require('./geth_commands.js'); let GethCommands = require('./geth_commands.js');
let BlockchainClient = function(blockchainConfig, client, env) {
if (client === 'geth') {
return new Blockchain({blockchainConfig: blockchainConfig, client: GethCommands, env: env});
} else {
throw new Error('unknown client');
}
};
/*eslint complexity: ["error", 22]*/ /*eslint complexity: ["error", 22]*/
let Blockchain = function(options) { class Blockchain {
constructor(options) {
this.blockchainConfig = options.blockchainConfig; this.blockchainConfig = options.blockchainConfig;
this.env = options.env || 'development'; this.env = options.env || 'development';
this.client = options.client; this.client = BlockchainClient(this.blockchainConfig, 'geth', this.env);
this.config = { this.config = {
geth_bin: this.blockchainConfig.geth_bin || 'geth', geth_bin: this.blockchainConfig.geth_bin || 'geth',
@ -31,16 +40,14 @@ let Blockchain = function(options) {
rpcApi: (this.blockchainConfig.rpcApi || ['eth', 'web3', 'net']), rpcApi: (this.blockchainConfig.rpcApi || ['eth', 'web3', 'net']),
vmdebug: this.blockchainConfig.vmdebug || false vmdebug: this.blockchainConfig.vmdebug || false
}; };
}
this.client = new options.client({config: this.config, env: this.env}); static runCommand(cmd) {
};
Blockchain.prototype.runCommand = function(cmd) {
console.log(("running: " + cmd.underline).green); console.log(("running: " + cmd.underline).green);
return shelljs.exec(cmd); return shelljs.exec(cmd);
}; }
Blockchain.prototype.run = function() { run() {
let self = this; let self = this;
console.log("===============================================================================".magenta); console.log("===============================================================================".magenta);
console.log("===============================================================================".magenta); console.log("===============================================================================".magenta);
@ -48,12 +55,12 @@ Blockchain.prototype.run = function() {
console.log("===============================================================================".magenta); console.log("===============================================================================".magenta);
console.log("===============================================================================".magenta); console.log("===============================================================================".magenta);
let address = this.initChainAndGetAddress(); let address = this.initChainAndGetAddress();
this.client.mainCommand(address, function(cmd) { this.client.mainCommand(address, function (cmd) {
self.runCommand(cmd); self.runCommand(cmd);
}); });
}; }
Blockchain.prototype.initChainAndGetAddress = function() { initChainAndGetAddress() {
let address = null, result; let address = null, result;
// ensure datadir exists, bypassing the interactive liabilities prompt. // ensure datadir exists, bypassing the interactive liabilities prompt.
@ -80,15 +87,8 @@ Blockchain.prototype.initChainAndGetAddress = function() {
} }
return address; return address;
};
let BlockchainClient = function(blockchainConfig, client, env) {
if (client === 'geth') {
return new Blockchain({blockchainConfig: blockchainConfig, client: GethCommands, env: env});
} else {
throw new Error('unknown client');
} }
}; }
module.exports = BlockchainClient; module.exports = Blockchain;

View File

@ -1,14 +1,15 @@
let async = require('async'); let async = require('async');
// TODO: make all of this async // TODO: make all of this async
let GethCommands = function(options) { class GethCommands {
constructor(options) {
this.config = options.config; this.config = options.config;
this.env = options.env || 'development'; this.env = options.env || 'development';
this.name = "Go-Ethereum (https://github.com/ethereum/go-ethereum)"; this.name = "Go-Ethereum (https://github.com/ethereum/go-ethereum)";
this.geth_bin = this.config.geth_bin || "geth"; this.geth_bin = this.config.geth_bin || "geth";
}; }
GethCommands.prototype.commonOptions = function() { commonOptions() {
let config = this.config; let config = this.config;
let cmd = ""; let cmd = "";
@ -31,9 +32,9 @@ GethCommands.prototype.commonOptions = function() {
} }
return cmd; return cmd;
}; }
GethCommands.prototype.determineNetworkType = function(config) { determineNetworkType(config) {
let cmd = ""; let cmd = "";
if (config.networkType === 'testnet') { if (config.networkType === 'testnet') {
cmd += "--testnet "; cmd += "--testnet ";
@ -43,9 +44,9 @@ GethCommands.prototype.determineNetworkType = function(config) {
cmd += "--networkid " + config.networkId + " "; cmd += "--networkid " + config.networkId + " ";
} }
return cmd; return cmd;
}; }
GethCommands.prototype.initGenesisCommmand = function() { initGenesisCommmand() {
let config = this.config; let config = this.config;
let cmd = this.geth_bin + " " + this.commonOptions(); let cmd = this.geth_bin + " " + this.commonOptions();
@ -54,17 +55,17 @@ GethCommands.prototype.initGenesisCommmand = function() {
} }
return cmd; return cmd;
}; }
GethCommands.prototype.newAccountCommand = function() { newAccountCommand() {
return this.geth_bin + " " + this.commonOptions() + "account new "; return this.geth_bin + " " + this.commonOptions() + "account new ";
}; }
GethCommands.prototype.listAccountsCommand = function() { listAccountsCommand() {
return this.geth_bin + " " + this.commonOptions() + "account list "; return this.geth_bin + " " + this.commonOptions() + "account list ";
}; }
GethCommands.prototype.determineRpcOptions = function(config) { determineRpcOptions(config) {
let cmd = ""; let cmd = "";
cmd += "--port " + config.port + " "; cmd += "--port " + config.port + " ";
@ -85,9 +86,9 @@ GethCommands.prototype.determineRpcOptions = function(config) {
} }
return cmd; return cmd;
}; }
GethCommands.prototype.mainCommand = function(address, done) { mainCommand(address, done) {
let self = this; let self = this;
let config = this.config; let config = this.config;
let rpc_api = (this.config.rpcApi || ['eth', 'web3', 'net']); let rpc_api = (this.config.rpcApi || ['eth', 'web3', 'net']);
@ -152,13 +153,14 @@ GethCommands.prototype.mainCommand = function(address, done) {
} }
callback(null, ""); callback(null, "");
} }
], function(err, results) { ], function (err, results) {
if (err) { if (err) {
throw new Error(err.message); throw new Error(err.message);
} }
done(self.geth_bin + " " + results.join(" ")); done(self.geth_bin + " " + results.join(" "));
}); });
}; }
}
module.exports = GethCommands; module.exports = GethCommands;

View File

@ -1,10 +1,11 @@
let shelljs = require('shelljs'); let shelljs = require('shelljs');
let Simulator = function(options) { class Simulator {
constructor(options) {
this.blockchainConfig = options.blockchainConfig; this.blockchainConfig = options.blockchainConfig;
}; }
Simulator.prototype.run = function(options) { run(options) {
let cmds = []; let cmds = [];
cmds.push("-p " + (this.blockchainConfig.rpcPort || options.port || 8545)); cmds.push("-p " + (this.blockchainConfig.rpcPort || options.port || 8545));
@ -12,7 +13,8 @@ Simulator.prototype.run = function(options) {
cmds.push("-a " + (options.num || 10)); cmds.push("-a " + (options.num || 10));
shelljs.exec('testrpc ' + cmds.join(' ')); shelljs.exec('testrpc ' + cmds.join(' '));
}; }
}
module.exports = Simulator; module.exports = Simulator;

View File

@ -1,11 +1,12 @@
let fs = require('../core/fs.js'); let fs = require('../core/fs.js');
let utils = require('../utils/utils.js'); let utils = require('../utils/utils.js');
let TemplateGenerator = function(templateName) { class TemplateGenerator {
constuctor(templateName) {
this.templateName = templateName; this.templateName = templateName;
}; }
TemplateGenerator.prototype.generate = function(destinationFolder, name) { generate(destinationFolder, name) {
let templatePath = fs.embarkPath(this.templateName); let templatePath = fs.embarkPath(this.templateName);
console.log('Initializing Embark Template....'.green); console.log('Initializing Embark Template....'.green);
@ -27,6 +28,7 @@ TemplateGenerator.prototype.generate = function(destinationFolder, name) {
console.log('-> '.green + 'embark run'.bold.cyan); console.log('-> '.green + 'embark run'.bold.cyan);
console.log('For more info go to http://github.com/iurimatias/embark-framework'.green); console.log('For more info go to http://github.com/iurimatias/embark-framework'.green);
} }
}; }
}
module.exports = TemplateGenerator; module.exports = TemplateGenerator;

View File

@ -1,5 +1,5 @@
class ABIGenerator {
let ABIGenerator = function(options) { constructor(options) {
this.blockchainConfig = options.blockchainConfig || {}; this.blockchainConfig = options.blockchainConfig || {};
this.storageConfig = options.storageConfig || {}; this.storageConfig = options.storageConfig || {};
this.communicationConfig = options.communicationConfig || {}; this.communicationConfig = options.communicationConfig || {};
@ -7,9 +7,9 @@ let ABIGenerator = function(options) {
this.rpcHost = options.blockchainConfig && options.blockchainConfig.rpcHost; this.rpcHost = options.blockchainConfig && options.blockchainConfig.rpcHost;
this.rpcPort = options.blockchainConfig && options.blockchainConfig.rpcPort; this.rpcPort = options.blockchainConfig && options.blockchainConfig.rpcPort;
this.plugins = options.plugins; this.plugins = options.plugins;
}; }
ABIGenerator.prototype.generateProvider = function() { generateProvider() {
let self = this; let self = this;
let result = ""; let result = "";
let providerPlugins; let providerPlugins;
@ -23,7 +23,7 @@ ABIGenerator.prototype.generateProvider = function() {
} }
if (this.plugins && providerPlugins.length > 0) { if (this.plugins && providerPlugins.length > 0) {
providerPlugins.forEach(function(plugin) { providerPlugins.forEach(function (plugin) {
result += plugin.generateProvider(self) + "\n"; result += plugin.generateProvider(self) + "\n";
}); });
} else { } else {
@ -36,9 +36,9 @@ ABIGenerator.prototype.generateProvider = function() {
} }
return result; return result;
}; }
ABIGenerator.prototype.generateContracts = function(useEmbarkJS) { generateContracts(useEmbarkJS) {
let self = this; let self = this;
let result = "\n"; let result = "\n";
let contractsPlugins; let contractsPlugins;
@ -52,11 +52,11 @@ ABIGenerator.prototype.generateContracts = function(useEmbarkJS) {
} }
if (this.plugins && contractsPlugins.length > 0) { if (this.plugins && contractsPlugins.length > 0) {
contractsPlugins.forEach(function(plugin) { contractsPlugins.forEach(function (plugin) {
result += plugin.generateContracts({contracts: self.contractsManager.contracts}); result += plugin.generateContracts({contracts: self.contractsManager.contracts});
}); });
} else { } else {
for(let className in this.contractsManager.contracts) { for (let className in this.contractsManager.contracts) {
let contract = this.contractsManager.contracts[className]; let contract = this.contractsManager.contracts[className];
let abi = JSON.stringify(contract.abiDefinition); let abi = JSON.stringify(contract.abiDefinition);
@ -73,9 +73,9 @@ ABIGenerator.prototype.generateContracts = function(useEmbarkJS) {
} }
return result; return result;
}; }
ABIGenerator.prototype.generateStorageInitialization = function(useEmbarkJS) { generateStorageInitialization(useEmbarkJS) {
let self = this; let self = this;
let result = "\n"; let result = "\n";
@ -86,9 +86,9 @@ ABIGenerator.prototype.generateStorageInitialization = function(useEmbarkJS) {
} }
return result; return result;
}; }
ABIGenerator.prototype.generateCommunicationInitialization = function(useEmbarkJS) { generateCommunicationInitialization(useEmbarkJS) {
let self = this; let self = this;
let result = "\n"; let result = "\n";
@ -101,9 +101,9 @@ ABIGenerator.prototype.generateCommunicationInitialization = function(useEmbarkJ
} }
return result; return result;
}; }
ABIGenerator.prototype.generateABI = function(options) { generateABI(options) {
let result = ""; let result = "";
result += this.generateProvider(); result += this.generateProvider();
@ -112,6 +112,7 @@ ABIGenerator.prototype.generateABI = function(options) {
result += this.generateCommunicationInitialization(options.useEmbarkJS); result += this.generateCommunicationInitialization(options.useEmbarkJS);
return result; return result;
}; }
}
module.exports = ABIGenerator; module.exports = ABIGenerator;

View File

@ -2,12 +2,13 @@
let async = require('../utils/async_extend.js'); let async = require('../utils/async_extend.js');
let SolcW = require('./solcW.js'); let SolcW = require('./solcW.js');
let Compiler = function(options) { class Compiler {
constructor(options) {
this.plugins = options.plugins; this.plugins = options.plugins;
this.logger = options.logger; this.logger = options.logger;
}; }
Compiler.prototype.compile_contracts = function(contractFiles, cb) { compile_contracts(contractFiles, cb) {
let available_compilers = { let available_compilers = {
//".se": this.compile_serpent //".se": this.compile_serpent
@ -17,8 +18,8 @@ Compiler.prototype.compile_contracts = function(contractFiles, cb) {
if (this.plugins) { if (this.plugins) {
let compilerPlugins = this.plugins.getPluginsFor('compilers'); let compilerPlugins = this.plugins.getPluginsFor('compilers');
if (compilerPlugins.length > 0) { if (compilerPlugins.length > 0) {
compilerPlugins.forEach(function(plugin) { compilerPlugins.forEach(function (plugin) {
plugin.compilers.forEach(function(compilerObject) { plugin.compilers.forEach(function (compilerObject) {
available_compilers[compilerObject.extension] = compilerObject.cb; available_compilers[compilerObject.extension] = compilerObject.cb;
}); });
}); });
@ -28,13 +29,13 @@ Compiler.prototype.compile_contracts = function(contractFiles, cb) {
let compiledObject = {}; let compiledObject = {};
async.eachObject(available_compilers, async.eachObject(available_compilers,
function(extension, compiler, callback) { function (extension, compiler, callback) {
// TODO: warn about files it doesn't know how to compile // TODO: warn about files it doesn't know how to compile
let matchingFiles = contractFiles.filter(function(file) { let matchingFiles = contractFiles.filter(function (file) {
return (file.filename.match(/\.[0-9a-z]+$/)[0] === extension); return (file.filename.match(/\.[0-9a-z]+$/)[0] === extension);
}); });
compiler.call(compiler, matchingFiles || [], function(err, compileResult) { compiler.call(compiler, matchingFiles || [], function (err, compileResult) {
Object.assign(compiledObject, compileResult); Object.assign(compiledObject, compileResult);
callback(err, compileResult); callback(err, compileResult);
}); });
@ -43,17 +44,17 @@ Compiler.prototype.compile_contracts = function(contractFiles, cb) {
cb(err, compiledObject); cb(err, compiledObject);
} }
); );
}; }
Compiler.prototype.compile_solidity = function(contractFiles, cb) { compile_solidity(contractFiles, cb) {
let self = this; let self = this;
let input = {}; let input = {};
let solcW; let solcW;
async.waterfall([ async.waterfall([
function prepareInput(callback) { function prepareInput(callback) {
for (let i = 0; i < contractFiles.length; i++){ for (let i = 0; i < contractFiles.length; i++) {
// TODO: this depends on the config // TODO: this depends on the config
let filename = contractFiles[i].filename.replace('app/contracts/',''); let filename = contractFiles[i].filename.replace('app/contracts/', '');
input[filename] = contractFiles[i].content.toString(); input[filename] = contractFiles[i].content.toString();
} }
callback(); callback();
@ -66,15 +67,15 @@ Compiler.prototype.compile_solidity = function(contractFiles, cb) {
} }
self.logger.info("loading solc compiler.."); self.logger.info("loading solc compiler..");
solcW.load_compiler(function(){ solcW.load_compiler(function () {
callback(); callback();
}); });
}, },
function compileContracts(callback) { function compileContracts(callback) {
self.logger.info("compiling contracts..."); self.logger.info("compiling contracts...");
solcW.compile({sources: input}, 1, function(output) { solcW.compile({sources: input}, 1, function (output) {
if (output.errors) { if (output.errors) {
return callback(new Error ("Solidity errors: " + output.errors).message); return callback(new Error("Solidity errors: " + output.errors).message);
} }
callback(null, output); callback(null, output);
}); });
@ -91,16 +92,17 @@ Compiler.prototype.compile_solidity = function(contractFiles, cb) {
compiled_object[className].code = contract.bytecode; compiled_object[className].code = contract.bytecode;
compiled_object[className].runtimeBytecode = contract.runtimeBytecode; compiled_object[className].runtimeBytecode = contract.runtimeBytecode;
compiled_object[className].realRuntimeBytecode = contract.runtimeBytecode.slice(0, -68); compiled_object[className].realRuntimeBytecode = contract.runtimeBytecode.slice(0, -68);
compiled_object[className].swarmHash = contract.runtimeBytecode.slice(-68).slice(0,64); compiled_object[className].swarmHash = contract.runtimeBytecode.slice(-68).slice(0, 64);
compiled_object[className].gasEstimates = contract.gasEstimates; compiled_object[className].gasEstimates = contract.gasEstimates;
compiled_object[className].functionHashes = contract.functionHashes; compiled_object[className].functionHashes = contract.functionHashes;
compiled_object[className].abiDefinition = JSON.parse(contract.interface); compiled_object[className].abiDefinition = JSON.parse(contract.interface);
} }
callback(null, compiled_object); callback(null, compiled_object);
} }
], function(err, result) { ], function (err, result) {
cb(err, result); cb(err, result);
}); });
}; };
}
module.exports = Compiler; module.exports = Compiler;

View File

@ -5,27 +5,8 @@ let Compiler = require('./compiler.js');
// TODO: create a contract object // TODO: create a contract object
let adjustGas = function(contract) { class ContractsManager {
let maxGas, adjustedGas; constructor(options) {
if (contract.gas === 'auto') {
if (contract.deploy || contract.deploy === undefined) {
if (contract.gasEstimates.creation !== undefined) {
// TODO: should sum it instead
maxGas = Math.max(contract.gasEstimates.creation[0], contract.gasEstimates.creation[1], 500000);
} else {
maxGas = 500000;
}
} else {
maxGas = 500000;
}
// TODO: put a check so it doesn't go over the block limit
adjustedGas = Math.round(maxGas * 1.40);
adjustedGas += 25000;
contract.gas = adjustedGas;
}
};
let ContractsManager = function(options) {
this.contractFiles = options.contractFiles; this.contractFiles = options.contractFiles;
this.contractsConfig = options.contractsConfig; this.contractsConfig = options.contractsConfig;
this.contracts = {}; this.contracts = {};
@ -33,21 +14,21 @@ let ContractsManager = function(options) {
this.plugins = options.plugins; this.plugins = options.plugins;
this.contractDependencies = {}; this.contractDependencies = {};
}; }
ContractsManager.prototype.build = function(done) { build(done) {
let self = this; let self = this;
async.waterfall([ async.waterfall([
function compileContracts(callback) { function compileContracts(callback) {
let compiler = new Compiler({plugins: self.plugins, logger: self.logger}); let compiler = new Compiler({plugins: self.plugins, logger: self.logger});
compiler.compile_contracts(self.contractFiles, function(err, compiledObject) { compiler.compile_contracts(self.contractFiles, function (err, compiledObject) {
self.compiledContracts = compiledObject; self.compiledContracts = compiledObject;
callback(err); callback(err);
}); });
}, },
function prepareContractsFromConfig(callback) { function prepareContractsFromConfig(callback) {
let className, contract; let className, contract;
for(className in self.contractsConfig.contracts) { for (className in self.contractsConfig.contracts) {
contract = self.contractsConfig.contracts[className]; contract = self.contractsConfig.contracts[className];
contract.className = className; contract.className = className;
@ -59,7 +40,7 @@ ContractsManager.prototype.build = function(done) {
}, },
function setDeployIntention(callback) { function setDeployIntention(callback) {
let className, contract; let className, contract;
for(className in self.contracts) { for (className in self.contracts) {
contract = self.contracts[className]; contract = self.contracts[className];
contract.deploy = (contract.deploy === undefined) || contract.deploy; contract.deploy = (contract.deploy === undefined) || contract.deploy;
} }
@ -67,7 +48,7 @@ ContractsManager.prototype.build = function(done) {
}, },
function prepareContractsFromCompilation(callback) { function prepareContractsFromCompilation(callback) {
let className, compiledContract, contractConfig, contract; let className, compiledContract, contractConfig, contract;
for(className in self.compiledContracts) { for (className in self.compiledContracts) {
compiledContract = self.compiledContracts[className]; compiledContract = self.compiledContracts[className];
contractConfig = self.contractsConfig.contracts[className]; contractConfig = self.contractsConfig.contracts[className];
@ -82,7 +63,7 @@ ContractsManager.prototype.build = function(done) {
contract.abiDefinition = compiledContract.abiDefinition; contract.abiDefinition = compiledContract.abiDefinition;
contract.gas = (contractConfig && contractConfig.gas) || self.contractsConfig.gas || 'auto'; contract.gas = (contractConfig && contractConfig.gas) || self.contractsConfig.gas || 'auto';
adjustGas(contract); self.adjustGas(contract);
contract.gasPrice = contract.gasPrice || self.contractsConfig.gasPrice; contract.gasPrice = contract.gasPrice || self.contractsConfig.gasPrice;
contract.type = 'file'; contract.type = 'file';
@ -96,10 +77,12 @@ ContractsManager.prototype.build = function(done) {
function dealWithSpecialConfigs(callback) { function dealWithSpecialConfigs(callback) {
let className, contract, parentContractName, parentContract; let className, contract, parentContractName, parentContract;
for(className in self.contracts) { for (className in self.contracts) {
contract = self.contracts[className]; contract = self.contracts[className];
if (contract.instanceOf === undefined) { continue; } if (contract.instanceOf === undefined) {
continue;
}
parentContractName = contract.instanceOf; parentContractName = contract.instanceOf;
parentContract = self.contracts[parentContractName]; parentContract = self.contracts[parentContractName];
@ -137,7 +120,7 @@ ContractsManager.prototype.build = function(done) {
}, },
function removeContractsWithNoCode(callback) { function removeContractsWithNoCode(callback) {
let className, contract; let className, contract;
for(className in self.contracts) { for (className in self.contracts) {
contract = self.contracts[className]; contract = self.contracts[className];
if (contract.code === undefined) { if (contract.code === undefined) {
@ -150,7 +133,7 @@ ContractsManager.prototype.build = function(done) {
}, },
function determineDependencies(callback) { function determineDependencies(callback) {
let className, contract; let className, contract;
for(className in self.contracts) { for (className in self.contracts) {
contract = self.contracts[className]; contract = self.contracts[className];
if (contract.args === []) continue; if (contract.args === []) continue;
@ -166,54 +149,54 @@ ContractsManager.prototype.build = function(done) {
} }
callback(); callback();
} }
], function(err, result) { ], function (err, result) {
if (err) { if (err) {
self.logger.error("Error Compiling/Building contracts: " + err); self.logger.error("Error Compiling/Building contracts: " + err);
} }
self.logger.trace("finished".underline); self.logger.trace("finished".underline);
done(err, self); done(err, self);
}); });
}; }
ContractsManager.prototype.getContract = function(className) { getContract(className) {
return this.contracts[className]; return this.contracts[className];
}; }
ContractsManager.prototype.sortContracts = function(contractList) { sortContracts(contractList) {
let converted_dependencies = [], i; let converted_dependencies = [], i;
for(let contract in this.contractDependencies) { for (let contract in this.contractDependencies) {
let dependencies = this.contractDependencies[contract]; let dependencies = this.contractDependencies[contract];
for(i=0; i < dependencies.length; i++) { for (i = 0; i < dependencies.length; i++) {
converted_dependencies.push([contract, dependencies[i]]); converted_dependencies.push([contract, dependencies[i]]);
} }
} }
let orderedDependencies = toposort(converted_dependencies).reverse(); let orderedDependencies = toposort(converted_dependencies).reverse();
let newList = contractList.sort(function(a,b) { let newList = contractList.sort(function (a, b) {
let order_a = orderedDependencies.indexOf(a.className); let order_a = orderedDependencies.indexOf(a.className);
let order_b = orderedDependencies.indexOf(b.className); let order_b = orderedDependencies.indexOf(b.className);
return order_a - order_b; return order_a - order_b;
}); });
return newList; return newList;
}; }
// TODO: should be built contracts // TODO: should be built contracts
ContractsManager.prototype.listContracts = function() { listContracts() {
let contracts = []; let contracts = [];
for(let className in this.contracts) { for (let className in this.contracts) {
let contract = this.contracts[className]; let contract = this.contracts[className];
contracts.push(contract); contracts.push(contract);
} }
return this.sortContracts(contracts); return this.sortContracts(contracts);
}; }
ContractsManager.prototype.contractsState = function() { contractsState() {
let data = []; let data = [];
for(let className in this.contracts) { for (let className in this.contracts) {
let contract = this.contracts[className]; let contract = this.contracts[className];
let contractData; let contractData;
@ -242,6 +225,27 @@ ContractsManager.prototype.contractsState = function() {
} }
return data; return data;
}; }
adjustGas(contract) {
let maxGas, adjustedGas;
if (contract.gas === 'auto') {
if (contract.deploy || contract.deploy === undefined) {
if (contract.gasEstimates.creation !== undefined) {
// TODO: should sum it instead
maxGas = Math.max(contract.gasEstimates.creation[0], contract.gasEstimates.creation[1], 500000);
} else {
maxGas = 500000;
}
} else {
maxGas = 500000;
}
// TODO: put a check so it doesn't go over the block limit
adjustedGas = Math.round(maxGas * 1.40);
adjustedGas += 25000;
contract.gas = adjustedGas;
}
}
}
module.exports = ContractsManager; module.exports = ContractsManager;

View File

@ -5,7 +5,8 @@ let RunCode = require('../core/runCode.js');
let DeployTracker = require('./deploy_tracker.js'); let DeployTracker = require('./deploy_tracker.js');
let ABIGenerator = require('./abi.js'); let ABIGenerator = require('./abi.js');
let Deploy = function(options) { class Deploy {
constructor(options) {
this.web3 = options.web3; this.web3 = options.web3;
this.contractsManager = options.contractsManager; this.contractsManager = options.contractsManager;
this.logger = options.logger; this.logger = options.logger;
@ -14,9 +15,9 @@ let Deploy = function(options) {
this.deployTracker = new DeployTracker({ this.deployTracker = new DeployTracker({
logger: options.logger, chainConfig: options.chainConfig, web3: options.web3, env: this.env logger: options.logger, chainConfig: options.chainConfig, web3: options.web3, env: this.env
}); });
}; }
Deploy.prototype.determineArguments = function(suppliedArgs) { determineArguments(suppliedArgs) {
let realArgs = [], l, arg, contractName, referedContract; let realArgs = [], l, arg, contractName, referedContract;
for (l = 0; l < suppliedArgs.length; l++) { for (l = 0; l < suppliedArgs.length; l++) {
@ -31,9 +32,9 @@ Deploy.prototype.determineArguments = function(suppliedArgs) {
} }
return realArgs; return realArgs;
}; }
Deploy.prototype.checkAndDeployContract = function(contract, params, callback) { checkAndDeployContract(contract, params, callback) {
let self = this; let self = this;
let suppliedArgs; let suppliedArgs;
let realArgs; let realArgs;
@ -70,7 +71,7 @@ Deploy.prototype.checkAndDeployContract = function(contract, params, callback) {
realArgs = self.determineArguments(params || contract.args); realArgs = self.determineArguments(params || contract.args);
this.deployContract(contract, realArgs, function(err, address) { this.deployContract(contract, realArgs, function (err, address) {
if (err) { if (err) {
return callback(new Error(err)); return callback(new Error(err));
} }
@ -91,15 +92,15 @@ Deploy.prototype.checkAndDeployContract = function(contract, params, callback) {
}); });
} }
}; }
Deploy.prototype.deployContract = function(contract, params, callback) { deployContract(contract, params, callback) {
let self = this; let self = this;
let contractObject = this.web3.eth.contract(contract.abiDefinition); let contractObject = this.web3.eth.contract(contract.abiDefinition);
let contractParams = (params || contract.args).slice(); let contractParams = (params || contract.args).slice();
this.web3.eth.getAccounts(function(err, accounts) { this.web3.eth.getAccounts(function (err, accounts) {
if (err) { if (err) {
return callback(new Error(err)); return callback(new Error(err));
} }
@ -116,7 +117,7 @@ Deploy.prototype.deployContract = function(contract, params, callback) {
}); });
self.logger.info("deploying " + contract.className.bold.cyan + " with ".green + contract.gas + " gas".green); self.logger.info("deploying " + contract.className.bold.cyan + " with ".green + contract.gas + " gas".green);
contractParams.push(function(err, transaction) { contractParams.push(function (err, transaction) {
self.logger.contractsState(self.contractsManager.contractsState()); self.logger.contractsState(self.contractsManager.contractsState());
if (err) { if (err) {
@ -138,18 +139,18 @@ Deploy.prototype.deployContract = function(contract, params, callback) {
contractObject["new"].apply(contractObject, contractParams); contractObject["new"].apply(contractObject, contractParams);
}); });
}; }
Deploy.prototype.deployAll = function(done) { deployAll(done) {
let self = this; let self = this;
this.logger.info("deploying contracts"); this.logger.info("deploying contracts");
async.eachOfSeries(this.contractsManager.listContracts(), async.eachOfSeries(this.contractsManager.listContracts(),
function(contract, key, callback) { function (contract, key, callback) {
self.logger.trace(arguments); self.logger.trace(arguments);
self.checkAndDeployContract(contract, null, callback); self.checkAndDeployContract(contract, null, callback);
}, },
function(err, results) { function (err, results) {
if (err) { if (err) {
self.logger.error("error deploying contracts"); self.logger.error("error deploying contracts");
self.logger.error(err.message); self.logger.error(err.message);
@ -161,6 +162,7 @@ Deploy.prototype.deployAll = function(done) {
} }
); );
}; };
}
module.exports = Deploy; module.exports = Deploy;

View File

@ -1,22 +1,20 @@
let async = require('async'); let async = require('async');
let Deploy = require('./deploy.js'); let Deploy = require('./deploy.js');
let ContractsManager = require('./contracts.js'); let ContractsManager = require('./contracts.js');
const EventEmitter = require('events').EventEmitter; let EventEmitter = require('events');
let DeployManager = function(options) { class DeployManager {
constructor(options) {
this.config = options.config; this.config = options.config;
this.logger = options.logger; this.logger = options.logger;
this.blockchainConfig = this.config.blockchainConfig; this.blockchainConfig = this.config.blockchainConfig;
this.plugins = options.plugins; this.plugins = options.plugins;
this.web3 = options.web3; this.web3 = options.web3;
this.chainConfig = (options.trackContracts !== false) ? this.config.chainTracker : false; this.chainConfig = (options.trackContracts !== false) ? this.config.chainTracker : false;
}; Object.create(EventEmitter.prototype);
}
DeployManager.prototype = Object.create(EventEmitter.prototype); deployContracts(done) {
DeployManager.prototype.deployContracts = function(done) {
let self = this; let self = this;
if (self.blockchainConfig === {} || self.blockchainConfig.enabled === false) { if (self.blockchainConfig === {} || self.blockchainConfig.enabled === false) {
@ -45,7 +43,7 @@ DeployManager.prototype.deployContracts = function(done) {
return callback(Error("error connecting to blockchain node")); return callback(Error("error connecting to blockchain node"));
} }
if (self.web3.currentProvider.isConnected === undefined) { if (self.web3.currentProvider.isConnected === undefined) {
self.web3.version.getNode(function(err, version) { self.web3.version.getNode(function (err, version) {
if (err) { if (err) {
return callback(Error("error connecting to blockchain node")); return callback(Error("error connecting to blockchain node"));
} }
@ -56,7 +54,7 @@ DeployManager.prototype.deployContracts = function(done) {
} }
}, },
function setDefaultAccount(contractsManager, web3, callback) { function setDefaultAccount(contractsManager, web3, callback) {
web3.eth.getAccounts(function(err, accounts) { web3.eth.getAccounts(function (err, accounts) {
if (err) { if (err) {
return callback(new Error(err)); return callback(new Error(err));
} }
@ -74,18 +72,20 @@ DeployManager.prototype.deployContracts = function(done) {
chainConfig: self.chainConfig, chainConfig: self.chainConfig,
env: self.config.env env: self.config.env
}); });
deploy.deployAll(function() { deploy.deployAll(function () {
self.emit('contractsDeployed', contractsManager); self.emit('contractsDeployed', contractsManager);
callback(null, contractsManager); callback(null, contractsManager);
}); });
} }
], function(err, result) { ], function (err, result) {
if (err) { if (err) {
done(err, null); done(err, null);
} else { } else {
done(null, result); done(null, result);
} }
}); });
}; }
}
module.exports = DeployManager; module.exports = DeployManager;

View File

@ -1,6 +1,7 @@
let fs = require('../core/fs.js'); let fs = require('../core/fs.js');
let DeployTracker = function(options) { class DeployTracker {
constructor(options) {
this.logger = options.logger; this.logger = options.logger;
this.env = options.env; this.env = options.env;
this.chainConfig = options.chainConfig; this.chainConfig = options.chainConfig;
@ -25,32 +26,37 @@ let DeployTracker = function(options) {
// TODO: add other params // TODO: add other params
//this.currentChain.networkId = ""; //this.currentChain.networkId = "";
//this.currentChain.networkType = "custom" //this.currentChain.networkType = "custom"
}; }
DeployTracker.prototype.loadConfig = function(config) { loadConfig(config) {
this.chainConfig = config; this.chainConfig = config;
return this; return this;
}; }
DeployTracker.prototype.trackContract = function(contractName, code, args, address) { trackContract(contractName, code, args, address) {
this.currentChain.contracts[this.web3.sha3(code + contractName + args.join(','))] = { this.currentChain.contracts[this.web3.sha3(code + contractName + args.join(','))] = {
name: contractName, name: contractName,
address: address address: address
}; };
}; }
DeployTracker.prototype.getContract = function(contractName, code, args) { getContract(contractName, code, args) {
let contract = this.currentChain.contracts[this.web3.sha3(code + contractName + args.join(','))]; let contract = this.currentChain.contracts[this.web3.sha3(code + contractName + args.join(','))];
if (contract && contract.address === undefined) { return false; } if (contract && contract.address === undefined) {
return false;
}
return contract; return contract;
}; }
// TODO: abstract this // TODO: abstract this
// chainConfig can be an abstract PersistentObject // chainConfig can be an abstract PersistentObject
DeployTracker.prototype.save = function() { save() {
if (this.chainConfig === false) { return; } if (this.chainConfig === false) {
return;
}
fs.writeJSONSync("./chains.json", this.chainConfig); fs.writeJSONSync("./chains.json", this.chainConfig);
}; }
}
module.exports = DeployTracker; module.exports = DeployTracker;

View File

@ -1,6 +1,6 @@
let solc; let solc;
process.on('message', function(msg) { process.on('message', function (msg) {
if (msg.action === 'loadCompiler') { if (msg.action === 'loadCompiler') {
solc = require('solc'); solc = require('solc');
process.send({result: "loadedCompiler"}); process.send({result: "loadedCompiler"});
@ -12,7 +12,7 @@ process.on('message', function(msg) {
} }
}); });
process.on('exit', function() { process.on('exit', function () {
process.exit(0); process.exit(0);
}); });

View File

@ -2,13 +2,14 @@ let utils = require('../utils/utils.js');
let solcProcess; let solcProcess;
let compilerLoaded = false; let compilerLoaded = false;
let SolcW = function() { class SolcW {
};
SolcW.prototype.load_compiler = function(done) { load_compiler(done) {
if (compilerLoaded) { done(); } if (compilerLoaded) {
done();
}
solcProcess = require('child_process').fork(utils.joinPath(__dirname, '/solcP.js')); solcProcess = require('child_process').fork(utils.joinPath(__dirname, '/solcP.js'));
solcProcess.once('message', function(msg) { solcProcess.once('message', function (msg) {
if (msg.result !== 'loadedCompiler') { if (msg.result !== 'loadedCompiler') {
return; return;
} }
@ -16,21 +17,22 @@ SolcW.prototype.load_compiler = function(done) {
done(); done();
}); });
solcProcess.send({action: 'loadCompiler'}); solcProcess.send({action: 'loadCompiler'});
}; }
SolcW.prototype.isCompilerLoaded = function() { isCompilerLoaded() {
return (compilerLoaded === true); return (compilerLoaded === true);
}; }
SolcW.prototype.compile = function(obj, optimize, done) { compile(obj, optimize, done) {
solcProcess.once('message', function(msg) { solcProcess.once('message', function (msg) {
if (msg.result !== 'compilation') { if (msg.result !== 'compilation') {
return; return;
} }
done(msg.output); done(msg.output);
}); });
solcProcess.send({action: 'compile', obj: obj, optimize: optimize}); solcProcess.send({action: 'compile', obj: obj, optimize: optimize});
}; }
}
module.exports = SolcW; module.exports = SolcW;

View File

@ -4,7 +4,8 @@ let utils = require('../utils/utils.js');
// TODO: add wrapper for fs so it can also work in the browser // TODO: add wrapper for fs so it can also work in the browser
// can work with both read and save // can work with both read and save
let Config = function(options) { class Config {
constructor(options) {
this.env = options.env; this.env = options.env;
this.blockchainConfig = {}; this.blockchainConfig = {};
this.contractsConfig = {}; this.contractsConfig = {};
@ -18,9 +19,10 @@ let Config = function(options) {
this.plugins = options.plugins; this.plugins = options.plugins;
this.logger = options.logger; this.logger = options.logger;
this.events = options.events; this.events = options.events;
}; }
}
Config.prototype.loadConfigFiles = function(options) { Config.prototype.loadConfigFiles = function (options) {
let interceptLogs = options.interceptLogs; let interceptLogs = options.interceptLogs;
if (options.interceptLogs === undefined) { if (options.interceptLogs === undefined) {
interceptLogs = true; interceptLogs = true;
@ -28,7 +30,7 @@ Config.prototype.loadConfigFiles = function(options) {
//Check if the config file exists //Check if the config file exists
let embarkConfigExists = fs.existsSync(options.embarkConfig); let embarkConfigExists = fs.existsSync(options.embarkConfig);
if(!embarkConfigExists){ if (!embarkConfigExists) {
this.logger.error('Cannot find file ' + options.embarkConfig + '. Please ensure you are running this command inside the Dapp folder'); this.logger.error('Cannot find file ' + options.embarkConfig + '. Please ensure you are running this command inside the Dapp folder');
process.exit(1); process.exit(1);
} }
@ -36,7 +38,13 @@ Config.prototype.loadConfigFiles = function(options) {
this.embarkConfig = fs.readJSONSync(options.embarkConfig); this.embarkConfig = fs.readJSONSync(options.embarkConfig);
this.embarkConfig.plugins = this.embarkConfig.plugins || {}; this.embarkConfig.plugins = this.embarkConfig.plugins || {};
this.plugins = new Plugins({plugins: this.embarkConfig.plugins, logger: this.logger, interceptLogs: interceptLogs, events: this.events, config: this}); this.plugins = new Plugins({
plugins: this.embarkConfig.plugins,
logger: this.logger,
interceptLogs: interceptLogs,
events: this.events,
config: this
});
this.plugins.loadPlugins(); this.plugins.loadPlugins();
this.load(); this.load();
@ -45,7 +53,7 @@ Config.prototype.loadConfigFiles = function(options) {
this.loadPluginContractFiles(); this.loadPluginContractFiles();
}; };
Config.prototype.load = Config.prototype.reloadConfig = function() { Config.prototype.load = Config.prototype.reloadConfig = function () {
this.loadEmbarkConfigFile(); this.loadEmbarkConfigFile();
this.loadBlockchainConfigFile(); this.loadBlockchainConfigFile();
this.loadStorageConfigFile(); this.loadStorageConfigFile();
@ -55,7 +63,7 @@ Config.prototype.load = Config.prototype.reloadConfig = function() {
this.loadChainTrackerFile(); this.loadChainTrackerFile();
}; };
Config.prototype.loadBlockchainConfigFile = function() { Config.prototype.loadBlockchainConfigFile = function () {
let defaultBlockchainConfig = fs.readJSONSync(this.configDir + "blockchain.json"); let defaultBlockchainConfig = fs.readJSONSync(this.configDir + "blockchain.json");
this.blockchainConfig = defaultBlockchainConfig[this.env] || {}; this.blockchainConfig = defaultBlockchainConfig[this.env] || {};
@ -64,7 +72,7 @@ Config.prototype.loadBlockchainConfigFile = function() {
} }
}; };
Config.prototype.loadContractsConfigFile = function() { Config.prototype.loadContractsConfigFile = function () {
let configObject = {}; let configObject = {};
let configPlugins = []; let configPlugins = [];
@ -72,8 +80,8 @@ Config.prototype.loadContractsConfigFile = function() {
configPlugins = kinds; configPlugins = kinds;
}); });
if (configPlugins.length > 0) { if (configPlugins.length > 0) {
configPlugins.forEach(function(plugin) { configPlugins.forEach(function (plugin) {
plugin.contractsConfigs.forEach(function(pluginConfig) { plugin.contractsConfigs.forEach(function (pluginConfig) {
configObject = utils.recursiveMerge(configObject, pluginConfig); configObject = utils.recursiveMerge(configObject, pluginConfig);
}); });
}); });
@ -88,7 +96,7 @@ Config.prototype.loadContractsConfigFile = function() {
}; };
Config.prototype.loadStorageConfigFile = function() { Config.prototype.loadStorageConfigFile = function () {
let configObject = { let configObject = {
"default": { "default": {
"enabled": true, "enabled": true,
@ -98,8 +106,7 @@ Config.prototype.loadStorageConfigFile = function() {
"host": "localhost", "host": "localhost",
"port": 5001 "port": 5001
}, },
"development": { "development": {}
}
}; };
//let configPlugins = this.plugins.getPluginsFor('storageConfig'); //let configPlugins = this.plugins.getPluginsFor('storageConfig');
@ -131,7 +138,7 @@ Config.prototype.loadStorageConfigFile = function() {
} }
}; };
Config.prototype.loadCommunicationConfigFile = function() { Config.prototype.loadCommunicationConfigFile = function () {
let configObject = { let configObject = {
"default": { "default": {
"enabled": true, "enabled": true,
@ -171,7 +178,7 @@ Config.prototype.loadCommunicationConfigFile = function() {
} }
}; };
Config.prototype.loadWebServerConfigFile = function() { Config.prototype.loadWebServerConfigFile = function () {
let webServerConfigJSON; let webServerConfigJSON;
if (fs.existsSync(this.configDir + "webserver.json")) { if (fs.existsSync(this.configDir + "webserver.json")) {
webServerConfigJSON = fs.readJSONSync(this.configDir + "webserver.json"); webServerConfigJSON = fs.readJSONSync(this.configDir + "webserver.json");
@ -186,7 +193,7 @@ Config.prototype.loadWebServerConfigFile = function() {
this.webServerConfig = utils.recursiveMerge(defaultWebConfig, webServerConfigJSON); this.webServerConfig = utils.recursiveMerge(defaultWebConfig, webServerConfigJSON);
}; };
Config.prototype.loadEmbarkConfigFile = function() { Config.prototype.loadEmbarkConfigFile = function () {
let contracts = this.embarkConfig.contracts; let contracts = this.embarkConfig.contracts;
this.contractsFiles = this.loadFiles(contracts); this.contractsFiles = this.loadFiles(contracts);
@ -194,20 +201,20 @@ Config.prototype.loadEmbarkConfigFile = function() {
this.configDir = this.embarkConfig.config; this.configDir = this.embarkConfig.config;
}; };
Config.prototype.loadPipelineConfigFile = function() { Config.prototype.loadPipelineConfigFile = function () {
let assets = this.embarkConfig.app; let assets = this.embarkConfig.app;
for(let targetFile in assets) { for (let targetFile in assets) {
this.assetFiles[targetFile] = this.loadFiles(assets[targetFile]); this.assetFiles[targetFile] = this.loadFiles(assets[targetFile]);
} }
}; };
Config.prototype.loadChainTrackerFile = function() { Config.prototype.loadChainTrackerFile = function () {
//let self = this; //let self = this;
let chainTracker; let chainTracker;
try { try {
chainTracker = fs.readJSONSync(this.chainsFile); chainTracker = fs.readJSONSync(this.chainsFile);
} }
catch(err) { catch (err) {
//self.logger.info(this.chainsFile + ' file not found, creating it...'); //self.logger.info(this.chainsFile + ' file not found, creating it...');
chainTracker = {}; chainTracker = {};
fs.writeJSONSync(this.chainsFile, {}); fs.writeJSONSync(this.chainsFile, {});
@ -215,32 +222,52 @@ Config.prototype.loadChainTrackerFile = function() {
this.chainTracker = chainTracker; this.chainTracker = chainTracker;
}; };
Config.prototype.loadFiles = function(files) { Config.prototype.loadFiles = function (files) {
let self = this; let self = this;
let originalFiles = utils.filesMatchingPattern(files); let originalFiles = utils.filesMatchingPattern(files);
let readFiles = []; let readFiles = [];
// get embark.js object first // get embark.js object first
originalFiles.filter(function(file) { originalFiles.filter(function (file) {
return file.indexOf('.') >= 0; return file.indexOf('.') >= 0;
}).filter(function(file) { }).filter(function (file) {
if (file === 'embark.js') { if (file === 'embark.js') {
if (self.blockchainConfig.enabled || self.communicationConfig.provider === 'whisper' || self.communicationConfig.available_providers.indexOf('whisper') >= 0) { if (self.blockchainConfig.enabled || self.communicationConfig.provider === 'whisper' || self.communicationConfig.available_providers.indexOf('whisper') >= 0) {
readFiles.push({filename: 'web3.js', content: fs.readFileSync(fs.embarkPath("js/web3.js")).toString(), path: fs.embarkPath("js/web3.js")}); readFiles.push({
filename: 'web3.js',
content: fs.readFileSync(fs.embarkPath("js/web3.js")).toString(),
path: fs.embarkPath("js/web3.js")
});
} }
if (self.storageConfig.enabled && (self.storageConfig.provider === 'ipfs' || self.storageConfig.available_providers.indexOf('ipfs') >= 0)) { if (self.storageConfig.enabled && (self.storageConfig.provider === 'ipfs' || self.storageConfig.available_providers.indexOf('ipfs') >= 0)) {
readFiles.push({filename: 'ipfs.js', content: fs.readFileSync(fs.embarkPath("js/ipfs.js")).toString(), path: fs.embarkPath("js/ipfs.js")}); readFiles.push({
filename: 'ipfs.js',
content: fs.readFileSync(fs.embarkPath("js/ipfs.js")).toString(),
path: fs.embarkPath("js/ipfs.js")
});
} }
if (self.communicationConfig.enabled && (self.communicationConfig.provider === 'orbit' || self.communicationConfig.available_providers.indexOf('orbit') >= 0)) { if (self.communicationConfig.enabled && (self.communicationConfig.provider === 'orbit' || self.communicationConfig.available_providers.indexOf('orbit') >= 0)) {
// TODO: remove duplicated files if functionality is the same for storage and orbit // TODO: remove duplicated files if functionality is the same for storage and orbit
readFiles.push({filename: 'ipfs-api.js', content: fs.readFileSync(fs.embarkPath("js/ipfs-api.min.js")).toString(), path: fs.embarkPath("js/ipfs-api.min.js")}); readFiles.push({
readFiles.push({filename: 'orbit.js', content: fs.readFileSync(fs.embarkPath("js/orbit.min.js")).toString(), path: fs.embarkPath("js/orbit.min.js")}); filename: 'ipfs-api.js',
content: fs.readFileSync(fs.embarkPath("js/ipfs-api.min.js")).toString(),
path: fs.embarkPath("js/ipfs-api.min.js")
});
readFiles.push({
filename: 'orbit.js',
content: fs.readFileSync(fs.embarkPath("js/orbit.min.js")).toString(),
path: fs.embarkPath("js/orbit.min.js")
});
} }
readFiles.push({filename: 'embark.js', content: fs.readFileSync(fs.embarkPath("js/build/embark.bundle.js")).toString(), path: fs.embarkPath("js/build/embark.bundle.js")}); readFiles.push({
filename: 'embark.js',
content: fs.readFileSync(fs.embarkPath("js/build/embark.bundle.js")).toString(),
path: fs.embarkPath("js/build/embark.bundle.js")
});
} }
}); });
@ -250,30 +277,30 @@ Config.prototype.loadFiles = function(files) {
let filePlugins = self.plugins.getPluginsFor('pipelineFiles'); let filePlugins = self.plugins.getPluginsFor('pipelineFiles');
if (filePlugins.length > 0) { if (filePlugins.length > 0) {
filePlugins.forEach(function(plugin) { filePlugins.forEach(function (plugin) {
try { try {
let fileObjects = plugin.runFilePipeline(); let fileObjects = plugin.runFilePipeline();
for (let i=0; i < fileObjects.length; i++) { for (let i = 0; i < fileObjects.length; i++) {
let fileObject = fileObjects[i]; let fileObject = fileObjects[i];
filesFromPlugins.push(fileObject); filesFromPlugins.push(fileObject);
} }
} }
catch(err) { catch (err) {
self.logger.error(err.message); self.logger.error(err.message);
} }
}); });
} }
filesFromPlugins.filter(function(file) { filesFromPlugins.filter(function (file) {
if (utils.fileMatchesPattern(files, file.intendedPath)) { if (utils.fileMatchesPattern(files, file.intendedPath)) {
readFiles.push(file); readFiles.push(file);
} }
}); });
// get user files // get user files
originalFiles.filter(function(file) { originalFiles.filter(function (file) {
return file.indexOf('.') >= 0; return file.indexOf('.') >= 0;
}).filter(function(file) { }).filter(function (file) {
if (file === 'embark.js') { if (file === 'embark.js') {
return; return;
} else if (file === 'abi.js') { } else if (file === 'abi.js') {
@ -286,15 +313,19 @@ Config.prototype.loadFiles = function(files) {
return readFiles; return readFiles;
}; };
Config.prototype.loadPluginContractFiles = function() { Config.prototype.loadPluginContractFiles = function () {
let self = this; let self = this;
let contractsPlugins = this.plugins.getPluginsFor('contractFiles'); let contractsPlugins = this.plugins.getPluginsFor('contractFiles');
if (contractsPlugins.length > 0) { if (contractsPlugins.length > 0) {
contractsPlugins.forEach(function(plugin) { contractsPlugins.forEach(function (plugin) {
plugin.contractsFiles.forEach(function(file) { plugin.contractsFiles.forEach(function (file) {
let filename = file.replace('./',''); let filename = file.replace('./', '');
self.contractsFiles.push({filename: filename, content: plugin.loadPluginFile(file), path: plugin.pathToFile(file)}); self.contractsFiles.push({
filename: filename,
content: plugin.loadPluginFile(file),
path: plugin.pathToFile(file)
});
}); });
}); });
} }

View File

@ -1,5 +1,5 @@
class Core {
let Core = function() {}; }
module.exports = Core; module.exports = Core;

View File

@ -1,27 +1,27 @@
let http = require('http'); let http = require('http');
let Web3 = require('web3'); let Web3 = require('web3');
let utils = require('../utils/utils.js'); let utils = require('../utils/utils.js');
let Events = require('./events.js'); let Events = require('./events.js');
let Logger = require('./logger.js'); let Logger = require('./logger.js');
let Config = require('./config.js'); let Config = require('./config.js');
let DeployManager = require('../contracts/deploy_manager.js'); let DeployManager = require('../contracts/deploy_manager.js');
let ABIGenerator = require('../contracts/abi.js'); let ABIGenerator = require('../contracts/abi.js');
let ServicesMonitor = require('./services_monitor.js'); let ServicesMonitor = require('./services_monitor.js');
let Pipeline = require('../pipeline/pipeline.js'); let Pipeline = require('../pipeline/pipeline.js');
let Server = require('../pipeline/server.js'); let Serve = require('../pipeline/server.js');
let Watch = require('../pipeline/watch.js'); let Watch = require('../pipeline/watch.js');
let version = require('../../package.json').version; let version = require('../../package.json');
let Engine = function(options) { class Engine {
constructor(options) {
this.env = options.env; this.env = options.env;
this.embarkConfig = options.embarkConfig; this.embarkConfig = options.embarkConfig;
this.interceptLogs = options.interceptLogs; this.interceptLogs = options.interceptLogs;
this.version = version; this.version = version;
}; }
}
Engine.prototype.init = function(_options) { Engine.prototype.init = function (_options) {
let self = this; let self = this;
let options = _options || {}; let options = _options || {};
this.events = new Events(); this.events = new Events();
@ -31,17 +31,17 @@ Engine.prototype.init = function(_options) {
this.plugins = this.config.plugins; this.plugins = this.config.plugins;
this.servicesMonitor = new ServicesMonitor({events: this.events, logger: this.logger}); this.servicesMonitor = new ServicesMonitor({events: this.events, logger: this.logger});
this.servicesMonitor.addCheck('embarkVersion', function(cb) { this.servicesMonitor.addCheck('embarkVersion', function (cb) {
return cb({name: 'Embark ' + self.version, status: 'green'}); return cb({name: 'Embark ' + self.version, status: 'green'});
}, 0); }, 0);
}; };
Engine.prototype.startMonitor = function() { Engine.prototype.startMonitor = function () {
let self = this; let self = this;
if (this.plugins) { if (this.plugins) {
let servicePlugins = this.plugins.getPluginsFor('serviceChecks'); let servicePlugins = this.plugins.getPluginsFor('serviceChecks');
servicePlugins.forEach(function(plugin) { servicePlugins.forEach(function (plugin) {
plugin.serviceChecks.forEach(function(pluginCheck) { plugin.serviceChecks.forEach(function (pluginCheck) {
self.servicesMonitor.addCheck(pluginCheck.checkName, pluginCheck.checkFn, pluginCheck.time); self.servicesMonitor.addCheck(pluginCheck.checkName, pluginCheck.checkFn, pluginCheck.time);
}); });
}); });
@ -49,7 +49,7 @@ Engine.prototype.startMonitor = function() {
this.servicesMonitor.startMonitor(); this.servicesMonitor.startMonitor();
}; };
Engine.prototype.startService = function(serviceName, _options) { Engine.prototype.startService = function (serviceName, _options) {
let options = _options || {}; let options = _options || {};
let services = { let services = {
@ -73,7 +73,7 @@ Engine.prototype.startService = function(serviceName, _options) {
return service.apply(this, [options]); return service.apply(this, [options]);
}; };
Engine.prototype.pipelineService = function(options) { Engine.prototype.pipelineService = function (options) {
let self = this; let self = this;
this.logger.setStatus("Building Assets"); this.logger.setStatus("Building Assets");
let pipeline = new Pipeline({ let pipeline = new Pipeline({
@ -83,7 +83,7 @@ Engine.prototype.pipelineService = function(options) {
logger: this.logger, logger: this.logger,
plugins: this.plugins plugins: this.plugins
}); });
this.events.on('abi', function(abi) { this.events.on('abi', function (abi) {
self.currentAbi = abi; self.currentAbi = abi;
pipeline.build(abi); pipeline.build(abi);
self.events.emit('outputDone'); self.events.emit('outputDone');
@ -99,9 +99,9 @@ Engine.prototype.pipelineService = function(options) {
//}); //});
}; };
Engine.prototype.abiService = function(options) { Engine.prototype.abiService = function (options) {
let self = this; let self = this;
let generateABICode = function(contractsManager) { let generateABICode = function (contractsManager) {
let abiGenerator = new ABIGenerator({ let abiGenerator = new ABIGenerator({
blockchainConfig: self.config.blockchainConfig, blockchainConfig: self.config.blockchainConfig,
contractsManager: contractsManager, contractsManager: contractsManager,
@ -121,7 +121,7 @@ Engine.prototype.abiService = function(options) {
this.events.on('blockchainDisabled', generateABICode); this.events.on('blockchainDisabled', generateABICode);
}; };
Engine.prototype.deploymentService = function(options) { Engine.prototype.deploymentService = function (options) {
let self = this; let self = this;
this.deployManager = new DeployManager({ this.deployManager = new DeployManager({
web3: options.web3 || self.web3, web3: options.web3 || self.web3,
@ -132,26 +132,29 @@ Engine.prototype.deploymentService = function(options) {
events: this.events events: this.events
}); });
this.events.on('file-event', function(fileType, path) { this.events.on('file-event', function (fileType, path) {
// TODO: for now need to deploy on asset chanes as well // TODO: for now need to deploy on asset chanes as well
// because the contractsManager config is corrupted after a deploy // because the contractsManager config is corrupted after a deploy
//if (fileType === 'contract' || fileType === 'config') { //if (fileType === 'contract' || fileType === 'config') {
self.config.reloadConfig(); self.config.reloadConfig();
self.deployManager.deployContracts(function() {}); self.deployManager.deployContracts(function () {
});
//} //}
}); });
}; };
Engine.prototype.fileWatchService = function(options) { Engine.prototype.fileWatchService = function (options) {
this.logger.setStatus("Watching for changes"); this.logger.setStatus("Watching for changes");
let watch = new Watch({logger: this.logger, events: this.events}); let watch = new Watch({logger: this.logger, events: this.events});
watch.start(); watch.start();
}; };
Engine.prototype.webServerService = function(options) { Engine.prototype.webServerService = function (options) {
let self = this; let self = this;
let webServerConfig = this.config.webServerConfig; let webServerConfig = this.config.webServerConfig;
if (!webServerConfig.enabled) { return; } if (!webServerConfig.enabled) {
return;
}
let host = options.host || webServerConfig.host; let host = options.host || webServerConfig.host;
let port = options.port || webServerConfig.port; let port = options.port || webServerConfig.port;
@ -163,43 +166,43 @@ Engine.prototype.webServerService = function(options) {
port: port port: port
}); });
self.servicesMonitor.addCheck('Webserver', function(cb) { self.servicesMonitor.addCheck('Webserver', function (cb) {
let devServer = 'Webserver (http://' + host + ':' + port + ')'; let devServer = 'Webserver (http://' + host + ':' + port + ')';
return cb({name: devServer, status: 'green'}); return cb({name: devServer, status: 'green'});
}); });
server.start(function(){ server.start(function () {
}); });
}; };
Engine.prototype.ipfsService = function(options) { Engine.prototype.ipfsService = function (options) {
let self = this; let self = this;
self.servicesMonitor.addCheck('IPFS', function(cb) { self.servicesMonitor.addCheck('IPFS', function (cb) {
utils.checkIsAvailable('http://localhost:5001', function(available) { utils.checkIsAvailable('http://localhost:5001', function (available) {
if (available) { if (available) {
//Ideally this method should be in an IPFS API JSONRPC wrapper //Ideally this method should be in an IPFS API JSONRPC wrapper
//The URL should also be flexible to accept non-default IPFS url //The URL should also be flexible to accept non-default IPFS url
self.logger.trace("Checking IPFS version..."); self.logger.trace("Checking IPFS version...");
http.get('http://localhost:5001/api/v0/version', function(res) { http.get('http://localhost:5001/api/v0/version', function (res) {
let body = ''; let body = '';
res.on('data', function(d) { res.on('data', function (d) {
body += d; body += d;
}); });
res.on('end', function() { res.on('end', function () {
try{ try {
let parsed = JSON.parse(body); let parsed = JSON.parse(body);
if(parsed.Version){ if (parsed.Version) {
return cb({name: ("IPFS " + parsed.Version), status: 'green'}); return cb({name: ("IPFS " + parsed.Version), status: 'green'});
} }
else{ else {
return cb({name: "IPFS ", status: 'green'}); return cb({name: "IPFS ", status: 'green'});
} }
} }
catch (e){ catch (e) {
return cb({name: "IPFS ", status: 'red'}); return cb({name: "IPFS ", status: 'red'});
} }
}); });
res.on('error', function(err) { res.on('error', function (err) {
self.logger.trace("Check IPFS version error: " + err); self.logger.trace("Check IPFS version error: " + err);
return cb({name: "IPFS ", status: 'red'}); return cb({name: "IPFS ", status: 'red'});
}); });
@ -212,7 +215,7 @@ Engine.prototype.ipfsService = function(options) {
}); });
}; };
Engine.prototype.web3Service = function(options) { Engine.prototype.web3Service = function (options) {
let self = this; let self = this;
this.web3 = options.web3; this.web3 = options.web3;
if (this.web3 === undefined) { if (this.web3 === undefined) {
@ -221,16 +224,19 @@ Engine.prototype.web3Service = function(options) {
this.web3.setProvider(new this.web3.providers.HttpProvider(web3Endpoint)); this.web3.setProvider(new this.web3.providers.HttpProvider(web3Endpoint));
} }
self.servicesMonitor.addCheck('Ethereum', function(cb) { self.servicesMonitor.addCheck('Ethereum', function (cb) {
if (self.web3.isConnected()) { if (self.web3.isConnected()) {
return cb({name: (self.web3.version.node.split("/")[0] + " " + self.web3.version.node.split("/")[1].split("-")[0] + " (Ethereum)"), status: 'green'}); return cb({
name: (self.web3.version.node.split("/")[0] + " " + self.web3.version.node.split("/")[1].split("-")[0] + " (Ethereum)"),
status: 'green'
});
} else { } else {
return cb({name: "No Blockchain node found", status: 'red'}); return cb({name: "No Blockchain node found", status: 'red'});
} }
}); });
self.servicesMonitor.addCheck('Whisper', function(cb) { self.servicesMonitor.addCheck('Whisper', function (cb) {
self.web3.version.getWhisper(function(err, res) { self.web3.version.getWhisper(function (err, res) {
if (err) { if (err) {
return cb({name: 'Whisper', status: 'red'}); return cb({name: 'Whisper', status: 'red'});
} else { } else {

View File

@ -1,4 +1,12 @@
//TODO: This is deprecated because Embark extends EventEmitter now //TODO: This is deprecated because Embark extends EventEmitter now
let EventEmitter = require('events'); let events = require('events');
class EventEmitter {
constructor(options) {
this.options = options;
}
}
EventEmitter.prototype = Object.create(events.EventEmitter.prototype);
module.exports = EventEmitter; module.exports = EventEmitter;

View File

@ -25,7 +25,7 @@ function writeJSONSync() {
return fs.writeJSONSync.apply(fs.writeJSONSync, arguments); return fs.writeJSONSync.apply(fs.writeJSONSync, arguments);
} }
function existsSync(){ function existsSync() {
return fs.existsSync.apply(fs.existsSync, arguments); return fs.existsSync.apply(fs.existsSync, arguments);
} }

View File

@ -1,39 +1,52 @@
let colors = require('colors'); let colors = require('colors');
let Logger = function(options) { class Logger {
constructor(options) {
this.logLevels = ['error', 'warn', 'info', 'debug', 'trace']; this.logLevels = ['error', 'warn', 'info', 'debug', 'trace'];
this.logLevel = options.logLevel || 'info'; this.logLevel = options.logLevel || 'info';
this.logFunction = options.logFunction || console.log; this.logFunction = options.logFunction || console.log;
this.contractsState = options.contractsState || function() {}; this.contractsState = options.contractsState || function () {
};
this.setStatus = options.setStatus || console.log; this.setStatus = options.setStatus || console.log;
}; }
}
Logger.prototype.error = function(txt) { Logger.prototype.error = function (txt) {
if (!(this.shouldLog('error'))) { return; } if (!(this.shouldLog('error'))) {
return;
}
this.logFunction(txt.red); this.logFunction(txt.red);
}; };
Logger.prototype.warn = function(txt) { Logger.prototype.warn = function (txt) {
if (!(this.shouldLog('warn'))) { return; } if (!(this.shouldLog('warn'))) {
return;
}
this.logFunction(txt.yellow); this.logFunction(txt.yellow);
}; };
Logger.prototype.info = function(txt) { Logger.prototype.info = function (txt) {
if (!(this.shouldLog('info'))) { return; } if (!(this.shouldLog('info'))) {
return;
}
this.logFunction(txt.green); this.logFunction(txt.green);
}; };
Logger.prototype.debug = function(txt) { Logger.prototype.debug = function (txt) {
if (!(this.shouldLog('debug'))) { return; } if (!(this.shouldLog('debug'))) {
return;
}
this.logFunction(txt); this.logFunction(txt);
}; };
Logger.prototype.trace = function(txt) { Logger.prototype.trace = function (txt) {
if (!(this.shouldLog('trace'))) { return; } if (!(this.shouldLog('trace'))) {
return;
}
this.logFunction(txt); this.logFunction(txt);
}; };
Logger.prototype.shouldLog = function(level) { Logger.prototype.shouldLog = function (level) {
return (this.logLevels.indexOf(level) <= this.logLevels.indexOf(this.logLevel)); return (this.logLevels.indexOf(level) <= this.logLevels.indexOf(this.logLevel));
}; };

View File

@ -3,7 +3,8 @@ let fs = require('./fs.js');
let utils = require('../utils/utils.js'); let utils = require('../utils/utils.js');
let camelcase = require("underscore.string").camelcase; let camelcase = require("underscore.string").camelcase;
let Plugin = function(options) { class Plugin {
constructor(options) {
this.config = {}; this.config = {};
for (let opt in options) { for (let opt in options) {
if (options.hasOwnProperty(opt)) { if (options.hasOwnProperty(opt)) {
@ -32,9 +33,10 @@ let Plugin = function(options) {
if (!(this instanceof Plugin)) { if (!(this instanceof Plugin)) {
return new Plugin(); return new Plugin();
} }
}; }
}
Plugin.prototype.runPlugin = Plugin.prototype.run = function() { Plugin.prototype.runPlugin = Plugin.prototype.run = function () {
if (this.shouldInterceptLogs) { if (this.shouldInterceptLogs) {
this.interceptLogs(this.pluginModule); this.interceptLogs(this.pluginModule);
} }
@ -42,15 +44,15 @@ Plugin.prototype.runPlugin = Plugin.prototype.run = function() {
this.call(this.loadPluginFile(fullyQualifiedPath), this); this.call(this.loadPluginFile(fullyQualifiedPath), this);
}; };
Plugin.prototype.loadPluginFile = function(filename) { Plugin.prototype.loadPluginFile = function (filename) {
return fs.readFileSync(this.pathToFile(filename)).toString(); return fs.readFileSync(this.pathToFile(filename)).toString();
}; };
Plugin.prototype.pathToFile = function(filename) { Plugin.prototype.pathToFile = function (filename) {
return utils.joinPath(this.pluginPath, filename); return utils.joinPath(this.pluginPath, filename);
}; };
Plugin.prototype.interceptLogs = function(context) { Plugin.prototype.interceptLogs = function (context) {
let self = this; let self = this;
// TODO: this is a bit nasty, figure out a better way // TODO: this is a bit nasty, figure out a better way
context.console = context.console || console; context.console = context.console || console;
@ -60,20 +62,20 @@ Plugin.prototype.interceptLogs = function(context) {
// //self.logger.error.apply(self.logger, arguments); // //self.logger.error.apply(self.logger, arguments);
// self.logger.error(self.name + " > " + txt); // self.logger.error(self.name + " > " + txt);
//}; //};
context.console.log = function(txt) { context.console.log = function (txt) {
self.logger.info(self.name + " > " + txt); self.logger.info(self.name + " > " + txt);
}; };
context.console.warn = function(txt) { context.console.warn = function (txt) {
self.logger.warn(self.name + " > " + txt); self.logger.warn(self.name + " > " + txt);
}; };
context.console.info = function(txt) { context.console.info = function (txt) {
self.logger.info(self.name + " > " + txt); self.logger.info(self.name + " > " + txt);
}; };
context.console.debug = function(txt) { context.console.debug = function (txt) {
// TODO: ue JSON.stringify // TODO: ue JSON.stringify
self.logger.debug(self.name + " > " + txt); self.logger.debug(self.name + " > " + txt);
}; };
context.console.trace = function(txt) { context.console.trace = function (txt) {
self.logger.trace(self.name + " > " + txt); self.logger.trace(self.name + " > " + txt);
}; };
}; };
@ -92,80 +94,80 @@ Plugin.prototype.register = function (classname, cb) {
}); });
// TODO: add deploy provider // TODO: add deploy provider
Plugin.prototype.registerClientWeb3Provider = function(cb) { Plugin.prototype.registerClientWeb3Provider = function (cb) {
this.clientWeb3Providers.push(cb); this.clientWeb3Providers.push(cb);
this.pluginTypes.push('clientWeb3Provider'); this.pluginTypes.push('clientWeb3Provider');
}; };
Plugin.prototype.registerContractsGeneration = function(cb) { Plugin.prototype.registerContractsGeneration = function (cb) {
this.contractsGenerators.push(cb); this.contractsGenerators.push(cb);
this.pluginTypes.push('contractGeneration'); this.pluginTypes.push('contractGeneration');
}; };
Plugin.prototype.registerPipeline = function(matcthingFiles, cb) { Plugin.prototype.registerPipeline = function (matcthingFiles, cb) {
// TODO: generate error for more than one pipeline per plugin // TODO: generate error for more than one pipeline per plugin
this.pipeline.push({matcthingFiles: matcthingFiles, cb: cb}); this.pipeline.push({matcthingFiles: matcthingFiles, cb: cb});
this.pluginTypes.push('pipeline'); this.pluginTypes.push('pipeline');
}; };
Plugin.prototype.addFileToPipeline = function(file, intendedPath, options) { Plugin.prototype.addFileToPipeline = function (file, intendedPath, options) {
this.pipelineFiles.push({file: file, intendedPath: intendedPath, options: options}); this.pipelineFiles.push({file: file, intendedPath: intendedPath, options: options});
this.pluginTypes.push('pipelineFiles'); this.pluginTypes.push('pipelineFiles');
}; };
Plugin.prototype.addContractFile = function(file) { Plugin.prototype.addContractFile = function (file) {
this.contractsFiles.push(file); this.contractsFiles.push(file);
this.pluginTypes.push('contractFiles'); this.pluginTypes.push('contractFiles');
}; };
Plugin.prototype.registerConsoleCommand = function(cb) { Plugin.prototype.registerConsoleCommand = function (cb) {
this.console.push(cb); this.console.push(cb);
this.pluginTypes.push('console'); this.pluginTypes.push('console');
}; };
Plugin.prototype.registerServiceCheck = function(checkName, checkFn, time) { Plugin.prototype.registerServiceCheck = function (checkName, checkFn, time) {
this.serviceChecks.push({checkName: checkName, checkFn: checkFn, time: time}); this.serviceChecks.push({checkName: checkName, checkFn: checkFn, time: time});
this.pluginTypes.push('serviceChecks'); this.pluginTypes.push('serviceChecks');
}; };
Plugin.prototype.has = function(pluginType) { Plugin.prototype.has = function (pluginType) {
return this.pluginTypes.indexOf(pluginType) >= 0; return this.pluginTypes.indexOf(pluginType) >= 0;
}; };
Plugin.prototype.generateProvider = function(args) { Plugin.prototype.generateProvider = function (args) {
return this.clientWeb3Providers.map(function(cb) { return this.clientWeb3Providers.map(function (cb) {
return cb.call(this, args); return cb.call(this, args);
}).join("\n"); }).join("\n");
}; };
Plugin.prototype.generateContracts = function(args) { Plugin.prototype.generateContracts = function (args) {
return this.contractsGenerators.map(function(cb) { return this.contractsGenerators.map(function (cb) {
return cb.call(this, args); return cb.call(this, args);
}).join("\n"); }).join("\n");
}; };
Plugin.prototype.registerContractConfiguration = function(config) { Plugin.prototype.registerContractConfiguration = function (config) {
this.contractsConfigs.push(config); this.contractsConfigs.push(config);
this.pluginTypes.push('contractsConfig'); this.pluginTypes.push('contractsConfig');
}; };
Plugin.prototype.registerCompiler = function(extension, cb) { Plugin.prototype.registerCompiler = function (extension, cb) {
this.compilers.push({extension: extension, cb: cb}); this.compilers.push({extension: extension, cb: cb});
this.pluginTypes.push('compilers'); this.pluginTypes.push('compilers');
}; };
Plugin.prototype.runCommands = function(cmd, options) { Plugin.prototype.runCommands = function (cmd, options) {
return this.console.map(function(cb) { return this.console.map(function (cb) {
return cb.call(this, cmd, options); return cb.call(this, cmd, options);
}).join("\n"); }).join("\n");
}; };
Plugin.prototype.runFilePipeline = function() { Plugin.prototype.runFilePipeline = function () {
let self = this; let self = this;
return this.pipelineFiles.map(function(file) { return this.pipelineFiles.map(function (file) {
let obj = {}; let obj = {};
obj.filename = file.file.replace('./',''); obj.filename = file.file.replace('./', '');
obj.content = self.loadPluginFile(file.file).toString(); obj.content = self.loadPluginFile(file.file).toString();
obj.intendedPath = file.intendedPath; obj.intendedPath = file.intendedPath;
obj.options = file.options; obj.options = file.options;
@ -175,7 +177,7 @@ Plugin.prototype.runFilePipeline = function() {
}); });
}; };
Plugin.prototype.runPipeline = function(args) { Plugin.prototype.runPipeline = function (args) {
// TODO: should iterate the pipelines // TODO: should iterate the pipelines
let pipeline = this.pipeline[0]; let pipeline = this.pipeline[0];
let shouldRunPipeline = utils.fileMatchesPattern(pipeline.matcthingFiles, args.targetFile); let shouldRunPipeline = utils.fileMatchesPattern(pipeline.matcthingFiles, args.targetFile);

View File

@ -1,9 +1,17 @@
const _ = require('underscore'); const _ = require('underscore');
const EventEmitter = require('events').EventEmitter; const EventEmitter = require('events').EventEmitter;
let Plugins = function (options) { const getPluginsFor = function (pluginType, plugins) {
return _.filter(plugins, pluginType);
};
class Plugins extends EventEmitter {
constructor(options) {
super();
//TODO: put an observer on this.plugins and call loadPlugin when a new item is added //TODO: put an observer on this.plugins and call loadPlugin when a new item is added
this.config = {}; this.config = {};
const loadPlugins = this.load;
for (let opt in options) { for (let opt in options) {
if (options.hasOwnProperty(opt)) { if (options.hasOwnProperty(opt)) {
this.config[opt] = options[opt]; this.config[opt] = options[opt];
@ -24,10 +32,9 @@ let Plugins = function (options) {
let pluginTypes = getPluginsFor(pluginType, this.config.plugins); let pluginTypes = getPluginsFor(pluginType, this.config.plugins);
return cb(pluginTypes); return cb(pluginTypes);
}); });
}
}; load() {
Plugins.prototype.load = Plugins.prototype.loadPlugins = function () {
let pluginConfig; let pluginConfig;
for (let i = 0; this.config.plugins.length > i; i++) { for (let i = 0; this.config.plugins.length > i; i++) {
pluginConfig = this.config.plugins[i].config; pluginConfig = this.config.plugins[i].config;
@ -35,18 +42,12 @@ Plugins.prototype.load = Plugins.prototype.loadPlugins = function () {
let plugin = new Plugin(pluginConfig); let plugin = new Plugin(pluginConfig);
plugin.run(); plugin.run();
} }
}; }
Plugins.prototype.listPlugins = function () { listPlugins() {
return this.config.plugins.join(', '); return this.config.plugins.join(', ');
}; }
let getPluginsFor = function (pluginType, plugins) { }
return _.filter(plugins, pluginType);
};
Plugins.prototype.getPluginsFor = getPluginsFor;
Plugins.prototype = Object.create(EventEmitter.prototype);
module.exports = Plugins; module.exports = Plugins;

View File

@ -8,7 +8,7 @@ let web3;
// ====================== // ======================
function doEval(code, _web3) { function doEval(code, _web3) {
if (_web3) { if (_web3) {
web3 = _web3; let web3 = _web3;
} }
return eval(code); // jshint ignore:line return eval(code); // jshint ignore:line
} }

View File

@ -3,22 +3,27 @@ let async = require('../utils/async_extend.js');
// TODO: need to separate colors from states // TODO: need to separate colors from states
// i.e use status: /on|off|warn/ not /red|green/ // i.e use status: /on|off|warn/ not /red|green/
// it's up to the logger or console to determine the color // it's up to the logger or console to determine the color
let ServicesMonitor = function(options) { class ServicesMonitor {
constructor(options) {
this.events = options.events; this.events = options.events;
this.logger = options.logger; this.logger = options.logger;
this.checkList = {}; this.checkList = {};
this.checkTimers = {}; this.checkTimers = {};
this.checkState = {}; this.checkState = {};
this.working = false; this.working = false;
}; }
}
;
ServicesMonitor.prototype.initCheck = function(checkName) { ServicesMonitor.prototype.initCheck = function (checkName) {
let self = this; let self = this;
let check = this.checkList[checkName]; let check = this.checkList[checkName];
if (!check) { return false; } if (!check) {
return false;
}
self.events.on('check:' + checkName, function(obj) { self.events.on('check:' + checkName, function (obj) {
// TODO: see todo above // TODO: see todo above
if (check && check.status === 'red' && obj.status === 'green') { if (check && check.status === 'red' && obj.status === 'green') {
self.events.emit('check:backOnline:' + checkName); self.events.emit('check:backOnline:' + checkName);
@ -32,19 +37,19 @@ ServicesMonitor.prototype.initCheck = function(checkName) {
}); });
if (check.interval !== 0) { if (check.interval !== 0) {
self.checkTimers[checkName] = setInterval(function() { self.checkTimers[checkName] = setInterval(function () {
check.fn.call(check.fn, function(obj) { check.fn.call(check.fn, function (obj) {
self.events.emit('check:' + checkName, obj); self.events.emit('check:' + checkName, obj);
}); });
}, check.interval); }, check.interval);
} }
check.fn.call(check.fn, function(obj) { check.fn.call(check.fn, function (obj) {
self.events.emit('check:' + checkName, obj); self.events.emit('check:' + checkName, obj);
}); });
}; };
ServicesMonitor.prototype.addCheck = function(checkName, checkFn, time) { ServicesMonitor.prototype.addCheck = function (checkName, checkFn, time) {
let self = this; let self = this;
this.logger.trace('add check: ' + checkName); this.logger.trace('add check: ' + checkName);
this.checkList[checkName] = {fn: checkFn, interval: time || 5000}; this.checkList[checkName] = {fn: checkFn, interval: time || 5000};
@ -54,22 +59,22 @@ ServicesMonitor.prototype.addCheck = function(checkName, checkFn, time) {
} }
}; };
ServicesMonitor.prototype.stopCheck = function(name) { ServicesMonitor.prototype.stopCheck = function (name) {
clearInterval(this.checkTimers[name]); clearInterval(this.checkTimers[name]);
delete this.checkTimers[name]; delete this.checkTimers[name];
delete this.checkList[name]; delete this.checkList[name];
delete this.checkState[name]; delete this.checkState[name];
}; };
ServicesMonitor.prototype.startMonitor = function() { ServicesMonitor.prototype.startMonitor = function () {
let self = this; let self = this;
this.working = true; this.working = true;
this.logger.trace('startMonitor'); this.logger.trace('startMonitor');
async.eachObject(this.checkList, function(checkName, check, callback) { async.eachObject(this.checkList, function (checkName, check, callback) {
self.initCheck(checkName); self.initCheck(checkName);
callback(); callback();
}, function(err) { }, function (err) {
if (err) { if (err) {
self.logger.error("error running service check"); self.logger.error("error running service check");
self.logger.error(err.message); self.logger.error(err.message);

View File

@ -1,4 +1,4 @@
let getSimulator = function() { let getSimulator = function () {
try { try {
return require('ethereumjs-testrpc'); return require('ethereumjs-testrpc');
} catch (e) { } catch (e) {
@ -17,15 +17,16 @@ let getSimulator = function() {
} }
}; };
let Test;
Test = (function (options) { class Test {
let async = require('async'); constructor(options) {
let opts = options === undefined ? {} : options; let opts = options === undefined ? {} : options;
opts.logLevel = opts.hasOwnProperty('logLevel') ? opts.logLevel : 'debug'; opts.logLevel = opts.hasOwnProperty('logLevel') ? opts.logLevel : 'debug';
opts.simulatorOptions = opts.hasOwnProperty('simulatorOptions') ? opts.simulatorOptions : {}; opts.simulatorOptions = opts.hasOwnProperty('simulatorOptions') ? opts.simulatorOptions : {};
let sim = getSimulator(); let sim = getSimulator();
}
function newWebThree() { newWebThree() {
try { try {
let Web3 = require('web3'); let Web3 = require('web3');
let web3 = new Web3(); let web3 = new Web3();
@ -35,73 +36,6 @@ Test = (function (options) {
throw new Error(e); throw new Error(e);
} }
} }
}
function deployAll(contractsConfig, cb) {
let RunCode = require('./runCode.js');
let self = this;
function newEngine () {
let Engine = require('./engine.js');
return new Engine({
env: opts.env || 'test',
// TODO: confi will need to detect if this is a obj
embarkConfig: opts.embarkConfig || 'embark.json',
interceptLogs: false
});
}
self.web3 = newWebThree();
self.engine = newEngine();
self.engine.init();
async.waterfall([
function getConfig(callback) {
self.engine.config.contractsConfig = {contracts: contractsConfig};
callback();
},
function startServices(callback) {
//{abiType: 'contracts', embarkJS: false}
self.engine.startService("abi");
self.engine.startService("deployment", {
web3: self.web3,
trackContracts: false
});
callback();
},
function deploy(callback) {
self.engine.events.on('abi-contracts-vanila', function (vanillaABI) {
callback(null, vanillaABI);
});
self.engine.deployManager.deployContracts(function (err, result) {
if (err) {
console.log(err);
callback(err);
}
});
}
], function (err, result) {
if (err) {
console.log("got error");
process.exit();
}
// this should be part of the waterfall and not just something done at the
// end
self.web3.eth.getAccounts(function (err, accounts) {
if (err) {
throw new Error(err);
}
self.web3.eth.defaultAccount = accounts[0];
RunCode.doEval(result, self.web3); // jshint ignore:line
cb();
});
});
}
return {
deployAll: deployAll,
sim: sim
};
}());
module.exports = Test; module.exports = Test;

View File

@ -2,51 +2,64 @@ let colors = require('colors');
// TODO: just logFunction changes, probably doesn't need a whole new module just // TODO: just logFunction changes, probably doesn't need a whole new module just
// for this // for this
let TestLogger = function(options) { class TestLogger {
constructor(options) {
this.logLevels = ['error', 'warn', 'info', 'debug', 'trace']; this.logLevels = ['error', 'warn', 'info', 'debug', 'trace'];
this.logs = []; this.logs = [];
this.logLevel = options.logLevel || 'info'; this.logLevel = options.logLevel || 'info';
}; }
TestLogger.prototype.logFunction = function() { logFunction() {
this.logs.push(arguments); this.logs.push(arguments);
}; }
TestLogger.prototype.contractsState = function() { contractsState() {
this.logs.push(arguments); this.logs.push(arguments);
}; }
TestLogger.prototype.availableServices = function() { availableServices() {
this.logs.push(arguments); this.logs.push(arguments);
}; }
TestLogger.prototype.error = function(txt) { error(txt) {
if (!(this.shouldLog('error'))) { return; } if (!(this.shouldLog('error'))) {
return;
}
this.logFunction(txt.red); this.logFunction(txt.red);
}; }
TestLogger.prototype.warn = function(txt) { warn(txt) {
if (!(this.shouldLog('warn'))) { return; } if (!(this.shouldLog('warn'))) {
return;
}
this.logFunction(txt.yellow); this.logFunction(txt.yellow);
}; }
TestLogger.prototype.info = function(txt) { info(txt) {
if (!(this.shouldLog('info'))) { return; } if (!(this.shouldLog('info'))) {
return;
}
this.logFunction(txt.green); this.logFunction(txt.green);
}; }
TestLogger.prototype.debug = function(txt) { debug(txt) {
if (!(this.shouldLog('debug'))) { return; } if (!(this.shouldLog('debug'))) {
return;
}
this.logFunction(txt); this.logFunction(txt);
}; }
TestLogger.prototype.trace = function(txt) { trace(txt) {
if (!(this.shouldLog('trace'))) { return; } if (!(this.shouldLog('trace'))) {
return;
}
this.logFunction(txt); this.logFunction(txt);
}; }
TestLogger.prototype.shouldLog = function(level) { shouldLog(level) {
return (this.logLevels.indexOf(level) <= this.logLevels.indexOf(this.logLevel)); return (this.logLevels.indexOf(level) <= this.logLevels.indexOf(this.logLevel));
}; }
}
module.exports = TestLogger; module.exports = TestLogger;

View File

@ -1,28 +1,29 @@
class CommandHistory {
let CommandHistory = function() { constructor() {
this.history = []; this.history = [];
this.pointer = -1; this.pointer = -1;
}; }
CommandHistory.prototype.addCommand = function(cmd) { addCommand(cmd) {
this.history.push(cmd); this.history.push(cmd);
this.pointer = this.history.length; this.pointer = this.history.length;
}; }
CommandHistory.prototype.getPreviousCommand = function(cmd) { getPreviousCommand(cmd) {
if (this.pointer >= 0) { if (this.pointer >= 0) {
this.pointer--; this.pointer--;
} }
return this.history[this.pointer]; return this.history[this.pointer];
}; }
CommandHistory.prototype.getNextCommand = function(cmd) { getNextCommand(cmd) {
if (this.pointer >= this.history.length) { if (this.pointer >= this.history.length) {
this.pointer = this.history.length - 1; this.pointer = this.history.length - 1;
return ''; return '';
} }
this.pointer++; this.pointer++;
return this.history[this.pointer]; return this.history[this.pointer];
}; }
}
module.exports = CommandHistory; module.exports = CommandHistory;

View File

@ -1,16 +1,17 @@
let utils = require('../utils/utils.js'); let utils = require('../utils/utils.js');
let RunCode = require('../core/runCode.js'); let RunCode = require('../core/runCode.js');
let Console = function(options) { class Console {
constructor(options) {
this.plugins = options.plugins; this.plugins = options.plugins;
this.version = options.version; this.version = options.version;
}; }
Console.prototype.runCode = function(code) { runCode(code) {
RunCode.doEval(code); // jshint ignore:line RunCode.doEval(code); // jshint ignore:line
}; }
Console.prototype.processEmbarkCmd = function(cmd) { processEmbarkCmd (cmd) {
if (cmd === 'help') { if (cmd === 'help') {
let helpText = [ let helpText = [
'Welcome to Embark ' + this.version, 'Welcome to Embark ' + this.version,
@ -28,9 +29,9 @@ Console.prototype.processEmbarkCmd = function(cmd) {
utils.exit(); utils.exit();
} }
return false; return false;
}; }
Console.prototype.executeCmd = function(cmd, callback) { executeCmd(cmd, callback) {
let plugin, pluginOutput; let plugin, pluginOutput;
let plugins = []; let plugins = [];
this.plugins.emit('get', 'console', (list) => { this.plugins.emit('get', 'console', (list) => {
@ -51,13 +52,14 @@ Console.prototype.executeCmd = function(cmd, callback) {
let result = RunCode.doEval(cmd); let result = RunCode.doEval(cmd);
return callback(result); return callback(result);
} }
catch(e) { catch (e) {
if (e.message.indexOf('not defined') > 0) { if (e.message.indexOf('not defined') > 0) {
return callback(("error: " + e.message).red + ("\nType " + "help".bold + " to see the list of available commands").cyan); return callback(("error: " + e.message).red + ("\nType " + "help".bold + " to see the list of available commands").cyan);
} else { } else {
return callback(e.message); return callback(e.message);
} }
} }
}; }
}
module.exports = Console; module.exports = Console;

View File

@ -3,14 +3,15 @@ let async = require('async');
let Monitor = require('./monitor.js'); let Monitor = require('./monitor.js');
let Console = require('./console.js'); let Console = require('./console.js');
let Dashboard = function(options) { class Dashboard {
constructor(options) {
this.logger = options.logger; this.logger = options.logger;
this.plugins = options.plugins; this.plugins = options.plugins;
this.version = options.version; this.version = options.version;
this.env = options.env; this.env = options.env;
}; }
Dashboard.prototype.start = function(done) { start(done) {
let console, monitor; let console, monitor;
let self = this; let self = this;
@ -32,11 +33,13 @@ Dashboard.prototype.start = function(done) {
// TODO: do this after monitor is rendered // TODO: do this after monitor is rendered
callback(); callback();
} }
], function() { ], function () {
self.console = console; self.console = console;
self.monitor = monitor; self.monitor = monitor;
done(); done();
}); });
}; }
}
module.exports = Dashboard; module.exports = Dashboard;

View File

@ -4,7 +4,8 @@ let blessed = require("blessed");
let CommandHistory = require('./command_history.js'); let CommandHistory = require('./command_history.js');
let version = require('../../package.json').version; let version = require('../../package.json').version;
function Dashboard(options) { class Dashboard {
constructor(options) {
let title = (options && options.title) || "Embark " + version; let title = (options && options.title) || "Embark " + version;
this.env = options.env; this.env = options.env;
this.console = options.console; this.console = options.console;
@ -26,7 +27,7 @@ function Dashboard(options) {
this.layoutModules(); this.layoutModules();
this.layoutCmd(); this.layoutCmd();
this.screen.key(["C-c"], function() { this.screen.key(["C-c"], function () {
process.exit(0); process.exit(0);
}); });
@ -38,9 +39,9 @@ function Dashboard(options) {
this.screen.render(); this.screen.render();
this.input.focus(); this.input.focus();
} }
Dashboard.prototype.availableServices = function(_services) { availableServices(_services) {
let services = []; let services = [];
let checkName; let checkName;
for (checkName in _services) { for (checkName in _services) {
@ -49,32 +50,32 @@ Dashboard.prototype.availableServices = function(_services) {
this.progress.setContent(services.join('\n')); this.progress.setContent(services.join('\n'));
this.screen.render(); this.screen.render();
}; }
Dashboard.prototype.setStatus = function(status) { setStatus(status) {
this.operations.setContent(status); this.operations.setContent(status);
this.screen.render(); this.screen.render();
}; }
Dashboard.prototype.setContracts = function(contracts) { setContracts(contracts) {
let data = []; let data = [];
data.push(["Contract Name", "Address", "Status"]); data.push(["Contract Name", "Address", "Status"]);
contracts.forEach(function(row) { contracts.forEach(function (row) {
data.push(row); data.push(row);
}); });
this.moduleTable.setData(data); this.moduleTable.setData(data);
this.screen.render(); this.screen.render();
}; }
Dashboard.prototype.logEntry = function(text) { logEntry(text) {
this.logText.log(text); this.logText.log(text);
this.screen.render(); this.screen.render();
}; }
Dashboard.prototype.layoutLog = function() { layoutLog() {
this.log = blessed.box({ this.log = blessed.box({
label: "Logs", label: "Logs",
padding: 1, padding: 1,
@ -111,9 +112,9 @@ Dashboard.prototype.layoutLog = function() {
}); });
this.screen.append(this.log); this.screen.append(this.log);
}; }
Dashboard.prototype.layoutModules = function() { layoutModules() {
this.modules = blessed.box({ this.modules = blessed.box({
label: "Contracts", label: "Contracts",
tags: true, tags: true,
@ -154,9 +155,9 @@ Dashboard.prototype.layoutModules = function() {
}); });
this.screen.append(this.modules); this.screen.append(this.modules);
}; }
Dashboard.prototype.layoutAssets = function() { layoutAssets() {
this.assets = blessed.box({ this.assets = blessed.box({
label: "Asset Pipeline", label: "Asset Pipeline",
tags: true, tags: true,
@ -195,9 +196,9 @@ Dashboard.prototype.layoutAssets = function() {
}); });
this.screen.append(this.assets); this.screen.append(this.assets);
}; }
Dashboard.prototype.layoutStatus = function() { layoutStatus() {
this.wrapper = blessed.layout({ this.wrapper = blessed.layout({
width: "25%", width: "25%",
@ -271,10 +272,9 @@ Dashboard.prototype.layoutStatus = function() {
}); });
this.screen.append(this.wrapper); this.screen.append(this.wrapper);
}; }
layoutCmd() {
Dashboard.prototype.layoutCmd = function() {
this.consoleBox = blessed.box({ this.consoleBox = blessed.box({
label: 'Console', label: 'Console',
tags: true, tags: true,
@ -316,32 +316,32 @@ Dashboard.prototype.layoutCmd = function() {
let self = this; let self = this;
this.input.key(["C-c"], function() { this.input.key(["C-c"], function () {
process.exit(0); process.exit(0);
}); });
this.input.key(["C-w"], function() { this.input.key(["C-w"], function () {
self.input.clearValue(); self.input.clearValue();
self.input.focus(); self.input.focus();
}); });
this.input.key(["up"], function() { this.input.key(["up"], function () {
let cmd = self.history.getPreviousCommand(); let cmd = self.history.getPreviousCommand();
self.input.setValue(cmd); self.input.setValue(cmd);
self.input.focus(); self.input.focus();
}); });
this.input.key(["down"], function() { this.input.key(["down"], function () {
let cmd = self.history.getNextCommand(); let cmd = self.history.getNextCommand();
self.input.setValue(cmd); self.input.setValue(cmd);
self.input.focus(); self.input.focus();
}); });
this.input.on('submit', function(data) { this.input.on('submit', function (data) {
if (data !== '') { if (data !== '') {
self.history.addCommand(data); self.history.addCommand(data);
self.logText.log('console> '.bold.green + data); self.logText.log('console> '.bold.green + data);
self.console.executeCmd(data, function(result) { self.console.executeCmd(data, function (result) {
self.logText.log(result); self.logText.log(result);
}); });
} }
@ -350,6 +350,8 @@ Dashboard.prototype.layoutCmd = function() {
}); });
this.screen.append(this.consoleBox); this.screen.append(this.consoleBox);
}; }
}
module.exports = Dashboard; module.exports = Dashboard;

View File

@ -16,7 +16,8 @@ let Config = require('./core/config');
* @api public * @api public
*/ */
let Embark = function (options) { class Embark {
constructor(options) {
this.version = require('../package.json').version; this.version = require('../package.json').version;
this.env = options.environment || options.env || "development"; this.env = options.environment || options.env || "development";
@ -172,10 +173,18 @@ let Embark = function (options) {
// TODO: should deploy if it hasn't already // TODO: should deploy if it hasn't already
this.upload = function (platform) { this.upload = function (platform) {
if (platform === 'ipfs') { if (platform === 'ipfs') {
let ipfs = new IPFS({buildDir: 'dist/', plugins: Embark.prototype.plugins, storageConfig: Embark.prototype.config.storageConfig}); let ipfs = new IPFS({
buildDir: 'dist/',
plugins: Embark.prototype.plugins,
storageConfig: Embark.prototype.config.storageConfig
});
ipfs.deploy(); ipfs.deploy();
} else if (platform === 'swarm') { } else if (platform === 'swarm') {
let swarm = new Swarm({buildDir: 'dist/', plugins: Embark.prototype.plugins, storageConfig: Embark.prototype.config.storageConfig}); let swarm = new Swarm({
buildDir: 'dist/',
plugins: Embark.prototype.plugins,
storageConfig: Embark.prototype.config.storageConfig
});
swarm.deploy(); swarm.deploy();
} else { } else {
console.log(("unknown platform: " + platform).red); console.log(("unknown platform: " + platform).red);
@ -187,7 +196,8 @@ let Embark = function (options) {
return new Embark(); return new Embark();
} }
return this; return this;
}; }
}
Embark.prototype = Object.create(EventEmitter.prototype); Embark.prototype = Object.create(EventEmitter.prototype);

View File

@ -1,17 +1,19 @@
/*jshint esversion: 6, loopfunc: true */ /*jshint esversion: 6, loopfunc: true */
let fs = require('../core/fs.js'); let fs = require('../core/fs.js');
let Pipeline = function(options) { class Pipeline {
constructor(options) {
this.buildDir = options.buildDir; this.buildDir = options.buildDir;
this.contractsFiles = options.contractsFiles; this.contractsFiles = options.contractsFiles;
this.assetFiles = options.assetFiles; this.assetFiles = options.assetFiles;
this.logger = options.logger; this.logger = options.logger;
this.plugins = options.plugins; this.plugins = options.plugins;
}; }
Pipeline.prototype.build = function(abi, path) { build(abi, path) {
let self = this; let self = this;
for(let targetFile in this.assetFiles) { for (let targetFile in this.assetFiles) {
let contentFiles = this.assetFiles[targetFile].map(file => { let contentFiles = this.assetFiles[targetFile].map(file => {
self.logger.trace("reading " + file.filename); self.logger.trace("reading " + file.filename);
@ -28,7 +30,7 @@ Pipeline.prototype.build = function(abi, path) {
} else { } else {
if (pipelinePlugins.length > 0) { if (pipelinePlugins.length > 0) {
pipelinePlugins.forEach(function(plugin) { pipelinePlugins.forEach(function (plugin) {
try { try {
if (file.options && file.options.skipPipeline) { if (file.options && file.options.skipPipeline) {
return; return;
@ -36,7 +38,7 @@ Pipeline.prototype.build = function(abi, path) {
file.content = plugin.runPipeline({targetFile: file.filename, source: file.content}); file.content = plugin.runPipeline({targetFile: file.filename, source: file.content});
file.modified = true; file.modified = true;
} }
catch(err) { catch (err) {
self.logger.error(err.message); self.logger.error(err.message);
} }
}); });
@ -58,7 +60,7 @@ Pipeline.prototype.build = function(abi, path) {
targetDir = targetDir + '/'; targetDir = targetDir + '/';
} }
contentFiles.map(function(file) { contentFiles.map(function (file) {
let filename = file.filename.replace('app/', ''); let filename = file.filename.replace('app/', '');
filename = filename.replace(targetDir, ''); filename = filename.replace(targetDir, '');
self.logger.info("writing file " + (self.buildDir + targetDir + filename).bold.dim); self.logger.info("writing file " + (self.buildDir + targetDir + filename).bold.dim);
@ -66,7 +68,7 @@ Pipeline.prototype.build = function(abi, path) {
fs.copySync(self.buildDir + targetDir + filename, file.path, {overwrite: true}); fs.copySync(self.buildDir + targetDir + filename, file.path, {overwrite: true});
}); });
} else { } else {
let content = contentFiles.map(function(file) { let content = contentFiles.map(function (file) {
return file.content; return file.content;
}).join("\n"); }).join("\n");
@ -74,7 +76,8 @@ Pipeline.prototype.build = function(abi, path) {
fs.writeFileSync(this.buildDir + targetFile, content); fs.writeFileSync(this.buildDir + targetFile, content);
} }
} }
}; }
}
module.exports = Pipeline; module.exports = Pipeline;

View File

@ -2,23 +2,26 @@ let finalhandler = require('finalhandler');
let http = require('http'); let http = require('http');
let serveStatic = require('serve-static'); let serveStatic = require('serve-static');
let Server = function(options) { class Server {
constructor(options) {
this.dist = options.dist || 'dist/'; this.dist = options.dist || 'dist/';
this.port = options.port || 8000; this.port = options.port || 8000;
this.hostname = options.host || 'localhost'; this.hostname = options.host || 'localhost';
this.logger = options.logger; this.logger = options.logger;
}; }
Server.prototype.start = function(callback) { start(callback) {
let serve = serveStatic(this.dist, {'index': ['index.html', 'index.htm']}); let serve = serveStatic(this.dist, {'index': ['index.html', 'index.htm']});
let server = http.createServer(function onRequest (req, res) { let server = http.createServer(function onRequest(req, res) {
serve(req, res, finalhandler(req, res)); serve(req, res, finalhandler(req, res));
}); });
this.logger.info("webserver available at " + ("http://" + this.hostname + ":" + this.port).bold.underline.green); this.logger.info("webserver available at " + ("http://" + this.hostname + ":" + this.port).bold.underline.green);
server.listen(this.port, this.hostname) ; server.listen(this.port, this.hostname);
callback(); callback();
}; }
}
module.exports = Server; module.exports = Server;

View File

@ -5,85 +5,86 @@ let fs = require('../core/fs.js');
// TODO: this should be receiving the config object not re-reading the // TODO: this should be receiving the config object not re-reading the
// embark.json file // embark.json file
let Watch = function(options) { class Watch {
constructor(options) {
this.logger = options.logger; this.logger = options.logger;
this.events = options.events; this.events = options.events;
}; }
Watch.prototype.start = function() { start() {
let self = this; let self = this;
// TODO: should come from the config object instead of reading the file // TODO: should come from the config object instead of reading the file
// directly // directly
let embarkConfig = fs.readJSONSync("embark.json"); let embarkConfig = fs.readJSONSync("embark.json");
this.watchAssets(embarkConfig, function() { this.watchAssets(embarkConfig, function () {
self.logger.trace('ready to watch asset changes'); self.logger.trace('ready to watch asset changes');
}); });
this.watchContracts(embarkConfig, function() { this.watchContracts(embarkConfig, function () {
self.logger.trace('ready to watch contract changes'); self.logger.trace('ready to watch contract changes');
}); });
this.watchConfigs(function() { this.watchConfigs(function () {
self.logger.trace('ready to watch config changes'); self.logger.trace('ready to watch config changes');
}); });
this.logger.info("ready to watch file changes"); this.logger.info("ready to watch file changes");
}; }
Watch.prototype.watchAssets = function(embarkConfig, callback) { watchAssets(embarkConfig, callback) {
let self = this; let self = this;
let appConfig = embarkConfig.app; let appConfig = embarkConfig.app;
let filesToWatch = []; let filesToWatch = [];
for(let targetFile in appConfig) { for (let targetFile in appConfig) {
filesToWatch.push(appConfig[targetFile]); filesToWatch.push(appConfig[targetFile]);
} }
this.watchFiles( this.watchFiles(
filesToWatch, filesToWatch,
function(eventName, path) { function (eventName, path) {
self.logger.info(`${eventName}: ${path}`); self.logger.info(`${eventName}: ${path}`);
self.events.emit('file-' + eventName, 'asset', path); self.events.emit('file-' + eventName, 'asset', path);
self.events.emit('file-event', 'asset', path); self.events.emit('file-event', 'asset', path);
}, },
function() { function () {
callback(); callback();
} }
); );
}; }
Watch.prototype.watchContracts = function(embarkConfig, callback) { watchContracts(embarkConfig, callback) {
let self = this; let self = this;
this.watchFiles( this.watchFiles(
[embarkConfig.contracts], [embarkConfig.contracts],
function(eventName, path) { function (eventName, path) {
self.logger.info(`${eventName}: ${path}`); self.logger.info(`${eventName}: ${path}`);
self.events.emit('file-' + eventName, 'contract', path); self.events.emit('file-' + eventName, 'contract', path);
self.events.emit('file-event', 'contract', path); self.events.emit('file-event', 'contract', path);
}, },
function() { function () {
callback(); callback();
} }
); );
}; }
Watch.prototype.watchConfigs = function(callback) { watchConfigs(callback) {
let self = this; let self = this;
this.watchFiles( this.watchFiles(
"config/**/contracts.json", "config/**/contracts.json",
function(eventName, path) { function (eventName, path) {
self.logger.info(`${eventName}: ${path}`); self.logger.info(`${eventName}: ${path}`);
self.events.emit('file-' + eventName, 'config', path); self.events.emit('file-' + eventName, 'config', path);
self.events.emit('file-event', 'config', path); self.events.emit('file-event', 'config', path);
}, },
function() { function () {
callback(); callback();
} }
); );
}; }
Watch.prototype.watchFiles = function(files, changeCallback, doneCallback) { watchFiles(files, changeCallback, doneCallback) {
this.logger.trace('watchFiles'); this.logger.trace('watchFiles');
this.logger.trace(files); this.logger.trace(files);
@ -96,6 +97,8 @@ Watch.prototype.watchFiles = function(files, changeCallback, doneCallback) {
.on('change', path => changeCallback('change', path)) .on('change', path => changeCallback('change', path))
.on('unlink', path => changeCallback('remove', path)) .on('unlink', path => changeCallback('remove', path))
.on('ready', doneCallback); .on('ready', doneCallback);
}; }
}
module.exports = Watch; module.exports = Watch;

View File

@ -2,21 +2,23 @@ let colors = require('colors');
let async = require('async'); let async = require('async');
let shelljs = require('shelljs'); let shelljs = require('shelljs');
let IPFS = function(options) { class IPFS {
constructor(options) {
this.options = options; this.options = options;
this.buildDir = options.buildDir || 'dist/'; this.buildDir = options.buildDir || 'dist/';
this.plugins = options.plugins; this.plugins = options.plugins;
this.storageConfig = options.storageConfig; this.storageConfig = options.storageConfig;
this.configIpfsBin = this.storageConfig.ipfs_bin || "ipfs"; this.configIpfsBin = this.storageConfig.ipfs_bin || "ipfs";
}; }
IPFS.prototype.deploy = function() { deploy() {
let self = this; let self = this;
async.waterfall([ async.waterfall([
function findBinary(callback) { function findBinary(callback) {
let ipfs_bin = shelljs.exec('which ' + self.configIpfsBin).output.split("\n")[0]; let ipfs_bin = shelljs.exec('which ' + self.configIpfsBin).output.split("\n")[0];
if (ipfs_bin === 'ipfs not found' || ipfs_bin === ''){ if (ipfs_bin === 'ipfs not found' || ipfs_bin === '') {
console.log(('=== WARNING: ' + self.configIpfsBin + ' not found or not in the path. Guessing ~/go/bin/ipfs for path').yellow); console.log(('=== WARNING: ' + self.configIpfsBin + ' not found or not in the path. Guessing ~/go/bin/ipfs for path').yellow);
ipfs_bin = "~/go/bin/ipfs"; ipfs_bin = "~/go/bin/ipfs";
} }
@ -44,13 +46,15 @@ IPFS.prototype.deploy = function() {
return callback(); return callback();
} }
], function(err, result) { ], function (err, result) {
if (err) { if (err) {
console.log("error uploading to ipfs".red); console.log("error uploading to ipfs".red);
console.log(err); console.log(err);
} }
}); });
}; }
}
module.exports = IPFS; module.exports = IPFS;

View File

@ -2,18 +2,19 @@ let colors = require('colors');
let async = require('async'); let async = require('async');
let shelljs = require('shelljs'); let shelljs = require('shelljs');
let Swarm = function(options) { class Swarm {
constructor(options) {
this.options = options; this.options = options;
this.buildDir = options.buildDir || 'dist/'; this.buildDir = options.buildDir || 'dist/';
}; }
Swarm.prototype.deploy = function() { deploy() {
let self = this; let self = this;
async.waterfall([ async.waterfall([
function findBinary(callback) { function findBinary(callback) {
let swarm_bin = shelljs.exec('which swarm').output.split("\n")[0]; let swarm_bin = shelljs.exec('which swarm').output.split("\n")[0];
if (swarm_bin==='swarm not found' || swarm_bin === ''){ if (swarm_bin === 'swarm not found' || swarm_bin === '') {
console.log('=== WARNING: Swarm not in an executable path. Guessing ~/go/bin/swarm for path'.yellow); console.log('=== WARNING: Swarm not in an executable path. Guessing ~/go/bin/swarm for path'.yellow);
swarm_bin = "~/go/bin/swarm"; swarm_bin = "~/go/bin/swarm";
} }
@ -43,13 +44,14 @@ Swarm.prototype.deploy = function() {
return callback(); return callback();
} }
], function(err, result) { ], function (err, result) {
if (err) { if (err) {
console.log("error uploading to swarm".red); console.log("error uploading to swarm".red);
console.log(err); console.log(err);
} }
}); });
}; }
}
module.exports = Swarm; module.exports = Swarm;

View File

@ -3,12 +3,13 @@ let async = require('async');
function asyncEachObject(object, iterator, callback) { function asyncEachObject(object, iterator, callback) {
async.each( async.each(
Object.keys(object || {}), Object.keys(object || {}),
function(key, next){ function (key, next) {
iterator(key, object[key], next); iterator(key, object[key], next);
}, },
callback callback
); );
} }
async.eachObject = asyncEachObject; async.eachObject = asyncEachObject;
module.exports = async; module.exports = async;

View File

@ -5,9 +5,9 @@ function extend(filename, async) {
return; return;
} }
async._waterfall = async.waterfall; async._waterfall = async.waterfall;
async.waterfall = function(_tasks, callback) { async.waterfall = function (_tasks, callback) {
let tasks = _tasks.map(function(t) { let tasks = _tasks.map(function (t) {
let fn = function() { let fn = function () {
console.log("async " + filename + ": " + t.name); console.log("async " + filename + ": " + t.name);
t.apply(t, arguments); t.apply(t, arguments);
}; };

View File

@ -22,9 +22,9 @@ function recursiveMerge(target, source) {
} }
function checkIsAvailable(url, callback) { function checkIsAvailable(url, callback) {
http.get(url, function(res) { http.get(url, function (res) {
callback(true); callback(true);
}).on('error', function(res) { }).on('error', function (res) {
callback(false); callback(false);
}); });
} }

View File

@ -1,6 +1,7 @@
/*globals describe, it*/ /*globals describe, it*/
let Blockchain = require('../lib/cmds/blockchain/blockchain.js'); const Blockchain = require('../lib/cmds/blockchain/blockchain');
let assert = require('assert'); // let BlockchainClient = require('../lib/cmds/blockchain/blockchain_client');
const assert = require('assert');
describe('embark.Blockchain', function() { describe('embark.Blockchain', function() {
//let Client = function() {}; //let Client = function() {};
@ -12,6 +13,7 @@ describe('embark.Blockchain', function() {
describe('with empty config', function() { describe('with empty config', function() {
it('should have a default config', function() { it('should have a default config', function() {
let config = { let config = {
blockchainConfig: {
networkType: 'custom', networkType: 'custom',
genesisBlock: false, genesisBlock: false,
geth_bin: 'geth', geth_bin: 'geth',
@ -29,9 +31,10 @@ describe('embark.Blockchain', function() {
vmdebug: false, vmdebug: false,
whisper: true, whisper: true,
account: {}, account: {},
bootnodes: "" bootnodes: "",
}; }
let blockchain = Blockchain(config, 'geth'); }
let blockchain = new Blockchain(config, 'geth');
assert.deepEqual(blockchain.config, config); assert.deepEqual(blockchain.config, config);
}); });
@ -59,7 +62,7 @@ describe('embark.Blockchain', function() {
account: {}, account: {},
bootnodes: "" bootnodes: ""
}; };
let blockchain = Blockchain(config, 'geth'); let blockchain = new Blockchain(config, 'geth');
assert.deepEqual(blockchain.config, config); assert.deepEqual(blockchain.config, config);
}); });

View File

@ -9,7 +9,7 @@ let readFile = function(file) {
}; };
describe('embark.Contratcs', function() { describe('embark.Contratcs', function() {
this.timeout(0);
describe('simple', function() { describe('simple', function() {
let contractsManager = new ContractsManager({ let contractsManager = new ContractsManager({
contractFiles: [ contractFiles: [