Merge pull request #8 from debris/autoprovider

Autoprovider
pull/272/merge
Marian OANCΞA 10 years ago
commit d85cef557b
  1. 12
      dist/ethereum.js
  2. 8
      dist/ethereum.js.map
  3. 2
      dist/ethereum.min.js
  4. 5
      example/index.html
  5. 31
      gulpfile.js
  6. 1
      index.js
  7. 103
      lib/autoprovider.js
  8. 31
      lib/httprpc.js
  9. 130
      lib/main.js
  10. 13
      lib/qt.js
  11. 24
      lib/websocket.js

12
dist/ethereum.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -3,7 +3,7 @@
<head>
<script type="text/javascript" src="js/es6-promise/promise.min.js"></script>
<script type="text/javascript" src="../dist/ethereum.min.js"></script>
<script type="text/javascript" src="../dist/ethereum.js"></script>
<script type="text/javascript">
if (window.Promise === undefined) {
@ -13,8 +13,9 @@ if (window.Promise === undefined) {
var web3 = require('web3');
//web3.setProvider(new web3.providers.QtProvider());
web3.setProvider(new web3.providers.HttpRpcProvider("http://localhost:8080"));
//web3.setProvider(new web3.providers.HttpRpcProvider("http://localhost:8080"));
// web3.setProvider(new web3.providers.WebSocketProvider("ws://localhost:40404/eth"));
web3.setProvider(new web3.providers.AutoProvider());
function testSnippet() {
web3.eth.watch({altered: web3.eth.coinbase}).changed(function() {

@ -25,8 +25,8 @@ var build = function(src, dst) {
detectGlobals: false,
bundleExternal: false
})
.add('./')
.require('./' + src + '.js', {expose: 'web3'})
.add('./' + src + '.js')
.transform('envify', {
NODE_ENV: 'build'
})
@ -50,6 +50,25 @@ var build = function(src, dst) {
.pipe(gulp.dest( DEST ));
};
var buildDev = function(src, dst) {
return browserify({
debug: true,
insert_global_vars: false,
detectGlobals: false,
bundleExternal: false
})
.require('./' + src + '.js', {expose: 'web3'})
.add('./' + src + '.js')
.transform('envify', {
NODE_ENV: 'build'
})
.transform('unreachable-branch-transform')
.bundle()
.pipe(exorcist(path.join( DEST, dst + '.js.map')))
.pipe(source(dst + '.js'))
.pipe(gulp.dest( DEST ));
};
var uglifyFile = function(file) {
return gulp.src( DEST + file + '.js')
.pipe(uglify())
@ -79,7 +98,11 @@ gulp.task('build', ['clean'], function () {
});
gulp.task('buildQt', ['clean'], function () {
return build('index_qt', 'ethereum_qt');
return build('index_qt', 'ethereum');
});
gulp.task('buildDev', ['clean'], function () {
return buildDev('index', 'ethereum');
});
gulp.task('uglify', ['build'], function(){
@ -87,7 +110,7 @@ gulp.task('uglify', ['build'], function(){
});
gulp.task('uglifyQt', ['buildQt'], function () {
return uglifyFile('ethereum_qt');
return uglifyFile('ethereum');
});
gulp.task('watch', function() {
@ -96,3 +119,5 @@ gulp.task('watch', function() {
gulp.task('default', ['bower', 'lint', 'build', 'uglify']);
gulp.task('qt', ['bower', 'lint', 'buildQt', 'uglifyQt']);
gulp.task('dev', ['bower', 'lint', 'buildDev']);

@ -2,5 +2,6 @@ var web3 = require('./lib/main');
web3.providers.WebSocketProvider = require('./lib/websocket');
web3.providers.HttpRpcProvider = require('./lib/httprpc');
web3.providers.QtProvider = require('./lib/qt');
web3.providers.AutoProvider = require('./lib/autoprovider');
module.exports = web3;

@ -0,0 +1,103 @@
/*
This file is part of ethereum.js.
ethereum.js is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
ethereum.js is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with ethereum.js. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file websocket.js
* @authors:
* Marek Kotewicz <marek@ethdev.com>
* Marian Oancea <marian@ethdev.com>
* @date 2014
*/
/*
* @brief if qt object is available, uses QtProvider,
* if not tries to connect over websockets
* if it fails, it uses HttpRpcProvider
*/
if (process.env.NODE_ENV !== 'build') {
var WebSocket = require('ws'); // jshint ignore:line
}
if (process.env.NODE_ENV !== 'build') {
var web3 = require('./web3'); // jshint ignore:line
}
var AutoProvider = function (userOptions) {
if (web3.haveProvider()) {
return;
}
// before we determine what provider we are, we have to cache request
this.sendQueue = [];
this.onmessageQueue = [];
if (navigator.qt) {
this.provider = new web3.providers.QtProvider();
return;
}
userOptions = userOptions || {};
var options = {
httprpc: userOptions.httprpc || 'http://localhost:8080',
websockets: userOptions.websockets || 'ws://localhost:40404/eth'
};
var self = this;
var closeWithSuccess = function (success) {
ws.close();
if (success) {
self.provider = new web3.providers.WebSocketProvider(options.websockets);
return;
}
self.provider = new web3.providers.HttpRpcProvider(options.httprpc);
self.poll = self.provider.poll.bind(self.provider);
self.sendQueue.forEach(function (payload) {
self.provider(payload);
});
self.onmessageQueue.forEach(function (handler) {
self.provider.onmessage = handler;
});
};
var ws = new WebSocket(options.websockets);
ws.onopen = function() {
closeWithSuccess(true);
};
ws.onerror = function() {
closeWithSuccess(false);
};
};
AutoProvider.prototype.send = function (payload) {
if (this.provider) {
this.provider.send(payload);
return;
}
this.sendQueue.push(payload);
};
Object.defineProperty(AutoProvider.prototype, 'onmessage', {
set: function (handler) {
if (this.provider) {
this.provider.onmessage = handler;
return;
}
this.onmessageQueue.push(handler);
}
});
module.exports = AutoProvider;

@ -21,26 +21,25 @@
* @date 2014
*/
if(process.env.NODE_ENV !== "build") {
if (process.env.NODE_ENV !== "build") {
var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; // jshint ignore:line
}
var HttpRpcProvider = function (host) {
var HttpRpcProvider = function (host) {
this.handlers = [];
this.host = host;
};
};
function formatJsonRpcObject(object) {
function formatJsonRpcObject(object) {
return {
jsonrpc: '2.0',
method: object.call,
params: object.args,
id: object._id
};
}
}
function formatJsonRpcMessage(message) {
function formatJsonRpcMessage(message) {
var object = JSON.parse(message);
return {
@ -48,9 +47,9 @@ if(process.env.NODE_ENV !== "build") {
data: object.result,
error: object.error
};
}
}
HttpRpcProvider.prototype.sendRequest = function (payload, cb) {
HttpRpcProvider.prototype.sendRequest = function (payload, cb) {
var data = formatJsonRpcObject(payload);
var request = new XMLHttpRequest();
@ -61,18 +60,18 @@ if(process.env.NODE_ENV !== "build") {
cb(request);
}
};
};
};
HttpRpcProvider.prototype.send = function (payload) {
HttpRpcProvider.prototype.send = function (payload) {
var self = this;
this.sendRequest(payload, function (request) {
self.handlers.forEach(function (handler) {
handler.call(self, formatJsonRpcMessage(request.responseText));
});
});
};
};
HttpRpcProvider.prototype.poll = function (payload, id) {
HttpRpcProvider.prototype.poll = function (payload, id) {
var self = this;
this.sendRequest(payload, function (request) {
var parsed = JSON.parse(request.responseText);
@ -83,12 +82,12 @@ if(process.env.NODE_ENV !== "build") {
handler.call(self, {_event: payload.call, _id: id, data: parsed.result});
});
});
};
};
Object.defineProperty(HttpRpcProvider.prototype, "onmessage", {
Object.defineProperty(HttpRpcProvider.prototype, "onmessage", {
set: function (handler) {
this.handlers.push(handler);
}
});
});
module.exports = HttpRpcProvider;

@ -22,7 +22,7 @@
* @date 2014
*/
function flattenPromise (obj) {
function flattenPromise (obj) {
if (obj instanceof Promise) {
return Promise.resolve(obj);
}
@ -59,9 +59,9 @@
}
return Promise.resolve(obj);
}
}
var ethMethods = function () {
var ethMethods = function () {
var blockCall = function (args) {
return typeof args[0] === "string" ? "eth_blockByHash" : "eth_blockByNumber";
};
@ -88,9 +88,9 @@
{ name: 'lll', call: 'eth_lll' }
];
return methods;
};
};
var ethProperties = function () {
var ethProperties = function () {
return [
{ name: 'coinbase', getter: 'eth_coinbase', setter: 'eth_setCoinbase' },
{ name: 'listening', getter: 'eth_listening', setter: 'eth_setListening' },
@ -102,18 +102,18 @@
{ name: 'defaultBlock', getter: 'eth_defaultBlock', setter: 'eth_setDefaultBlock' },
{ name: 'number', getter: 'eth_number'}
];
};
};
var dbMethods = function () {
var dbMethods = function () {
return [
{ name: 'put', call: 'db_put' },
{ name: 'get', call: 'db_get' },
{ name: 'putString', call: 'db_putString' },
{ name: 'getString', call: 'db_getString' }
];
};
};
var shhMethods = function () {
var shhMethods = function () {
return [
{ name: 'post', call: 'shh_post' },
{ name: 'newIdentity', call: 'shh_newIdentity' },
@ -121,9 +121,9 @@
{ name: 'newGroup', call: 'shh_newGroup' },
{ name: 'addToGroup', call: 'shh_addToGroup' }
];
};
};
var ethWatchMethods = function () {
var ethWatchMethods = function () {
var newFilter = function (args) {
return typeof args[0] === 'string' ? 'eth_newFilterString' : 'eth_newFilter';
};
@ -133,17 +133,17 @@
{ name: 'uninstallFilter', call: 'eth_uninstallFilter' },
{ name: 'getMessages', call: 'eth_getMessages' }
];
};
};
var shhWatchMethods = function () {
var shhWatchMethods = function () {
return [
{ name: 'newFilter', call: 'shh_newFilter' },
{ name: 'uninstallFilter', call: 'shh_uninstallFilter' },
{ name: 'getMessage', call: 'shh_getMessages' }
];
};
};
var setupMethods = function (obj, methods) {
var setupMethods = function (obj, methods) {
methods.forEach(function (method) {
obj[method.name] = function () {
return flattenPromise(Array.prototype.slice.call(arguments)).then(function (args) {
@ -164,9 +164,9 @@
});
};
});
};
};
var setupProperties = function (obj, properties) {
var setupProperties = function (obj, properties) {
properties.forEach(function (property) {
var proto = {};
proto.get = function () {
@ -199,9 +199,9 @@
}
Object.defineProperty(obj, property.name, proto);
});
};
};
var web3 = {
var web3 = {
_callbacks: {},
_events: {},
providers: {},
@ -288,24 +288,24 @@
var cb = callbacks[id];
cb(data);
}
};
};
var eth = web3.eth;
setupMethods(eth, ethMethods());
setupProperties(eth, ethProperties());
setupMethods(web3.db, dbMethods());
setupMethods(web3.shh, shhMethods());
var eth = web3.eth;
setupMethods(eth, ethMethods());
setupProperties(eth, ethProperties());
setupMethods(web3.db, dbMethods());
setupMethods(web3.shh, shhMethods());
var ethWatch = {
var ethWatch = {
changed: 'eth_changed'
};
setupMethods(ethWatch, ethWatchMethods());
var shhWatch = {
};
setupMethods(ethWatch, ethWatchMethods());
var shhWatch = {
changed: 'shh_changed'
};
setupMethods(shhWatch, shhWatchMethods());
};
setupMethods(shhWatch, shhWatchMethods());
var ProviderManager = function() {
var ProviderManager = function() {
this.queued = [];
this.polls = [];
this.ready = false;
@ -324,9 +324,9 @@
setTimeout(poll, 12000);
};
poll();
};
};
ProviderManager.prototype.send = function(data, cb) {
ProviderManager.prototype.send = function(data, cb) {
data._id = this.id;
if (cb) {
web3._callbacks[data._id] = cb;
@ -341,53 +341,57 @@
console.warn("provider is not set");
this.queued.push(data);
}
};
};
ProviderManager.prototype.set = function(provider) {
ProviderManager.prototype.set = function(provider) {
if(this.provider !== undefined && this.provider.unload !== undefined) {
this.provider.unload();
}
this.provider = provider;
this.ready = true;
};
};
ProviderManager.prototype.sendQueued = function() {
ProviderManager.prototype.sendQueued = function() {
for(var i = 0; this.queued.length; i++) {
// Resend
this.send(this.queued[i]);
}
};
};
ProviderManager.prototype.installed = function() {
ProviderManager.prototype.installed = function() {
return this.provider !== undefined;
};
};
ProviderManager.prototype.startPolling = function (data, pollId) {
ProviderManager.prototype.startPolling = function (data, pollId) {
if (!this.provider || !this.provider.poll) {
return;
}
this.polls.push({data: data, id: pollId});
};
};
ProviderManager.prototype.stopPolling = function (pollId) {
ProviderManager.prototype.stopPolling = function (pollId) {
for (var i = this.polls.length; i--;) {
var poll = this.polls[i];
if (poll.id === pollId) {
this.polls.splice(i, 1);
}
}
};
};
web3.provider = new ProviderManager();
web3.provider = new ProviderManager();
web3.setProvider = function(provider) {
web3.setProvider = function(provider) {
provider.onmessage = messageHandler;
web3.provider.set(provider);
web3.provider.sendQueued();
};
};
web3.haveProvider = function() {
return !!web3.provider.provider;
};
var Filter = function(options, impl) {
var Filter = function(options, impl) {
this.impl = impl;
this.callbacks = [];
@ -398,42 +402,42 @@
web3.on(impl.changed, id, self.trigger.bind(self));
web3.provider.startPolling({call: impl.changed, args: [id]}, id);
});
};
};
Filter.prototype.arrived = function(callback) {
Filter.prototype.arrived = function(callback) {
this.changed(callback);
};
};
Filter.prototype.changed = function(callback) {
Filter.prototype.changed = function(callback) {
var self = this;
this.promise.then(function(id) {
self.callbacks.push(callback);
});
};
};
Filter.prototype.trigger = function(messages) {
Filter.prototype.trigger = function(messages) {
for(var i = 0; i < this.callbacks.length; i++) {
this.callbacks[i].call(this, messages);
}
};
};
Filter.prototype.uninstall = function() {
Filter.prototype.uninstall = function() {
var self = this;
this.promise.then(function (id) {
self.impl.uninstallFilter(id);
web3.provider.stopPolling(id);
web3.off(impl.changed, id);
});
};
};
Filter.prototype.messages = function() {
Filter.prototype.messages = function() {
var self = this;
return this.promise.then(function (id) {
return self.impl.getMessages(id);
});
};
};
function messageHandler(data) {
function messageHandler(data) {
if(data._event !== undefined) {
web3.trigger(data._event, data._id, data.data);
return;
@ -446,7 +450,7 @@
delete web3._callbacks[data._id];
}
}
}
}
module.exports = web3;
module.exports = web3;

@ -16,11 +16,12 @@
*/
/** @file qt.js
* @authors:
* Jeffrey Wilcke <jeff@ethdev.com>
* Marek Kotewicz <marek@ethdev.com>
* @date 2014
*/
var QtProvider = function() {
var QtProvider = function() {
this.handlers = [];
var self = this;
@ -29,16 +30,16 @@
handler.call(self, JSON.parse(message.data));
});
};
};
};
QtProvider.prototype.send = function(payload) {
QtProvider.prototype.send = function(payload) {
navigator.qt.postMessage(JSON.stringify(payload));
};
};
Object.defineProperty(QtProvider.prototype, "onmessage", {
Object.defineProperty(QtProvider.prototype, "onmessage", {
set: function(handler) {
this.handlers.push(handler);
}
});
});
module.exports = QtProvider;

