# All files / src/eventsRelay ContractEventsSubscription.js

100% Statements 24/24
100% Branches 5/5
100% Functions 5/5
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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

    1x

    1x

    3x
    3x

    3x

    3x

    3x

    1x

    4x
    4x
    4x
    4x
    4x

    4x
    4x
    4x

    4x

    4x
    1x

    3x

    3x

    3x

    3x

     /**
     * Copyright (c) 2018-present, Leap DAO (leapdao.org)
     *
     * This source code is licensed under the Mozilla Public License Version 2.0
     * found in the LICENSE file in the root directory of this source tree.
     */

    const EventEmitter = require('events');

    const BATCH_SIZE = 5000;
    async function getPastEvents(contract, fromBlock, toBlock) {
      const batchCount = Math.ceil((toBlock - fromBlock) / BATCH_SIZE);
      const events = [];

      for (let i = 0; i < batchCount; i += 1) {
        /* eslint-disable no-await-in-loop */
        events.push(
          await contract.getPastEvents('allEvents', {
            fromBlock: i * BATCH_SIZE + fromBlock,
            toBlock: Math.min(toBlock, i * BATCH_SIZE + fromBlock + BATCH_SIZE),
          })
        );
        /* eslint-enable */
      }

      return events.reduce((result, ev) => result.concat(ev), []);
    }

    module.exports = class ContractEventsSubscription extends EventEmitter {
      constructor(web3, contract, fromBlock = null) {
        super();
        this.fromBlock = fromBlock;
        this.web3 = web3;
        this.contract = contract;
        this.fetchEvents = this.fetchEvents.bind(this);
      }

      async init() {
        const initialEvetns = await this.fetchEvents();
        setInterval(this.fetchEvents, 5 * 1000);
        return initialEvetns;
      }

      async fetchEvents() {
        const blockNumber = await this.web3.eth.getBlockNumber();

        if (this.fromBlock === blockNumber) {
          return null;
        }

        const events = await getPastEvents(
          this.contract,
          this.fromBlock || 0,
          blockNumber
        );

        this.emit('events', events);

        this.fromBlock = blockNumber;

        return events;
      }
    };