Skip to content

Instantly share code, notes, and snippets.

@DeviateFish
Created August 21, 2017 02:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save DeviateFish/46f6170fdd03e2306243ec0f45cb6227 to your computer and use it in GitHub Desktop.
Save DeviateFish/46f6170fdd03e2306243ec0f45cb6227 to your computer and use it in GitHub Desktop.
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var BlockDaemon = function() {
this._blockFilter = null;
this.started = false;
EventEmitter.call(this);
};
util.inherits(BlockDaemon, EventEmitter);
BlockDaemon.prototype.start = function() {
if (!this.web3) {
throw new Error('Must call `setWeb3` before starting for the first time');
}
if (!this.web3.isConnected()) {
throw new Error('Web3 is not connected');
}
this._blockFilter = this.web3.eth.filter('latest', this.emit.bind(this, 'block'));
this.started = true;
};
BlockDaemon.prototype.stop = function() {
if (this._blockFilter) {
this._blockFilter.stopWatching();
this.started = false;
}
};
BlockDaemon.prototype.setWeb3 = function(web3) {
var started = this.started;
this.stop();
this.web3 = web3;
if (started) {
this.start();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment