diff --git a/lib/plugins.js b/lib/plugins.js index b86f76b5..5157adfa 100644 --- a/lib/plugins.js +++ b/lib/plugins.js @@ -393,9 +393,13 @@ function plugins (settings, deviceId) { if (!exchange.active(settings, cryptoCode)) return + const direction = doBuy ? 'cashIn' : 'cashOut' + const internalTxId = tx ? tx.id : rec.id logger.debug('[%s] Pushing trade: %d', market, cryptoAtoms) if (!tradesQueues[market]) tradesQueues[market] = [] tradesQueues[market].push({ + direction, + internalTxId, fiatCode, cryptoAtoms, cryptoCode, @@ -428,12 +432,15 @@ function plugins (settings, deviceId) { if (filtered.length === 0) return null + const internalTxIdList = _.uniqBy('txId', _.map(tradeElement => { return { txId: tradeElement.internalTxId, direction: tradeElement.direction } })(filtered)) + const cryptoAtoms = filtered .reduce((prev, current) => prev.plus(current.cryptoAtoms), BN(0)) const timestamp = filtered.map(r => r.timestamp).reduce((acc, r) => Math.max(acc, r), 0) const consolidatedTrade = { + internalTxIdList, fiatCode, cryptoAtoms, cryptoCode, @@ -504,6 +511,18 @@ function plugins (settings, deviceId) { }) } + function recordTradeAndTx (tradeId, internalTxIdList) { + _.map(internalTxId => { + let entry = { trade_id: tradeId } + if (internalTxId.direction === 'cashIn') { + entry.cash_in_tx_id = internalTxId.txId + return db.none(pgp.helpers.insert(entry, null, 'cashin_tx_trades')) + } + entry.cash_out_tx_id = internalTxId.txId + return db.none(pgp.helpers.insert(entry, null, 'cashout_tx_trades')) + }, internalTxIdList) + } + function convertBigNumFields (obj) { const convert = (value, key) => _.includes(key, ['cryptoAtoms', 'fiat']) ? value.toString() @@ -533,8 +552,9 @@ function plugins (settings, deviceId) { _.mapKeys(_.snakeCase) ) const tradeEntry = massage(_tradeEntry, error) - const sql = pgp.helpers.insert(tradeEntry, null, 'trades') - return db.none(sql) + const sql = pgp.helpers.insert(tradeEntry, null, 'trades') + 'RETURNING *' + return db.oneOrNone(sql) + .then(newTrade => recordTradeAndTx(newTrade.id, _tradeEntry.internalTxIdList)) } function sendMessage (rec) { diff --git a/migrations/1616687417371-add_internal_tx_to_trades.js b/migrations/1616687417371-add_internal_tx_to_trades.js new file mode 100644 index 00000000..cffed9e6 --- /dev/null +++ b/migrations/1616687417371-add_internal_tx_to_trades.js @@ -0,0 +1,22 @@ +const db = require('./db') + +exports.up = function (next) { + var sql = [ + `CREATE TABLE cashout_tx_trades ( + cash_out_tx_id uuid REFERENCES cash_out_txs(id), + trade_id serial REFERENCES trades(id), + CONSTRAINT cashout_trade_pkey PRIMARY KEY (cash_out_tx_id,trade_id) + )`, + `CREATE TABLE cashin_tx_trades ( + cash_in_tx_id uuid REFERENCES cash_in_txs(id), + trade_id serial REFERENCES trades(id), + CONSTRAINT cashin_trade_pkey PRIMARY KEY (cash_in_tx_id,trade_id) + )` + ] + + db.multi(sql, next) +} + +exports.down = function (next) { + next() +}