rename cartridge to cassette

This commit is contained in:
Josh Harvey 2017-04-24 01:20:00 +03:00
parent cc32bc39e8
commit 8674816d27
9 changed files with 67 additions and 66 deletions

View file

@ -6,13 +6,13 @@ const uuid = require('uuid')
// //
// We can either require canononical denominations for 3+, or try to expand // We can either require canononical denominations for 3+, or try to expand
// this algorithm. // this algorithm.
exports.makeChange = function makeChange (cartridges, amount) { exports.makeChange = function makeChange (cassettes, amount) {
// Note: Everything here is converted to primitive numbers, // Note: Everything here is converted to primitive numbers,
// since they're all integers, well within JS number range, // since they're all integers, well within JS number range,
// and this is way more efficient in a tight loop. // and this is way more efficient in a tight loop.
const small = cartridges[0] const small = cassettes[0]
const large = cartridges[1] const large = cassettes[1]
const largeDenom = large.denomination const largeDenom = large.denomination
const smallDenom = small.denomination const smallDenom = small.denomination
@ -28,8 +28,8 @@ exports.makeChange = function makeChange (cartridges, amount) {
if (smallCount > small.count) continue if (smallCount > small.count) continue
return [ return [
{count: smallCount, denomination: small.denomination, id: uuid.v4()}, {provisioned: smallCount, denomination: small.denomination, id: uuid.v4()},
{count: i, denomination: largeDenom, id: uuid.v4()} {provisioned: i, denomination: largeDenom, id: uuid.v4()}
] ]
} }

View file

@ -169,11 +169,10 @@ function registerTrades (pi, txVector) {
function logAction (rec, tx) { function logAction (rec, tx) {
const action = { const action = {
tx_id: tx.id, tx_id: tx.id,
action: 'sendCoins', action: tx.sendCompleted ? 'sendCoins' : 'sendCoinsError',
error: rec.error, error: rec.error,
error_code: rec.errorCode, error_code: rec.errorCode,
tx_hash: rec.txHash, tx_hash: rec.txHash
success: rec.sendConfirmed === true
} }
const sql = pgp.helpers.insert(action, null, 'cash_in_actions') const sql = pgp.helpers.insert(action, null, 'cash_in_actions')

View file

@ -18,7 +18,7 @@ module.exports = {
const mapValuesWithKey = _.mapValues.convert({cap: false}) const mapValuesWithKey = _.mapValues.convert({cap: false})
const UPDATEABLE_FIELDS = ['txHash', 'status', 'dispensed', 'notified', 'redeem', const UPDATEABLE_FIELDS = ['txHash', 'status', 'dispense', 'notified', 'redeem',
'phone', 'error', 'confirmationTime', 'swept'] 'phone', 'error', 'confirmationTime', 'swept']
const STALE_INCOMING_TX_AGE = T.week const STALE_INCOMING_TX_AGE = T.week
@ -27,6 +27,7 @@ const MAX_NOTIFY_AGE = 2 * T.days
const MIN_NOTIFY_AGE = 5 * T.minutes const MIN_NOTIFY_AGE = 5 * T.minutes
function post (tx, pi) { function post (tx, pi) {
console.log('DEBUG101: %j', tx)
const TransactionMode = pgp.txMode.TransactionMode const TransactionMode = pgp.txMode.TransactionMode
const isolationLevel = pgp.txMode.isolationLevel const isolationLevel = pgp.txMode.isolationLevel
const tmSRD = new TransactionMode({tiLevel: isolationLevel.serializable}) const tmSRD = new TransactionMode({tiLevel: isolationLevel.serializable})
@ -49,19 +50,14 @@ function post (tx, pi) {
const [, newTx] = txVector const [, newTx] = txVector
return postProcess(txVector, pi) return postProcess(txVector, pi)
.then(changes => update(newTx, changes)) .then(changes => update(newTx, changes))
.then(savedTx => {
return logAction(tx, savedTx)
.then(_.constant(savedTx))
})
}) })
} }
function logError (action, err) { function logError (action, err, tx) {
return logAction({ return logAction(action, {
action,
error: err.message, error: err.message,
error_code: err.name error_code: err.name
}) }, tx)
} }
function mapDispense (tx) { function mapDispense (tx) {
@ -69,25 +65,23 @@ function mapDispense (tx) {
if (_.isEmpty(bills)) return {} if (_.isEmpty(bills)) return {}
const dispense = { return {
provisioned_1: bills[0].provisioned, provisioned_1: bills[0].provisioned,
provisioned_2: bills[1].provisioned, provisioned_2: bills[1].provisioned,
dispensed_1: bills[0].actualDispense, dispensed_1: bills[0].dispensed,
dispensed_2: bills[1].actualDispense, dispensed_2: bills[1].dispensed,
rejected_1: bills[0].rejected, rejected_1: bills[0].rejected,
rejected_2: bills[1].rejected, rejected_2: bills[1].rejected,
denomination_1: bills[0].denomination, denomination_1: bills[0].denomination,
denomination_2: bills[1].denomination denomination_2: bills[1].denomination
} }
return dispense
} }
function logDispense (tx) { function logDispense (tx) {
const baseRec = {error: tx.error, errorCode: tx.errorCode} const baseRec = {error: tx.error, error_code: tx.errorCode}
const rec = _.merge(mapDispense(tx), baseRec) const rec = _.merge(mapDispense(tx), baseRec)
const action = tx.dispenseConfirmed ? 'dispense' : 'dispenseError'
return logAction('dispense', rec, tx) return logAction(action, rec, tx)
} }
function logActionById (action, _rec, txId) { function logActionById (action, _rec, txId) {
@ -98,9 +92,10 @@ function logActionById (action, _rec, txId) {
} }
function logAction (action, _rec, tx) { function logAction (action, _rec, tx) {
const rec = _.assign(_rec, {action, tx_id: tx.id, redeem: tx.redeem}) const rec = _.assign(_rec, {action, tx_id: tx.id, redeem: !!tx.redeem})
const sql = pgp.helpers.insert(rec, null, 'cash_out_actions') const sql = pgp.helpers.insert(rec, null, 'cash_out_actions')
console.log('DEBUG110: %j', sql)
return db.none(sql) return db.none(sql)
.then(_.constant(tx)) .then(_.constant(tx))
} }
@ -217,11 +212,11 @@ function preProcess (oldTx, newTx, pi) {
.then(_.set('toAddress', _, newTxHd)) .then(_.set('toAddress', _, newTxHd))
}) })
.then(addressedTx => { .then(addressedTx => {
const rec = {toAddress: addressedTx.toAddress} const rec = {to_address: addressedTx.toAddress}
return logAction('provisionAddress', rec, addressedTx) return logAction('provisionAddress', rec, addressedTx)
}) })
.catch(err => { .catch(err => {
return logError('provisionAddress', err) return logError('provisionAddress', err, newTx)
.then(() => { throw err }) .then(() => { throw err })
}) })
} }
@ -234,7 +229,9 @@ function preProcess (oldTx, newTx, pi) {
return logAction(updatedTx.status, {}, updatedTx) return logAction(updatedTx.status, {}, updatedTx)
} }
if (_.isNil(oldTx.dispenseConfirmed) && _.isBoolean(updatedTx.dispenseConfirmed)) { console.log('DEBUG120: %j', [oldTx, updatedTx])
if (!oldTx.dispenseConfirmed && updatedTx.dispenseConfirmed) {
console.log('DEBUG121')
return logDispense(updatedTx) return logDispense(updatedTx)
.then(pi.updateCassettes(updatedTx)) .then(pi.updateCassettes(updatedTx))
} }
@ -254,18 +251,24 @@ function preProcess (oldTx, newTx, pi) {
function postProcess (txVector, pi) { function postProcess (txVector, pi) {
const [, newTx] = txVector const [, newTx] = txVector
if (newTx.dispensed && !newTx.bills) { if (newTx.dispense && !newTx.bills) {
return pi.buildCartridges() return pi.buildCassettes()
.then(cartridges => { .then(cassettes => {
pi.sell(newTx) pi.sell(newTx)
return _.set('bills', billMath.makeChange(cartridges.cartridges, newTx.fiat), newTx) return _.set('bills', billMath.makeChange(cassettes.cassettes, newTx.fiat), newTx)
}) })
.then(tx => { .then(tx => {
const rec = {provisioned_1: tx.bills[0], provisioned_2: tx.bills[1]} const rec = {
provisioned_1: tx.bills[0].provisioned,
provisioned_2: tx.bills[1].provisioned,
denomination_1: tx.bills[0].denomination,
denomination_2: tx.bills[1].denomination
}
return logAction('provisionNotes', rec, tx) return logAction('provisionNotes', rec, tx)
}) })
.catch(err => { .catch(err => {
return logError('provisionNotes', err) return logError('provisionNotesError', err, newTx)
.then(() => { throw err }) .then(() => { throw err })
}) })
} }
@ -333,7 +336,7 @@ function monitorUnnotified (settings) {
const sql = `select * const sql = `select *
from cash_out_txs from cash_out_txs
where ((extract(epoch from (now() - created))) * 1000)<$1 where ((extract(epoch from (now() - created))) * 1000)<$1
and notified=$2 and dispensed=$3 and notified=$2 and dispense=$3
and phone is not null and phone is not null
and status in ('instant', 'confirmed') and status in ('instant', 'confirmed')
and (redeem=$4 or ((extract(epoch from (now() - created))) * 1000)>$5)` and (redeem=$4 or ((extract(epoch from (now() - created))) * 1000)>$5)`
@ -349,7 +352,7 @@ function cancel (txId) {
const updateRec = { const updateRec = {
'dispense_time': 'now()^', 'dispense_time': 'now()^',
error: 'Operator cancel', error: 'Operator cancel',
dispensed: true dispense: true
} }
return Promise.resolve() return Promise.resolve()

View file

@ -72,47 +72,47 @@ function plugins (settings, deviceId) {
return balances return balances
} }
function buildCartridges () { function buildCassettes () {
const config = configManager.machineScoped(deviceId, settings.config) const config = configManager.machineScoped(deviceId, settings.config)
if (!config.cashOutEnabled) return Promise.resolve() if (!config.cashOutEnabled) return Promise.resolve()
const cartridges = [ config.topCashOutDenomination, const cassettes = [ config.topCashOutDenomination,
config.bottomCashOutDenomination ] config.bottomCashOutDenomination ]
const virtualCartridges = [config.virtualCashOutDenomination] const virtualCassettes = [config.virtualCashOutDenomination]
return dbm.cartridgeCounts(deviceId) return dbm.cassetteCounts(deviceId)
.then(rec => { .then(rec => {
if (argv.cassettes) { if (argv.cassettes) {
const counts = argv.cassettes.split(',') const counts = argv.cassettes.split(',')
return { return {
cartridges: [ cassettes: [
{ {
denomination: parseInt(cartridges[0], 10), denomination: parseInt(cassettes[0], 10),
count: parseInt(counts[0], 10) count: parseInt(counts[0], 10)
}, },
{ {
denomination: parseInt(cartridges[1], 10), denomination: parseInt(cassettes[1], 10),
count: parseInt(counts[1], 10) count: parseInt(counts[1], 10)
} }
], ],
virtualCartridges virtualCassettes
} }
} }
return { return {
cartridges: [ cassettes: [
{ {
denomination: parseInt(cartridges[0], 10), denomination: parseInt(cassettes[0], 10),
count: parseInt(rec.counts[0], 10) count: parseInt(rec.counts[0], 10)
}, },
{ {
denomination: parseInt(cartridges[1], 10), denomination: parseInt(cassettes[1], 10),
count: parseInt(rec.counts[1], 10) count: parseInt(rec.counts[1], 10)
} }
], ],
virtualCartridges virtualCassettes
} }
}) })
} }
@ -138,20 +138,20 @@ function plugins (settings, deviceId) {
const currentConfigVersionPromise = fetchCurrentConfigVersion() const currentConfigVersionPromise = fetchCurrentConfigVersion()
const promises = [ const promises = [
buildCartridges(), buildCassettes(),
pingPromise, pingPromise,
currentConfigVersionPromise currentConfigVersionPromise
].concat(tickerPromises, balancePromises) ].concat(tickerPromises, balancePromises)
return Promise.all(promises) return Promise.all(promises)
.then(arr => { .then(arr => {
const cartridges = arr[0] const cassettes = arr[0]
const currentConfigVersion = arr[2] const currentConfigVersion = arr[2]
const tickers = arr.slice(3, cryptoCodes.length + 3) const tickers = arr.slice(3, cryptoCodes.length + 3)
const balances = arr.slice(cryptoCodes.length + 3) const balances = arr.slice(cryptoCodes.length + 3)
return { return {
cartridges, cassettes,
rates: buildRates(tickers), rates: buildRates(tickers),
balances: buildBalances(balances), balances: buildBalances(balances),
currentConfigVersion currentConfigVersion
@ -194,10 +194,10 @@ function plugins (settings, deviceId) {
function dispenseAck (tx) { function dispenseAck (tx) {
const config = configManager.machineScoped(deviceId, settings.config) const config = configManager.machineScoped(deviceId, settings.config)
const cartridges = [ config.topCashOutDenomination, const cassettes = [ config.topCashOutDenomination,
config.bottomCashOutDenomination ] config.bottomCashOutDenomination ]
return dbm.addDispense(deviceId, tx, cartridges) return dbm.addDispense(deviceId, tx, cassettes)
} }
function fiatBalance (fiatCode, cryptoCode) { function fiatBalance (fiatCode, cryptoCode) {
@ -517,9 +517,9 @@ function plugins (settings, deviceId) {
// However, we should make all config changes atomic in the future. // However, we should make all config changes atomic in the future.
const config = configManager.machineScoped(deviceId, settings.config) const config = configManager.machineScoped(deviceId, settings.config)
const topCashOutDenomination = config.topCashOutDenomination - const topCashOutDenomination = config.topCashOutDenomination -
(tx.bills[0].actualDispense + tx.bills[0].rejected) (tx.bills[0].dispensed + tx.bills[0].rejected)
const bottomCashOutDenomination = config.bottomCashOutDenomination - const bottomCashOutDenomination = config.bottomCashOutDenomination -
(tx.bills[1].actualDispense + tx.bills[1].rejected) (tx.bills[1].dispensed + tx.bills[1].rejected)
const newFields = [ const newFields = [
{ {
@ -575,7 +575,7 @@ function plugins (settings, deviceId) {
sweepHd, sweepHd,
sendMessage, sendMessage,
checkBalances, checkBalances,
buildCartridges, buildCassettes,
updateCassettes, updateCassettes,
buy, buy,
sell sell

View file

@ -23,7 +23,7 @@ exports.recordDeviceEvent = function recordDeviceEvent (deviceId, event) {
return db.none(sql, values) return db.none(sql, values)
} }
exports.cartridgeCounts = function cartridgeCounts (deviceId) { exports.cassetteCounts = function cassetteCounts (deviceId) {
const sql = 'SELECT cassette1, cassette2 FROM devices ' + const sql = 'SELECT cassette1, cassette2 FROM devices ' +
'WHERE device_id=$1' 'WHERE device_id=$1'

View file

@ -49,7 +49,7 @@ function toObj (row) {
function fetchPhoneTx (phone) { function fetchPhoneTx (phone) {
const sql = `select * from cash_out_txs const sql = `select * from cash_out_txs
where phone=$1 and dispensed=$2 where phone=$1 and dispense=$2
and (extract(epoch from (coalesce(confirmation_time, now()) - created))) * 1000 < $3` and (extract(epoch from (coalesce(confirmation_time, now()) - created))) * 1000 < $3`
const values = [phone, false, TRANSACTION_EXPIRATION] const values = [phone, false, TRANSACTION_EXPIRATION]

View file

@ -38,7 +38,7 @@ function poll (req, res, next) {
return pi.pollQueries(deviceTime, req.query) return pi.pollQueries(deviceTime, req.query)
.then(results => { .then(results => {
const cartridges = results.cartridges const cassettes = results.cassettes
const reboot = pid && reboots[deviceId] && reboots[deviceId] === pid const reboot = pid && reboots[deviceId] && reboots[deviceId] === pid
const langs = config.machineLanguages const langs = config.machineLanguages
@ -58,7 +58,7 @@ function poll (req, res, next) {
txLimit: config.cashInTransactionLimit, txLimit: config.cashInTransactionLimit,
idVerificationEnabled: config.idVerificationEnabled, idVerificationEnabled: config.idVerificationEnabled,
smsVerificationEnabled: config.smsVerificationEnabled, smsVerificationEnabled: config.smsVerificationEnabled,
cartridges, cassettes,
twoWayMode: config.cashOutEnabled, twoWayMode: config.cashOutEnabled,
zeroConfLimit: config.zeroConfLimit, zeroConfLimit: config.zeroConfLimit,
fiatTxLimit: config.cashOutTransactionLimit, fiatTxLimit: config.cashOutTransactionLimit,

View file

@ -4,12 +4,11 @@ exports.up = function (next) {
var sql = [ var sql = [
`create table cash_in_actions ( `create table cash_in_actions (
id serial primary key, id serial primary key,
tx_id uuid references cash_in_txs not null, tx_id uuid not null,
action text not null, action text not null,
error text, error text,
error_code text, error_code text,
tx_hash text, tx_hash text,
success boolean not null,
created timestamptz not null default now() created timestamptz not null default now()
)` )`
] ]

View file

@ -4,13 +4,12 @@ exports.up = function (next) {
var sql = [ var sql = [
`create table cash_out_actions ( `create table cash_out_actions (
id serial primary key, id serial primary key,
tx_id uuid references cash_out_txs not null, tx_id uuid not null,
action text not null, action text not null,
to_address text, to_address text,
error text, error text,
error_code text, error_code text,
tx_hash text, tx_hash text,
success boolean not null,
provisioned_1 integer, provisioned_1 integer,
provisioned_2 integer, provisioned_2 integer,
dispensed_1 integer, dispensed_1 integer,
@ -30,7 +29,8 @@ exports.up = function (next) {
'alter table cash_out_txs drop column denomination_1', 'alter table cash_out_txs drop column denomination_1',
'alter table cash_out_txs drop column denomination_2', 'alter table cash_out_txs drop column denomination_2',
'alter table cash_out_txs drop column dispense_error', 'alter table cash_out_txs drop column dispense_error',
'alter table cash_out_txs add column dispense_confirmed boolean default false' 'alter table cash_out_txs add column dispense_confirmed boolean default false',
'alter table cash_out_txs rename column dispensed to dispense'
] ]
db.multi(sql, next) db.multi(sql, next)
} }