diff --git a/lib/postgresql_interface.js b/lib/postgresql_interface.js index 0ef47907..d21fad3f 100644 --- a/lib/postgresql_interface.js +++ b/lib/postgresql_interface.js @@ -15,6 +15,8 @@ function inspect(rec) { } */ +var SATOSHI_FACTOR = 1e8; + function isUniqueViolation(err) { return err.code === '23505'; } @@ -170,10 +172,34 @@ function billsAndTxs(client, session, cb) { }); } + +// TODO: these should broken out to a common library, they are used by both +// lamassu-machine and lamassu-server and need to stay in sync. +function bitcoinFractionalDigits(amount) { + var log = Math.floor(Math.log(amount) / Math.log(10)); + return (log > 0) ? 2 : 2 - log; +} + +function truncateBitcoins(bitcoins) { + var decimalDigits = bitcoinFractionalDigits(bitcoins); + var adjuster = Math.pow(10, decimalDigits); + return (Math.round(bitcoins * adjuster) / adjuster); +} + +function truncateSatoshis(satoshis) { + var bitcoins = satoshis / SATOSHI_FACTOR; + var truncated = truncateBitcoins(bitcoins); + return Math.round(truncated * SATOSHI_FACTOR); +} +// END TODO + function computeSendAmount(tx, totals) { + var fiatRemaining = (tx.fiat || totals.billsFiat) - totals.txFiat; + var satoshisRemaining = (tx.satoshis || totals.billsSatoshis) - + totals.txSatoshis; var result = { - fiat: (tx.fiat || totals.billsFiat) - totals.txFiat, - satoshis: (tx.satoshis || totals.billsSatoshis) - totals.txSatoshis + fiat: fiatRemaining, + satoshis: truncateSatoshis(satoshisRemaining) }; if (result.fiat < 0 || result.satoshis < 0) { logger.warn({tx: tx, totals: totals, result: result},