@ -16,16 +16,17 @@
*/
/** @file websocket.js
* @authors:
* Jeffrey Wilcke <jeff@ethdev.com>
* Marek Kotewicz <marek@ethdev.com>
* Marian Oancea <marian@ethdev.com>
* @date 2014
*/
if(process.env.NODE_ENV !== "build") {
if (process.env.NODE_ENV !== "build") {
var WebSocket = require('ws'); // jshint ignore:line
}
var WebSocketProvider = function(host) {
var WebSocketProvider = function(host) {
// onmessage handlers
this.handlers = [];
// queue will be filled with messages if send is invoked before the ws is ready
@ -49,8 +50,9 @@ if(process.env.NODE_ENV !== "build") {
self.send(self.queued[i]);
}
};
};
WebSocketProvider.prototype.send = function(payload) {
};
WebSocketProvider.prototype.send = function(payload) {
if(this.ready) {
var data = JSON.stringify(payload);
@ -58,17 +60,17 @@ if(process.env.NODE_ENV !== "build") {
} else {
this.queued.push(payload);
}
};
};
WebSocketProvider.prototype.onMessage = function(handler) {
WebSocketProvider.prototype.onMessage = function(handler) {
this.handlers.push(handler);
};
};
WebSocketProvider.prototype.unload = function() {
WebSocketProvider.prototype.unload = function() {
this.ws.close();
};
Object.defineProperty(WebSocketProvider.prototype, "onmessage", {
};
Object.defineProperty(WebSocketProvider.prototype, "onmessage", {
set: function(provider) { this.onMessage(provider); }
});
});
module.exports = WebSocketProvider;

Loading…
Cancel
Save