react-authedmine
Version:
Authedmine from CoinHive.com
127 lines (99 loc) • 2.94 kB
JavaScript
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import load from 'load-script';
class AuthedMine extends Component {
constructor(props) {
super(props);
this.setState({
loaded: false,
});
};
loadAuthedMine() {
return new Promise((resolve, reject) => {
load('https://authedmine.com/lib/authedmine.min.js', (err, script) => {
if (err) {
return reject(err);
}
return this.setState({ loaded: true }, () => resolve(script));
});
});
}
componentWillMount() {
this.setState(Object.assign({}, this.defaultProps, this.props));
}
async componentDidMount() {
const [err, _] = await this.loadAuthedMine();
if (err) {
throw new Error(err);
}
if (this.state.run) {
this.initMiner();
this.start();
}
}
componentWillReceiveProps(nextProps) {
if (this.state.loaded && this.state.run) {
if (this.state.userName !== nextProps.userName) {
const isRunning = this.miner.isRunning;
if (nextProps !== this.props) {
this.initMiner();
}
if (isRunning) {
this.start();
}
}
}
this.setState(Object.assign({}, this.defaultProps, this.props));
}
initMiner() {
if (this.miner) {
this.stop();
delete this.miner();
}
if (this.state.userName) {
this.miner = CoinHive.User(this.props.siteKey, this.props.userName);
} else {
this.miner = CoinHive.Anonymous(this.props.siteKey);
}
if (this.state.autoThreads) {
this.miner.setAutoThreadsEnabled(this.state.autoThreads);
} else {
this.miner.setNumThreads(this.state.threads);
}
if (this.state.throttle) {
this.miner.setThrottle(this.state.throttle);
}
}
start() {
if (!this.miner) {
return null;
}
this.miner.start();
}
stop() {
if (!this.miner) {
return null;
}
this.miner.stop();
}
on(e, cb) {
this.miner.on(e, cb);
}
render() {
return null;
}
}
AuthedMine.propTypes = {
run: PropTypes.bool.isRequired,
siteKey: PropTypes.string,
userName: PropTypes.string,
autoThreads: PropTypes.bool,
threads: PropTypes.number,
throttle: PropTypes.number,
};
AuthedMine.defaultProps = {
siteKey: '4JhmNo9o1xspPb3GrouihQ5N7cB0V6EQ',
autoThreads: false,
threads: 1,
};
export default AuthedMine;