chore: server code formatting
This commit is contained in:
parent
aedabcbdee
commit
68517170e2
234 changed files with 9824 additions and 6195 deletions
|
|
@ -1,51 +1,63 @@
|
|||
const _ = require('lodash/fp')
|
||||
const pgp = require('pg-promise')()
|
||||
|
||||
module.exports = {logDispense, logActionById, logAction, logError}
|
||||
module.exports = { logDispense, logActionById, logAction, logError }
|
||||
|
||||
function logDispense (t, tx) {
|
||||
const baseRec = {error: tx.error, error_code: tx.errorCode}
|
||||
function logDispense(t, tx) {
|
||||
const baseRec = { error: tx.error, error_code: tx.errorCode }
|
||||
const rec = _.merge(mapDispense(tx), baseRec)
|
||||
const action = _.isEmpty(tx.error) ? 'dispense' : 'dispenseError'
|
||||
return logAction(t, action, rec, tx)
|
||||
}
|
||||
|
||||
function logActionById (t, action, _rec, txId) {
|
||||
const rec = _.assign(_rec, {action, tx_id: txId, redeem: false})
|
||||
function logActionById(t, action, _rec, txId) {
|
||||
const rec = _.assign(_rec, { action, tx_id: txId, redeem: false })
|
||||
const sql = pgp.helpers.insert(rec, null, 'cash_out_actions')
|
||||
|
||||
return t.none(sql)
|
||||
}
|
||||
|
||||
function logAction (t, action, _rec, tx) {
|
||||
const rec = _.assign(_rec, {action, tx_id: tx.id, redeem: !!tx.redeem, device_id: tx.deviceId})
|
||||
function logAction(t, action, _rec, tx) {
|
||||
const rec = _.assign(_rec, {
|
||||
action,
|
||||
tx_id: tx.id,
|
||||
redeem: !!tx.redeem,
|
||||
device_id: tx.deviceId,
|
||||
})
|
||||
const sql = pgp.helpers.insert(rec, null, 'cash_out_actions')
|
||||
|
||||
return t.none(sql)
|
||||
.then(_.constant(tx))
|
||||
return t.none(sql).then(_.constant(tx))
|
||||
}
|
||||
|
||||
function logError (t, action, err, tx) {
|
||||
return logAction(t, action, {
|
||||
error: err.message,
|
||||
error_code: err.name
|
||||
}, tx)
|
||||
function logError(t, action, err, tx) {
|
||||
return logAction(
|
||||
t,
|
||||
action,
|
||||
{
|
||||
error: err.message,
|
||||
error_code: err.name,
|
||||
},
|
||||
tx,
|
||||
)
|
||||
}
|
||||
|
||||
function mapDispense (tx) {
|
||||
function mapDispense(tx) {
|
||||
const bills = tx.bills
|
||||
|
||||
if (_.isEmpty(bills)) return {}
|
||||
|
||||
const res = {}
|
||||
|
||||
_.forEach(it => {
|
||||
const suffix = _.snakeCase(bills[it].name.replace(/cassette/gi, ''))
|
||||
res[`provisioned_${suffix}`] = bills[it].provisioned
|
||||
res[`denomination_${suffix}`] = bills[it].denomination
|
||||
res[`dispensed_${suffix}`] = bills[it].dispensed
|
||||
res[`rejected_${suffix}`] = bills[it].rejected
|
||||
}, _.times(_.identity(), _.size(bills)))
|
||||
_.forEach(
|
||||
it => {
|
||||
const suffix = _.snakeCase(bills[it].name.replace(/cassette/gi, ''))
|
||||
res[`provisioned_${suffix}`] = bills[it].provisioned
|
||||
res[`denomination_${suffix}`] = bills[it].denomination
|
||||
res[`dispensed_${suffix}`] = bills[it].dispensed
|
||||
res[`rejected_${suffix}`] = bills[it].rejected
|
||||
},
|
||||
_.times(_.identity(), _.size(bills)),
|
||||
)
|
||||
|
||||
return res
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,170 +13,208 @@ const toObj = helper.toObj
|
|||
|
||||
module.exports = { atomic }
|
||||
|
||||
function atomic (tx, pi, fromClient) {
|
||||
function atomic(tx, pi, fromClient) {
|
||||
const TransactionMode = pgp.txMode.TransactionMode
|
||||
const isolationLevel = pgp.txMode.isolationLevel
|
||||
const mode = new TransactionMode({ tiLevel: isolationLevel.serializable })
|
||||
function transaction (t) {
|
||||
function transaction(t) {
|
||||
const sql = 'SELECT * FROM cash_out_txs WHERE id=$1 FOR UPDATE'
|
||||
|
||||
return t.oneOrNone(sql, [tx.id])
|
||||
return t
|
||||
.oneOrNone(sql, [tx.id])
|
||||
.then(toObj)
|
||||
.then(oldTx => {
|
||||
const isStale = fromClient && oldTx && (oldTx.txVersion >= tx.txVersion)
|
||||
const isStale = fromClient && oldTx && oldTx.txVersion >= tx.txVersion
|
||||
if (isStale) throw new E.StaleTxError({ txId: tx.id })
|
||||
|
||||
// Server doesn't bump version, so we just prevent from version being older.
|
||||
const isStaleFromServer = !fromClient && oldTx && (oldTx.txVersion > tx.txVersion)
|
||||
if (isStaleFromServer) throw new Error('Stale Error: server triggered', tx.id)
|
||||
const isStaleFromServer =
|
||||
!fromClient && oldTx && oldTx.txVersion > tx.txVersion
|
||||
if (isStaleFromServer)
|
||||
throw new Error('Stale Error: server triggered', tx.id)
|
||||
|
||||
return preProcess(t, oldTx, tx, pi)
|
||||
.then(preProcessedTx => cashOutLow.upsert(t, oldTx, preProcessedTx))
|
||||
return preProcess(t, oldTx, tx, pi).then(preProcessedTx =>
|
||||
cashOutLow.upsert(t, oldTx, preProcessedTx),
|
||||
)
|
||||
})
|
||||
}
|
||||
return db.tx({ mode }, transaction)
|
||||
}
|
||||
|
||||
function preProcess (t, oldTx, newTx, pi) {
|
||||
function preProcess(t, oldTx, newTx, pi) {
|
||||
if (!oldTx) {
|
||||
return pi.isHd(newTx)
|
||||
return pi
|
||||
.isHd(newTx)
|
||||
.then(isHd => nextHd(t, isHd, newTx))
|
||||
.then(newTxHd => {
|
||||
return pi.newAddress(newTxHd)
|
||||
.then(_.merge(newTxHd))
|
||||
return pi.newAddress(newTxHd).then(_.merge(newTxHd))
|
||||
})
|
||||
.then(addressedTx => {
|
||||
const rec = {
|
||||
to_address: addressedTx.toAddress,
|
||||
layer_2_address: addressedTx.layer2Address
|
||||
layer_2_address: addressedTx.layer2Address,
|
||||
}
|
||||
|
||||
return cashOutActions.logAction(t, 'provisionAddress', rec, addressedTx)
|
||||
})
|
||||
.catch(err => {
|
||||
pi.notifyOperator(newTx, { isRedemption: false, error: 'Error while provisioning address' })
|
||||
.catch((err) => logger.error('Failure sending transaction notification', err))
|
||||
return cashOutActions.logError(t, 'provisionAddress', err, newTx)
|
||||
.then(() => { throw err })
|
||||
pi.notifyOperator(newTx, {
|
||||
isRedemption: false,
|
||||
error: 'Error while provisioning address',
|
||||
}).catch(err =>
|
||||
logger.error('Failure sending transaction notification', err),
|
||||
)
|
||||
return cashOutActions
|
||||
.logError(t, 'provisionAddress', err, newTx)
|
||||
.then(() => {
|
||||
throw err
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
return Promise.resolve(updateStatus(oldTx, newTx))
|
||||
.then(updatedTx => {
|
||||
if (updatedTx.status !== oldTx.status) {
|
||||
const isZeroConf = pi.isZeroConf(updatedTx)
|
||||
updatedTx.justAuthorized = wasJustAuthorized(oldTx, updatedTx, isZeroConf)
|
||||
return Promise.resolve(updateStatus(oldTx, newTx)).then(updatedTx => {
|
||||
if (updatedTx.status !== oldTx.status) {
|
||||
const isZeroConf = pi.isZeroConf(updatedTx)
|
||||
updatedTx.justAuthorized = wasJustAuthorized(oldTx, updatedTx, isZeroConf)
|
||||
|
||||
const rec = {
|
||||
to_address: updatedTx.toAddress,
|
||||
tx_hash: updatedTx.txHash
|
||||
}
|
||||
|
||||
return cashOutActions.logAction(t, updatedTx.status, rec, updatedTx)
|
||||
const rec = {
|
||||
to_address: updatedTx.toAddress,
|
||||
tx_hash: updatedTx.txHash,
|
||||
}
|
||||
|
||||
const hasError = !oldTx.error && newTx.error
|
||||
const hasDispenseOccurred = !oldTx.dispenseConfirmed && dispenseOccurred(newTx.bills)
|
||||
return cashOutActions.logAction(t, updatedTx.status, rec, updatedTx)
|
||||
}
|
||||
|
||||
if (hasError || hasDispenseOccurred) {
|
||||
return cashOutActions.logDispense(t, updatedTx)
|
||||
.then(it => updateCassettes(t, updatedTx).then(() => it) )
|
||||
.then((t) => {
|
||||
pi.notifyOperator(updatedTx, { isRedemption: true })
|
||||
.catch((err) => logger.error('Failure sending transaction notification', err))
|
||||
return t
|
||||
})
|
||||
}
|
||||
const hasError = !oldTx.error && newTx.error
|
||||
const hasDispenseOccurred =
|
||||
!oldTx.dispenseConfirmed && dispenseOccurred(newTx.bills)
|
||||
|
||||
if (!oldTx.phone && newTx.phone) {
|
||||
return cashOutActions.logAction(t, 'addPhone', {}, updatedTx)
|
||||
}
|
||||
if (hasError || hasDispenseOccurred) {
|
||||
return cashOutActions
|
||||
.logDispense(t, updatedTx)
|
||||
.then(it => updateCassettes(t, updatedTx).then(() => it))
|
||||
.then(t => {
|
||||
pi.notifyOperator(updatedTx, { isRedemption: true }).catch(err =>
|
||||
logger.error('Failure sending transaction notification', err),
|
||||
)
|
||||
return t
|
||||
})
|
||||
}
|
||||
|
||||
if (!oldTx.redeem && newTx.redeem) {
|
||||
return cashOutActions.logAction(t, 'redeemLater', {}, updatedTx)
|
||||
}
|
||||
if (!oldTx.phone && newTx.phone) {
|
||||
return cashOutActions.logAction(t, 'addPhone', {}, updatedTx)
|
||||
}
|
||||
|
||||
return updatedTx
|
||||
})
|
||||
if (!oldTx.redeem && newTx.redeem) {
|
||||
return cashOutActions.logAction(t, 'redeemLater', {}, updatedTx)
|
||||
}
|
||||
|
||||
return updatedTx
|
||||
})
|
||||
}
|
||||
|
||||
function nextHd (t, isHd, tx) {
|
||||
function nextHd(t, isHd, tx) {
|
||||
if (!isHd) return Promise.resolve(tx)
|
||||
|
||||
return t.one("select nextval('hd_indices_seq') as hd_index")
|
||||
return t
|
||||
.one("select nextval('hd_indices_seq') as hd_index")
|
||||
.then(row => _.set('hdIndex', row.hd_index, tx))
|
||||
}
|
||||
|
||||
function updateCassettes (t, tx) {
|
||||
function updateCassettes(t, tx) {
|
||||
if (!dispenseOccurred(tx.bills)) return Promise.resolve()
|
||||
|
||||
const billsStmt = _.join(', ')(_.map(it => `${tx.bills[it].name} = ${tx.bills[it].name} - $${it + 1}`)(_.range(0, _.size(tx.bills))))
|
||||
const billsStmt = _.join(', ')(
|
||||
_.map(it => `${tx.bills[it].name} = ${tx.bills[it].name} - $${it + 1}`)(
|
||||
_.range(0, _.size(tx.bills)),
|
||||
),
|
||||
)
|
||||
const returnStmt = _.join(', ')(_.map(bill => `${bill.name}`)(tx.bills))
|
||||
|
||||
const sql = `UPDATE devices SET ${billsStmt} WHERE device_id = $${_.size(tx.bills) + 1} RETURNING ${returnStmt}`
|
||||
|
||||
const values = []
|
||||
|
||||
_.forEach(it => values.push(
|
||||
tx.bills[it].dispensed + tx.bills[it].rejected
|
||||
), _.times(_.identity(), _.size(tx.bills)))
|
||||
_.forEach(
|
||||
it => values.push(tx.bills[it].dispensed + tx.bills[it].rejected),
|
||||
_.times(_.identity(), _.size(tx.bills)),
|
||||
)
|
||||
|
||||
values.push(tx.deviceId)
|
||||
|
||||
return t.one(sql, values)
|
||||
}
|
||||
|
||||
function wasJustAuthorized (oldTx, newTx, isZeroConf) {
|
||||
const isAuthorized = () => _.includes(oldTx.status, ['notSeen', 'published', 'rejected']) &&
|
||||
function wasJustAuthorized(oldTx, newTx, isZeroConf) {
|
||||
const isAuthorized = () =>
|
||||
_.includes(oldTx.status, ['notSeen', 'published', 'rejected']) &&
|
||||
_.includes(newTx.status, ['authorized', 'instant', 'confirmed'])
|
||||
|
||||
const isConfirmed = () => _.includes(oldTx.status, ['notSeen', 'published', 'authorized', 'rejected']) &&
|
||||
_.includes(newTx.status, ['instant', 'confirmed'])
|
||||
const isConfirmed = () =>
|
||||
_.includes(oldTx.status, [
|
||||
'notSeen',
|
||||
'published',
|
||||
'authorized',
|
||||
'rejected',
|
||||
]) && _.includes(newTx.status, ['instant', 'confirmed'])
|
||||
|
||||
return isZeroConf ? isAuthorized() : isConfirmed()
|
||||
}
|
||||
|
||||
function isPublished (status) {
|
||||
return _.includes(status, ['published', 'rejected', 'authorized', 'instant', 'confirmed'])
|
||||
function isPublished(status) {
|
||||
return _.includes(status, [
|
||||
'published',
|
||||
'rejected',
|
||||
'authorized',
|
||||
'instant',
|
||||
'confirmed',
|
||||
])
|
||||
}
|
||||
|
||||
function isConfirmed (status) {
|
||||
function isConfirmed(status) {
|
||||
return status === 'confirmed'
|
||||
}
|
||||
|
||||
function updateStatus (oldTx, newTx) {
|
||||
function updateStatus(oldTx, newTx) {
|
||||
const oldStatus = oldTx.status
|
||||
const newStatus = ratchetStatus(oldStatus, newTx.status)
|
||||
|
||||
const publishedAt = !oldTx.publishedAt && isPublished(newStatus)
|
||||
? 'now()^'
|
||||
: undefined
|
||||
const publishedAt =
|
||||
!oldTx.publishedAt && isPublished(newStatus) ? 'now()^' : undefined
|
||||
|
||||
const confirmedAt = !oldTx.confirmedAt && isConfirmed(newStatus)
|
||||
? 'now()^'
|
||||
: undefined
|
||||
const confirmedAt =
|
||||
!oldTx.confirmedAt && isConfirmed(newStatus) ? 'now()^' : undefined
|
||||
|
||||
const updateRec = {
|
||||
publishedAt,
|
||||
confirmedAt,
|
||||
status: newStatus
|
||||
status: newStatus,
|
||||
}
|
||||
|
||||
return _.merge(newTx, updateRec)
|
||||
}
|
||||
|
||||
function ratchetStatus (oldStatus, newStatus) {
|
||||
const statusOrder = ['notSeen', 'published', 'rejected',
|
||||
'authorized', 'instant', 'confirmed']
|
||||
function ratchetStatus(oldStatus, newStatus) {
|
||||
const statusOrder = [
|
||||
'notSeen',
|
||||
'published',
|
||||
'rejected',
|
||||
'authorized',
|
||||
'instant',
|
||||
'confirmed',
|
||||
]
|
||||
|
||||
if (oldStatus === newStatus) return oldStatus
|
||||
if (newStatus === 'insufficientFunds') return newStatus
|
||||
|
||||
const idx = Math.max(statusOrder.indexOf(oldStatus), statusOrder.indexOf(newStatus))
|
||||
const idx = Math.max(
|
||||
statusOrder.indexOf(oldStatus),
|
||||
statusOrder.indexOf(newStatus),
|
||||
)
|
||||
return statusOrder[idx]
|
||||
}
|
||||
|
||||
function dispenseOccurred (bills) {
|
||||
function dispenseOccurred(bills) {
|
||||
if (_.isEmpty(bills)) return false
|
||||
return _.every(_.overEvery([_.has('dispensed'), _.has('rejected')]), bills)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,18 +40,31 @@ const SNAKE_CASE_BILL_FIELDS = [
|
|||
'provisioned_recycler_3',
|
||||
'provisioned_recycler_4',
|
||||
'provisioned_recycler_5',
|
||||
'provisioned_recycler_6'
|
||||
'provisioned_recycler_6',
|
||||
]
|
||||
|
||||
const BILL_FIELDS = _.map(_.camelCase, SNAKE_CASE_BILL_FIELDS)
|
||||
|
||||
module.exports = { redeemableTxs, toObj, toDb, REDEEMABLE_AGE, CASH_OUT_TRANSACTION_STATES }
|
||||
module.exports = {
|
||||
redeemableTxs,
|
||||
toObj,
|
||||
toDb,
|
||||
REDEEMABLE_AGE,
|
||||
CASH_OUT_TRANSACTION_STATES,
|
||||
}
|
||||
|
||||
const mapValuesWithKey = _.mapValues.convert({cap: false})
|
||||
const mapValuesWithKey = _.mapValues.convert({ cap: false })
|
||||
|
||||
function convertBigNumFields (obj) {
|
||||
function convertBigNumFields(obj) {
|
||||
const convert = (value, key) => {
|
||||
if (_.includes(key, [ 'cryptoAtoms', 'receivedCryptoAtoms', 'fiat', 'fixedFee' ])) {
|
||||
if (
|
||||
_.includes(key, [
|
||||
'cryptoAtoms',
|
||||
'receivedCryptoAtoms',
|
||||
'fiat',
|
||||
'fixedFee',
|
||||
])
|
||||
) {
|
||||
// BACKWARDS_COMPATIBILITY 10.1
|
||||
// bills before 10.2 don't have fixedFee
|
||||
if (key === 'fixedFee' && !value) return new BN(0).toString()
|
||||
|
|
@ -59,62 +72,62 @@ function convertBigNumFields (obj) {
|
|||
}
|
||||
|
||||
// Only test isNil for these fields since the others should not be empty.
|
||||
if (_.includes(key, [ 'commissionPercentage', 'rawTickerPrice' ]) && !_.isNil(value)) {
|
||||
if (
|
||||
_.includes(key, ['commissionPercentage', 'rawTickerPrice']) &&
|
||||
!_.isNil(value)
|
||||
) {
|
||||
return value.toString()
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
const convertKey = key => _.includes(key, ['cryptoAtoms', 'fiat'])
|
||||
? key + '#'
|
||||
: key
|
||||
const convertKey = key =>
|
||||
_.includes(key, ['cryptoAtoms', 'fiat']) ? key + '#' : key
|
||||
|
||||
return _.mapKeys(convertKey, mapValuesWithKey(convert, obj))
|
||||
}
|
||||
|
||||
function convertField (key) {
|
||||
function convertField(key) {
|
||||
return _.snakeCase(key)
|
||||
}
|
||||
|
||||
function addDbBills (tx) {
|
||||
function addDbBills(tx) {
|
||||
const bills = tx.bills
|
||||
if (_.isEmpty(bills)) return tx
|
||||
|
||||
const billsObj = _.flow(
|
||||
_.reduce(
|
||||
(acc, value) => {
|
||||
const suffix = _.snakeCase(value.name.replace(/cassette/gi, ''))
|
||||
return {
|
||||
...acc,
|
||||
[`provisioned_${suffix}`]: value.provisioned,
|
||||
[`denomination_${suffix}`]: value.denomination
|
||||
}
|
||||
},
|
||||
{}
|
||||
),
|
||||
_.reduce((acc, value) => {
|
||||
const suffix = _.snakeCase(value.name.replace(/cassette/gi, ''))
|
||||
return {
|
||||
...acc,
|
||||
[`provisioned_${suffix}`]: value.provisioned,
|
||||
[`denomination_${suffix}`]: value.denomination,
|
||||
}
|
||||
}, {}),
|
||||
it => {
|
||||
const missingKeys = _.reduce(
|
||||
(acc, value) => {
|
||||
return _.assign({ [value]: 0 })(acc)
|
||||
},
|
||||
{}
|
||||
)(_.difference(SNAKE_CASE_BILL_FIELDS, _.keys(it)))
|
||||
const missingKeys = _.reduce((acc, value) => {
|
||||
return _.assign({ [value]: 0 })(acc)
|
||||
}, {})(_.difference(SNAKE_CASE_BILL_FIELDS, _.keys(it)))
|
||||
return _.assign(missingKeys, it)
|
||||
}
|
||||
},
|
||||
)(bills)
|
||||
|
||||
return _.assign(tx, billsObj)
|
||||
}
|
||||
|
||||
function toDb (tx) {
|
||||
const massager = _.flow(convertBigNumFields, addDbBills,
|
||||
_.omit(['direction', 'bills', 'promoCodeApplied']), _.mapKeys(convertField))
|
||||
function toDb(tx) {
|
||||
const massager = _.flow(
|
||||
convertBigNumFields,
|
||||
addDbBills,
|
||||
_.omit(['direction', 'bills', 'promoCodeApplied']),
|
||||
_.mapKeys(convertField),
|
||||
)
|
||||
|
||||
return massager(tx)
|
||||
}
|
||||
|
||||
function toObj (row) {
|
||||
function toObj(row) {
|
||||
if (!row) return null
|
||||
|
||||
const keys = _.keys(row)
|
||||
|
|
@ -126,7 +139,14 @@ function toObj (row) {
|
|||
newObj[objKey] = new BN(row[key])
|
||||
return
|
||||
}
|
||||
if (_.includes(key, ['crypto_atoms', 'fiat', 'commission_percentage', 'raw_ticker_price'])) {
|
||||
if (
|
||||
_.includes(key, [
|
||||
'crypto_atoms',
|
||||
'fiat',
|
||||
'commission_percentage',
|
||||
'raw_ticker_price',
|
||||
])
|
||||
) {
|
||||
newObj[objKey] = new BN(row[key])
|
||||
return
|
||||
}
|
||||
|
|
@ -137,11 +157,20 @@ function toObj (row) {
|
|||
newObj.direction = 'cashOut'
|
||||
|
||||
if (_.every(_.isNil, _.at(BILL_FIELDS, newObj))) return newObj
|
||||
if (_.some(_.isNil, _.at(BILL_FIELDS, newObj))) throw new Error('Missing cassette values')
|
||||
if (_.some(_.isNil, _.at(BILL_FIELDS, newObj)))
|
||||
throw new Error('Missing cassette values')
|
||||
|
||||
const billFieldsArr = _.concat(
|
||||
_.map(it => ({ name: `cassette${it + 1}`, denomination: newObj[`denomination${it + 1}`], provisioned: newObj[`provisioned${it + 1}`] }))(_.range(0, MAX_CASSETTES)),
|
||||
_.map(it => ({ name: `recycler${it + 1}`, denomination: newObj[`denominationRecycler${it + 1}`], provisioned: newObj[`provisionedRecycler${it + 1}`] }))(_.range(0, MAX_RECYCLERS)),
|
||||
_.map(it => ({
|
||||
name: `cassette${it + 1}`,
|
||||
denomination: newObj[`denomination${it + 1}`],
|
||||
provisioned: newObj[`provisioned${it + 1}`],
|
||||
}))(_.range(0, MAX_CASSETTES)),
|
||||
_.map(it => ({
|
||||
name: `recycler${it + 1}`,
|
||||
denomination: newObj[`denominationRecycler${it + 1}`],
|
||||
provisioned: newObj[`provisionedRecycler${it + 1}`],
|
||||
}))(_.range(0, MAX_RECYCLERS)),
|
||||
)
|
||||
|
||||
// There can't be bills with denomination === 0.
|
||||
|
|
@ -151,7 +180,7 @@ function toObj (row) {
|
|||
return _.set('bills', bills, _.omit(BILL_FIELDS, newObj))
|
||||
}
|
||||
|
||||
function redeemableTxs (deviceId) {
|
||||
function redeemableTxs(deviceId) {
|
||||
const sql = `select * from cash_out_txs
|
||||
where device_id=$1
|
||||
and redeem=$2
|
||||
|
|
@ -164,6 +193,5 @@ function redeemableTxs (deviceId) {
|
|||
)
|
||||
and extract(epoch from (now() - greatest(created, confirmed_at))) < $4`
|
||||
|
||||
return db.any(sql, [deviceId, true, false, REDEEMABLE_AGE])
|
||||
.then(_.map(toObj))
|
||||
return db.any(sql, [deviceId, true, false, REDEEMABLE_AGE]).then(_.map(toObj))
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,73 +7,91 @@ const { anonymousCustomer } = require('../constants')
|
|||
const toDb = helper.toDb
|
||||
const toObj = helper.toObj
|
||||
|
||||
const UPDATEABLE_FIELDS = ['txHash', 'txVersion', 'status', 'dispense', 'dispenseConfirmed',
|
||||
'notified', 'redeem', 'phone', 'error', 'swept', 'publishedAt', 'confirmedAt', 'errorCode',
|
||||
'receivedCryptoAtoms', 'walletScore', 'customerId' ]
|
||||
const UPDATEABLE_FIELDS = [
|
||||
'txHash',
|
||||
'txVersion',
|
||||
'status',
|
||||
'dispense',
|
||||
'dispenseConfirmed',
|
||||
'notified',
|
||||
'redeem',
|
||||
'phone',
|
||||
'error',
|
||||
'swept',
|
||||
'publishedAt',
|
||||
'confirmedAt',
|
||||
'errorCode',
|
||||
'receivedCryptoAtoms',
|
||||
'walletScore',
|
||||
'customerId',
|
||||
]
|
||||
|
||||
module.exports = {upsert, update, insert}
|
||||
module.exports = { upsert, update, insert }
|
||||
|
||||
function upsert (t, oldTx, tx) {
|
||||
function upsert(t, oldTx, tx) {
|
||||
if (!oldTx) {
|
||||
return insert(t, tx)
|
||||
.then(newTx => [oldTx, newTx])
|
||||
return insert(t, tx).then(newTx => [oldTx, newTx])
|
||||
}
|
||||
|
||||
return update(t, tx, diff(oldTx, tx))
|
||||
.then(newTx => [oldTx, newTx, tx.justAuthorized])
|
||||
return update(t, tx, diff(oldTx, tx)).then(newTx => [
|
||||
oldTx,
|
||||
newTx,
|
||||
tx.justAuthorized,
|
||||
])
|
||||
}
|
||||
|
||||
function insert (t, tx) {
|
||||
function insert(t, tx) {
|
||||
const dbTx = toDb(tx)
|
||||
|
||||
const sql = pgp.helpers.insert(dbTx, null, 'cash_out_txs') + ' returning *'
|
||||
return t.one(sql)
|
||||
.then(toObj)
|
||||
return t.one(sql).then(toObj)
|
||||
}
|
||||
|
||||
function update (t, tx, changes) {
|
||||
function update(t, tx, changes) {
|
||||
if (_.isEmpty(changes)) return Promise.resolve(tx)
|
||||
|
||||
const dbChanges = toDb(changes)
|
||||
const sql = pgp.helpers.update(dbChanges, null, 'cash_out_txs') +
|
||||
const sql =
|
||||
pgp.helpers.update(dbChanges, null, 'cash_out_txs') +
|
||||
pgp.as.format(' where id=$1', [tx.id])
|
||||
|
||||
const newTx = _.merge(tx, changes)
|
||||
|
||||
return t.none(sql)
|
||||
.then(() => newTx)
|
||||
return t.none(sql).then(() => newTx)
|
||||
}
|
||||
|
||||
function diff (oldTx, newTx) {
|
||||
function diff(oldTx, newTx) {
|
||||
let updatedTx = {}
|
||||
|
||||
UPDATEABLE_FIELDS.forEach(fieldKey => {
|
||||
if (oldTx && _.isEqualWith(nilEqual, oldTx[fieldKey], newTx[fieldKey])) return
|
||||
if (oldTx && _.isEqualWith(nilEqual, oldTx[fieldKey], newTx[fieldKey]))
|
||||
return
|
||||
|
||||
// We never null out an existing field
|
||||
if (oldTx && _.isNil(newTx[fieldKey])) return updatedTx[fieldKey] = oldTx[fieldKey]
|
||||
if (oldTx && _.isNil(newTx[fieldKey]))
|
||||
return (updatedTx[fieldKey] = oldTx[fieldKey])
|
||||
|
||||
switch (fieldKey) {
|
||||
case 'customerId':
|
||||
if (oldTx.customerId === anonymousCustomer.uuid) {
|
||||
return updatedTx['customerId'] = newTx['customerId']
|
||||
return (updatedTx['customerId'] = newTx['customerId'])
|
||||
}
|
||||
return
|
||||
// prevent dispense changing from 'true' to 'false'
|
||||
case 'dispense':
|
||||
if (!oldTx.dispense) {
|
||||
return updatedTx[fieldKey] = newTx[fieldKey]
|
||||
return (updatedTx[fieldKey] = newTx[fieldKey])
|
||||
}
|
||||
return
|
||||
default:
|
||||
return updatedTx[fieldKey] = newTx[fieldKey]
|
||||
return (updatedTx[fieldKey] = newTx[fieldKey])
|
||||
}
|
||||
})
|
||||
|
||||
return updatedTx
|
||||
}
|
||||
|
||||
function nilEqual (a, b) {
|
||||
function nilEqual(a, b) {
|
||||
if (_.isNil(a) && _.isNil(b)) return true
|
||||
|
||||
return undefined
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ module.exports = {
|
|||
monitorLiveIncoming,
|
||||
monitorStaleIncoming,
|
||||
monitorUnnotified,
|
||||
cancel
|
||||
cancel,
|
||||
}
|
||||
|
||||
const STALE_INCOMING_TX_AGE = T.day
|
||||
|
|
@ -31,38 +31,40 @@ const INSUFFICIENT_FUNDS_CODE = 570
|
|||
|
||||
const toObj = helper.toObj
|
||||
|
||||
function selfPost (tx, pi) {
|
||||
function selfPost(tx, pi) {
|
||||
return post(tx, pi, false)
|
||||
}
|
||||
|
||||
function post (tx, pi, fromClient = true) {
|
||||
function post(tx, pi, fromClient = true) {
|
||||
logger.silly('Updating cashout -- tx:', JSON.stringify(tx))
|
||||
logger.silly('Updating cashout -- fromClient:', JSON.stringify(fromClient))
|
||||
return cashOutAtomic.atomic(tx, pi, fromClient)
|
||||
.then(txVector => {
|
||||
const [, newTx, justAuthorized] = txVector
|
||||
return postProcess(txVector, justAuthorized, pi)
|
||||
.then(changes => cashOutLow.update(db, newTx, changes))
|
||||
})
|
||||
return cashOutAtomic.atomic(tx, pi, fromClient).then(txVector => {
|
||||
const [, newTx, justAuthorized] = txVector
|
||||
return postProcess(txVector, justAuthorized, pi).then(changes =>
|
||||
cashOutLow.update(db, newTx, changes),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function postProcess (txVector, justAuthorized, pi) {
|
||||
function postProcess(txVector, justAuthorized, pi) {
|
||||
const [oldTx, newTx] = txVector
|
||||
|
||||
if (justAuthorized) {
|
||||
pi.sell(newTx)
|
||||
pi.notifyOperator(newTx, { isRedemption: false })
|
||||
.catch((err) => logger.error('Failure sending transaction notification', err))
|
||||
pi.notifyOperator(newTx, { isRedemption: false }).catch(err =>
|
||||
logger.error('Failure sending transaction notification', err),
|
||||
)
|
||||
}
|
||||
|
||||
if ((newTx.dispense && !oldTx.dispense) || (newTx.redeem && !oldTx.redeem)) {
|
||||
return pi.buildAvailableUnits(newTx.id)
|
||||
return pi
|
||||
.buildAvailableUnits(newTx.id)
|
||||
.then(units => {
|
||||
units = _.concat(units.cassettes, units.recyclers)
|
||||
logger.silly('Computing bills to dispense:', {
|
||||
txId: newTx.id,
|
||||
units: units,
|
||||
fiat: newTx.fiat
|
||||
fiat: newTx.fiat,
|
||||
})
|
||||
const bills = billMath.makeChange(units, newTx.fiat)
|
||||
logger.silly('Bills to dispense:', JSON.stringify(bills))
|
||||
|
|
@ -73,27 +75,38 @@ function postProcess (txVector, justAuthorized, pi) {
|
|||
.then(bills => {
|
||||
const rec = {}
|
||||
|
||||
_.forEach(it => {
|
||||
const suffix = _.snakeCase(bills[it].name.replace(/cassette/gi, ''))
|
||||
rec[`provisioned_${suffix}`] = bills[it].provisioned
|
||||
rec[`denomination_${suffix}`] = bills[it].denomination
|
||||
}, _.times(_.identity(), _.size(bills)))
|
||||
_.forEach(
|
||||
it => {
|
||||
const suffix = _.snakeCase(bills[it].name.replace(/cassette/gi, ''))
|
||||
rec[`provisioned_${suffix}`] = bills[it].provisioned
|
||||
rec[`denomination_${suffix}`] = bills[it].denomination
|
||||
},
|
||||
_.times(_.identity(), _.size(bills)),
|
||||
)
|
||||
|
||||
return cashOutActions.logAction(db, 'provisionNotes', rec, newTx)
|
||||
return cashOutActions
|
||||
.logAction(db, 'provisionNotes', rec, newTx)
|
||||
.then(_.constant({ bills }))
|
||||
})
|
||||
.catch(err => {
|
||||
pi.notifyOperator(newTx, { error: err.message, isRedemption: true })
|
||||
.catch((err) => logger.error('Failure sending transaction notification', err))
|
||||
return cashOutActions.logError(db, 'provisionNotesError', err, newTx)
|
||||
.then(() => { throw err })
|
||||
pi.notifyOperator(newTx, {
|
||||
error: err.message,
|
||||
isRedemption: true,
|
||||
}).catch(err =>
|
||||
logger.error('Failure sending transaction notification', err),
|
||||
)
|
||||
return cashOutActions
|
||||
.logError(db, 'provisionNotesError', err, newTx)
|
||||
.then(() => {
|
||||
throw err
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
return Promise.resolve({})
|
||||
}
|
||||
|
||||
function fetchOpenTxs (statuses, fromAge, toAge) {
|
||||
function fetchOpenTxs(statuses, fromAge, toAge) {
|
||||
const sql = `select *
|
||||
from cash_out_txs
|
||||
where ((extract(epoch from (now() - created))) * 1000)>$1
|
||||
|
|
@ -103,20 +116,27 @@ function fetchOpenTxs (statuses, fromAge, toAge) {
|
|||
|
||||
const statusClause = _.map(pgp.as.text, statuses).join(',')
|
||||
|
||||
return db.any(sql, [fromAge, toAge, statusClause])
|
||||
return db
|
||||
.any(sql, [fromAge, toAge, statusClause])
|
||||
.then(rows => rows.map(toObj))
|
||||
}
|
||||
|
||||
function processTxStatus (tx, settings) {
|
||||
function processTxStatus(tx, settings) {
|
||||
const pi = plugins(settings, tx.deviceId)
|
||||
|
||||
return pi.getStatus(tx)
|
||||
.then(res => _.assign(tx, { receivedCryptoAtoms: res.receivedCryptoAtoms, status: res.status }))
|
||||
return pi
|
||||
.getStatus(tx)
|
||||
.then(res =>
|
||||
_.assign(tx, {
|
||||
receivedCryptoAtoms: res.receivedCryptoAtoms,
|
||||
status: res.status,
|
||||
}),
|
||||
)
|
||||
.then(_tx => getWalletScore(_tx, pi))
|
||||
.then(_tx => selfPost(_tx, pi))
|
||||
}
|
||||
|
||||
function getWalletScore (tx, pi) {
|
||||
function getWalletScore(tx, pi) {
|
||||
const statuses = ['published', 'authorized', 'confirmed', 'insufficientFunds']
|
||||
|
||||
if (!_.includes(tx.status, statuses) || !_.isNil(tx.walletScore)) {
|
||||
|
|
@ -124,40 +144,54 @@ function getWalletScore (tx, pi) {
|
|||
}
|
||||
|
||||
// Transaction shows up on the blockchain, we can request the sender address
|
||||
return pi.isWalletScoringEnabled(tx)
|
||||
.then(isEnabled => {
|
||||
if (!isEnabled) return tx
|
||||
return pi.rateTransaction(tx)
|
||||
.then(res =>
|
||||
res.isValid
|
||||
? _.assign(tx, { walletScore: res.score })
|
||||
: _.assign(tx, {
|
||||
return pi.isWalletScoringEnabled(tx).then(isEnabled => {
|
||||
if (!isEnabled) return tx
|
||||
return pi
|
||||
.rateTransaction(tx)
|
||||
.then(res =>
|
||||
res.isValid
|
||||
? _.assign(tx, { walletScore: res.score })
|
||||
: _.assign(tx, {
|
||||
walletScore: res.score,
|
||||
error: 'Chain analysis score is above defined threshold',
|
||||
errorCode: 'scoreThresholdReached',
|
||||
dispense: true
|
||||
})
|
||||
)
|
||||
.catch(error => _.assign(tx, {
|
||||
dispense: true,
|
||||
}),
|
||||
)
|
||||
.catch(error =>
|
||||
_.assign(tx, {
|
||||
walletScore: 10,
|
||||
error: `Failure getting address score: ${error.message}`,
|
||||
errorCode: 'walletScoringError',
|
||||
dispense: true
|
||||
}))
|
||||
})
|
||||
dispense: true,
|
||||
}),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function monitorLiveIncoming (settings) {
|
||||
function monitorLiveIncoming(settings) {
|
||||
const statuses = ['notSeen', 'published', 'insufficientFunds']
|
||||
return monitorIncoming(settings, statuses, 0, STALE_LIVE_INCOMING_TX_AGE)
|
||||
}
|
||||
|
||||
function monitorStaleIncoming (settings) {
|
||||
const statuses = ['notSeen', 'published', 'authorized', 'instant', 'rejected', 'insufficientFunds']
|
||||
return monitorIncoming(settings, statuses, STALE_LIVE_INCOMING_TX_AGE, STALE_INCOMING_TX_AGE)
|
||||
function monitorStaleIncoming(settings) {
|
||||
const statuses = [
|
||||
'notSeen',
|
||||
'published',
|
||||
'authorized',
|
||||
'instant',
|
||||
'rejected',
|
||||
'insufficientFunds',
|
||||
]
|
||||
return monitorIncoming(
|
||||
settings,
|
||||
statuses,
|
||||
STALE_LIVE_INCOMING_TX_AGE,
|
||||
STALE_INCOMING_TX_AGE,
|
||||
)
|
||||
}
|
||||
|
||||
function monitorIncoming (settings, statuses, fromAge, toAge) {
|
||||
function monitorIncoming(settings, statuses, fromAge, toAge) {
|
||||
return fetchOpenTxs(statuses, fromAge, toAge)
|
||||
.then(txs => pEachSeries(txs, tx => processTxStatus(tx, settings)))
|
||||
.catch(err => {
|
||||
|
|
@ -169,7 +203,7 @@ function monitorIncoming (settings, statuses, fromAge, toAge) {
|
|||
})
|
||||
}
|
||||
|
||||
function monitorUnnotified (settings) {
|
||||
function monitorUnnotified(settings) {
|
||||
const sql = `select *
|
||||
from cash_out_txs
|
||||
where ((extract(epoch from (now() - created))) * 1000)<$1
|
||||
|
|
@ -179,23 +213,26 @@ function monitorUnnotified (settings) {
|
|||
and (redeem=$4 or ((extract(epoch from (now() - created))) * 1000)>$5)`
|
||||
|
||||
const notify = tx => plugins(settings, tx.deviceId).notifyConfirmation(tx)
|
||||
return db.any(sql, [MAX_NOTIFY_AGE, false, false, true, MIN_NOTIFY_AGE])
|
||||
return db
|
||||
.any(sql, [MAX_NOTIFY_AGE, false, false, true, MIN_NOTIFY_AGE])
|
||||
.then(rows => _.map(toObj, rows))
|
||||
.then(txs => Promise.all(txs.map(notify)))
|
||||
.catch(logger.error)
|
||||
}
|
||||
|
||||
function cancel (txId) {
|
||||
function cancel(txId) {
|
||||
const updateRec = {
|
||||
error: 'Operator cancel',
|
||||
error_code: 'operatorCancel',
|
||||
dispense: true
|
||||
dispense: true,
|
||||
}
|
||||
|
||||
return Promise.resolve()
|
||||
.then(() => {
|
||||
return pgp.helpers.update(updateRec, null, 'cash_out_txs') +
|
||||
pgp.as.format(' where id=$1', [txId])
|
||||
return (
|
||||
pgp.helpers.update(updateRec, null, 'cash_out_txs') +
|
||||
pgp.as.format(' where id=$1', [txId])
|
||||
)
|
||||
})
|
||||
.then(sql => db.result(sql, false))
|
||||
.then(res => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue