forked from MetaMask/eth-block-tracker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpolling.js
More file actions
59 lines (45 loc) · 1.84 KB
/
polling.js
File metadata and controls
59 lines (45 loc) · 1.84 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
const test = require('tape')
const GanacheCore = require('ganache-core')
const pify = require('pify')
const PollingBlockTracker = require('../src/polling')
const noop = () => {}
module.exports = (test, testLabel, PollingBlockTracker) => {
test(`${testLabel} - latest`, async (t) => {
const provider = GanacheCore.provider()
const blockTracker = new PollingBlockTracker({
provider,
pollingInterval: 100,
})
try {
t.equal(blockTracker.isRunning(), false, 'PollingBlockTracker should begin stopped')
const blocks = []
blockTracker.on('latest', (block) => blocks.push(block))
t.equal(blockTracker.isRunning(), true, 'PollingBlockTracker should start after listener is added')
t.equal(blocks.length, 0, 'no blocks so far')
await newLatestBlock(blockTracker)
t.equal(blocks.length, 1, 'saw 1st block')
await triggerNextBlock(provider)
await newLatestBlock(blockTracker)
t.equal(blocks.length, 2, 'saw 2nd block')
await triggerNextBlock(provider)
await triggerNextBlock(provider)
await triggerNextBlock(provider)
const lastBlock = await newLatestBlock(blockTracker)
t.equal(blocks.length, 3, 'saw only 5th block')
t.equal(Number.parseInt(lastBlock, 16), 4, 'saw correct block, with number 4')
blockTracker.removeAllListeners()
t.equal(blockTracker.isRunning(), false, 'PollingBlockTracker stops after all listeners are removed')
} catch (err) {
t.ifError(err)
}
// cleanup
blockTracker.removeAllListeners()
t.end()
})
}
async function triggerNextBlock(provider) {
await pify((cb) => provider.sendAsync({ id: 1, method: 'evm_mine', jsonrpc: '2.0', params: [] }, cb))()
}
async function newLatestBlock(blockTracker) {
return await pify(blockTracker.once, { errorFirst: false }).call(blockTracker, 'latest')
}