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
56 lines (43 loc) · 1.84 KB
/
Copy pathsubscribe.js
File metadata and controls
56 lines (43 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
const GanacheCore = require('ganache-core');
const pify = require('pify');
module.exports = (test, testLabel, SubscribeBlockTracker) => {
test(`${testLabel} - latest`, async (t) => {
const provider = GanacheCore.provider();
const blockTracker = new SubscribeBlockTracker({
provider,
});
try {
t.equal(blockTracker.isRunning(), false, 'SubscribeBlockTracker should begin stopped');
const blocks = [];
blockTracker.on('latest', (block) => blocks.push(block));
t.equal(blockTracker.isRunning(), true, 'SubscribeBlockTracker 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');
const latestBlock = newLatestBlock(blockTracker);
await triggerNextBlock(provider);
await latestBlock;
t.equal(blocks.length, 2, 'saw 2nd block');
await triggerNextBlock(provider);
await triggerNextBlock(provider);
const lastBlockPromise = newLatestBlock(blockTracker);
await triggerNextBlock(provider);
const lastBlock = await lastBlockPromise;
t.equal(blocks.length, 5, 'saw all intermediate blocks');
t.equal(Number.parseInt(lastBlock, 16), 4, 'saw correct block, with number 4');
blockTracker.removeAllListeners();
t.equal(blockTracker.isRunning(), false, 'SubscribeBlockTracker 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');
}