From 5fca3802c41cfd25a4a2d5246ad8f68dbbd16375 Mon Sep 17 00:00:00 2001 From: Iuri Matias Date: Wed, 2 Oct 2019 17:58:42 -0400 Subject: [PATCH] cleanup --- examples/react-example1/src/App.js | 1 - src/database.js | 9 +++------ src/eventSyncer.js | 22 +++++++++++----------- src/logSyncer.js | 25 ++++++++++++------------- src/poc.js | 30 ------------------------------ src/react/index.js | 10 +++++----- src/simulator.js | 27 --------------------------- src/subspace.js | 13 +++++-------- src/utils.js | 1 - 9 files changed, 36 insertions(+), 102 deletions(-) delete mode 100644 src/poc.js delete mode 100644 src/simulator.js diff --git a/examples/react-example1/src/App.js b/examples/react-example1/src/App.js index 741976f..28f3fce 100644 --- a/examples/react-example1/src/App.js +++ b/examples/react-example1/src/App.js @@ -22,7 +22,6 @@ class App extends React.Component { await subspace.init(); Product = await ProductContract.getInstance(); - console.dir(Product.options) const rating$ = subspace.trackEvent(Product, "Rating").pipe(map(x => parseInt(x.rating))); window.Product = Product; diff --git a/src/database.js b/src/database.js index 96dfa6e..6920afa 100644 --- a/src/database.js +++ b/src/database.js @@ -21,12 +21,10 @@ const getENV = function () { } return 'BROWSER'; } - + return 'CORDOVA'; }; - - class Database { constructor(dbFilename, events, cb) { @@ -56,20 +54,19 @@ class Database { let firstKnownBlock = 0; let lastKnownBlock = 0; - if(collection && collection.count()){ + if (collection && collection.count()){ firstKnownBlock = collection.min('blockNumber'); lastKnownBlock = collection.max('blockNumber'); } else { this.db.addCollection(eventKey); } - + return { firstKnownBlock: firstKnownBlock || 0, lastKnownBlock: lastKnownBlock || 0 }; } - getEventsFor(eventKey) { let children = this.db.getCollection(eventKey); return children.find(); diff --git a/src/eventSyncer.js b/src/eventSyncer.js index e78c1f5..104259e 100644 --- a/src/eventSyncer.js +++ b/src/eventSyncer.js @@ -2,15 +2,15 @@ import { fromEvent, ReplaySubject } from 'rxjs'; import hash from 'object-hash'; class EventSyncer { + constructor(web3, events, db) { this.events = events; this.web3 = web3; this.db = db; - this.subscriptions = []; } - track(contractInstance, eventName, filterConditionsOrCb, gteBlockNum){ + track(contractInstance, eventName, filterConditionsOrCb, gteBlockNum) { const isFilterFunction = typeof filterConditionsOrCb === 'function'; const eventKey = hash(Object.assign({address: contractInstance.options.address}, (isFilterFunction ? {filterConditionsOrCb} : (filterConditionsOrCb || {})))); @@ -30,10 +30,10 @@ class EventSyncer { let contractObserver = fromEvent(this.events, eventKey) contractObserver.subscribe((e) => { - if(!e) return; + if (!e) return; const id = hash({eventName, blockNumber: e.blockNumber, transactionIndex: e.transactionIndex, logIndex: e.logIndex}); - + // TODO: would be nice if this was smart enough to understand the type of returnValues and do the needed conversions const eventData = { id, @@ -47,8 +47,8 @@ class EventSyncer { // TODO: test reorgs sub.next({blockNumber: e.blockNumber, ...e.returnValues}); - - if(e.removed){ + + if (e.removed){ this.db.deleteEvent(eventKey, id); return; } @@ -83,7 +83,7 @@ class EventSyncer { _retrieveEvents(eventKey, firstKnownBlock, lastKnownBlock, filterConditions, filterConditionsCb, contractInstance, eventName) { // TODO: this should be moved to a 'smart' module // it should be able to do events X at the time to avoid slow downs as well as the 10k limit - + if (firstKnownBlock == 0 || (firstKnownBlock > 0 && firstKnownBlock <= filterConditions.fromBlock)) { if (filterConditions.toBlock === 'latest') { // emit DB Events [fromBlock, lastKnownBlock] @@ -129,7 +129,7 @@ class EventSyncer { } } } - + _serveDBEvents(eventKey, firstKnownBlock, lastKnownBlock, filterConditions, filterConditionsCb) { const cb = this._parseEventCBFactory(filterConditions, filterConditionsCb, eventKey); const storedEvents = this.db.getEventsFor(eventKey).filter(x => x.blockNumber >= firstKnownBlock && x.blockNumber <= lastKnownBlock); @@ -137,7 +137,7 @@ class EventSyncer { cb(null, ev); }); } - + _getPastEvents(contract, eventName, filterConditions, filterConditionsCb, eventKey) { const cb = this._parseEventCBFactory(filterConditions, filterConditionsCb, eventKey); contract.getPastEvents.apply(contract, [eventName, filterConditions, (err, events) => { @@ -146,13 +146,13 @@ class EventSyncer { }); }]); } - + _subscribeToEvent(event, filterConditions, filterConditionsCb, eventKey) { const s = event.apply(event, [filterConditions, this._parseEventCBFactory(filterConditions, filterConditionsCb, eventKey) ]); this.subscriptions.push(s); return s; } - + _parseEventCBFactory = (filterConditions, filterConditionsCb, eventKey) => (err, ev) => { if(err) { console.error(err); diff --git a/src/logSyncer.js b/src/logSyncer.js index 41cf310..77217e4 100644 --- a/src/logSyncer.js +++ b/src/logSyncer.js @@ -10,18 +10,17 @@ class LogSyncer { this.subscriptions = []; } - track(options){ + track(options) { const eventKey = 'logs-' + hash(options || {}); const filterConditions = Object.assign({fromBlock: 0, toBlock: "latest"}, options || {}); - const eventSummary = this.db.getLastKnownEvent(eventKey); const sub = new ReplaySubject(); const logObserver = fromEvent(this.events, eventKey) logObserver.subscribe((e) => { - if(!e) return; - + if (!e) return; + // TODO: would be nice if this was smart enough to understand the type of returnValues and do the needed conversions const eventData = { id: hash({eventName: eventKey, blockNumber: e.blockNumber, transactionIndex: e.transactionIndex, logIndex: e.logIndex}), @@ -105,7 +104,7 @@ class LogSyncer { } } } - + _serveDBEvents(eventKey, firstKnownBlock, lastKnownBlock, filterConditions) { const cb = this._parseEventCBFactory(filterConditions, eventKey); const storedEvents = this.db.getEventsFor(eventKey).filter(x => x.blockNumber >= firstKnownBlock && x.blockNumber <= lastKnownBlock); @@ -113,7 +112,7 @@ class LogSyncer { cb(null, ev); }); } - + _getPastEvents(filterConditions, eventKey) { const cb = this._parseEventCBFactory(filterConditions, eventKey); this.web3.getPastLogs(options, (err, logs) => { @@ -126,31 +125,31 @@ class LogSyncer { }) }); } - + _subscribeToEvent(filterConditions, eventKey) { const s = this.web3.subscribe('logs', filterConditions, this._parseEventCBFactory(filterConditions, eventKey)); this.subscriptions.push(s); return s; } - + _parseEventCBFactory = (filterConditions, eventKey) => (err, ev) => { - if(err) { + if (err) { throw new Error(err); } if (filterConditions) { - if(filterConditions.address && ev.address.toLowerCase() !== filterConditions.address.toLowerCase()) return; - if(filterConditions.topics){ + if (filterConditions.address && ev.address.toLowerCase() !== filterConditions.address.toLowerCase()) return; + if (filterConditions.topics){ let shouldSkip = false; filterConditions.topics.forEach((topic, i) => { - if(topic != null && (!ev.topics[i] || ev.topics[i].toLowerCase() !== topic.toLowerCase())){ + if (topic != null && (!ev.topics[i] || ev.topics[i].toLowerCase() !== topic.toLowerCase())){ shouldSkip = true; } }); if(shouldSkip) return; } } - + this.events.emit(eventKey, ev); } diff --git a/src/poc.js b/src/poc.js deleted file mode 100644 index e2847f7..0000000 --- a/src/poc.js +++ /dev/null @@ -1,30 +0,0 @@ -// var Web3 = require('web3') -const Events = require('events') -const { map, scan } = require('rxjs/operators'); - -const Simulator = require('./simulator.js') -const EventSyncer = require('./eventSyncer.js') - -const events = new Events() -const eventSyncer = new EventSyncer(events); - -eventSyncer.init(run); - -function run() { - let myscan = scan((acc, curr) => { - acc.push(curr); - if (acc.length > 4) { - acc.shift(); - } - return acc; - }, []) - - let mymap = map(arr => arr.reduce((acc, current) => acc + current, 0) / arr.length) - - eventSyncer.trackEvent('contractEvent', ((x) => x.from === "0x123")).pipe(map(x => x.rating), myscan, mymap).subscribe((v) => { - console.dir("current average is " + v) - }) - - const simulator = new Simulator(events); - simulator.emitEvents() -} \ No newline at end of file diff --git a/src/react/index.js b/src/react/index.js index 77607d1..e5407a5 100644 --- a/src/react/index.js +++ b/src/react/index.js @@ -41,11 +41,11 @@ export function observe(WrappedComponent) { } }); } - + componentDidMount() { Object.keys(this.props).forEach(this.subscribeToProp); } - + componentWillUnmount() { this.state.subscriptions.forEach(subscription => { subscription.unsubscribe(); @@ -54,7 +54,7 @@ export function observe(WrappedComponent) { componentDidUpdate(prevProps) { Object.keys(prevProps).forEach(prop => { - if(!prevProps[prop] && this.props[prop]){ + if (!prevProps[prop] && this.props[prop]){ this.subscribeToProp(prop); } else if(prevProps[prop] !== this.props[prop]){ this.unsubscribe(prop); @@ -64,10 +64,10 @@ export function observe(WrappedComponent) { // TODO: check if prevProps and currProps are different, and unsubscribe from prevProp } - + render() { const props = Object.keys(this.props).reduce((accum, curr) => { - if(!isObservable(this.props[curr])){ + if (!isObservable(this.props[curr])){ accum[curr] = this.props[curr]; return accum; } diff --git a/src/simulator.js b/src/simulator.js deleted file mode 100644 index e4cec30..0000000 --- a/src/simulator.js +++ /dev/null @@ -1,27 +0,0 @@ -class Simulator { - - constructor(events) { - this.events = events; - this.contractEvents = [ - { id: 1, from: "0x123", type: "Rating", rating: 3 }, - { id: 2, from: "0x123", type: "Rating", rating: 1 }, - { id: 3, from: "0x234", type: "Rating", rating: 5 }, - { id: 4, from: "0x123", type: "Rating", rating: 4 }, - { id: 5, from: "0x123", type: "Rating", rating: 2 }, - { id: 6, from: "0x342", type: "Rating", rating: 2 } - ] - } - - emitEvents() { - let i = 0 - // emit contract event each 1 second - setInterval(() => { - if (i >= this.contractEvents.length) return - this.events.emit("contractEvent", this.contractEvents[i]) - i += 1 - }, 1 * 1000) - } - -} - -module.exports = Simulator; \ No newline at end of file diff --git a/src/subspace.js b/src/subspace.js index 0c79fae..3c4af60 100644 --- a/src/subspace.js +++ b/src/subspace.js @@ -13,7 +13,6 @@ import LogSyncer from './logSyncer'; export default class Subspace { constructor(provider, options = {}) { - if(provider.constructor.name !== "WebsocketProvider"){ console.warn("subspace: it's recommended to use a websocket provider to react to new events"); } @@ -26,7 +25,7 @@ export default class Subspace { this.options.callInterval = options.callInterval || 0; this.options.dbFilename = options.dbFilename || 'subspace.db'; this.latestBlockNumber = undefined; - + this.newBlocksSubscription = null; this.intervalTracker = null; this.callables = []; @@ -63,7 +62,6 @@ export default class Subspace { return this.logSyncer.track(options); } - _initNewBlocksSubscription() { if(this.newBlocksSubscription != null || this.options.callInterval !== 0) return; @@ -72,7 +70,7 @@ export default class Subspace { sub.error(err); return; } - + this.callables.forEach(fn => { fn(); }); @@ -87,7 +85,6 @@ export default class Subspace { fn(); }); }, this.options.callInterval); - } // TODO: should save value in database? @@ -104,12 +101,12 @@ export default class Subspace { sub.next(result); }]); }; - + callContractMethod(); this._initNewBlocksSubscription(); this._initCallInterval(); - + this.callables.push(callContractMethod); return sub.pipe(distinctUntilChanged((a, b) => equal(a, b))); @@ -153,7 +150,7 @@ export default class Subspace { this._initNewBlocksSubscription(); this._initCallInterval(); - + this.callables.push(callFn); return sub.pipe(distinctUntilChanged((a, b) => equal(a, b))); diff --git a/src/utils.js b/src/utils.js index c5a0ce4..1037f32 100644 --- a/src/utils.js +++ b/src/utils.js @@ -3,7 +3,6 @@ export function randomString() { return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); } - export function isAddress(address) { return /^(0x)?[0-9a-fA-F]{40}$/i.test(address) };