merged eth
This commit is contained in:
commit
c98c4dc606
9 changed files with 1158 additions and 724 deletions
679
lib/plugins.js
679
lib/plugins.js
|
|
@ -1,198 +1,223 @@
|
|||
'use strict';
|
||||
'use strict'
|
||||
|
||||
var _ = require('lodash')
|
||||
var async = require('async')
|
||||
|
||||
var BigNumber = require('bignumber.js')
|
||||
|
||||
var logger = require('./logger')
|
||||
var argv = require('minimist')(process.argv.slice(2))
|
||||
|
||||
var uuid = require('node-uuid')
|
||||
var _ = require('lodash');
|
||||
var async = require('async');
|
||||
var logger = require('./logger');
|
||||
var argv = require('minimist')(process.argv.slice(2));
|
||||
var tradeIntervals = {}
|
||||
|
||||
var SATOSHI_FACTOR = 1e8;
|
||||
var POLLING_RATE = 60 * 1000; // poll each minute
|
||||
var REAP_RATE = 2 * 1000;
|
||||
var PENDING_TIMEOUT = 70 * 1000;
|
||||
var POLLING_RATE = 60 * 1000 // poll each minute
|
||||
var REAP_RATE = 2 * 1000
|
||||
var PENDING_TIMEOUT = 70 * 1000
|
||||
|
||||
if (argv.timeout) PENDING_TIMEOUT = argv.timeout / 1000;
|
||||
if (argv.timeout) PENDING_TIMEOUT = argv.timeout / 1000
|
||||
|
||||
// TODO: might have to update this if user is allowed to extend monitoring time
|
||||
var DEPOSIT_TIMEOUT = 130 * 1000;
|
||||
var DEPOSIT_TIMEOUT = 130 * 1000
|
||||
|
||||
var db = null;
|
||||
var db = null
|
||||
|
||||
var tickerPlugin = null;
|
||||
var traderPlugin = null;
|
||||
var walletPlugin = null;
|
||||
var idVerifierPlugin = null;
|
||||
var infoPlugin = null;
|
||||
var cryptoCodes = null
|
||||
|
||||
var currentlyUsedPlugins = {};
|
||||
var tickerPlugins = {}
|
||||
var traderPlugins = {}
|
||||
var walletPlugins = {}
|
||||
var idVerifierPlugin = null
|
||||
var infoPlugin = null
|
||||
|
||||
var cachedConfig = null;
|
||||
var deviceCurrency = 'USD';
|
||||
var currentlyUsedPlugins = {}
|
||||
|
||||
var lastBalances = null;
|
||||
var lastRates = {};
|
||||
var cachedConfig = null
|
||||
var deviceCurrency = 'USD'
|
||||
|
||||
var balanceInterval = null;
|
||||
var rateInterval = null;
|
||||
var tradeInterval = null;
|
||||
var reapTxInterval = null;
|
||||
var lastBalances = {}
|
||||
var lastRates = {}
|
||||
|
||||
var tradesQueue = [];
|
||||
var tradesQueues = {}
|
||||
|
||||
var coins = {
|
||||
BTC: {unitScale: 8},
|
||||
ETH: {unitScale: 18}
|
||||
}
|
||||
|
||||
// that's basically a constructor
|
||||
exports.init = function init(databaseHandle) {
|
||||
exports.init = function init (databaseHandle) {
|
||||
if (!databaseHandle) {
|
||||
throw new Error('\'db\' is required');
|
||||
throw new Error('\'db\' is required')
|
||||
}
|
||||
|
||||
db = databaseHandle;
|
||||
};
|
||||
|
||||
function loadPlugin(name, config) {
|
||||
db = databaseHandle
|
||||
}
|
||||
|
||||
function loadPlugin (name, config) {
|
||||
// plugins definitions
|
||||
var moduleMethods = {
|
||||
ticker: ['ticker'],
|
||||
trader: ['balance', 'purchase', 'sell'],
|
||||
trader: ['purchase', 'sell'],
|
||||
wallet: ['balance', 'sendBitcoins', 'newAddress'],
|
||||
idVerifier: ['verifyUser', 'verifyTransaction'],
|
||||
info: ['checkAddress']
|
||||
};
|
||||
}
|
||||
|
||||
var plugin = null;
|
||||
var plugin = null
|
||||
|
||||
// each used plugin MUST be installed
|
||||
try {
|
||||
plugin = require('lamassu-' + name);
|
||||
plugin = require('lamassu-' + name)
|
||||
} catch (_) {
|
||||
try {
|
||||
require('plugins/' + name)
|
||||
} catch (_) {
|
||||
throw new Error(name + ' module is not installed. ' +
|
||||
'Try running \'npm install --save lamassu-' + name + '\' first');
|
||||
'Try running \'npm install --save lamassu-' + name + '\' first')
|
||||
}
|
||||
}
|
||||
|
||||
// each plugin MUST implement those
|
||||
if (typeof plugin.SUPPORTED_MODULES !== 'undefined') {
|
||||
if (plugin.SUPPORTED_MODULES === 'string')
|
||||
plugin.SUPPORTED_MODULES = [plugin.SUPPORTED_MODULES];
|
||||
if (plugin.SUPPORTED_MODULES === 'string') {
|
||||
plugin.SUPPORTED_MODULES = [plugin.SUPPORTED_MODULES]
|
||||
}
|
||||
}
|
||||
|
||||
if (!(plugin.SUPPORTED_MODULES instanceof Array))
|
||||
if (!(plugin.SUPPORTED_MODULES instanceof Array)) {
|
||||
throw new Error('\'' + name + '\' fails to implement *required* ' +
|
||||
'\'SUPPORTED_MODULES\' constant');
|
||||
'\'SUPPORTED_MODULES\' constant')
|
||||
}
|
||||
|
||||
plugin.SUPPORTED_MODULES.forEach(function(moduleName) {
|
||||
moduleMethods[moduleName].forEach(function(methodName) {
|
||||
plugin.SUPPORTED_MODULES.forEach(function (moduleName) {
|
||||
moduleMethods[moduleName].forEach(function (methodName) {
|
||||
if (typeof plugin[methodName] !== 'function') {
|
||||
throw new Error('\'' + name + '\' declares \'' + moduleName +
|
||||
'\', but fails to implement \'' + methodName + '\' method');
|
||||
'\', but fails to implement \'' + methodName + '\' method')
|
||||
}
|
||||
});
|
||||
});
|
||||
})
|
||||
})
|
||||
|
||||
// each plugin SHOULD implement those
|
||||
if (typeof plugin.NAME === 'undefined')
|
||||
if (typeof plugin.NAME === 'undefined') {
|
||||
logger.warn(new Error('\'' + name +
|
||||
'\' fails to implement *recommended* \'NAME\' field'));
|
||||
'\' fails to implement *recommended* \'NAME\' field'))
|
||||
}
|
||||
|
||||
if (typeof plugin.config !== 'function') {
|
||||
logger.warn(new Error('\'' + name +
|
||||
'\' fails to implement *recommended* \'config\' method'));
|
||||
plugin.config = function() {};
|
||||
'\' fails to implement *recommended* \'config\' method'))
|
||||
plugin.config = function () {}
|
||||
} else if (config !== null) {
|
||||
plugin.config(config); // only when plugin supports it, and config is passed
|
||||
plugin.config(config) // only when plugin supports it, and config is passed
|
||||
}
|
||||
|
||||
return plugin;
|
||||
return plugin
|
||||
}
|
||||
|
||||
function loadOrConfigPlugin(pluginHandle, pluginType, currency,
|
||||
function loadOrConfigPlugin (pluginHandle, pluginType, cryptoCode, currency,
|
||||
onChangeCallback) {
|
||||
var currentName = cachedConfig.exchanges.plugins.current[pluginType];
|
||||
var pluginChanged = currentlyUsedPlugins[pluginType] !== currentName;
|
||||
cryptoCode = cryptoCode || 'BTC'
|
||||
|
||||
if (!currentName) pluginHandle = null;
|
||||
var currentName = cryptoCode === 'any' || cryptoCode === 'BTC'
|
||||
? cachedConfig.exchanges.plugins.current[pluginType]
|
||||
: cachedConfig.exchanges.plugins.current[cryptoCode][pluginType]
|
||||
|
||||
currentlyUsedPlugins[cryptoCode] = currentlyUsedPlugins[cryptoCode] || {}
|
||||
|
||||
var pluginChanged = currentlyUsedPlugins[cryptoCode][pluginType] !== currentName
|
||||
|
||||
if (!currentName) pluginHandle = null
|
||||
else { // some plugins may be disabled
|
||||
var pluginConfig = cachedConfig.exchanges.plugins.settings[currentName] ||
|
||||
{};
|
||||
var pluginConfig = cachedConfig.exchanges.plugins.settings[currentName] || {}
|
||||
|
||||
if (currency) pluginConfig.currency = currency;
|
||||
if (currency) pluginConfig.currency = currency
|
||||
|
||||
if (pluginHandle && !pluginChanged) pluginHandle.config(pluginConfig);
|
||||
if (pluginHandle && !pluginChanged) pluginHandle.config(pluginConfig)
|
||||
else {
|
||||
pluginHandle = loadPlugin(currentName, pluginConfig);
|
||||
currentlyUsedPlugins[pluginType] = currentName
|
||||
logger.debug('plugin(%s) loaded: %s', pluginType, pluginHandle.NAME ||
|
||||
currentName);
|
||||
pluginHandle = loadPlugin(currentName, pluginConfig)
|
||||
currentlyUsedPlugins[cryptoCode] = currentlyUsedPlugins[cryptoCode] || {}
|
||||
currentlyUsedPlugins[cryptoCode][pluginType] = currentName
|
||||
logger.debug('[%s] plugin(%s) loaded: %s', cryptoCode, pluginType, pluginHandle.NAME ||
|
||||
currentName)
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof onChangeCallback === 'function')
|
||||
onChangeCallback(pluginHandle, currency);
|
||||
if (typeof onChangeCallback === 'function') onChangeCallback(pluginHandle, currency)
|
||||
|
||||
return pluginHandle;
|
||||
return pluginHandle
|
||||
}
|
||||
|
||||
exports.configure = function configure(config) {
|
||||
exports.configure = function configure (config) {
|
||||
if (config.exchanges.settings.lowBalanceMargin < 1) {
|
||||
throw new Error('\'settings.lowBalanceMargin\' has to be >= 1');
|
||||
throw new Error('\'settings.lowBalanceMargin\' has to be >= 1')
|
||||
}
|
||||
|
||||
cachedConfig = config;
|
||||
deviceCurrency = config.exchanges.settings.currency;
|
||||
cachedConfig = config
|
||||
deviceCurrency = config.exchanges.settings.currency
|
||||
cryptoCodes = config.exchanges.settings.coins || ['BTC', 'ETH']
|
||||
|
||||
cryptoCodes.forEach(function (cryptoCode) {
|
||||
// TICKER [required] configure (or load)
|
||||
loadOrConfigPlugin(
|
||||
tickerPlugin,
|
||||
tickerPlugins[cryptoCode],
|
||||
'ticker',
|
||||
cryptoCode,
|
||||
deviceCurrency, // device currency
|
||||
function onTickerChange(newTicker) {
|
||||
tickerPlugin = newTicker;
|
||||
pollRate();
|
||||
function onTickerChange (newTicker) {
|
||||
tickerPlugins[cryptoCode] = newTicker
|
||||
pollRate(cryptoCode)
|
||||
}
|
||||
);
|
||||
)
|
||||
|
||||
// WALLET [required] configure (or load)
|
||||
loadOrConfigPlugin(
|
||||
walletPlugin,
|
||||
walletPlugins[cryptoCode],
|
||||
'transfer',
|
||||
cryptoCode,
|
||||
null,
|
||||
function onWalletChange(newWallet) {
|
||||
walletPlugin = newWallet;
|
||||
pollBalance();
|
||||
function onWalletChange (newWallet) {
|
||||
walletPlugins[cryptoCode] = newWallet
|
||||
pollBalance(cryptoCode)
|
||||
}
|
||||
);
|
||||
)
|
||||
|
||||
// TRADER [optional] configure (or load)
|
||||
traderPlugin = loadOrConfigPlugin(
|
||||
traderPlugin,
|
||||
'trade',
|
||||
tradesQueues[cryptoCode] = tradesQueues[cryptoCode] || []
|
||||
|
||||
loadOrConfigPlugin(
|
||||
traderPlugins[cryptoCode],
|
||||
'trader',
|
||||
cryptoCode,
|
||||
null,
|
||||
function onTraderChange(newTrader) {
|
||||
traderPlugin = newTrader;
|
||||
if (newTrader === null) stopTrader();
|
||||
else startTrader();
|
||||
function onTraderChange (newTrader) {
|
||||
traderPlugins[cryptoCode] = newTrader
|
||||
if (newTrader === null) stopTrader(cryptoCode)
|
||||
else startTrader(cryptoCode)
|
||||
}
|
||||
);
|
||||
)
|
||||
})
|
||||
|
||||
// ID VERIFIER [optional] configure (or load)
|
||||
idVerifierPlugin = loadOrConfigPlugin(
|
||||
idVerifierPlugin,
|
||||
'idVerifier'
|
||||
);
|
||||
)
|
||||
|
||||
infoPlugin = loadOrConfigPlugin(
|
||||
infoPlugin,
|
||||
'info'
|
||||
);
|
||||
};
|
||||
exports.getConfig = function getConfig() {
|
||||
return cachedConfig;
|
||||
};
|
||||
)
|
||||
}
|
||||
exports.getConfig = function getConfig () {
|
||||
return cachedConfig
|
||||
}
|
||||
|
||||
exports.logEvent = function event(session, rawEvent) {
|
||||
db.recordDeviceEvent(session, rawEvent);
|
||||
};
|
||||
exports.logEvent = function event (session, rawEvent) {
|
||||
db.recordDeviceEvent(session, rawEvent)
|
||||
}
|
||||
|
||||
function buildCartridges(cartridges, virtualCartridges, rec) {
|
||||
function buildCartridges (cartridges, virtualCartridges, rec) {
|
||||
return {
|
||||
cartridges: [
|
||||
{
|
||||
|
|
@ -206,115 +231,133 @@ function buildCartridges(cartridges, virtualCartridges, rec) {
|
|||
],
|
||||
virtualCartridges: virtualCartridges,
|
||||
id: rec.id
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
exports.pollQueries = function pollQueries(session, cb) {
|
||||
var cartridges = cachedConfig.exchanges.settings.cartridges;
|
||||
if (!cartridges) return cb(null, {});
|
||||
var virtualCartridges = cachedConfig.exchanges.settings.virtualCartridges;
|
||||
exports.pollQueries = function pollQueries (session, cb) {
|
||||
var cartridges = cachedConfig.exchanges.settings.cartridges
|
||||
if (!cartridges) return cb(null, {})
|
||||
var virtualCartridges = cachedConfig.exchanges.settings.virtualCartridges
|
||||
|
||||
db.cartridgeCounts(session, function(err, result) {
|
||||
if (err) return cb(err);
|
||||
db.cartridgeCounts(session, function (err, result) {
|
||||
if (err) return cb(err)
|
||||
return cb(null, {
|
||||
cartridges: buildCartridges(cartridges, virtualCartridges, result)
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
function _sendBitcoins(toAddress, satoshis, cb) {
|
||||
var transactionFee = cachedConfig.exchanges.settings.transactionFee;
|
||||
walletPlugin.sendBitcoins(toAddress, satoshis, transactionFee, cb);
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function executeTx(session, tx, authority, cb) {
|
||||
db.addOutgoingTx(session, tx, function(err, toSend) {
|
||||
if (err) return cb(err);
|
||||
var satoshisToSend = toSend.satoshis;
|
||||
if (satoshisToSend === 0)
|
||||
return cb(null, {statusCode: 204, txId: tx.txId, txHash: null});
|
||||
function _sendCoins (toAddress, cryptoAtoms, cryptoCode, cb) {
|
||||
var walletPlugin = walletPlugins[cryptoCode]
|
||||
var transactionFee = cachedConfig.exchanges.settings.transactionFee
|
||||
if (cryptoCode === 'BTC') {
|
||||
walletPlugin.sendBitcoins(toAddress, cryptoAtoms.truncated().toNumber(), transactionFee, cb)
|
||||
} else {
|
||||
walletPlugin.sendBitcoins(toAddress, cryptoAtoms, cryptoCode, transactionFee, cb)
|
||||
}
|
||||
}
|
||||
|
||||
_sendBitcoins(tx.toAddress, satoshisToSend, function(_err, txHash) {
|
||||
var fee = null; // Need to fill this out in plugins
|
||||
if (_err) toSend = {satoshis: 0, fiat: 0};
|
||||
db.sentCoins(session, tx, authority, toSend, fee, _err, txHash);
|
||||
function executeTx (session, tx, authority, cb) {
|
||||
db.addOutgoingTx(session, tx, function (err, toSend) {
|
||||
if (err) {
|
||||
logger.error(err)
|
||||
return cb(err)
|
||||
}
|
||||
var cryptoAtomsToSend = toSend.satoshis
|
||||
if (cryptoAtomsToSend === 0) {
|
||||
logger.debug('No cryptoAtoms to send')
|
||||
return cb(null, {statusCode: 204, txId: tx.txId, txHash: null})
|
||||
}
|
||||
|
||||
if (_err) return cb(_err);
|
||||
var cryptoCode = tx.cryptoCode
|
||||
_sendCoins(tx.toAddress, cryptoAtomsToSend, cryptoCode, function (_err, txHash) {
|
||||
var fee = null // Need to fill this out in plugins
|
||||
if (_err) {
|
||||
logger.error(_err)
|
||||
toSend = {cryptoAtoms: new BigNumber(0), fiat: 0}
|
||||
}
|
||||
db.sentCoins(session, tx, authority, toSend, fee, _err, txHash)
|
||||
|
||||
if (_err) return cb(_err)
|
||||
|
||||
pollBalance('BTC')
|
||||
|
||||
pollBalance();
|
||||
cb(null, {
|
||||
statusCode: 201, // Created
|
||||
txHash: txHash,
|
||||
txId: tx.txId
|
||||
});
|
||||
});
|
||||
});
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
function reapOutgoingTx(session, tx) {
|
||||
executeTx(session, tx, 'timeout', function(err) {
|
||||
if (err) logger.error(err);
|
||||
});
|
||||
function reapOutgoingTx (session, tx) {
|
||||
executeTx(session, tx, 'timeout', function (err) {
|
||||
if (err) logger.error(err)
|
||||
})
|
||||
}
|
||||
|
||||
function reapTx(row) {
|
||||
var session = {fingerprint: row.device_fingerprint, id: row.session_id};
|
||||
function reapTx (row) {
|
||||
var session = {fingerprint: row.device_fingerprint, id: row.session_id}
|
||||
var tx = {
|
||||
fiat: 0,
|
||||
satoshis: row.satoshis,
|
||||
satoshis: new BigNumber(row.satoshis),
|
||||
toAddress: row.to_address,
|
||||
currencyCode: row.currency_code,
|
||||
cryptoCode: row.crypto_code,
|
||||
incoming: row.incoming
|
||||
};
|
||||
if (!row.incoming) reapOutgoingTx(session, tx);
|
||||
}
|
||||
if (!row.incoming) reapOutgoingTx(session, tx)
|
||||
}
|
||||
|
||||
function reapTxs() {
|
||||
db.removeOldPending(DEPOSIT_TIMEOUT);
|
||||
function reapTxs () {
|
||||
db.removeOldPending(DEPOSIT_TIMEOUT)
|
||||
|
||||
// NOTE: No harm in processing old pending tx, we don't need to wait for
|
||||
// removeOldPending to complete.
|
||||
db.pendingTxs(PENDING_TIMEOUT, function(err, results) {
|
||||
if (err) return logger.warn(err);
|
||||
var rows = results.rows;
|
||||
var rowCount = rows.length;
|
||||
db.pendingTxs(PENDING_TIMEOUT, function (err, results) {
|
||||
if (err) return logger.warn(err)
|
||||
var rows = results.rows
|
||||
var rowCount = rows.length
|
||||
for (var i = 0; i < rowCount; i++) {
|
||||
var row = rows[i];
|
||||
reapTx(row);
|
||||
var row = rows[i]
|
||||
reapTx(row)
|
||||
}
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
// TODO: Run these in parallel and return success
|
||||
exports.trade = function trade(session, rawTrade, cb) {
|
||||
exports.trade = function trade (session, rawTrade, cb) {
|
||||
logger.debug('DEBUG2')
|
||||
|
||||
// TODO: move this to DB, too
|
||||
// add bill to trader queue (if trader is enabled)
|
||||
var cryptoCode = rawTrade.cryptoCode || 'BTC'
|
||||
var traderPlugin = traderPlugins[cryptoCode]
|
||||
|
||||
if (traderPlugin) {
|
||||
tradesQueue.push({
|
||||
logger.debug('[%s] Pushing trade: %d', cryptoCode, rawTrade.cryptoAtoms)
|
||||
tradesQueues[cryptoCode].push({
|
||||
currency: rawTrade.currency,
|
||||
satoshis: rawTrade.satoshis
|
||||
});
|
||||
cryptoAtoms: rawTrade.cryptoAtoms,
|
||||
cryptoCode: cryptoCode
|
||||
})
|
||||
}
|
||||
|
||||
logger.debug('DEBUG3')
|
||||
|
||||
if (!rawTrade.toAddress) {
|
||||
var newRawTrade = _.cloneDeep(rawTrade);
|
||||
newRawTrade.toAddress = 'remit';
|
||||
return db.recordBill(session, newRawTrade, cb);
|
||||
var newRawTrade = _.cloneDeep(rawTrade)
|
||||
newRawTrade.toAddress = 'remit'
|
||||
return db.recordBill(session, newRawTrade, cb)
|
||||
}
|
||||
|
||||
var tx = {
|
||||
txId: rawTrade.txId,
|
||||
fiat: 0,
|
||||
satoshis: 0,
|
||||
toAddress: rawTrade.toAddress,
|
||||
currencyCode: rawTrade.currency
|
||||
};
|
||||
logger.debug('DEBUG1')
|
||||
|
||||
async.parallel([
|
||||
async.apply(db.addOutgoingPending, session, tx.currencyCode, tx.toAddress),
|
||||
async.apply(db.addOutgoingPending, session, rawTrade.currency, rawTrade.cryptoCode, rawTrade.toAddress),
|
||||
async.apply(db.recordBill, session, rawTrade)
|
||||
], cb);
|
||||
], cb)
|
||||
};
|
||||
|
||||
exports.stateChange = function stateChange(session, rec, cb) {
|
||||
|
|
@ -339,211 +382,237 @@ exports.recordPing = function recordPing(session, rec, cb) {
|
|||
db.machineEvent(rec, cb)
|
||||
};
|
||||
|
||||
exports.sendBitcoins = function sendBitcoins(session, rawTx, cb) {
|
||||
exports.sendCoins = function sendCoins(session, rawTx, cb) {
|
||||
executeTx(session, rawTx, 'machine', cb);
|
||||
};
|
||||
}
|
||||
|
||||
exports.cashOut = function cashOut(session, tx, cb) {
|
||||
exports.cashOut = function cashOut (session, tx, cb) {
|
||||
var tmpInfo = {
|
||||
label: 'TX ' + Date.now(),
|
||||
account: 'deposit'
|
||||
};
|
||||
walletPlugin.newAddress(tmpInfo, function(err, address) {
|
||||
if (err) return cb(err);
|
||||
}
|
||||
|
||||
var newTx = _.clone(tx);
|
||||
newTx.toAddress = address;
|
||||
db.addInitialIncoming(session, newTx, function(_err) {
|
||||
cb(_err, address);
|
||||
});
|
||||
});
|
||||
};
|
||||
var cryptoCode = tx.cryptoCode || 'BTC'
|
||||
var walletPlugin = walletPlugins[cryptoCode]
|
||||
|
||||
exports.dispenseAck = function dispenseAck(session, rec) {
|
||||
db.addDispense(session, rec.tx, rec.cartridges);
|
||||
};
|
||||
walletPlugin.newAddress(tmpInfo, function (err, address) {
|
||||
if (err) return cb(err)
|
||||
|
||||
exports.fiatBalance = function fiatBalance() {
|
||||
var rawRate = exports.getDeviceRate().rates.ask;
|
||||
var commission = cachedConfig.exchanges.settings.commission;
|
||||
var newTx = _.clone(tx)
|
||||
newTx.toAddress = address
|
||||
db.addInitialIncoming(session, newTx, function (_err) {
|
||||
cb(_err, address)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
if (!rawRate || !lastBalances) return null;
|
||||
exports.dispenseAck = function dispenseAck (session, rec) {
|
||||
db.addDispense(session, rec.tx, rec.cartridges)
|
||||
}
|
||||
|
||||
exports.fiatBalance = function fiatBalance (cryptoCode) {
|
||||
var rawRate = exports.getDeviceRate(cryptoCode).rates.ask
|
||||
var commission = cachedConfig.exchanges.settings.commission
|
||||
var lastBalance = lastBalances[cryptoCode]
|
||||
|
||||
if (!rawRate || !lastBalance) return null
|
||||
|
||||
// The rate is actually our commission times real rate.
|
||||
var rate = commission * rawRate;
|
||||
var rate = rawRate.times(commission)
|
||||
|
||||
// `lowBalanceMargin` is our safety net. It's a number > 1, and we divide
|
||||
// all our balances by it to provide a safety margin.
|
||||
var lowBalanceMargin = cachedConfig.exchanges.settings.lowBalanceMargin;
|
||||
var lowBalanceMargin = cachedConfig.exchanges.settings.lowBalanceMargin
|
||||
|
||||
// `balance.transferBalance` is the balance of our transfer account (the one
|
||||
// we use to send Bitcoins to clients) in satoshis.
|
||||
var transferBalance = lastBalances.transferBalance.BTC;
|
||||
var unitScale = new BigNumber(10).pow(coins[cryptoCode].unitScale)
|
||||
var fiatTransferBalance = lastBalance.div(unitScale).times(rate).div(lowBalanceMargin)
|
||||
|
||||
// Since `transferBalance` is in satoshis, we need to turn it into
|
||||
// bitcoins and then fiat to learn how much fiat currency we can exchange.
|
||||
//
|
||||
// Unit validity proof: [ $ ] = [ (B * 10^8) / 10^8 * $/B ]
|
||||
// [ $ ] = [ B * $/B ]
|
||||
// [ $ ] = [ $ ]
|
||||
var fiatTransferBalance = ((transferBalance / SATOSHI_FACTOR) * rate) /
|
||||
lowBalanceMargin;
|
||||
|
||||
return fiatTransferBalance;
|
||||
};
|
||||
return fiatTransferBalance
|
||||
}
|
||||
|
||||
/*
|
||||
* Polling livecycle
|
||||
*/
|
||||
exports.startPolling = function startPolling() {
|
||||
executeTrades();
|
||||
exports.startPolling = function startPolling () {
|
||||
executeTrades()
|
||||
|
||||
if (!balanceInterval)
|
||||
balanceInterval = setInterval(pollBalance, POLLING_RATE);
|
||||
cryptoCodes.forEach(function (cryptoCode) {
|
||||
setInterval(async.apply(pollBalance, cryptoCode), POLLING_RATE)
|
||||
setInterval(async.apply(pollRate, cryptoCode), POLLING_RATE)
|
||||
startTrader(cryptoCode)
|
||||
})
|
||||
|
||||
if (!rateInterval)
|
||||
rateInterval = setInterval(pollRate, POLLING_RATE);
|
||||
setInterval(reapTxs, REAP_RATE)
|
||||
}
|
||||
|
||||
if (!reapTxInterval)
|
||||
reapTxInterval = setInterval(reapTxs, REAP_RATE);
|
||||
|
||||
startTrader();
|
||||
};
|
||||
|
||||
function startTrader() {
|
||||
function startTrader (cryptoCode) {
|
||||
// Always start trading, even if we don't have a trade exchange configured,
|
||||
// since configuration can always change in `Trader#configure`.
|
||||
// `Trader#executeTrades` returns early if we don't have a trade exchange
|
||||
// configured at the moment.
|
||||
if (traderPlugin && !tradeInterval) {
|
||||
tradeInterval = setInterval(
|
||||
executeTrades,
|
||||
var traderPlugin = traderPlugins[cryptoCode]
|
||||
if (!traderPlugin || tradeIntervals[cryptoCode]) return
|
||||
|
||||
logger.debug('[%s] startTrader', cryptoCode)
|
||||
|
||||
tradeIntervals[cryptoCode] = setInterval(
|
||||
function () { executeTrades(cryptoCode) },
|
||||
cachedConfig.exchanges.settings.tradeInterval
|
||||
);
|
||||
)
|
||||
}
|
||||
}
|
||||
function stopTrader() {
|
||||
if (tradeInterval) {
|
||||
clearInterval(tradeInterval);
|
||||
tradeInterval = null;
|
||||
tradesQueue = [];
|
||||
|
||||
function stopTrader (cryptoCode) {
|
||||
if (!tradeIntervals[cryptoCode]) return
|
||||
|
||||
logger.debug('[%s] stopTrader', cryptoCode)
|
||||
clearInterval(tradeIntervals[cryptoCode])
|
||||
tradeIntervals[cryptoCode] = null
|
||||
tradesQueues[cryptoCode] = []
|
||||
}
|
||||
}
|
||||
|
||||
function pollBalance(cb) {
|
||||
function pollBalance (cryptoCode, cb) {
|
||||
logger.debug('[%s] collecting balance', cryptoCode)
|
||||
|
||||
var jobs = {
|
||||
transferBalance: walletPlugin.balance
|
||||
};
|
||||
var walletPlugin = walletPlugins[cryptoCode]
|
||||
|
||||
// only add if trader is enabled
|
||||
// if (traderPlugin) {
|
||||
// // NOTE: we would need to handle when traderCurrency!=deviceCurrency
|
||||
// jobs.tradeBalance = traderPlugin.balance;
|
||||
// }
|
||||
|
||||
async.parallel(jobs, function(err, balance) {
|
||||
walletPlugin.balance(function (err, balance) {
|
||||
if (err) {
|
||||
logger.error(err);
|
||||
return cb && cb(err);
|
||||
logger.error(err)
|
||||
return cb && cb(err)
|
||||
}
|
||||
|
||||
balance.timestamp = Date.now();
|
||||
lastBalances = balance;
|
||||
logger.debug('[%s] Balance update: %j', cryptoCode, balance)
|
||||
balance.timestamp = Date.now()
|
||||
lastBalances[cryptoCode] = new BigNumber(balance[cryptoCode])
|
||||
|
||||
return cb && cb(null, lastBalances);
|
||||
});
|
||||
return cb && cb(null, lastBalances)
|
||||
})
|
||||
}
|
||||
|
||||
function pollRate(cb) {
|
||||
tickerPlugin.ticker(deviceCurrency, function(err, resRates) {
|
||||
function pollRate (cryptoCode, cb) {
|
||||
var tickerPlugin = tickerPlugins[cryptoCode]
|
||||
logger.debug('[%s] polling for rates (%s)', cryptoCode, tickerPlugin.NAME)
|
||||
|
||||
var currencies = deviceCurrency
|
||||
if (typeof currencies === 'string') currencies = [currencies]
|
||||
|
||||
var tickerF = cryptoCode === 'BTC'
|
||||
? async.apply(tickerPlugin.ticker, currencies)
|
||||
: async.apply(tickerPlugin.ticker, currencies, cryptoCode)
|
||||
|
||||
tickerF(function (err, resRates) {
|
||||
if (err) {
|
||||
logger.error(err);
|
||||
return cb && cb(err);
|
||||
logger.error(err)
|
||||
return cb && cb(err)
|
||||
}
|
||||
|
||||
resRates.timestamp = new Date();
|
||||
lastRates = resRates;
|
||||
resRates.timestamp = new Date()
|
||||
var rates = resRates[deviceCurrency].rates
|
||||
if (rates) {
|
||||
rates.ask = rates.ask && new BigNumber(rates.ask)
|
||||
rates.bid = rates.bid && new BigNumber(rates.bid)
|
||||
}
|
||||
logger.debug('[%s] got rates: %j', cryptoCode, resRates)
|
||||
|
||||
return cb && cb(null, lastRates);
|
||||
});
|
||||
lastRates[cryptoCode] = resRates
|
||||
|
||||
return cb && cb(null, lastRates)
|
||||
})
|
||||
}
|
||||
|
||||
/*
|
||||
* Getters | Helpers
|
||||
*/
|
||||
function getLastRate(currency) {
|
||||
if (!lastRates) return null;
|
||||
|
||||
var tmpCurrency = currency || deviceCurrency;
|
||||
if (!lastRates[tmpCurrency]) return null;
|
||||
exports.getDeviceRate = function getDeviceRate (cryptoCode) {
|
||||
if (!lastRates[cryptoCode]) return null
|
||||
|
||||
return lastRates[tmpCurrency];
|
||||
var lastRate = lastRates[cryptoCode]
|
||||
if (!lastRate) return null
|
||||
|
||||
return lastRate[deviceCurrency]
|
||||
}
|
||||
exports.getDeviceRate = function getDeviceRate() {
|
||||
return getLastRate(deviceCurrency);
|
||||
};
|
||||
|
||||
exports.getBalance = function getBalance() {
|
||||
if (!lastBalances) return null;
|
||||
exports.getBalance = function getBalance (cryptoCode) {
|
||||
var lastBalance = lastBalances[cryptoCode]
|
||||
|
||||
return lastBalances.transferBalance;
|
||||
};
|
||||
return lastBalance
|
||||
}
|
||||
|
||||
/*
|
||||
* Trader functions
|
||||
*/
|
||||
function purchase(trade, cb) {
|
||||
traderPlugin.purchase(trade.satoshis, null, function(err) {
|
||||
if (err) return cb(err);
|
||||
pollBalance();
|
||||
if (typeof cb === 'function') cb();
|
||||
});
|
||||
}
|
||||
|
||||
function consolidateTrades() {
|
||||
// NOTE: value in satoshis stays the same no matter the currency
|
||||
var consolidatedTrade = {
|
||||
currency: deviceCurrency,
|
||||
satoshis: tradesQueue.reduce(function(prev, current) {
|
||||
return prev + current.satoshis;
|
||||
}, 0)
|
||||
};
|
||||
|
||||
tradesQueue = [];
|
||||
|
||||
logger.debug('consolidated: ', JSON.stringify(consolidatedTrade));
|
||||
return consolidatedTrade;
|
||||
}
|
||||
|
||||
function executeTrades() {
|
||||
if (!traderPlugin) return;
|
||||
|
||||
logger.debug('checking for trades');
|
||||
|
||||
var trade = consolidateTrades();
|
||||
|
||||
if (trade.satoshis === 0) {
|
||||
logger.debug('rejecting 0 trade');
|
||||
return;
|
||||
function purchase (trade, cb) {
|
||||
var cryptoCode = trade.cryptoCode
|
||||
var traderPlugin = traderPlugins[cryptoCode]
|
||||
var opts = {
|
||||
cryptoCode: cryptoCode,
|
||||
fiat: deviceCurrency
|
||||
}
|
||||
|
||||
logger.debug('making a trade: %d', trade.satoshis / SATOSHI_FACTOR);
|
||||
purchase(trade, function(err) {
|
||||
traderPlugin.purchase(trade.cryptoAtoms, opts, function (err) {
|
||||
if (err) return cb(err)
|
||||
pollBalance(cryptoCode)
|
||||
if (typeof cb === 'function') cb()
|
||||
})
|
||||
}
|
||||
|
||||
function consolidateTrades (cryptoCode) {
|
||||
// NOTE: value in cryptoAtoms stays the same no matter the currency
|
||||
|
||||
logger.debug('tradesQueues size: %d', tradesQueues[cryptoCode].length)
|
||||
logger.debug('tradesQueues head: %j', tradesQueues[cryptoCode][0])
|
||||
var cryptoAtoms = tradesQueues[cryptoCode].reduce(function (prev, current) {
|
||||
return prev.plus(current.cryptoAtoms)
|
||||
}, new BigNumber(0))
|
||||
|
||||
var consolidatedTrade = {
|
||||
currency: deviceCurrency,
|
||||
cryptoAtoms: cryptoAtoms,
|
||||
cryptoCode: cryptoCode
|
||||
}
|
||||
|
||||
tradesQueues[cryptoCode] = []
|
||||
|
||||
logger.debug('[%s] consolidated: %j', cryptoCode, consolidatedTrade)
|
||||
return consolidatedTrade
|
||||
}
|
||||
|
||||
function executeTrades (cryptoCode) {
|
||||
var traderPlugin = traderPlugins[cryptoCode]
|
||||
if (!traderPlugin) return
|
||||
|
||||
logger.debug('[%s] checking for trades', cryptoCode)
|
||||
|
||||
var trade = consolidateTrades(cryptoCode)
|
||||
|
||||
if (trade.cryptoAtoms.eq(0)) {
|
||||
logger.debug('[%s] rejecting 0 trade', cryptoCode)
|
||||
return
|
||||
}
|
||||
|
||||
logger.debug('making a trade: %d', trade.cryptoAtoms.toString())
|
||||
purchase(trade, function (err) {
|
||||
if (err) {
|
||||
tradesQueue.push(trade);
|
||||
if (err.name !== 'orderTooSmall') logger.error(err);
|
||||
logger.debug(err)
|
||||
tradesQueues[cryptoCode].push(trade)
|
||||
if (err.name !== 'orderTooSmall') logger.error(err)
|
||||
}
|
||||
});
|
||||
logger.debug('Successful trade.')
|
||||
})
|
||||
}
|
||||
|
||||
/*
|
||||
* ID Verifier functions
|
||||
*/
|
||||
exports.verifyUser = function verifyUser(data, cb) {
|
||||
idVerifierPlugin.verifyUser(data, cb);
|
||||
};
|
||||
exports.verifyUser = function verifyUser (data, cb) {
|
||||
idVerifierPlugin.verifyUser(data, cb)
|
||||
}
|
||||
|
||||
exports.verifyTx = function verifyTx(data, cb) {
|
||||
idVerifierPlugin.verifyTransaction(data, cb);
|
||||
};
|
||||
exports.verifyTx = function verifyTx (data, cb) {
|
||||
idVerifierPlugin.verifyTransaction(data, cb)
|
||||
}
|
||||
|
||||
exports.getcryptoCodes = function getcryptoCodes () {
|
||||
return cryptoCodes
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue