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,9 +27,9 @@ 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 {
@ -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)')
@ -102,9 +102,9 @@ 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')
@ -116,9 +116,9 @@ Cmd.prototype.blockchain = function() {
}); });
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')
@ -132,18 +132,18 @@ Cmd.prototype.simulator = function() {
}); });
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)')
@ -154,15 +154,17 @@ Cmd.prototype.upload = function() {
}); });
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);
@ -51,9 +58,9 @@ Blockchain.prototype.run = function() {
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']);
@ -158,7 +159,8 @@ GethCommands.prototype.mainCommand = function(address, done) {
} }
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;
@ -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;
@ -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
@ -43,9 +44,9 @@ 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;
@ -102,5 +103,6 @@ Compiler.prototype.compile_solidity = function(contractFiles, cb) {
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,9 +14,9 @@ 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) {
@ -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';
@ -99,7 +80,9 @@ ContractsManager.prototype.build = function(done) {
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];
@ -173,13 +156,13 @@ ContractsManager.prototype.build = function(done) {
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) {
@ -198,19 +181,19 @@ ContractsManager.prototype.sortContracts = function(contractList) {
}); });
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) {
@ -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;
@ -91,9 +92,9 @@ 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);
@ -138,9 +139,9 @@ 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");
@ -162,5 +163,6 @@ 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) {
@ -86,6 +84,8 @@ DeployManager.prototype.deployContracts = function(done) {
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

@ -2,11 +2,12 @@ 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') {
@ -16,13 +17,13 @@ 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;
@ -30,7 +31,8 @@ SolcW.prototype.compile = function(obj, optimize, done) {
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,7 +19,8 @@ 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;
@ -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();
@ -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');
@ -227,20 +234,40 @@ Config.prototype.loadFiles = function(files) {
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")
});
} }
}); });
@ -294,7 +321,11 @@ Config.prototype.loadPluginContractFiles = function() {
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,25 +1,25 @@
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;
@ -137,7 +137,8 @@ Engine.prototype.deploymentService = function(options) {
// 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 () {
});
//} //}
}); });
}; };
@ -151,7 +152,9 @@ Engine.prototype.fileWatchService = function(options) {
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;
@ -223,7 +226,10 @@ Engine.prototype.web3Service = function(options) {
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'});
} }

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

@ -1,35 +1,48 @@
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);
}; };

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,7 +33,8 @@ 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) {

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,20 +3,25 @@ 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

View File

@ -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) => {
@ -58,6 +59,7 @@ Console.prototype.executeCmd = function(cmd, callback) {
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;
@ -37,6 +38,8 @@ Dashboard.prototype.start = function(done) {
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;
@ -40,7 +41,7 @@ function Dashboard(options) {
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,14 +50,14 @@ 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"]);
@ -67,14 +68,14 @@ Dashboard.prototype.setContracts = function(contracts) {
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,
@ -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,15 +1,17 @@
/*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) {
@ -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,14 +2,15 @@ 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) {
@ -19,6 +20,8 @@ Server.prototype.start = function(callback) {
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,12 +5,13 @@ 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
@ -29,9 +30,9 @@ Watch.prototype.start = function() {
}); });
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 = [];
@ -51,9 +52,9 @@ Watch.prototype.watchAssets = function(embarkConfig, callback) {
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],
@ -66,9 +67,9 @@ Watch.prototype.watchContracts = function(embarkConfig, callback) {
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",
@ -81,9 +82,9 @@ Watch.prototype.watchConfigs = function(callback) {
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,15 +2,17 @@ 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) {
@ -50,7 +52,9 @@ IPFS.prototype.deploy = function() {
console.log(err); console.log(err);
} }
}); });
}; }
}
module.exports = IPFS; module.exports = IPFS;

View File

@ -2,12 +2,13 @@ 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) {
@ -49,7 +50,8 @@ Swarm.prototype.deploy = function() {
console.log(err); console.log(err);
} }
}); });
}; }
}
module.exports = Swarm; module.exports = Swarm;

View File

@ -9,6 +9,7 @@ function asyncEachObject(object, iterator, callback) {
callback callback
); );
} }
async.eachObject = asyncEachObject; async.eachObject = asyncEachObject;
module.exports = async; module.exports = async;

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: [