embark-area-51/lib/contracts/provider.js

100 lines
2.5 KiB
JavaScript
Raw Normal View History

2018-05-10 18:52:30 +00:00
const ProviderEngine = require('web3-provider-engine');
const RpcSubprovider = require('web3-provider-engine/subproviders/rpc.js');
const async = require('async');
2018-05-17 17:48:39 +00:00
const AccountParser = require('./accountParser');
const fundAccount = require('./fundAccount');
const NO_ACCOUNTS = 'noAccounts';
2018-05-10 18:52:30 +00:00
class Provider {
2018-05-10 18:52:51 +00:00
constructor(options) {
this.web3 = options.web3;
this.accountsConfig = options.accountsConfig;
this.web3Endpoint = options.web3Endpoint;
2018-05-10 18:52:51 +00:00
this.logger = options.logger;
2018-05-18 13:46:39 +00:00
this.isDev = options.isDev;
2018-05-10 18:52:30 +00:00
this.engine = new ProviderEngine();
2018-05-14 16:08:03 +00:00
this.asyncMethods = {};
}
2018-05-10 18:52:30 +00:00
startWeb3Provider(callback) {
const self = this;
self.engine.addProvider(new RpcSubprovider({
rpcUrl: self.web3Endpoint
2018-05-10 18:52:30 +00:00
}));
// network connectivity error
self.engine.on('error', (err) => {
2018-05-10 18:52:30 +00:00
// report connectivity errors
self.logger.error(err.stack);
});
self.engine.start();
self.web3.setProvider(self);
self.accounts = AccountParser.parseAccountsConfig(self.accountsConfig, self.web3, self.logger);
self.addresses = [];
async.waterfall([
function populateWeb3Wallet(next) {
if (!self.accounts.length) {
return next(NO_ACCOUNTS);
}
self.accounts.forEach(account => {
self.addresses.push(account.address);
self.web3.eth.accounts.wallet.add(account);
});
self.asyncMethods = {
eth_accounts: self.eth_accounts.bind(self)
};
next();
}
], function (err) {
if (err && err !== NO_ACCOUNTS) {
self.logger.error((err));
}
callback();
2018-05-10 18:52:30 +00:00
});
}
fundAccounts(callback) {
const self = this;
if (!self.accounts.length) {
return callback();
}
if (!self.isDev) {
return callback();
}
async.each(self.accounts, (account, eachCb) => {
fundAccount(self.web3, account.address, eachCb);
}, callback);
}
2018-05-22 13:40:45 +00:00
stop() {
this.engine.stop();
}
2018-05-11 15:41:54 +00:00
eth_accounts(payload, cb) {
return cb(null, this.addresses);
}
sendAsync(payload, callback) {
let method = this.asyncMethods[payload.method];
if (method) {
return method.call(method, payload, (err, result) => {
if (err) {
return callback(err);
}
let response = {'id': payload.id, 'jsonrpc': '2.0', 'result': result};
callback(null, response);
});
}
2018-05-10 18:52:30 +00:00
this.engine.sendAsync.apply(this.engine, arguments);
}
send() {
2018-05-10 18:52:30 +00:00
return this.engine.send.apply(this.engine, arguments);
}
}
module.exports = Provider;