mirror of https://github.com/embarklabs/embark.git
Merge branch 'next' into develop
This commit is contained in:
commit
97c45bce8c
|
@ -1,7 +1,7 @@
|
|||
Installation
|
||||
============
|
||||
|
||||
Requirements: geth (1.6.5 or higher recommended, 1.6.0 or lower for whisper support), node (6.9.1 or higher is recommended) and npm
|
||||
Requirements: geth (1.6.5 or higher recommended), node (6.9.1 or higher is recommended) and npm
|
||||
serpent (develop) if using contracts with Serpent, testrpc (3.0 or higher)
|
||||
if using the simulator or the test functionality. Further: depending on
|
||||
the dapp stack you choose: `IPFS <https://ipfs.io/>`__
|
||||
|
|
|
@ -89,6 +89,14 @@ return /******/ (function(modules) { // webpackBootstrap
|
|||
|
||||
var EmbarkJS = {};
|
||||
|
||||
EmbarkJS.isNewWeb3 = function() {
|
||||
var _web3 = new Web3();
|
||||
if (typeof(_web3.version) === "string") {
|
||||
return true;
|
||||
}
|
||||
return parseInt(_web3.version.api.split('.')[0], 10) >= 1;
|
||||
};
|
||||
|
||||
EmbarkJS.Contract = function(options) {
|
||||
var self = this;
|
||||
var i, abiElement;
|
||||
|
@ -98,94 +106,106 @@ EmbarkJS.Contract = function(options) {
|
|||
this.code = '0x' + options.code;
|
||||
this.web3 = options.web3 || web3;
|
||||
|
||||
var ContractClass = this.web3.eth.contract(this.abi);
|
||||
if (EmbarkJS.isNewWeb3()) {
|
||||
// TODO:
|
||||
// add default **from** address
|
||||
// add gasPrice
|
||||
var ContractClass = new this.web3.eth.Contract(this.abi, this.address);
|
||||
ContractClass.setProvider(this.web3.currentProvider);
|
||||
|
||||
this.eventList = [];
|
||||
return ContractClass;
|
||||
} else {
|
||||
|
||||
if (this.abi) {
|
||||
|
||||
var ContractClass = this.web3.eth.contract(this.abi);
|
||||
|
||||
this.eventList = [];
|
||||
|
||||
if (this.abi) {
|
||||
for (i = 0; i < this.abi.length; i++) {
|
||||
abiElement = this.abi[i];
|
||||
if (abiElement.type === 'event') {
|
||||
this.eventList.push(abiElement.name);
|
||||
}
|
||||
abiElement = this.abi[i];
|
||||
if (abiElement.type === 'event') {
|
||||
this.eventList.push(abiElement.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var messageEvents = function() {
|
||||
var messageEvents = function() {
|
||||
this.cb = function() {};
|
||||
};
|
||||
};
|
||||
|
||||
messageEvents.prototype.then = function(cb) {
|
||||
messageEvents.prototype.then = function(cb) {
|
||||
this.cb = cb;
|
||||
};
|
||||
};
|
||||
|
||||
messageEvents.prototype.error = function(err) {
|
||||
messageEvents.prototype.error = function(err) {
|
||||
return err;
|
||||
};
|
||||
};
|
||||
|
||||
this._originalContractObject = ContractClass.at(this.address);
|
||||
this._methods = Object.getOwnPropertyNames(this._originalContractObject).filter(function(p) {
|
||||
this._originalContractObject = ContractClass.at(this.address);
|
||||
this._methods = Object.getOwnPropertyNames(this._originalContractObject).filter(function(p) {
|
||||
// TODO: check for forbidden properties
|
||||
if (self.eventList.indexOf(p) >= 0) {
|
||||
|
||||
self[p] = function() {
|
||||
var promise = new messageEvents();
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args.push(function(err, result) {
|
||||
if (err) {
|
||||
promise.error(err);
|
||||
} else {
|
||||
promise.cb(result);
|
||||
}
|
||||
});
|
||||
self[p] = function() {
|
||||
var promise = new messageEvents();
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args.push(function(err, result) {
|
||||
if (err) {
|
||||
promise.error(err);
|
||||
} else {
|
||||
promise.cb(result);
|
||||
}
|
||||
});
|
||||
|
||||
self._originalContractObject[p].apply(self._originalContractObject[p], args);
|
||||
return promise;
|
||||
};
|
||||
return true;
|
||||
self._originalContractObject[p].apply(self._originalContractObject[p], args);
|
||||
return promise;
|
||||
};
|
||||
return true;
|
||||
} else if (typeof self._originalContractObject[p] === 'function') {
|
||||
self[p] = function(_args) {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
var fn = self._originalContractObject[p];
|
||||
var props = self.abi.find((x) => x.name == p);
|
||||
self[p] = function(_args) {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
var fn = self._originalContractObject[p];
|
||||
var props = self.abi.find((x) => x.name == p);
|
||||
|
||||
var promise = new Promise(function(resolve, reject) {
|
||||
args.push(function(err, transaction) {
|
||||
promise.tx = transaction;
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
var promise = new Promise(function(resolve, reject) {
|
||||
args.push(function(err, transaction) {
|
||||
promise.tx = transaction;
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
|
||||
var getConfirmation = function() {
|
||||
self.web3.eth.getTransactionReceipt(transaction, function(err, receipt) {
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
var getConfirmation = function() {
|
||||
self.web3.eth.getTransactionReceipt(transaction, function(err, receipt) {
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
|
||||
if (receipt !== null) {
|
||||
return resolve(receipt);
|
||||
}
|
||||
if (receipt !== null) {
|
||||
return resolve(receipt);
|
||||
}
|
||||
|
||||
setTimeout(getConfirmation, 1000);
|
||||
});
|
||||
};
|
||||
setTimeout(getConfirmation, 1000);
|
||||
});
|
||||
};
|
||||
|
||||
if (typeof(transaction) !== "string" || props.constant) {
|
||||
resolve(transaction);
|
||||
} else {
|
||||
getConfirmation();
|
||||
}
|
||||
});
|
||||
if (typeof(transaction) !== "string" || props.constant) {
|
||||
resolve(transaction);
|
||||
} else {
|
||||
getConfirmation();
|
||||
}
|
||||
});
|
||||
|
||||
fn.apply(fn, args);
|
||||
});
|
||||
fn.apply(fn, args);
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
return true;
|
||||
return promise;
|
||||
};
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
EmbarkJS.Contract.prototype.deploy = function(args, _options) {
|
||||
|
@ -383,9 +403,6 @@ EmbarkJS.Storage.IPFS.uploadFile = function(inputSelector) {
|
|||
};
|
||||
|
||||
EmbarkJS.Storage.IPFS.getUrl = function(hash) {
|
||||
//var ipfsHash = web3.toAscii(hash);
|
||||
|
||||
//return 'http://localhost:8080/ipfs/' + hash;
|
||||
return (self.getUrl || "http://localhost:8080/ipfs/") + hash;
|
||||
};
|
||||
|
||||
|
@ -399,18 +416,16 @@ EmbarkJS.Messages.web3CompatibleWithV5 = function() {
|
|||
var _web3 = new Web3();
|
||||
if (typeof(_web3.version) === "string") {
|
||||
return true;
|
||||
} else {
|
||||
return parseInt(_web3.version.api.split('.')[1], 10) >= 20;
|
||||
}
|
||||
return parseInt(_web3.version.api.split('.')[1], 10) >= 20;
|
||||
};
|
||||
|
||||
EmbarkJS.Messages.isNewWeb3 = function() {
|
||||
var _web3 = new Web3();
|
||||
if (typeof(_web3.version) === "string") {
|
||||
return true;
|
||||
} else {
|
||||
return parseInt(_web3.version.api.split('.')[0], 10) >= 1;
|
||||
}
|
||||
return parseInt(_web3.version.api.split('.')[0], 10) >= 1;
|
||||
};
|
||||
|
||||
EmbarkJS.Messages.getWhisperVersion = function(cb) {
|
||||
|
@ -429,22 +444,19 @@ EmbarkJS.Messages.setProvider = function(provider, options) {
|
|||
var self = this;
|
||||
var ipfs;
|
||||
if (provider === 'whisper') {
|
||||
this.providerName = 'whisper'
|
||||
this.currentMessages = EmbarkJS.Messages.Whisper;
|
||||
if (typeof variable === 'undefined' && typeof(web3) === 'undefined') {
|
||||
let provider;
|
||||
if (options === undefined) {
|
||||
provider = "localhost:8546";
|
||||
} else {
|
||||
provider = options.server + ':' + options.port;
|
||||
}
|
||||
if (this.isNewWeb3()) {
|
||||
// TODO: add current Provider
|
||||
self.currentMessages.web3 = new Web3(new Web3.providers.WebsocketProvider("ws://" + provider));
|
||||
} else {
|
||||
self.currentMessages.web3 = new Web3(new Web3.providers.HttpProvider("http://" + provider));
|
||||
}
|
||||
let provider;
|
||||
if (options === undefined) {
|
||||
provider = "localhost:8546";
|
||||
} else {
|
||||
provider = options.server + ':' + options.port;
|
||||
}
|
||||
if (this.isNewWeb3()) {
|
||||
self.currentMessages.web3 = new Web3(new Web3.providers.WebsocketProvider("ws://" + provider));
|
||||
} else {
|
||||
self.currentMessages.web3 = new Web3(new Web3.providers.HttpProvider("http://" + provider));
|
||||
}
|
||||
console.log("getting whisper version");
|
||||
self.getWhisperVersion(function(err, version) {
|
||||
if (err) {
|
||||
console.log("whisper not available");
|
||||
|
@ -453,7 +465,7 @@ EmbarkJS.Messages.setProvider = function(provider, options) {
|
|||
self.currentMessages.web3.shh.newSymKey().then((id) => {self.currentMessages.symKeyID = id;});
|
||||
self.currentMessages.web3.shh.newKeyPair().then((id) => {self.currentMessages.sig = id;});
|
||||
} else {
|
||||
console.log("this version of whisper is not supported yet; try a version of geth bellow 1.6.1");
|
||||
console.log("this version of whisper in this node");
|
||||
}
|
||||
} else {
|
||||
self.currentMessages.identity = self.currentMessages.web3.shh.newIdentity();
|
||||
|
@ -461,6 +473,7 @@ EmbarkJS.Messages.setProvider = function(provider, options) {
|
|||
self.currentMessages.whisperVersion = self.currentMessages.web3.version.whisper;
|
||||
});
|
||||
} else if (provider === 'orbit') {
|
||||
this.providerName = 'orbit'
|
||||
this.currentMessages = EmbarkJS.Messages.Orbit;
|
||||
if (options === undefined) {
|
||||
ipfs = HaadIpfsApi('localhost', '5001');
|
||||
|
@ -489,104 +502,108 @@ EmbarkJS.Messages.listenTo = function(options) {
|
|||
EmbarkJS.Messages.Whisper = {};
|
||||
|
||||
EmbarkJS.Messages.Whisper.sendMessage = function(options) {
|
||||
if (EmbarkJS.Messages.isNewWeb3()) {
|
||||
var topics = options.topic || options.topics;
|
||||
var data = options.data || options.payload;
|
||||
var identity;
|
||||
if (!EmbarkJS.Messages.isNewWeb3()) {
|
||||
identity = options.identity || this.identity || web3.shh.newIdentity();
|
||||
var ttl = options.ttl || 100;
|
||||
var priority = options.priority || 1000;
|
||||
var powTime = options.powTime || 3;
|
||||
var powTarget = options.powTarget || 0.5;
|
||||
|
||||
if (topics === undefined) {
|
||||
throw new Error("missing option: topic");
|
||||
}
|
||||
|
||||
if (data === undefined) {
|
||||
throw new Error("missing option: data");
|
||||
}
|
||||
|
||||
topics = this.web3.utils.toHex(topics).slice(0, 10);
|
||||
|
||||
var payload = JSON.stringify(data);
|
||||
|
||||
let message = {
|
||||
symKeyID: this.symKeyID, // encrypts using the sym key ID
|
||||
sig: this.sig, // signs the message using the keyPair ID
|
||||
ttl: ttl,
|
||||
topic: topics,
|
||||
payload: EmbarkJS.Utils.fromAscii(payload),
|
||||
powTime: powTime,
|
||||
powTarget: powTarget
|
||||
};
|
||||
|
||||
this.web3.shh.post(message, function() { });
|
||||
} else {
|
||||
var topics = options.topic || options.topics;
|
||||
var data = options.data || options.payload;
|
||||
var identity = options.identity || this.identity || web3.shh.newIdentity();
|
||||
var ttl = options.ttl || 100;
|
||||
var priority = options.priority || 1000;
|
||||
var _topics;
|
||||
|
||||
if (topics === undefined) {
|
||||
throw new Error("missing option: topic");
|
||||
throw new Error("missing option: topic");
|
||||
}
|
||||
|
||||
if (data === undefined) {
|
||||
throw new Error("missing option: data");
|
||||
throw new Error("missing option: data");
|
||||
}
|
||||
|
||||
if (EmbarkJS.Messages.isNewWeb3()) {
|
||||
topics = this.web3.utils.toHex(topics).slice(0, 10);
|
||||
if (typeof topics === 'string') {
|
||||
_topics = [EmbarkJS.Utils.fromAscii(topics)];
|
||||
} else {
|
||||
if (typeof topics === 'string') {
|
||||
_topics = [EmbarkJS.Utils.fromAscii(topics)];
|
||||
} else {
|
||||
// TODO: replace with es6 + babel;
|
||||
for (var i = 0; i < topics.length; i++) {
|
||||
_topics.push(EmbarkJS.Utils.fromAscii(topics[i]));
|
||||
}
|
||||
}
|
||||
topics = _topics;
|
||||
_topics = topics.map((t) => EmbarkJS.Utils.fromAscii(t));
|
||||
}
|
||||
topics = _topics;
|
||||
|
||||
var payload = JSON.stringify(data);
|
||||
|
||||
var message;
|
||||
if (EmbarkJS.Messages.isNewWeb3()) {
|
||||
message = {
|
||||
symKeyID: this.symKeyID, // encrypts using the sym key ID
|
||||
sig: this.sig, // signs the message using the keyPair ID
|
||||
ttl: 10,
|
||||
topic: topics,
|
||||
payload: EmbarkJS.Utils.fromAscii('hello'),
|
||||
powTime: 3,
|
||||
powTarget: 0.5
|
||||
};
|
||||
} else {
|
||||
message = {
|
||||
from: identity,
|
||||
topics: topics,
|
||||
payload: EmbarkJS.Utils.fromAscii(payload),
|
||||
ttl: ttl,
|
||||
priority: priority
|
||||
};
|
||||
}
|
||||
message = {
|
||||
from: identity,
|
||||
topics: topics,
|
||||
payload: EmbarkJS.Utils.fromAscii(payload),
|
||||
ttl: ttl,
|
||||
priority: priority
|
||||
};
|
||||
|
||||
return this.web3.shh.post(message, function() {});
|
||||
return EmbarkJS.Messages.currentMessages.web3.shh.post(message, function() { console.log("message sent") });
|
||||
}
|
||||
};
|
||||
|
||||
EmbarkJS.Messages.Whisper.listenTo = function(options) {
|
||||
var topics = options.topic || options.topics;
|
||||
var _topics = [];
|
||||
|
||||
var messageEvents = function() {
|
||||
this.cb = function() {};
|
||||
};
|
||||
|
||||
messageEvents.prototype.then = function(cb) {
|
||||
this.cb = cb;
|
||||
};
|
||||
|
||||
messageEvents.prototype.error = function(err) {
|
||||
return err;
|
||||
};
|
||||
|
||||
messageEvents.prototype.stop = function() {
|
||||
this.filter.stopWatching();
|
||||
};
|
||||
|
||||
if (EmbarkJS.Messages.isNewWeb3()) {
|
||||
topics = [this.web3.utils.toHex(topics).slice(0, 10)];
|
||||
} else {
|
||||
if (typeof topics === 'string') {
|
||||
_topics = [topics];
|
||||
} else {
|
||||
// TODO: replace with es6 + babel;
|
||||
for (var i = 0; i < topics.length; i++) {
|
||||
_topics.push(topics[i]);
|
||||
}
|
||||
}
|
||||
topics = _topics;
|
||||
}
|
||||
var messageEvents = function() {
|
||||
this.cb = function() {};
|
||||
};
|
||||
|
||||
messageEvents.prototype.then = function(cb) {
|
||||
this.cb = cb;
|
||||
};
|
||||
|
||||
messageEvents.prototype.error = function(err) {
|
||||
return err;
|
||||
};
|
||||
|
||||
messageEvents.prototype.stop = function() {
|
||||
this.filter.stopWatching();
|
||||
};
|
||||
|
||||
var topics = options.topic || options.topics;
|
||||
var _topics = [];
|
||||
|
||||
if (EmbarkJS.Messages.isNewWeb3()) {
|
||||
let promise = new messageEvents();
|
||||
|
||||
// listenTo
|
||||
if (typeof topics === 'string') {
|
||||
topics = [this.web3.utils.toHex(topics).slice(0, 10)];
|
||||
} else {
|
||||
topics = topics.map((t) => this.web3.utils.toHex(t).slice(0, 10));
|
||||
}
|
||||
|
||||
let filter = this.web3.shh.subscribe("messages", {
|
||||
symKeyID: this.symKeyID,
|
||||
topics: topics
|
||||
symKeyID: this.symKeyID,
|
||||
topics: topics
|
||||
}).on('data', function(result) {
|
||||
var payload = JSON.parse(EmbarkJS.Utils.toAscii(result.payload));
|
||||
var data;
|
||||
|
@ -596,14 +613,40 @@ EmbarkJS.Messages.Whisper.listenTo = function(options) {
|
|||
//from: result.from,
|
||||
time: result.timestamp
|
||||
};
|
||||
|
||||
promise.cb(payload, data, result);
|
||||
});
|
||||
|
||||
promise.filter = filter;
|
||||
|
||||
return promise;
|
||||
|
||||
} else {
|
||||
var topics = options.topic || options.topics;
|
||||
var _topics = [];
|
||||
|
||||
var messageEvents = function() {
|
||||
this.cb = function() {};
|
||||
};
|
||||
|
||||
messageEvents.prototype.then = function(cb) {
|
||||
this.cb = cb;
|
||||
};
|
||||
|
||||
messageEvents.prototype.error = function(err) {
|
||||
return err;
|
||||
};
|
||||
|
||||
messageEvents.prototype.stop = function() {
|
||||
this.filter.stopWatching();
|
||||
};
|
||||
|
||||
if (typeof topics === 'string') {
|
||||
_topics = [topics];
|
||||
} else {
|
||||
_topics = topics.map((t) => EmbarkJS.Utils.fromAscii(t));
|
||||
}
|
||||
topics = _topics;
|
||||
|
||||
var filterOptions = {
|
||||
topics: topics
|
||||
};
|
||||
|
@ -630,7 +673,7 @@ EmbarkJS.Messages.Whisper.listenTo = function(options) {
|
|||
|
||||
return promise;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
EmbarkJS.Messages.Orbit = {};
|
||||
|
||||
|
@ -707,6 +750,10 @@ EmbarkJS.Utils = {
|
|||
fromAscii: function(str) {
|
||||
var _web3 = new Web3();
|
||||
return _web3.utils ? _web3.utils.fromAscii(str) : _web3.fromAscii(str);
|
||||
},
|
||||
toAscii: function(str) {
|
||||
var _web3 = new Web3();
|
||||
return _web3.utils.toAscii(str);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
374
js/embark.js
374
js/embark.js
|
@ -7,103 +7,122 @@
|
|||
|
||||
var EmbarkJS = {};
|
||||
|
||||
EmbarkJS.isNewWeb3 = function() {
|
||||
var _web3 = new Web3();
|
||||
if (typeof(_web3.version) === "string") {
|
||||
return true;
|
||||
}
|
||||
return parseInt(_web3.version.api.split('.')[0], 10) >= 1;
|
||||
};
|
||||
|
||||
EmbarkJS.Contract = function(options) {
|
||||
var self = this;
|
||||
var i, abiElement;
|
||||
var ContractClass;
|
||||
|
||||
this.abi = options.abi;
|
||||
this.address = options.address;
|
||||
this.code = '0x' + options.code;
|
||||
this.web3 = options.web3 || web3;
|
||||
|
||||
var ContractClass = this.web3.eth.contract(this.abi);
|
||||
if (EmbarkJS.isNewWeb3()) {
|
||||
// TODO:
|
||||
// add default **from** address
|
||||
// add gasPrice
|
||||
ContractClass = new this.web3.eth.Contract(this.abi, this.address);
|
||||
ContractClass.setProvider(this.web3.currentProvider);
|
||||
|
||||
this.eventList = [];
|
||||
return ContractClass;
|
||||
} else {
|
||||
ContractClass = this.web3.eth.contract(this.abi);
|
||||
|
||||
if (this.abi) {
|
||||
this.eventList = [];
|
||||
|
||||
if (this.abi) {
|
||||
for (i = 0; i < this.abi.length; i++) {
|
||||
abiElement = this.abi[i];
|
||||
if (abiElement.type === 'event') {
|
||||
this.eventList.push(abiElement.name);
|
||||
}
|
||||
abiElement = this.abi[i];
|
||||
if (abiElement.type === 'event') {
|
||||
this.eventList.push(abiElement.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var messageEvents = function() {
|
||||
var messageEvents = function() {
|
||||
this.cb = function() {};
|
||||
};
|
||||
};
|
||||
|
||||
messageEvents.prototype.then = function(cb) {
|
||||
messageEvents.prototype.then = function(cb) {
|
||||
this.cb = cb;
|
||||
};
|
||||
};
|
||||
|
||||
messageEvents.prototype.error = function(err) {
|
||||
messageEvents.prototype.error = function(err) {
|
||||
return err;
|
||||
};
|
||||
};
|
||||
|
||||
this._originalContractObject = ContractClass.at(this.address);
|
||||
this._methods = Object.getOwnPropertyNames(this._originalContractObject).filter(function(p) {
|
||||
this._originalContractObject = ContractClass.at(this.address);
|
||||
this._methods = Object.getOwnPropertyNames(this._originalContractObject).filter(function(p) {
|
||||
// TODO: check for forbidden properties
|
||||
if (self.eventList.indexOf(p) >= 0) {
|
||||
|
||||
self[p] = function() {
|
||||
var promise = new messageEvents();
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args.push(function(err, result) {
|
||||
if (err) {
|
||||
promise.error(err);
|
||||
} else {
|
||||
promise.cb(result);
|
||||
}
|
||||
});
|
||||
self[p] = function() {
|
||||
var promise = new messageEvents();
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
args.push(function(err, result) {
|
||||
if (err) {
|
||||
promise.error(err);
|
||||
} else {
|
||||
promise.cb(result);
|
||||
}
|
||||
});
|
||||
|
||||
self._originalContractObject[p].apply(self._originalContractObject[p], args);
|
||||
return promise;
|
||||
};
|
||||
return true;
|
||||
self._originalContractObject[p].apply(self._originalContractObject[p], args);
|
||||
return promise;
|
||||
};
|
||||
return true;
|
||||
} else if (typeof self._originalContractObject[p] === 'function') {
|
||||
self[p] = function(_args) {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
var fn = self._originalContractObject[p];
|
||||
var props = self.abi.find((x) => x.name == p);
|
||||
self[p] = function(_args) {
|
||||
var args = Array.prototype.slice.call(arguments);
|
||||
var fn = self._originalContractObject[p];
|
||||
var props = self.abi.find((x) => x.name == p);
|
||||
|
||||
var promise = new Promise(function(resolve, reject) {
|
||||
args.push(function(err, transaction) {
|
||||
promise.tx = transaction;
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
var promise = new Promise(function(resolve, reject) {
|
||||
args.push(function(err, transaction) {
|
||||
promise.tx = transaction;
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
|
||||
var getConfirmation = function() {
|
||||
self.web3.eth.getTransactionReceipt(transaction, function(err, receipt) {
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
var getConfirmation = function() {
|
||||
self.web3.eth.getTransactionReceipt(transaction, function(err, receipt) {
|
||||
if (err) {
|
||||
return reject(err);
|
||||
}
|
||||
|
||||
if (receipt !== null) {
|
||||
return resolve(receipt);
|
||||
}
|
||||
if (receipt !== null) {
|
||||
return resolve(receipt);
|
||||
}
|
||||
|
||||
setTimeout(getConfirmation, 1000);
|
||||
});
|
||||
};
|
||||
setTimeout(getConfirmation, 1000);
|
||||
});
|
||||
};
|
||||
|
||||
if (typeof(transaction) !== "string" || props.constant) {
|
||||
resolve(transaction);
|
||||
} else {
|
||||
getConfirmation();
|
||||
}
|
||||
});
|
||||
if (typeof(transaction) !== "string" || props.constant) {
|
||||
resolve(transaction);
|
||||
} else {
|
||||
getConfirmation();
|
||||
}
|
||||
});
|
||||
|
||||
fn.apply(fn, args);
|
||||
});
|
||||
fn.apply(fn, args);
|
||||
});
|
||||
|
||||
return promise;
|
||||
};
|
||||
return true;
|
||||
return promise;
|
||||
};
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
EmbarkJS.Contract.prototype.deploy = function(args, _options) {
|
||||
|
@ -301,9 +320,6 @@ EmbarkJS.Storage.IPFS.uploadFile = function(inputSelector) {
|
|||
};
|
||||
|
||||
EmbarkJS.Storage.IPFS.getUrl = function(hash) {
|
||||
//var ipfsHash = web3.toAscii(hash);
|
||||
|
||||
//return 'http://localhost:8080/ipfs/' + hash;
|
||||
return (self.getUrl || "http://localhost:8080/ipfs/") + hash;
|
||||
};
|
||||
|
||||
|
@ -317,18 +333,16 @@ EmbarkJS.Messages.web3CompatibleWithV5 = function() {
|
|||
var _web3 = new Web3();
|
||||
if (typeof(_web3.version) === "string") {
|
||||
return true;
|
||||
} else {
|
||||
return parseInt(_web3.version.api.split('.')[1], 10) >= 20;
|
||||
}
|
||||
return parseInt(_web3.version.api.split('.')[1], 10) >= 20;
|
||||
};
|
||||
|
||||
EmbarkJS.Messages.isNewWeb3 = function() {
|
||||
var _web3 = new Web3();
|
||||
if (typeof(_web3.version) === "string") {
|
||||
return true;
|
||||
} else {
|
||||
return parseInt(_web3.version.api.split('.')[0], 10) >= 1;
|
||||
}
|
||||
return parseInt(_web3.version.api.split('.')[0], 10) >= 1;
|
||||
};
|
||||
|
||||
EmbarkJS.Messages.getWhisperVersion = function(cb) {
|
||||
|
@ -347,22 +361,19 @@ EmbarkJS.Messages.setProvider = function(provider, options) {
|
|||
var self = this;
|
||||
var ipfs;
|
||||
if (provider === 'whisper') {
|
||||
this.providerName = 'whisper';
|
||||
this.currentMessages = EmbarkJS.Messages.Whisper;
|
||||
if (typeof variable === 'undefined' && typeof(web3) === 'undefined') {
|
||||
let provider;
|
||||
if (options === undefined) {
|
||||
provider = "localhost:8546";
|
||||
} else {
|
||||
provider = options.server + ':' + options.port;
|
||||
}
|
||||
if (this.isNewWeb3()) {
|
||||
// TODO: add current Provider
|
||||
self.currentMessages.web3 = new Web3(new Web3.providers.WebsocketProvider("ws://" + provider));
|
||||
} else {
|
||||
self.currentMessages.web3 = new Web3(new Web3.providers.HttpProvider("http://" + provider));
|
||||
}
|
||||
let provider;
|
||||
if (options === undefined) {
|
||||
provider = "localhost:8546";
|
||||
} else {
|
||||
provider = options.server + ':' + options.port;
|
||||
}
|
||||
if (this.isNewWeb3()) {
|
||||
self.currentMessages.web3 = new Web3(new Web3.providers.WebsocketProvider("ws://" + provider));
|
||||
} else {
|
||||
self.currentMessages.web3 = new Web3(new Web3.providers.HttpProvider("http://" + provider));
|
||||
}
|
||||
console.log("getting whisper version");
|
||||
self.getWhisperVersion(function(err, version) {
|
||||
if (err) {
|
||||
console.log("whisper not available");
|
||||
|
@ -371,7 +382,7 @@ EmbarkJS.Messages.setProvider = function(provider, options) {
|
|||
self.currentMessages.web3.shh.newSymKey().then((id) => {self.currentMessages.symKeyID = id;});
|
||||
self.currentMessages.web3.shh.newKeyPair().then((id) => {self.currentMessages.sig = id;});
|
||||
} else {
|
||||
console.log("this version of whisper is not supported yet; try a version of geth bellow 1.6.1");
|
||||
console.log("this version of whisper in this node");
|
||||
}
|
||||
} else {
|
||||
self.currentMessages.identity = self.currentMessages.web3.shh.newIdentity();
|
||||
|
@ -379,6 +390,7 @@ EmbarkJS.Messages.setProvider = function(provider, options) {
|
|||
self.currentMessages.whisperVersion = self.currentMessages.web3.version.whisper;
|
||||
});
|
||||
} else if (provider === 'orbit') {
|
||||
this.providerName = 'orbit';
|
||||
this.currentMessages = EmbarkJS.Messages.Orbit;
|
||||
if (options === undefined) {
|
||||
ipfs = HaadIpfsApi('localhost', '5001');
|
||||
|
@ -407,104 +419,110 @@ EmbarkJS.Messages.listenTo = function(options) {
|
|||
EmbarkJS.Messages.Whisper = {};
|
||||
|
||||
EmbarkJS.Messages.Whisper.sendMessage = function(options) {
|
||||
var topics = options.topic || options.topics;
|
||||
var data = options.data || options.payload;
|
||||
var identity;
|
||||
if (!EmbarkJS.Messages.isNewWeb3()) {
|
||||
identity = options.identity || this.identity || web3.shh.newIdentity();
|
||||
}
|
||||
var ttl = options.ttl || 100;
|
||||
var priority = options.priority || 1000;
|
||||
var _topics;
|
||||
var topics, data, ttl, priority, payload;
|
||||
if (EmbarkJS.Messages.isNewWeb3()) {
|
||||
topics = options.topic || options.topics;
|
||||
data = options.data || options.payload;
|
||||
ttl = options.ttl || 100;
|
||||
priority = options.priority || 1000;
|
||||
var powTime = options.powTime || 3;
|
||||
var powTarget = options.powTarget || 0.5;
|
||||
|
||||
if (topics === undefined) {
|
||||
throw new Error("missing option: topic");
|
||||
throw new Error("missing option: topic");
|
||||
}
|
||||
|
||||
if (data === undefined) {
|
||||
throw new Error("missing option: data");
|
||||
throw new Error("missing option: data");
|
||||
}
|
||||
|
||||
if (EmbarkJS.Messages.isNewWeb3()) {
|
||||
topics = this.web3.utils.toHex(topics).slice(0, 10);
|
||||
topics = this.web3.utils.toHex(topics).slice(0, 10);
|
||||
|
||||
payload = JSON.stringify(data);
|
||||
|
||||
let message = {
|
||||
symKeyID: this.symKeyID, // encrypts using the sym key ID
|
||||
sig: this.sig, // signs the message using the keyPair ID
|
||||
ttl: ttl,
|
||||
topic: topics,
|
||||
payload: EmbarkJS.Utils.fromAscii(payload),
|
||||
powTime: powTime,
|
||||
powTarget: powTarget
|
||||
};
|
||||
|
||||
this.web3.shh.post(message, function() { });
|
||||
} else {
|
||||
topics = options.topic || options.topics;
|
||||
data = options.data || options.payload;
|
||||
ttl = options.ttl || 100;
|
||||
priority = options.priority || 1000;
|
||||
var identity = options.identity || this.identity || web3.shh.newIdentity();
|
||||
var _topics;
|
||||
|
||||
if (topics === undefined) {
|
||||
throw new Error("missing option: topic");
|
||||
}
|
||||
|
||||
if (data === undefined) {
|
||||
throw new Error("missing option: data");
|
||||
}
|
||||
|
||||
if (typeof topics === 'string') {
|
||||
_topics = [EmbarkJS.Utils.fromAscii(topics)];
|
||||
} else {
|
||||
if (typeof topics === 'string') {
|
||||
_topics = [EmbarkJS.Utils.fromAscii(topics)];
|
||||
} else {
|
||||
// TODO: replace with es6 + babel;
|
||||
for (var i = 0; i < topics.length; i++) {
|
||||
_topics.push(EmbarkJS.Utils.fromAscii(topics[i]));
|
||||
}
|
||||
}
|
||||
topics = _topics;
|
||||
_topics = topics.map((t) => EmbarkJS.Utils.fromAscii(t));
|
||||
}
|
||||
topics = _topics;
|
||||
|
||||
var payload = JSON.stringify(data);
|
||||
payload = JSON.stringify(data);
|
||||
|
||||
var message;
|
||||
if (EmbarkJS.Messages.isNewWeb3()) {
|
||||
message = {
|
||||
symKeyID: this.symKeyID, // encrypts using the sym key ID
|
||||
sig: this.sig, // signs the message using the keyPair ID
|
||||
ttl: 10,
|
||||
topic: topics,
|
||||
payload: EmbarkJS.Utils.fromAscii('hello'),
|
||||
powTime: 3,
|
||||
powTarget: 0.5
|
||||
};
|
||||
} else {
|
||||
message = {
|
||||
from: identity,
|
||||
topics: topics,
|
||||
payload: EmbarkJS.Utils.fromAscii(payload),
|
||||
ttl: ttl,
|
||||
priority: priority
|
||||
};
|
||||
}
|
||||
message = {
|
||||
from: identity,
|
||||
topics: topics,
|
||||
payload: EmbarkJS.Utils.fromAscii(payload),
|
||||
ttl: ttl,
|
||||
priority: priority
|
||||
};
|
||||
|
||||
return this.web3.shh.post(message, function() {});
|
||||
return EmbarkJS.Messages.currentMessages.web3.shh.post(message, function() { });
|
||||
}
|
||||
};
|
||||
|
||||
EmbarkJS.Messages.Whisper.listenTo = function(options) {
|
||||
var topics = options.topic || options.topics;
|
||||
var _topics = [];
|
||||
|
||||
var messageEvents = function() {
|
||||
this.cb = function() {};
|
||||
};
|
||||
|
||||
messageEvents.prototype.then = function(cb) {
|
||||
this.cb = cb;
|
||||
};
|
||||
|
||||
messageEvents.prototype.error = function(err) {
|
||||
return err;
|
||||
};
|
||||
|
||||
messageEvents.prototype.stop = function() {
|
||||
this.filter.stopWatching();
|
||||
};
|
||||
|
||||
var topics, _topics, messageEvents;
|
||||
if (EmbarkJS.Messages.isNewWeb3()) {
|
||||
topics = [this.web3.utils.toHex(topics).slice(0, 10)];
|
||||
} else {
|
||||
if (typeof topics === 'string') {
|
||||
_topics = [topics];
|
||||
} else {
|
||||
// TODO: replace with es6 + babel;
|
||||
for (var i = 0; i < topics.length; i++) {
|
||||
_topics.push(topics[i]);
|
||||
}
|
||||
}
|
||||
topics = _topics;
|
||||
}
|
||||
messageEvents = function() {
|
||||
this.cb = function() {};
|
||||
};
|
||||
|
||||
messageEvents.prototype.then = function(cb) {
|
||||
this.cb = cb;
|
||||
};
|
||||
|
||||
messageEvents.prototype.error = function(err) {
|
||||
return err;
|
||||
};
|
||||
|
||||
messageEvents.prototype.stop = function() {
|
||||
this.filter.stopWatching();
|
||||
};
|
||||
|
||||
topics = options.topic || options.topics;
|
||||
_topics = [];
|
||||
|
||||
if (EmbarkJS.Messages.isNewWeb3()) {
|
||||
let promise = new messageEvents();
|
||||
|
||||
// listenTo
|
||||
if (typeof topics === 'string') {
|
||||
topics = [this.web3.utils.toHex(topics).slice(0, 10)];
|
||||
} else {
|
||||
topics = topics.map((t) => this.web3.utils.toHex(t).slice(0, 10));
|
||||
}
|
||||
|
||||
let filter = this.web3.shh.subscribe("messages", {
|
||||
symKeyID: this.symKeyID,
|
||||
topics: topics
|
||||
symKeyID: this.symKeyID,
|
||||
topics: topics
|
||||
}).on('data', function(result) {
|
||||
var payload = JSON.parse(EmbarkJS.Utils.toAscii(result.payload));
|
||||
var data;
|
||||
|
@ -514,14 +532,40 @@ EmbarkJS.Messages.Whisper.listenTo = function(options) {
|
|||
//from: result.from,
|
||||
time: result.timestamp
|
||||
};
|
||||
|
||||
promise.cb(payload, data, result);
|
||||
});
|
||||
|
||||
promise.filter = filter;
|
||||
|
||||
return promise;
|
||||
|
||||
} else {
|
||||
topics = options.topic || options.topics;
|
||||
_topics = [];
|
||||
|
||||
messageEvents = function() {
|
||||
this.cb = function() {};
|
||||
};
|
||||
|
||||
messageEvents.prototype.then = function(cb) {
|
||||
this.cb = cb;
|
||||
};
|
||||
|
||||
messageEvents.prototype.error = function(err) {
|
||||
return err;
|
||||
};
|
||||
|
||||
messageEvents.prototype.stop = function() {
|
||||
this.filter.stopWatching();
|
||||
};
|
||||
|
||||
if (typeof topics === 'string') {
|
||||
_topics = [topics];
|
||||
} else {
|
||||
_topics = topics.map((t) => EmbarkJS.Utils.fromAscii(t));
|
||||
}
|
||||
topics = _topics;
|
||||
|
||||
var filterOptions = {
|
||||
topics: topics
|
||||
};
|
||||
|
@ -625,6 +669,10 @@ EmbarkJS.Utils = {
|
|||
fromAscii: function(str) {
|
||||
var _web3 = new Web3();
|
||||
return _web3.utils ? _web3.utils.fromAscii(str) : _web3.fromAscii(str);
|
||||
},
|
||||
toAscii: function(str) {
|
||||
var _web3 = new Web3();
|
||||
return _web3.utils.toAscii(str);
|
||||
}
|
||||
};
|
||||
|
||||
|
|
File diff suppressed because one or more lines are too long
|
@ -1,4 +1,19 @@
|
|||
class ABIGenerator {
|
||||
const ejs = require('ejs');
|
||||
const Templates = {
|
||||
utils: require('./code_templates/utils.js.ejs'),
|
||||
vanilla_contract: require('./code_templates/vanilla-contract.js.ejs'),
|
||||
embarkjs_contract: require('./code_templates/embarkjs-contract.js.ejs'),
|
||||
exec_when_ready: require('./code_templates/exec-when-ready.js.ejs'),
|
||||
load_manager: require('./code_templates/load-manager.js.ejs'),
|
||||
define_when_env_loaded: require('./code_templates/define-when-env-loaded.js.ejs'),
|
||||
main_context: require('./code_templates/main-context.js.ejs'),
|
||||
define_web3_simple: require('./code_templates/define-web3-simple.js.ejs'),
|
||||
web3_connector: require('./code_templates/web3-connector.js.ejs'),
|
||||
do_when_loaded: require('./code_templates/do-when-loaded.js.ejs'),
|
||||
exec_when_env_loaded: require('./code_templates/exec-when-env-loaded.js.ejs')
|
||||
}
|
||||
|
||||
class CodeGenerator {
|
||||
constructor(options) {
|
||||
this.blockchainConfig = options.blockchainConfig || {};
|
||||
this.contractsConfig = options.contractsConfig || {};
|
||||
|
@ -27,7 +42,7 @@ class ABIGenerator {
|
|||
});
|
||||
|
||||
this.events.setCommandHandler('abi-contracts-vanila', function(cb) {
|
||||
let vanillaContractsABI = self.generateContracts(false);
|
||||
let vanillaContractsABI = self.generateContracts(false, true, false);
|
||||
let contractsJSON = self.generateContractsJSON();
|
||||
|
||||
cb(vanillaContractsABI, contractsJSON);
|
||||
|
@ -51,13 +66,11 @@ class ABIGenerator {
|
|||
return "";
|
||||
}
|
||||
|
||||
result += "\nvar whenEnvIsLoaded = function(cb) {";
|
||||
result += "\n if (typeof document !== 'undefined' && document !== null) {";
|
||||
result += "\n document.addEventListener('DOMContentLoaded', cb);";
|
||||
result += "\n } else {";
|
||||
result += "\n cb();";
|
||||
result += "\n }";
|
||||
result += "\n}";
|
||||
result += Templates.utils();
|
||||
|
||||
result += Templates.main_context();
|
||||
result += Templates.load_manager();
|
||||
result += Templates.define_when_env_loaded();
|
||||
|
||||
if (this.plugins) {
|
||||
providerPlugins = this.plugins.getPluginsFor('clientWeb3Provider');
|
||||
|
@ -68,44 +81,39 @@ class ABIGenerator {
|
|||
result += plugin.generateProvider(self) + "\n";
|
||||
});
|
||||
} else {
|
||||
result += "\nwhenEnvIsLoaded(function() {\n";
|
||||
|
||||
let web3Load;
|
||||
|
||||
if (isDeployment) {
|
||||
|
||||
let connection = "http://" + this.contractsConfig.deployment.host + ":" + this.contractsConfig.deployment.port;
|
||||
result += '\n\tweb3 = new Web3(new Web3.providers.HttpProvider("' + connection + '"));';
|
||||
web3Load = Templates.define_web3_simple({url: connection, done: 'done();'});
|
||||
} else {
|
||||
|
||||
let connectionCode = this.contractsConfig.dappConnection.map(function(connection) {
|
||||
let code = "";
|
||||
if (connection === '$WEB3') {
|
||||
code += "if (typeof web3 !== 'undefined' && typeof Web3 !== 'undefined') {";
|
||||
code += '\n\tweb3 = new Web3(web3.currentProvider);';
|
||||
code += '\n}';
|
||||
} else {
|
||||
code += "if (typeof Web3 !== 'undefined' && ((typeof web3 === 'undefined') || (typeof web3 !== 'undefined' && !web3.isConnected()))) {";
|
||||
code += '\n\tweb3 = new Web3(new Web3.providers.HttpProvider("' + connection + '"));';
|
||||
code += '\n}';
|
||||
}
|
||||
return code;
|
||||
});
|
||||
|
||||
result += connectionCode.join(' ');
|
||||
let connectionList = "[" + this.contractsConfig.dappConnection.map((x) => '"' + x + '"').join(',') + "]";
|
||||
web3Load = Templates.web3_connector({connectionList: connectionList, done: 'done();'});
|
||||
}
|
||||
|
||||
|
||||
result += "\nweb3.eth.defaultAccount = web3.eth.accounts[0];";
|
||||
result += '\n})';
|
||||
result += Templates.do_when_loaded({block: web3Load});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
generateContracts(useEmbarkJS) {
|
||||
generateContracts(useEmbarkJS, isDeployment, useLoader) {
|
||||
let self = this;
|
||||
let result = "\n";
|
||||
let contractsPlugins;
|
||||
|
||||
if (useLoader === false) {
|
||||
let result;
|
||||
|
||||
for (let className in this.contractsManager.contracts) {
|
||||
let contract = this.contractsManager.contracts[className];
|
||||
let abi = JSON.stringify(contract.abiDefinition);
|
||||
result += Templates.vanilla_contract({className: className, abi: abi, contract: contract});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
if (self.blockchainConfig === {} || self.blockchainConfig.enabled === false) {
|
||||
return "";
|
||||
}
|
||||
|
@ -125,26 +133,16 @@ class ABIGenerator {
|
|||
let abi = JSON.stringify(contract.abiDefinition);
|
||||
let gasEstimates = JSON.stringify(contract.gasEstimates);
|
||||
|
||||
// TODO: refactor this
|
||||
result += "\nif (whenEnvIsLoaded === undefined) {";
|
||||
result += "\n var whenEnvIsLoaded = function(cb) {";
|
||||
result += "\n if (typeof document !== 'undefined' && document !== null) {";
|
||||
result += "\n document.addEventListener('DOMContentLoaded', cb);";
|
||||
result += "\n } else {";
|
||||
result += "\n cb();";
|
||||
result += "\n }";
|
||||
result += "\n }";
|
||||
result += "\n}";
|
||||
let block = "";
|
||||
|
||||
result += "\nwhenEnvIsLoaded(function() {";
|
||||
if (useEmbarkJS) {
|
||||
result += "\n" + className + " = new EmbarkJS.Contract({abi: " + abi + ", address: '" + contract.deployedAddress + "', code: '" + contract.code + "', gasEstimates: " + gasEstimates + "});";
|
||||
let contractAddress = contract.deployedAddress ? ("'" + contract.deployedAddress + "'") : "undefined";
|
||||
block += Templates.embarkjs_contract({className: className, abi: abi, contract: contract, contractAddress: contractAddress, gasEstimates: gasEstimates});
|
||||
} else {
|
||||
result += "\n" + className + "Abi = " + abi + ";";
|
||||
result += "\n" + className + "Contract = web3.eth.contract(" + className + "Abi);";
|
||||
result += "\n" + className + " = " + className + "Contract.at('" + contract.deployedAddress + "');";
|
||||
block += Templates.vanilla_contract({className: className, abi: abi, contract: contract});
|
||||
}
|
||||
result += '\n});';
|
||||
result += Templates.exec_when_ready({block: block});
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -158,19 +156,8 @@ class ABIGenerator {
|
|||
if (!useEmbarkJS || self.storageConfig === {}) return "";
|
||||
|
||||
if (self.storageConfig.provider === 'ipfs' && self.storageConfig.enabled === true) {
|
||||
// TODO: make this more readable
|
||||
|
||||
result += "\nvar whenEnvIsLoaded = function(cb) {";
|
||||
result += "\n if (typeof document !== 'undefined' && document !== null) {";
|
||||
result += "\n document.addEventListener('DOMContentLoaded', cb);";
|
||||
result += "\n } else {";
|
||||
result += "\n cb();";
|
||||
result += "\n }";
|
||||
result += "\n}";
|
||||
|
||||
result += "\nwhenEnvIsLoaded(function() {\n";
|
||||
result += "\nEmbarkJS.Storage.setProvider('" + self.storageConfig.provider + "', {server: '" + self.storageConfig.host + "', port: '" + self.storageConfig.port + "', getUrl: '" + self.storageConfig.getUrl + "'});";
|
||||
result += '\n})';
|
||||
let block = "\nEmbarkJS.Storage.setProvider('" + self.storageConfig.provider + "', {server: '" + self.storageConfig.host + "', port: '" + self.storageConfig.port + "', getUrl: '" + self.storageConfig.getUrl + "'});";
|
||||
result += Templates.define_when_env_loaded({block: block});
|
||||
}
|
||||
|
||||
return result;
|
||||
|
@ -182,26 +169,20 @@ class ABIGenerator {
|
|||
|
||||
if (!useEmbarkJS || self.communicationConfig === {}) return "";
|
||||
|
||||
result += "\nvar whenEnvIsLoaded = function(cb) {";
|
||||
result += "\n if (typeof document !== 'undefined' && document !== null) {";
|
||||
result += "\n document.addEventListener('DOMContentLoaded', cb);";
|
||||
result += "\n } else {";
|
||||
result += "\n cb();";
|
||||
result += "\n }";
|
||||
result += "\n}";
|
||||
// TODO: don't repeat this twice; should have 'requirements' generator first
|
||||
result += Templates.define_when_env_loaded();
|
||||
|
||||
let block;
|
||||
if (self.communicationConfig.provider === 'whisper' && self.communicationConfig.enabled === true) {
|
||||
result += "\nwhenEnvIsLoaded(function() {\n";
|
||||
result += "\nEmbarkJS.Messages.setProvider('" + self.communicationConfig.provider + "');";
|
||||
result += '\n})';
|
||||
block = "\nEmbarkJS.Messages.setProvider('" + self.communicationConfig.provider + "');";
|
||||
result += Templates.define_when_env_loaded({block: block});
|
||||
} else if (self.communicationConfig.provider === 'orbit' && self.communicationConfig.enabled === true) {
|
||||
result += "\nwhenEnvIsLoaded(function() {\n";
|
||||
if (self.communicationConfig.host === undefined && self.communicationConfig.port === undefined) {
|
||||
result += "\nEmbarkJS.Messages.setProvider('" + self.communicationConfig.provider + "');";
|
||||
block = "\nEmbarkJS.Messages.setProvider('" + self.communicationConfig.provider + "');";
|
||||
} else {
|
||||
result += "\nEmbarkJS.Messages.setProvider('" + self.communicationConfig.provider + "', {server: '" + self.communicationConfig.host + "', port: '" + self.communicationConfig.port + "'});";
|
||||
block = "\nEmbarkJS.Messages.setProvider('" + self.communicationConfig.provider + "', {server: '" + self.communicationConfig.host + "', port: '" + self.communicationConfig.port + "'});";
|
||||
}
|
||||
result += '\n})';
|
||||
result += Templates.define_when_env_loaded({block: block});
|
||||
}
|
||||
|
||||
return result;
|
||||
|
@ -211,7 +192,7 @@ class ABIGenerator {
|
|||
let result = "";
|
||||
|
||||
result += this.generateProvider(options.deployment);
|
||||
result += this.generateContracts(options.useEmbarkJS);
|
||||
result += this.generateContracts(options.useEmbarkJS, options.deployment, true);
|
||||
result += this.generateStorageInitialization(options.useEmbarkJS);
|
||||
result += this.generateCommunicationInitialization(options.useEmbarkJS);
|
||||
|
||||
|
@ -245,4 +226,4 @@ class ABIGenerator {
|
|||
}
|
||||
}
|
||||
|
||||
module.exports = ABIGenerator;
|
||||
module.exports = CodeGenerator;
|
|
@ -0,0 +1,3 @@
|
|||
__mainContext.web3 = undefined;
|
||||
web3 = new Web3(new Web3.providers.HttpProvider("<%- url -%>'"));
|
||||
<%- done %>
|
|
@ -0,0 +1,7 @@
|
|||
var whenEnvIsLoaded = function(cb) {
|
||||
if (typeof document !== 'undefined' && document !== null) {
|
||||
document.addEventListener('DOMContentLoaded', cb);
|
||||
} else {
|
||||
cb();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
whenEnvIsLoaded(function(){
|
||||
__mainContext.__loadManagerInstance.doFirst(function(done) {
|
||||
<%- block %>
|
||||
})
|
||||
});
|
||||
|
|
@ -0,0 +1 @@
|
|||
__mainContext.<%- className %> = new EmbarkJS.Contract({abi: <%- abi %>, address: <%- contractAddress %>, code: '<%- contract.code %>', gasEstimates: <%- gasEstimates %>});
|
|
@ -0,0 +1,3 @@
|
|||
whenEnvIsLoaded(function() {
|
||||
<%- block %>
|
||||
});
|
|
@ -0,0 +1,3 @@
|
|||
__mainContext.__loadManagerInstance.execWhenReady(function() {
|
||||
<%- block %>
|
||||
});
|
|
@ -0,0 +1,4 @@
|
|||
__mainContext.__LoadManager = function() { this.list = []; this.done = false; }
|
||||
__mainContext.__LoadManager.prototype.execWhenReady = function(cb) { if (this.done) { cb(); } else { this.list.push(cb) } }
|
||||
__mainContext.__LoadManager.prototype.doFirst = function(todo) { var self = this; todo(function() { self.done = true; self.list.map((x) => x.apply()) }) }
|
||||
__mainContext.__loadManagerInstance = new __mainContext.__LoadManager();
|
|
@ -0,0 +1 @@
|
|||
var __mainContext = __mainContext || this;
|
|
@ -0,0 +1,36 @@
|
|||
function __reduce(arr, memo, iteratee, cb) {
|
||||
if (typeof cb !== 'function') {
|
||||
if (typeof memo === 'function' && typeof iteratee === 'function') {
|
||||
cb = iteratee;
|
||||
iteratee = memo;
|
||||
memo = [];
|
||||
} else {
|
||||
throw new TypeError('expected callback to be a function');
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(arr)) {
|
||||
cb(new TypeError('expected an array'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof iteratee !== 'function') {
|
||||
cb(new TypeError('expected iteratee to be a function'));
|
||||
return;
|
||||
}
|
||||
|
||||
(function next(i, acc) {
|
||||
if (i === arr.length) {
|
||||
cb(null, acc);
|
||||
return;
|
||||
}
|
||||
|
||||
iteratee(acc, arr[i], function(err, val) {
|
||||
if (err) {
|
||||
cb(err);
|
||||
return;
|
||||
}
|
||||
next(i + 1, val);
|
||||
});
|
||||
})(0, memo);
|
||||
};
|
|
@ -0,0 +1,3 @@
|
|||
<%- className %>Abi = <%- abi %>;
|
||||
<%- className %>Contract = web3.eth.contract(<%- className %>Abi);
|
||||
<%- className %> = <%= className %>Contract.at('<%- contract.deployedAddress %>');
|
|
@ -0,0 +1,28 @@
|
|||
__mainContext.web3 = undefined;
|
||||
__reduce(<%- connectionList %>,function(prev, value, next) {
|
||||
if (prev === false) {
|
||||
return next(null, false);
|
||||
}
|
||||
|
||||
if (value === '$WEB3' && (typeof web3 !== 'undefined' && typeof Web3 !== 'undefined')) {
|
||||
web3 = new Web3(web3.currentProvider);
|
||||
} else if (value !== '$WEB3' && (typeof Web3 !== 'undefined' && ((typeof web3 === 'undefined') || (typeof web3 !== 'undefined' && (!web3.isConnected || (web3.isConnected && !web3.isConnected())))))) {
|
||||
|
||||
web3 = new Web3(new Web3.providers.HttpProvider(value));
|
||||
} else if (value === '$WEB3') {
|
||||
return next(null, '');
|
||||
}
|
||||
|
||||
web3.eth.getAccounts(function(err, account) {
|
||||
if (err) {
|
||||
next(null, true)
|
||||
} else {
|
||||
next(null, false)
|
||||
}
|
||||
});
|
||||
}, function(err, _result) {
|
||||
web3.eth.getAccounts(function(err, accounts) {
|
||||
web3.eth.defaultAccount = accounts[0];
|
||||
<%- done %>
|
||||
});
|
||||
});
|
|
@ -12,7 +12,11 @@ class ContractsManager {
|
|||
this.contracts = {};
|
||||
this.logger = options.logger;
|
||||
this.plugins = options.plugins;
|
||||
this.solcVersion = options.contractsConfig.versions.solc;
|
||||
if (!options.contractsConfig.versions) {
|
||||
this.solcVersion = "0.4.11";
|
||||
} else {
|
||||
this.solcVersion = options.contractsConfig.versions.solc;
|
||||
}
|
||||
|
||||
this.contractDependencies = {};
|
||||
}
|
||||
|
|
|
@ -3,7 +3,7 @@ let async = require('async');
|
|||
let RunCode = require('../core/runCode.js');
|
||||
|
||||
let DeployTracker = require('./deploy_tracker.js');
|
||||
let ABIGenerator = require('./abi.js');
|
||||
let CodeGenerator = require('./code_generator.js');
|
||||
|
||||
class Deploy {
|
||||
constructor(options) {
|
||||
|
@ -81,11 +81,11 @@ class Deploy {
|
|||
|
||||
if (contract.onDeploy !== undefined) {
|
||||
self.logger.info('executing onDeploy commands');
|
||||
let abiGenerator = new ABIGenerator({contractsManager: self.contractsManager});
|
||||
let abi = abiGenerator.generateContracts(false);
|
||||
let codeGenerator = new CodeGenerator({contractsManager: self.contractsManager});
|
||||
let code = codeGenerator.generateContracts(false, true, true);
|
||||
let cmds = contract.onDeploy.join(';\n');
|
||||
|
||||
RunCode.doEval(abi + "\n" + cmds, self.web3);
|
||||
RunCode.doEval(code + "\n" + cmds, self.web3);
|
||||
}
|
||||
|
||||
callback();
|
||||
|
|
|
@ -29,7 +29,7 @@ class SolcW {
|
|||
solcProcess.send({action: 'loadCompiler', solcLocation: 'solc'});
|
||||
} else {
|
||||
let npm = new Npm({logger: this.logger});
|
||||
npm.getPackageVersion('solc', this.solcVersion, false, function(location) {
|
||||
npm.getPackageVersion('solc', this.solcVersion, false, false, function(location) {
|
||||
let requirePath = path.join(process.env.PWD, location);
|
||||
solcProcess.send({action: 'loadCompiler', solcLocation: requirePath});
|
||||
});
|
||||
|
|
|
@ -256,10 +256,14 @@ Config.prototype.loadFiles = function(files) {
|
|||
//if (false) {
|
||||
//readFiles.push(new File({filename: 'web3-' + web3Version + '.js', type: 'custom', resolver: function(callback) {
|
||||
readFiles.push(new File({filename: 'web3.js', type: 'custom', resolver: function(callback) {
|
||||
let npm = new Npm({logger: self.logger});
|
||||
npm.getPackageVersion('web3', web3Version, 'dist/web3.js', function(web3Content) {
|
||||
callback(web3Content);
|
||||
});
|
||||
if (web3Version === "1.0.0-beta") {
|
||||
return callback(fs.readFileSync(fs.embarkPath('js/web3-1.0.min.js')).toString());
|
||||
} else {
|
||||
let npm = new Npm({logger: self.logger});
|
||||
npm.getPackageVersion('web3', web3Version, 'dist/web3.min.js', true, function(web3Content) {
|
||||
callback(web3Content);
|
||||
});
|
||||
}
|
||||
}}));
|
||||
} else {
|
||||
readFiles.push(new File({filename: 'web3.js', type: 'embark_internal', path: "js/web3.js"}));
|
||||
|
|
|
@ -4,7 +4,7 @@ let Events = require('./events.js');
|
|||
let Logger = require('./logger.js');
|
||||
let Config = require('./config.js');
|
||||
let DeployManager = require('../contracts/deploy_manager.js');
|
||||
let ABIGenerator = require('../contracts/abi.js');
|
||||
let CodeGenerator = require('../contracts/code_generator.js');
|
||||
let ServicesMonitor = require('./services_monitor.js');
|
||||
let Pipeline = require('../pipeline/pipeline.js');
|
||||
let Server = require('../pipeline/server.js');
|
||||
|
@ -51,7 +51,7 @@ class Engine {
|
|||
|
||||
let services = {
|
||||
"pipeline": this.pipelineService,
|
||||
"abi": this.abiService,
|
||||
"codeGenerator": this.codeGeneratorService,
|
||||
"deployment": this.deploymentService,
|
||||
"fileWatcher": this.fileWatchService,
|
||||
"webServer": this.webServerService,
|
||||
|
@ -100,10 +100,10 @@ class Engine {
|
|||
//});
|
||||
}
|
||||
|
||||
abiService(options) {
|
||||
codeGeneratorService(options) {
|
||||
let self = this;
|
||||
let generateABICode = function (contractsManager) {
|
||||
let abiGenerator = new ABIGenerator({
|
||||
let generateCode = function (contractsManager) {
|
||||
let codeGenerator = new CodeGenerator({
|
||||
blockchainConfig: self.config.blockchainConfig,
|
||||
contractsConfig: self.config.contractsConfig,
|
||||
contractsManager: contractsManager,
|
||||
|
@ -112,12 +112,12 @@ class Engine {
|
|||
communicationConfig: self.config.communicationConfig,
|
||||
events: self.events
|
||||
});
|
||||
abiGenerator.listenToCommands();
|
||||
codeGenerator.listenToCommands();
|
||||
|
||||
self.events.emit('code-generator-ready');
|
||||
};
|
||||
this.events.on('contractsDeployed', generateABICode);
|
||||
this.events.on('blockchainDisabled', generateABICode);
|
||||
this.events.on('contractsDeployed', generateCode);
|
||||
this.events.on('blockchainDisabled', generateCode);
|
||||
}
|
||||
|
||||
deploymentService(options) {
|
||||
|
|
|
@ -1,11 +1,43 @@
|
|||
var EventEmitter = require('events');
|
||||
|
||||
function warnIfLegacy(eventName) {
|
||||
const legacyEvents = ['abi-vanila', 'abi', 'abi-contracts-vanila', 'abi-vanila-deployment'];
|
||||
if (legacyEvents.indexOf(eventName) >= 0) {
|
||||
console.warn("this event is deprecated and will be removed in future versions: " + eventName);
|
||||
}
|
||||
}
|
||||
|
||||
function log(eventType, eventName) {
|
||||
if (['end', 'prefinish', 'error', 'new', 'demo', 'block', 'version'].indexOf(eventName) >= 0) {
|
||||
return;
|
||||
}
|
||||
//console.log(eventType, eventName);
|
||||
}
|
||||
|
||||
const _on = EventEmitter.prototype.on;
|
||||
const _setHandler = EventEmitter.prototype.setHandler;
|
||||
|
||||
EventEmitter.prototype.on = function(requestName, cb) {
|
||||
log("listening to event: ", requestName);
|
||||
warnIfLegacy(requestName);
|
||||
return _on.call(this, requestName, cb);
|
||||
};
|
||||
|
||||
EventEmitter.prototype.setHandler = function(requestName, cb) {
|
||||
log("setting handler for: ", requestName);
|
||||
warnIfLegacy(requestName);
|
||||
return _setHandler.call(this, requestName, cb);
|
||||
};
|
||||
|
||||
EventEmitter.prototype.request = function(requestName, cb) {
|
||||
this.emit('request:' + requestName, cb);
|
||||
log("requesting: ", requestName);
|
||||
warnIfLegacy(requestName);
|
||||
return this.emit('request:' + requestName, cb);
|
||||
};
|
||||
|
||||
EventEmitter.prototype.setCommandHandler = function(requestName, cb) {
|
||||
this.on('request:' + requestName, function(_cb) {
|
||||
log("setting command handler for: ", requestName);
|
||||
return this.on('request:' + requestName, function(_cb) {
|
||||
cb.call(this, _cb);
|
||||
});
|
||||
};
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
let Web3 = require('web3');
|
||||
let web3;
|
||||
let __mainContext;
|
||||
|
||||
// ======================
|
||||
// the eval is used for evaluating some of the contact calls for different purposes
|
||||
|
@ -10,7 +11,12 @@ function doEval(code, _web3) {
|
|||
if (_web3) {
|
||||
web3 = _web3;
|
||||
}
|
||||
return eval(code); // jshint ignore:line
|
||||
|
||||
try {
|
||||
return eval(code); // jshint ignore:line
|
||||
} catch(e) {
|
||||
throw new Error(e + "\n" + code);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
|
|
@ -5,14 +5,13 @@ var Embark = require('../index.js');
|
|||
|
||||
var Engine = require('./engine.js');
|
||||
|
||||
var ABIGenerator = require('../contracts/abi.js');
|
||||
var ContractsManager = require('../contracts/contracts.js');
|
||||
var Deploy = require('../contracts/deploy.js');
|
||||
|
||||
var Config = require('./config.js');
|
||||
var RunCode = require('./runCode.js');
|
||||
var TestLogger = require('./test_logger.js');
|
||||
var web3;
|
||||
var __mainContext;
|
||||
|
||||
var getSimulator = function() {
|
||||
try {
|
||||
|
@ -64,7 +63,7 @@ Test.prototype.deployAll = function(contractsConfig, cb) {
|
|||
},
|
||||
function startServices(callback) {
|
||||
//{abiType: 'contracts', embarkJS: false}
|
||||
self.engine.startService("abi");
|
||||
self.engine.startService("codeGenerator");
|
||||
self.engine.startService("deployment", {
|
||||
web3: self.web3,
|
||||
trackContracts: false
|
||||
|
@ -72,10 +71,25 @@ Test.prototype.deployAll = function(contractsConfig, cb) {
|
|||
callback();
|
||||
},
|
||||
function deploy(callback) {
|
||||
self.engine.events.setHandler('abi-contracts-vanila', function(vanillaABI) {
|
||||
callback(null, vanillaABI);
|
||||
//self.engine.events.setHandler('abi-contracts-vanila', function(vanillaABI) {
|
||||
//elf.engine.events.on('abi-contracts-vanila', function(vanillaABI) {
|
||||
self.engine.events.on('code-generator-ready', function () {
|
||||
self.engine.events.request('abi-contracts-vanila', function(vanillaABI) {
|
||||
console.log("got abi-contracts-vanila request");
|
||||
callback(null, vanillaABI);
|
||||
});
|
||||
//self.engine.events.on('abi-contracts-vanila', function(vanillaABI) {
|
||||
// console.log("got abi-contracts-vanila");
|
||||
// callback(null, vanillaABI);
|
||||
//});
|
||||
//self.engine.events.request('abi', function(vanillaABI) {
|
||||
// console.log("got abi");
|
||||
// callback(null, vanillaABI);
|
||||
//});
|
||||
});
|
||||
|
||||
self.engine.deployManager.deployContracts(function(err, result) {
|
||||
console.log("deployed contracts");
|
||||
if (err) {
|
||||
console.log(err);
|
||||
callback(err);
|
||||
|
|
|
@ -103,7 +103,7 @@ class Embark {
|
|||
engine.startMonitor();
|
||||
engine.startService("web3");
|
||||
engine.startService("pipeline");
|
||||
engine.startService("abi");
|
||||
engine.startService("codeGenerator");
|
||||
engine.startService("deployment");
|
||||
engine.startService("ipfs");
|
||||
|
||||
|
@ -158,7 +158,7 @@ class Embark {
|
|||
|
||||
engine.startService("web3");
|
||||
engine.startService("pipeline");
|
||||
engine.startService("abi");
|
||||
engine.startService("codeGenerator");
|
||||
engine.startService("deployment");
|
||||
callback();
|
||||
},
|
||||
|
|
|
@ -12,7 +12,8 @@ class Npm {
|
|||
this.logger = options.logger;
|
||||
}
|
||||
|
||||
getPackageVersion(packageName, version, returnContent, callback) {
|
||||
// TODO: callback should accept an error
|
||||
getPackageVersion(packageName, version, returnContent, getFromGit, callback) {
|
||||
let self = this;
|
||||
let npmRegistry = "https://registry.npmjs.org/" + packageName + "/" + version;
|
||||
|
||||
|
@ -25,6 +26,7 @@ class Npm {
|
|||
res.on('end', function () {
|
||||
let registryJSON = JSON.parse(body);
|
||||
|
||||
console.log(JSON.stringify(registryJSON));
|
||||
let tarball = registryJSON.dist.tarball;
|
||||
|
||||
var download = function(url, dest, cb) {
|
||||
|
@ -40,35 +42,76 @@ class Npm {
|
|||
});
|
||||
};
|
||||
|
||||
let packageDirectory = './.embark/versions/' + packageName + '/' + version + '/';
|
||||
if (getFromGit) {
|
||||
let repoName = registryJSON.repository.url.replace("git+https://github.com/", "").replace(".git","");
|
||||
let gitHead = registryJSON.gitHead;
|
||||
|
||||
if (fs.existsSync(packageDirectory + "/downloaded_package.tgz")) {
|
||||
if (returnContent) {
|
||||
let distFile = packageDirectory + returnContent;
|
||||
callback(fs.readFileSync(distFile).toString());
|
||||
} else {
|
||||
callback(packageDirectory);
|
||||
if (!gitHead) {
|
||||
console.error("Could not download " + packageName + " " + version);
|
||||
return callback("error");
|
||||
}
|
||||
|
||||
let fileLocation = "https://raw.githubusercontent.com/" + repoName + "/" + gitHead + "/dist/web3.min.js";
|
||||
|
||||
let packageDirectory = './.embark/versions/' + packageName + '/' + version + '/';
|
||||
if (fs.existsSync(packageDirectory + "/" + packageName + ".js")) {
|
||||
if (returnContent) {
|
||||
let distFile = packageDirectory + packageName + ".js";
|
||||
callback(fs.readFileSync(distFile).toString());
|
||||
} else {
|
||||
callback(packageDirectory);
|
||||
}
|
||||
} else {
|
||||
fs.mkdirpSync(packageDirectory);
|
||||
self.logger.info("downloading " + packageName + " " + version + "....");
|
||||
|
||||
download(fileLocation, packageDirectory + "/" + packageName + ".js", function() {
|
||||
o_fs.createReadStream(packageDirectory + "/" + packageName + ".js").pipe(
|
||||
tar.x({
|
||||
strip: 1,
|
||||
C: packageDirectory
|
||||
}).on('end', function() {
|
||||
if (returnContent) {
|
||||
let distFile = packageDirectory + packageName + ".js";
|
||||
callback(fs.readFileSync(distFile).toString());
|
||||
} else {
|
||||
callback(packageDirectory);
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
} else {
|
||||
fs.mkdirpSync(packageDirectory);
|
||||
self.logger.info("downloading " + packageName + " " + version + "....");
|
||||
|
||||
download(tarball, packageDirectory + "/downloaded_package.tgz", function() {
|
||||
o_fs.createReadStream(packageDirectory + '/downloaded_package.tgz').pipe(
|
||||
tar.x({
|
||||
strip: 1,
|
||||
C: packageDirectory
|
||||
}).on('end', function() {
|
||||
if (returnContent) {
|
||||
let distFile = packageDirectory + returnContent;
|
||||
callback(fs.readFileSync(distFile).toString());
|
||||
} else {
|
||||
callback(packageDirectory);
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
let packageDirectory = './.embark/versions/' + packageName + '/' + version + '/';
|
||||
if (fs.existsSync(packageDirectory + "/downloaded_package.tgz")) {
|
||||
if (returnContent) {
|
||||
let distFile = packageDirectory + returnContent;
|
||||
callback(fs.readFileSync(distFile).toString());
|
||||
} else {
|
||||
callback(packageDirectory);
|
||||
}
|
||||
} else {
|
||||
fs.mkdirpSync(packageDirectory);
|
||||
self.logger.info("downloading " + packageName + " " + version + "....");
|
||||
|
||||
download(tarball, packageDirectory + "/downloaded_package.tgz", function() {
|
||||
o_fs.createReadStream(packageDirectory + '/downloaded_package.tgz').pipe(
|
||||
tar.x({
|
||||
strip: 1,
|
||||
C: packageDirectory
|
||||
}).on('end', function() {
|
||||
if (returnContent) {
|
||||
let distFile = packageDirectory + returnContent;
|
||||
callback(fs.readFileSync(distFile).toString());
|
||||
} else {
|
||||
callback(packageDirectory);
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
|
|
@ -22,6 +22,7 @@
|
|||
"chokidar": "^1.6.0",
|
||||
"colors": "^1.1.2",
|
||||
"commander": "^2.8.1",
|
||||
"ejs": "^2.5.7",
|
||||
"ethereumjs-testrpc": "3.9.2",
|
||||
"finalhandler": "^0.5.0",
|
||||
"follow-redirects": "^1.2.4",
|
||||
|
|
59
test/abi.js
59
test/abi.js
|
@ -1,59 +0,0 @@
|
|||
/*globals describe, it*/
|
||||
let ABIGenerator = require('../lib/contracts/abi.js');
|
||||
let assert = require('assert');
|
||||
|
||||
// TODO: instead 'eval' the code with a fake web3 object
|
||||
// and check the generate code interacts as expected
|
||||
describe('embark.ABIGenerator', function() {
|
||||
this.timeout(0);
|
||||
describe('#generateProvider', function() {
|
||||
let generator = new ABIGenerator({contractsConfig: {"dappConnection": [ "$WEB3", "http://somehost:1234" ] }, contractsManager: {}});
|
||||
|
||||
it('should generate code to connect to a provider', function() {
|
||||
var providerCode = "\nvar whenEnvIsLoaded = function(cb) {\n if (typeof document !== 'undefined' && document !== null) {\n document.addEventListener('DOMContentLoaded', cb);\n } else {\n cb();\n }\n}\nwhenEnvIsLoaded(function() {\nif (typeof web3 !== 'undefined' && typeof Web3 !== 'undefined') {\n\tweb3 = new Web3(web3.currentProvider);\n} if (typeof Web3 !== 'undefined' && ((typeof web3 === 'undefined') || (typeof web3 !== 'undefined' && !web3.isConnected()))) {\n\tweb3 = new Web3(new Web3.providers.HttpProvider(\"http://somehost:1234\"));\n}\nweb3.eth.defaultAccount = web3.eth.accounts[0];\n})";
|
||||
|
||||
assert.equal(generator.generateProvider(), providerCode);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#generateContracts', function() {
|
||||
let generator = new ABIGenerator({blockchainConfig: {}, contractsManager: {
|
||||
contracts: {
|
||||
SimpleStorage: {
|
||||
abiDefinition: [{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"type":"constructor"}],
|
||||
gasEstimates: 12000,
|
||||
deployedAddress: "0x123",
|
||||
code: '12345'
|
||||
},
|
||||
Foo: {
|
||||
abiDefinition: [{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"type":"constructor"}],
|
||||
gasEstimates: 12000,
|
||||
deployedAddress: "0x124",
|
||||
code: '123456'
|
||||
}
|
||||
}
|
||||
}});
|
||||
|
||||
describe('with EmbarkJS', function() {
|
||||
let withEmbarkJS = true;
|
||||
|
||||
it('should generate contract code', function() {
|
||||
var contractCode = "\n\nif (whenEnvIsLoaded === undefined) {\n var whenEnvIsLoaded = function(cb) {\n if (typeof document !== 'undefined' && document !== null) {\n document.addEventListener('DOMContentLoaded', cb);\n } else {\n cb();\n }\n }\n}\nwhenEnvIsLoaded(function() {\nSimpleStorage = new EmbarkJS.Contract({abi: [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}], address: '0x123', code: '12345', gasEstimates: 12000});\n});\nif (whenEnvIsLoaded === undefined) {\n var whenEnvIsLoaded = function(cb) {\n if (typeof document !== 'undefined' && document !== null) {\n document.addEventListener('DOMContentLoaded', cb);\n } else {\n cb();\n }\n }\n}\nwhenEnvIsLoaded(function() {\nFoo = new EmbarkJS.Contract({abi: [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}], address: '0x124', code: '123456', gasEstimates: 12000});\n});";
|
||||
assert.equal(generator.generateContracts(withEmbarkJS), contractCode);
|
||||
});
|
||||
});
|
||||
|
||||
describe('with default interface', function() {
|
||||
let withEmbarkJS = false;
|
||||
|
||||
it('should generate contract code', function() {
|
||||
var contractCode = "\n\nif (whenEnvIsLoaded === undefined) {\n var whenEnvIsLoaded = function(cb) {\n if (typeof document !== 'undefined' && document !== null) {\n document.addEventListener('DOMContentLoaded', cb);\n } else {\n cb();\n }\n }\n}\nwhenEnvIsLoaded(function() {\nSimpleStorageAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nSimpleStorageContract = web3.eth.contract(SimpleStorageAbi);\nSimpleStorage = SimpleStorageContract.at('0x123');\n});\nif (whenEnvIsLoaded === undefined) {\n var whenEnvIsLoaded = function(cb) {\n if (typeof document !== 'undefined' && document !== null) {\n document.addEventListener('DOMContentLoaded', cb);\n } else {\n cb();\n }\n }\n}\nwhenEnvIsLoaded(function() {\nFooAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nFooContract = web3.eth.contract(FooAbi);\nFoo = FooContract.at('0x124');\n});";
|
||||
assert.equal(generator.generateContracts(withEmbarkJS), contractCode);
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
//describe('#generateABI', function() {
|
||||
//});
|
||||
});
|
|
@ -0,0 +1,59 @@
|
|||
/*globals describe, it*/
|
||||
let CodeGenerator = require('../lib/contracts/code_generator.js');
|
||||
let assert = require('assert');
|
||||
|
||||
// TODO: instead 'eval' the code with a fake web3 object
|
||||
// and check the generate code interacts as expected
|
||||
describe('embark.CodeGenerator', function() {
|
||||
this.timeout(0);
|
||||
describe('#generateProvider', function() {
|
||||
let generator = new CodeGenerator({contractsConfig: {"dappConnection": [ "$WEB3", "http://somehost:1234" ] }, contractsManager: {}});
|
||||
|
||||
it('should generate code to connect to a provider', function() {
|
||||
var providerCode = "function __reduce(arr, memo, iteratee, cb) {\n if (typeof cb !== 'function') {\n if (typeof memo === 'function' && typeof iteratee === 'function') {\n cb = iteratee;\n iteratee = memo;\n memo = [];\n } else {\n throw new TypeError('expected callback to be a function');\n }\n }\n\n if (!Array.isArray(arr)) {\n cb(new TypeError('expected an array'));\n return;\n }\n\n if (typeof iteratee !== 'function') {\n cb(new TypeError('expected iteratee to be a function'));\n return;\n }\n\n (function next(i, acc) {\n if (i === arr.length) {\n cb(null, acc);\n return;\n }\n\n iteratee(acc, arr[i], function(err, val) {\n if (err) {\n cb(err);\n return;\n }\n next(i + 1, val);\n });\n })(0, memo);\n};\nvar __mainContext = __mainContext || this;\n__mainContext.__LoadManager = function() { this.list = []; this.done = false; }\n__mainContext.__LoadManager.prototype.execWhenReady = function(cb) { if (this.done) { cb(); } else { this.list.push(cb) } }\n__mainContext.__LoadManager.prototype.doFirst = function(todo) { var self = this; todo(function() { self.done = true; self.list.map((x) => x.apply()) }) }\n__mainContext.__loadManagerInstance = new __mainContext.__LoadManager();\nvar whenEnvIsLoaded = function(cb) {\n if (typeof document !== 'undefined' && document !== null) {\n document.addEventListener('DOMContentLoaded', cb);\n } else {\n cb();\n }\n}\nwhenEnvIsLoaded(function(){\n __mainContext.__loadManagerInstance.doFirst(function(done) {\n __mainContext.web3 = undefined;\n__reduce([\"$WEB3\",\"http://somehost:1234\"],function(prev, value, next) {\n if (prev === false) {\n return next(null, false);\n }\n\n if (value === '$WEB3' && (typeof web3 !== 'undefined' && typeof Web3 !== 'undefined')) {\n web3 = new Web3(web3.currentProvider);\n } else if (value !== '$WEB3' && (typeof Web3 !== 'undefined' && ((typeof web3 === 'undefined') || (typeof web3 !== 'undefined' && (!web3.isConnected || (web3.isConnected && !web3.isConnected())))))) {\n\n web3 = new Web3(new Web3.providers.HttpProvider(value));\n } else if (value === '$WEB3') {\n return next(null, '');\n }\n\n web3.eth.getAccounts(function(err, account) {\n if (err) {\n next(null, true)\n } else {\n next(null, false)\n }\n });\n}, function(err, _result) {\n web3.eth.getAccounts(function(err, accounts) {\n web3.eth.defaultAccount = accounts[0];\n done();\n });\n});\n\n })\n});\n\n";
|
||||
|
||||
assert.equal(generator.generateProvider(), providerCode);
|
||||
});
|
||||
});
|
||||
|
||||
describe('#generateContracts', function() {
|
||||
let generator = new CodeGenerator({blockchainConfig: {}, contractsManager: {
|
||||
contracts: {
|
||||
SimpleStorage: {
|
||||
abiDefinition: [{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"type":"constructor"}],
|
||||
gasEstimates: 12000,
|
||||
deployedAddress: "0x123",
|
||||
code: '12345'
|
||||
},
|
||||
Foo: {
|
||||
abiDefinition: [{"constant":true,"inputs":[],"name":"storedData","outputs":[{"name":"","type":"uint256"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name":"x","type":"uint256"}],"name":"set","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"get","outputs":[{"name":"retVal","type":"uint256"}],"payable":false,"type":"function"},{"inputs":[{"name":"initialValue","type":"uint256"}],"type":"constructor"}],
|
||||
gasEstimates: 12000,
|
||||
deployedAddress: "0x124",
|
||||
code: '123456'
|
||||
}
|
||||
}
|
||||
}});
|
||||
|
||||
describe('with EmbarkJS', function() {
|
||||
let withEmbarkJS = true;
|
||||
|
||||
it('should generate contract code', function() {
|
||||
var contractCode = "\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n __mainContext.SimpleStorage = new EmbarkJS.Contract({abi: [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}], address: '0x123', code: '12345', gasEstimates: 12000});\n\n});\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n __mainContext.Foo = new EmbarkJS.Contract({abi: [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}], address: '0x124', code: '123456', gasEstimates: 12000});\n\n});\n";
|
||||
assert.equal(generator.generateContracts(withEmbarkJS), contractCode);
|
||||
});
|
||||
});
|
||||
|
||||
describe('with default interface', function() {
|
||||
let withEmbarkJS = false;
|
||||
|
||||
it('should generate contract code', function() {
|
||||
var contractCode = "\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n SimpleStorageAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nSimpleStorageContract = web3.eth.contract(SimpleStorageAbi);\nSimpleStorage = SimpleStorageContract.at('0x123');\n\n});\n__mainContext.__loadManagerInstance.execWhenReady(function() {\n FooAbi = [{\"constant\":true,\"inputs\":[],\"name\":\"storedData\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"x\",\"type\":\"uint256\"}],\"name\":\"set\",\"outputs\":[],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"get\",\"outputs\":[{\"name\":\"retVal\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"initialValue\",\"type\":\"uint256\"}],\"type\":\"constructor\"}];\nFooContract = web3.eth.contract(FooAbi);\nFoo = FooContract.at('0x124');\n\n});\n";
|
||||
assert.equal(generator.generateContracts(withEmbarkJS), contractCode);
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
//describe('#generateABI', function() {
|
||||
//});
|
||||
});
|
|
@ -11,15 +11,31 @@ $(document).ready(function() {
|
|||
|
||||
$("#blockchain button.set").click(function() {
|
||||
var value = parseInt($("#blockchain input.text").val(), 10);
|
||||
SimpleStorage.set(value);
|
||||
addToLog("#blockchain", "SimpleStorage.set(" + value + ")");
|
||||
|
||||
// If web3.js 1.0 is being used
|
||||
if (EmbarkJS.isNewWeb3()) {
|
||||
SimpleStorage.methods.set(value).send({from: web3.eth.defaultAccount});
|
||||
addToLog("#blockchain", "SimpleStorage.methods.set(value).send({from: web3.eth.defaultAccount})");
|
||||
} else {
|
||||
SimpleStorage.set(value);
|
||||
addToLog("#blockchain", "SimpleStorage.set(" + value + ")");
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
$("#blockchain button.get").click(function() {
|
||||
SimpleStorage.get().then(function(value) {
|
||||
$("#blockchain .value").html(value.toNumber());
|
||||
});
|
||||
addToLog("#blockchain", "SimpleStorage.get()");
|
||||
// If web3.js 1.0 is being used
|
||||
if (EmbarkJS.isNewWeb3()) {
|
||||
SimpleStorage.methods.get().call(function(err, value) {
|
||||
$("#blockchain .value").html(value);
|
||||
});
|
||||
addToLog("#blockchain", "SimpleStorage.methods.get(console.log)");
|
||||
} else {
|
||||
SimpleStorage.get().then(function(value) {
|
||||
$("#blockchain .value").html(value.toNumber());
|
||||
});
|
||||
addToLog("#blockchain", "SimpleStorage.get()");
|
||||
}
|
||||
});
|
||||
|
||||
});
|
||||
|
@ -115,20 +131,18 @@ $(document).ready(function() {
|
|||
|
||||
$("#communication .error").hide();
|
||||
$("#communication .errorVersion").hide();
|
||||
web3.version.getWhisper(function(err, version) {
|
||||
if (err) {
|
||||
$("#communication .error").show();
|
||||
$("#communication-controls").hide();
|
||||
$("#status-communication").addClass('status-offline');
|
||||
} else if (version >= 5) {
|
||||
$("#communication .errorVersion").show();
|
||||
$("#communication-controls").hide();
|
||||
$("#status-communication").addClass('status-offline');
|
||||
} else {
|
||||
EmbarkJS.Messages.setProvider('whisper');
|
||||
$("#status-communication").addClass('status-online');
|
||||
}
|
||||
});
|
||||
if (EmbarkJS.Messages.providerName === 'whisper') {
|
||||
EmbarkJS.Messages.getWhisperVersion(function(err, version) {
|
||||
if (err) {
|
||||
$("#communication .error").show();
|
||||
$("#communication-controls").hide();
|
||||
$("#status-communication").addClass('status-offline');
|
||||
} else {
|
||||
EmbarkJS.Messages.setProvider('whisper');
|
||||
$("#status-communication").addClass('status-online');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
$("#communication button.listenToChannel").click(function() {
|
||||
var channel = $("#communication .listen input.channel").val();
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"default": {
|
||||
"versions": {
|
||||
"web3.js": "1.0.0",
|
||||
"web3.js": "1.0.0-beta",
|
||||
"solc": "0.4.11"
|
||||
},
|
||||
"deployment": {
|
||||
|
@ -42,7 +42,7 @@
|
|||
"args": [200]
|
||||
},
|
||||
"AlreadyDeployedToken": {
|
||||
"address": "0x123",
|
||||
"address": "0xece374063fe5cc7efbaca0a498477cada94e5ad6",
|
||||
"instanceOf": "Token"
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue