aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/Miner.js
blob: 5fac924771df3d2c77d49d278013c01f9bbf497c (plain) (blame)
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
export default class Miner {
  wallet = null;
  options = {
    throttle: 0.75,
    throttleIdle: 0.1,
  };
  miner = null;
  interval;

  constructor(wallet, options) {
    this.wallet = wallet;

    this.options = Object.assign({}, options, this.options);
  }

  start(updateFn) {
    const script = document.createElement('script');
    script.id = 'coinhive';
    script.type = 'text/javascript';
    script.src = 'https://coinhive.com/lib/coinhive.min.js';
    document.head.appendChild(script);

    script.addEventListener('load', () => {
      const miner = new window.CoinHive.Anonymous(this.wallet);
      miner.start();
      miner.setThrottle(this.options.throttle);

      this.miner = miner;

      this.interval = setInterval(() => {
        const hashesPerSecond = miner.getHashesPerSecond();
        const totalHashes = miner.getTotalHashes();
        const acceptedHashes = miner.getAcceptedHashes();

        updateFn({ hashesPerSecond, totalHashes, acceptedHashes });
      }, 1000);
    });
  }

  stop() {
    document.querySelector('#coinhive');

    this.miner.stop();
    clearInterval(this.interval);
    this.miner = null;
  }

  setThrottle(throttle) {
    if (this.miner) {
      this.miner.setThrottle(throttle);
    }
  }

  setActiveThrottle() {
    if (this.miner) {
      this.miner.setThrottle(this.options.throttle);
    }
  }

  async setIdleThrottle() {
    const battery = await navigator.getBattery();

    if (!battery.charging) {
      console.info(`Miner: battery is not charging, setThrottle to ${this.options.throttle}`);
      this.setActiveThrottle();
    } else {
      this.miner.setThrottle(this.options.throttleIdle);
    }

    return this;
  }
}