forked from MetaMask/eth-block-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubscribe.js
More file actions
74 lines (64 loc) · 1.77 KB
/
subscribe.js
File metadata and controls
74 lines (64 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const createRandomId = require('json-rpc-random-id')()
const BaseBlockTracker = require('./base')
class SubscribeBlockTracker extends BaseBlockTracker {
constructor (opts = {}) {
// parse + validate args
if (!opts.provider) {
throw new Error('SubscribeBlockTracker - no provider specified.')
}
// BaseBlockTracker constructor
super(opts)
// config
this._provider = opts.provider
}
//
// public
//
async checkForLatestBlock () {
return await this.getLatestBlock()
}
//
// private
//
async _start () {
if (this._subscriptionId === undefined || this._subscriptionId === null) {
try {
const blockNumber = await this._call('eth_blockNumber')
this._subscriptionId = await this._call('eth_subscribe', 'newHeads', {})
this._provider.on('data', this._handleSubData.bind(this))
this._newPotentialLatest(blockNumber)
} catch (e) {
this.emit('error', e)
}
}
}
async _end () {
if (this._subscriptionId !== null && this._subscriptionId !== undefined) {
try {
await this._call('eth_unsubscribe', this._subscriptionId)
delete this._subscriptionId
} catch (e) {
this.emit('error', e)
}
}
}
_call (method, ...params) {
return new Promise((resolve, reject) => {
this._provider.sendAsync({
id: createRandomId(), method, params, jsonrpc: '2.0',
}, (err, res) => {
if (err) {
reject(err)
} else {
resolve(res.result)
}
})
})
}
_handleSubData (_, data) {
if (data.method === 'eth_subscription' && data.params.subscription === this._subscriptionId) {
this._newPotentialLatest(data.params.result.number)
}
}
}
module.exports = SubscribeBlockTracker