-
-
Save DeviateFish/46f6170fdd03e2306243ec0f45cb6227 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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