From 58cda9cc7fb79ca9df6746de7f9662bc08dc156a Mon Sep 17 00:00:00 2001 From: Stefan Malzner Date: Fri, 13 Oct 2017 12:29:40 +0200 Subject: initial commit --- src/lib/Miner.js | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 src/lib/Miner.js (limited to 'src/lib/Miner.js') 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 @@ +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; + } +} -- cgit v1.2.3-70-g09d2