forked from MetaMask/eth-block-tracker
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubscribe.js
More file actions
89 lines (79 loc) · 2.38 KB
/
subscribe.js
File metadata and controls
89 lines (79 loc) · 2.38 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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();
});
};
/**
* Calls the `evm_mine` RPC method via the given provider.
*
* @param {any} provider - The provider.
* @returns {Promise<any>} A promise that resolves to the result of the `evm_mine` call.
*/
async function triggerNextBlock(provider) {
await pify((cb) =>
provider.sendAsync(
{ id: 1, method: 'evm_mine', jsonrpc: '2.0', params: [] },
cb,
),
)();
}
/**
* Fetches the latest block via the given block tracker.
*
* @param {BaseBlockTracker} blockTracker - The block tracker.
* @returns {Promise<Block>} The promise for the block.
*/
async function newLatestBlock(blockTracker) {
return await pify(blockTracker.once, { errorFirst: false }).call(
blockTracker,
'latest',
);
}