All files / src/utils BlockTicker.js

0% Statements 0/14
0% Branches 0/19
0% Functions 0/3
0% Lines 0/12
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                                                   
const getBlockAverageTime = require('./getBlockAverageTime');
 
module.exports = class BlockTicker {
  constructor(web3, subscribers = []) {
    this.web3 = web3;
    this.subscribers = subscribers;
    this.latestBlock = this.latestBlock.bind(this);
  }
 
  subscribe(subscriber) {
    this.subscribers.push(subscriber);
  }
 
  async init() {
    const interval = Math.max(1, (await getBlockAverageTime(this.web3)) * 0.7);
    setInterval(this.latestBlock, interval * 1000);
  }
 
  async latestBlock() {
    const blockNumber = await this.web3.eth.getBlockNumber();
    for (const subscriber of this.subscribers) {
      subscriber(blockNumber);
    }
  }
};