chore: update big number package

This commit is contained in:
José Oliveira 2021-06-15 22:34:36 +01:00 committed by Josh Harvey
parent 8aa18dd21c
commit ea44478b48
30 changed files with 186 additions and 144 deletions

View file

@ -15,7 +15,7 @@ function computeCrypto (cryptoCode, value) {
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
return BN(value).shift(unitScale)
return new BN(value).shiftedBy(unitScale)
} catch (err) {
return null
}

View file

@ -3,7 +3,7 @@ const BN = require('../lib/bn')
const account = {token: 'xxx'}
strike.newAddress(account, {cryptoCode: 'BTC', cryptoAtoms: BN(10000)})
strike.newAddress(account, { cryptoCode: 'BTC', cryptoAtoms: new BN(10000) })
.then(r => {
console.log(r)

View file

@ -43,14 +43,14 @@ function computeCrypto (cryptoCode, _balance) {
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
return BN(_balance).shift(-unitScale).round(5)
return new BN(_balance).shiftedBy(-unitScale).decimalPlaces(5)
}
function computeFiat (rate, cryptoCode, _balance) {
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
return BN(_balance).shift(-unitScale).mul(rate).round(5)
return new BN(_balance).shiftedBy(-unitScale).times(rate).decimalPlaces(5)
}
function getFunding (_cryptoCode) {
@ -75,7 +75,7 @@ function getFunding (_cryptoCode) {
return Promise.all(promises)
.then(([fundingRec, ratesRec]) => {
const rates = ratesRec.rates
const rate = (rates.ask.add(rates.bid)).div(2)
const rate = (rates.ask.plus(rates.bid)).div(2)
const fundingConfirmedBalance = fundingRec.fundingConfirmedBalance
const fiatConfirmedBalance = computeFiat(rate, cryptoCode, fundingConfirmedBalance)
const pending = fundingRec.fundingPendingBalance

View file

@ -20,10 +20,9 @@ const massageUpdates = _.flow(_.omit(massageUpdateFields),
module.exports = {toObj, upsert, insert, update, massage, isClearToSend}
function convertBigNumFields (obj) {
const convert = value => value && value.isBigNumber
const convert = value => value && value._isBigNumber
? value.toString()
: value
return _.mapValues(convert, obj)
}
@ -36,7 +35,7 @@ function toObj (row) {
keys.forEach(key => {
const objKey = _.camelCase(key)
if (_.includes(key, ['crypto_atoms', 'fiat', 'cash_in_fee', 'cash_in_fee_crypto', 'commission_percentage', 'raw_ticker_price'])) {
newObj[objKey] = BN(row[key])
newObj[objKey] = new BN(row[key])
return
}
@ -114,7 +113,7 @@ function ensureRatchet (oldField, newField, fieldKey) {
}
if (_.isNil(newField)) return false
if (oldField.isBigNumber && newField.isBigNumber) return BN(oldField).eq(newField)
if (oldField.isBigNumber && newField.isBigNumber) return new BN(oldField).eq(newField)
if (oldField.toString() === newField.toString()) return true
return false

View file

@ -71,11 +71,11 @@ function toObj (row) {
keys.forEach(key => {
const objKey = _.camelCase(key)
if (key === 'received_crypto_atoms' && row[key]) {
newObj[objKey] = BN(row[key])
newObj[objKey] = new BN(row[key])
return
}
if (_.includes(key, ['crypto_atoms', 'fiat', 'commission_percentage', 'raw_ticker_price'])) {
newObj[objKey] = BN(row[key])
newObj[objKey] = new BN(row[key])
return
}

View file

@ -1,5 +1,5 @@
const yup = require('yup')
const BigNumber = require('../../../lib/bn')
const BN = require('../../../lib/bn')
const car = require('../coinatmradar')
const db = require('../../db')
@ -108,43 +108,43 @@ const settings = {
const rates = [
{
rates: {
ask: BigNumber(19164.3),
bid: BigNumber(19164.2)
ask: new BN(19164.3),
bid: new BN(19164.2)
},
timestamp: +new Date()
},
{
rates: {
ask: BigNumber(594.54),
bid: BigNumber(594.09)
ask: new BN(594.54),
bid: new BN(594.09)
},
timestamp: +new Date()
},
{
rates: {
ask: BigNumber(84.38),
bid: BigNumber(84.37)
ask: new BN(84.38),
bid: new BN(84.37)
},
timestamp: +new Date()
},
{
rates: {
ask: BigNumber(102.8),
bid: BigNumber(101.64)
ask: new BN(102.8),
bid: new BN(101.64)
},
timestamp: +new Date()
},
{
rates: {
ask: BigNumber(74.91),
bid: BigNumber(74.12)
ask: new BN(74.91),
bid: new BN(74.12)
},
timestamp: +new Date()
},
{
rates: {
ask: BigNumber(284.4),
bid: BigNumber(284.4)
ask: new BN(284.4),
bid: new BN(284.4)
},
timestamp: +new Date()
}

View file

@ -7,31 +7,31 @@ function truncateCrypto (cryptoAtoms, cryptoCode) {
if (cryptoAtoms.eq(0)) return cryptoAtoms
const scale = coinUtils.getCryptoCurrency(cryptoCode).displayScale
const scaleFactor = BN(10).pow(scale)
const scaleFactor = new BN(10).pow(scale)
return BN(cryptoAtoms).truncated().div(scaleFactor)
.round(DECIMAL_PLACES).times(scaleFactor)
return new BN(cryptoAtoms).integerValue(BN.ROUND_DOWN).div(scaleFactor)
.decimalPlaces(DECIMAL_PLACES).times(scaleFactor)
}
function fiatToCrypto (tx, rec, deviceId, config) {
const usableFiat = rec.fiat - rec.cashInFee
const commissions = configManager.getCommissions(tx.cryptoCode, deviceId, config)
const tickerRate = BN(tx.rawTickerPrice)
const tickerRate = new BN(tx.rawTickerPrice)
const discount = getDiscountRate(tx.discount, commissions[tx.direction])
const rate = tickerRate.mul(discount).round(5)
const rate = tickerRate.times(discount).decimalPlaces(5)
const unitScale = coinUtils.getCryptoCurrency(tx.cryptoCode).unitScale
const unitScaleFactor = BN(10).pow(unitScale)
const unitScaleFactor = new BN(10).pow(unitScale)
return truncateCrypto(BN(usableFiat).div(rate.div(unitScaleFactor)), tx.cryptoCode)
return truncateCrypto(new BN(usableFiat).div(rate.div(unitScaleFactor)), tx.cryptoCode)
}
function getDiscountRate (discount, commission) {
const bnDiscount = discount ? BN(discount) : BN(0)
const bnCommission = BN(commission)
const percentageDiscount = BN(1).sub(bnDiscount.div(100))
const bnDiscount = discount ? new BN(discount) : new BN(0)
const bnCommission = new BN(commission)
const percentageDiscount = new BN(1).minus(bnDiscount.div(100))
const percentageCommission = bnCommission.div(100)
return BN(1).add(percentageDiscount.mul(percentageCommission))
return new BN(1).plus(percentageDiscount.times(percentageCommission))
}
module.exports = {

View file

@ -165,7 +165,7 @@ function getById (id, userToken) {
function getDailyVolume (id, txId) {
const queries = txId ? getDailyVolumeMinusCurrentTxQueries(id, txId) : getDailyVolumeQueries(id)
return Promise.all(queries).then(([cashIn, cashOut]) => {
const dailyVolume = BN(cashIn.total).add(cashOut.total)
const dailyVolume = new BN(cashIn.total).plus(cashOut.total)
const hoursTillLimitClear = getHoursTillLimitClear(cashIn.maxdate, cashOut.maxdate)
return { dailyVolume, hoursTillLimitClear }
})

View file

@ -10,14 +10,14 @@ function computeCrypto (cryptoCode, _balance) {
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
return BN(_balance).shift(-unitScale).round(5)
return new BN(_balance).shiftedBy(-unitScale).decimalPlaces(5)
}
function computeFiat (rate, cryptoCode, _balance) {
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
return BN(_balance).shift(-unitScale).mul(rate).round(5)
return new BN(_balance).shiftedBy(-unitScale).times(rate).decimalPlaces(5)
}
function getSingleCoinFunding (settings, fiatCode, cryptoCode) {
@ -29,7 +29,7 @@ function getSingleCoinFunding (settings, fiatCode, cryptoCode) {
return Promise.all(promises)
.then(([fundingRec, ratesRec]) => {
const rates = ratesRec.rates
const rate = (rates.ask.add(rates.bid)).div(2)
const rate = (rates.ask.plus(rates.bid)).div(2)
const fundingConfirmedBalance = fundingRec.fundingConfirmedBalance
const fiatConfirmedBalance = computeFiat(rate, cryptoCode, fundingConfirmedBalance)
const pending = fundingRec.fundingPendingBalance

View file

@ -1,4 +1,4 @@
const BigNumber = require('../../../lib/bn')
const BN = require('../../../lib/bn')
const notifier = require('..')
const utils = require('../utils')
@ -47,9 +47,9 @@ const tx = {
deviceId:
'490ab16ee0c124512dc769be1f3e7ee3894ce1e5b4b8b975e134fb326e551e88',
toAddress: 'bc1q7s4yy5n9vp6zhlf6mrw3cttdgx5l3ysr2mhc4v',
cryptoAtoms: BigNumber(252100),
cryptoAtoms: new BN(252100),
cryptoCode: 'BTC',
fiat: BigNumber(55),
fiat: new BN(55),
fiatCode: 'USD',
fee: null,
txHash: null,
@ -63,14 +63,14 @@ const tx = {
errorCode: null,
operatorCompleted: false,
sendPending: true,
cashInFee: BigNumber(2),
cashInFeeCrypto: BigNumber(9500),
cashInFee: new BN(2),
cashInFeeCrypto: new BN(9500),
minimumTx: 5,
customerId: '47ac1184-8102-11e7-9079-8f13a7117867',
txVersion: 6,
termsAccepted: false,
commissionPercentage: BigNumber(0.11),
rawTickerPrice: BigNumber(18937.4),
commissionPercentage: new BN(0.11),
rawTickerPrice: new BN(18937.4),
isPaperWallet: false,
direction: 'cashIn'
}

View file

@ -52,21 +52,21 @@ function plugins (settings, deviceId) {
if (!rateRec) return
const cashInCommission = BN(1).add(BN(commissions.cashIn).div(100))
const cashInCommission = new BN(1).plus(new BN(commissions.cashIn).div(100))
const cashOutCommission = _.isNil(commissions.cashOut)
? undefined
: BN(1).add(BN(commissions.cashOut).div(100))
: new BN(1).plus(new BN(commissions.cashOut).div(100))
if (Date.now() - rateRec.timestamp > STALE_TICKER) return logger.warn('Stale rate for ' + cryptoCode)
const rate = rateRec.rates
withCommission ? rates[cryptoCode] = {
cashIn: rate.ask.mul(cashInCommission).round(5),
cashOut: cashOutCommission && rate.bid.div(cashOutCommission).round(5)
cashIn: rate.ask.times(cashInCommission).decimalPlaces(5),
cashOut: cashOutCommission && rate.bid.div(cashOutCommission).decimalPlaces(5)
} : rates[cryptoCode] = {
cashIn: rate.ask.round(5),
cashOut: rate.bid.round(5)
cashIn: rate.ask.decimalPlaces(5),
cashOut: rate.bid.decimalPlaces(5)
}
})
return rates
@ -200,10 +200,10 @@ function plugins (settings, deviceId) {
const cryptoCode = coinParams[0]
const cryptoNetwork = coinParams[1]
const commissions = configManager.getCommissions(cryptoCode, deviceId, settings.config)
const minimumTx = BN(commissions.minimumTx)
const cashInFee = BN(commissions.fixedFee)
const cashInCommission = BN(commissions.cashIn)
const cashOutCommission = _.isNumber(commissions.cashOut) ? BN(commissions.cashOut) : null
const minimumTx = new BN(commissions.minimumTx)
const cashInFee = new BN(commissions.fixedFee)
const cashInCommission = new BN(commissions.cashIn)
const cashOutCommission = _.isNumber(commissions.cashOut) ? new BN(commissions.cashOut) : null
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
return {
@ -326,23 +326,23 @@ function plugins (settings, deviceId) {
if (!rates || !balanceRec) return null
const rawRate = rates.rates.ask
const cashInCommission = BN(1).minus(BN(commissions.cashIn).div(100))
const cashInCommission = new BN(1).minus(new BN(commissions.cashIn).div(100))
const balance = balanceRec.balance
if (!rawRate || !balance) return null
const rate = rawRate.div(cashInCommission)
const lowBalanceMargin = BN(1.03)
const lowBalanceMargin = new BN(1.03)
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
const shiftedRate = rate.shift(-unitScale)
const fiatTransferBalance = balance.mul(shiftedRate).div(lowBalanceMargin)
const shiftedRate = rate.shiftedBy(-unitScale)
const fiatTransferBalance = balance.times(shiftedRate).div(lowBalanceMargin)
return {
timestamp: balanceRec.timestamp,
balance: fiatTransferBalance.truncated().toString()
balance: fiatTransferBalance.integerValue(BN.ROUND_DOWN).toString()
}
})
}
@ -400,7 +400,7 @@ function plugins (settings, deviceId) {
function buyAndSell (rec, doBuy, tx) {
const cryptoCode = rec.cryptoCode
const fiatCode = rec.fiatCode
const cryptoAtoms = doBuy ? commissionMath.fiatToCrypto(tx, rec, deviceId, settings.config) : rec.cryptoAtoms.neg()
const cryptoAtoms = doBuy ? commissionMath.fiatToCrypto(tx, rec, deviceId, settings.config) : rec.cryptoAtoms.negated()
const market = [fiatCode, cryptoCode].join('')
@ -449,7 +449,7 @@ function plugins (settings, deviceId) {
const [cashInTxs, cashOutTxs] = _.compose(partitionByDirection, _.uniqBy('internalTxId'))(filtered)
const cryptoAtoms = filtered
.reduce((prev, current) => prev.plus(current.cryptoAtoms), BN(0))
.reduce((prev, current) => prev.plus(current.cryptoAtoms), new BN(0))
const timestamp = filtered.map(r => r.timestamp).reduce((acc, r) => Math.max(acc, r), 0)
@ -669,11 +669,11 @@ function plugins (settings, deviceId) {
fiatCode
}
if (_.isFinite(lowAlertThreshold) && BN(fiatBalance.balance).lt(lowAlertThreshold)) {
if (_.isFinite(lowAlertThreshold) && new BN(fiatBalance.balance).lt(lowAlertThreshold)) {
return _.set('code')('LOW_CRYPTO_BALANCE')(req)
}
if (_.isFinite(highAlertThreshold) && BN(fiatBalance.balance).gt(highAlertThreshold)) {
if (_.isFinite(highAlertThreshold) && new BN(fiatBalance.balance).gt(highAlertThreshold)) {
return _.set('code')('HIGH_CRYPTO_BALANCE')(req)
}
@ -695,7 +695,7 @@ function plugins (settings, deviceId) {
}
function randomCode () {
return BN(crypto.randomBytes(3).toString('hex'), 16).shift(-6).toFixed(6).slice(-6)
return new BN(crypto.randomBytes(3).toString('hex'), 16).shiftedBy(-6).toFixed(6).slice(-6)
}
function getPhoneCode (phone) {

View file

@ -11,7 +11,7 @@ function ticker (fiatCode, cryptoCode) {
return axios.get('https://bitpay.com/rates/' + cryptoCode + '/' + fiatCode)
.then(r => {
const data = r.data.data
const price = BN(data.rate.toString())
const price = new BN(data.rate.toString())
return {
rates: {
ask: price,

View file

@ -40,8 +40,8 @@ function getCurrencyRates (ticker, fiatCode, cryptoCode) {
return ticker.fetchTicker(symbol)
.then(res => ({
rates: {
ask: BN(res.ask),
bid: BN(res.bid)
ask: new BN(res.ask),
bid: new BN(res.bid)
}
}))
} catch (e) {
@ -52,7 +52,7 @@ function getCurrencyRates (ticker, fiatCode, cryptoCode) {
function findCurrencyRates (fxRates, fiatCode) {
const rates = _.find(_.matchesProperty('code', fiatCode), fxRates)
if (!rates || !rates.rate) throw new Error(`Unsupported currency: ${fiatCode}`)
return BN(rates.rate.toString())
return new BN(rates.rate.toString())
}
module.exports = { ticker }

View file

@ -3,8 +3,8 @@ const BN = require('../../bn')
function ticker (fiatCode, cryptoCode) {
return Promise.resolve({
rates: {
ask: BN(105),
bid: BN(100)
ask: new BN(105),
bid: new BN(100)
}
})
}

View file

@ -35,13 +35,13 @@ function checkCryptoCode (cryptoCode) {
function accountBalance (cryptoCode) {
return checkCryptoCode(cryptoCode)
.then(() => fetch('getwalletinfo'))
.then(({ balance }) => BN(balance).shift(unitScale).round())
.then(({ balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
}
function accountUnconfirmedBalance (cryptoCode) {
return checkCryptoCode(cryptoCode)
.then(() => fetch('getwalletinfo'))
.then(({ unconfirmed_balance: balance }) => BN(balance).shift(unitScale).round())
.then(({ unconfirmed_balance: balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
}
// We want a balance that includes all spends (0 conf) but only deposits that
@ -52,14 +52,14 @@ function balance (account, cryptoCode, settings, operatorId) {
function sendCoins (account, tx, settings, operatorId) {
const { toAddress, cryptoAtoms, cryptoCode } = tx
const coins = cryptoAtoms.shift(-unitScale).toFixed(8)
const coins = cryptoAtoms.shiftedBy(-unitScale).toFixed(8)
return checkCryptoCode(cryptoCode)
.then(() => fetch('sendtoaddress', [toAddress, coins]))
.then((txId) => fetch('gettransaction', [txId]))
.then((res) => _.pick(['fee', 'txid'], res))
.then((pickedObj) => {
return {
fee: BN(pickedObj.fee).abs().shift(unitScale).round(),
fee: new BN(pickedObj.fee).abs().shiftedBy(unitScale).decimalPlaces(0),
txid: pickedObj.txid
}
})
@ -76,7 +76,7 @@ function newAddress (account, info, tx, settings, operatorId) {
function addressBalance (address, confs) {
return fetch('getreceivedbyaddress', [address, confs])
.then(r => BN(r).shift(unitScale).round())
.then(r => new BN(r).shiftedBy(unitScale).decimalPlaces(0))
}
function confirmedBalance (address, cryptoCode) {

View file

@ -35,13 +35,13 @@ function checkCryptoCode (cryptoCode) {
function accountBalance (cryptoCode) {
return checkCryptoCode(cryptoCode)
.then(() => fetch('getwalletinfo'))
.then(({ balance }) => BN(balance).shift(unitScale).round())
.then(({ balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
}
function accountUnconfirmedBalance (cryptoCode) {
return checkCryptoCode(cryptoCode)
.then(() => fetch('getwalletinfo'))
.then(({ unconfirmed_balance: balance }) => BN(balance).shift(unitScale).round())
.then(({ unconfirmed_balance: balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
}
// We want a balance that includes all spends (0 conf) but only deposits that
@ -52,7 +52,7 @@ function balance (account, cryptoCode, settings, operatorId) {
function sendCoins (account, tx, settings, operatorId) {
const { toAddress, cryptoAtoms, cryptoCode } = tx
const coins = cryptoAtoms.shift(-unitScale).toFixed(8)
const coins = cryptoAtoms.shiftedBy(-unitScale).toFixed(8)
return checkCryptoCode(cryptoCode)
.then(() => fetch('sendtoaddress', [toAddress, coins]))
@ -60,7 +60,7 @@ function sendCoins (account, tx, settings, operatorId) {
.then((res) => _.pick(['fee', 'txid'], res))
.then((pickedObj) => {
return {
fee: BN(pickedObj.fee).abs().shift(unitScale).round(),
fee: new BN(pickedObj.fee).abs().shiftedBy(unitScale).decimalPlaces(0),
txid: pickedObj.txid
}
})
@ -77,7 +77,7 @@ function newAddress (account, info, tx, settings, operatorId) {
function addressBalance (address, confs) {
return fetch('getreceivedbyaddress', [address, confs])
.then(r => BN(r).shift(unitScale).round())
.then(r => new BN(r).shiftedBy(unitScale).decimalPlaces(0))
}
function confirmedBalance (address, cryptoCode) {

View file

@ -70,7 +70,7 @@ function sendCoins (account, tx, settings, operatorId) {
let fee = parseFloat(result.transfer.feeString)
let txid = result.transfer.txid
return { txid: txid, fee: BN(fee).round() }
return { txid: txid, fee: new BN(fee).decimalPlaces(0) }
})
.catch(err => {
if (err.message === 'insufficient funds') throw new E.InsufficientFundsError()
@ -81,7 +81,7 @@ function sendCoins (account, tx, settings, operatorId) {
function balance (account, cryptoCode, settings, operatorId) {
return checkCryptoCode(cryptoCode)
.then(() => getWallet(account, cryptoCode))
.then(wallet => BN(wallet._wallet.spendableBalanceString))
.then(wallet => new BN(wallet._wallet.spendableBalanceString))
}
function newAddress (account, info, tx, settings, operatorId) {
@ -120,8 +120,8 @@ function getStatus (account, tx, requested, settings, operatorId) {
it.type === 'receive'
)
const sum = _.reduce((acc, val) => val.add(acc), BN(0))
const toBn = _.map(it => BN(it.valueString))
const sum = _.reduce((acc, val) => val.plus(acc), new BN(0))
const toBn = _.map(it => new BN(it.valueString))
const confirmed = _.compose(sum, toBn, filterConfirmed)(transfers)
const pending = _.compose(sum, toBn, filterPending)(transfers)
@ -143,8 +143,8 @@ function newFunding (account, cryptoCode, settings, operatorId) {
const fundingAddress = result.address
return wallet.updateAddress({ address: fundingAddress, label: 'Funding Address' })
.then(() => ({
fundingPendingBalance: BN(wallet._wallet.balanceString),
fundingConfirmedBalance: BN(wallet._wallet.confirmedBalanceString),
fundingPendingBalance: new BN(wallet._wallet.balanceString),
fundingConfirmedBalance: new BN(wallet._wallet.confirmedBalanceString),
fundingAddress: getCashAddress(fundingAddress, cryptoCode)
}))
})

View file

@ -36,13 +36,13 @@ function checkCryptoCode (cryptoCode) {
function accountBalance (cryptoCode) {
return checkCryptoCode(cryptoCode)
.then(() => fetch('getwalletinfo'))
.then(({ balance }) => BN(balance).shift(unitScale).round())
.then(({ balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
}
function accountUnconfirmedBalance (cryptoCode) {
return checkCryptoCode(cryptoCode)
.then(() => fetch('getwalletinfo'))
.then(({ unconfirmed_balance: balance }) => BN(balance).shift(unitScale).round())
.then(({ unconfirmed_balance: balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
}
// We want a balance that includes all spends (0 conf) but only deposits that
@ -53,7 +53,7 @@ function balance (account, cryptoCode, settings, operatorId) {
function sendCoins (account, tx, settings, operatorId) {
const { toAddress, cryptoAtoms, cryptoCode } = tx
const coins = cryptoAtoms.shift(-unitScale).toFixed(8)
const coins = cryptoAtoms.shiftedBy(-unitScale).toFixed(8)
return checkCryptoCode(cryptoCode)
.then(() => fetch('sendtoaddress', [toAddress, coins]))
@ -61,7 +61,7 @@ function sendCoins (account, tx, settings, operatorId) {
.then((res) => _.pick(['fee', 'txid'], res))
.then((pickedObj) => {
return {
fee: BN(pickedObj.fee).abs().shift(unitScale).round(),
fee: new BN(pickedObj.fee).abs().shiftedBy(unitScale).decimalPlaces(0),
txid: pickedObj.txid
}
})
@ -78,7 +78,7 @@ function newAddress (account, info, tx, settings, operatorId) {
function addressBalance (address, confs) {
return fetch('getreceivedbyaddress', [address, confs])
.then(r => BN(r).shift(unitScale).round())
.then(r => new BN(r).shiftedBy(unitScale).decimalPlaces(0))
}
function confirmedBalance (address, cryptoCode) {

View file

@ -38,7 +38,7 @@ function connect (url) {
}
}
const hex = bigNum => '0x' + bigNum.truncated().toString(16)
const hex = bigNum => '0x' + bigNum.integerValue(BN.ROUND_DOWN).toString(16)
function privateKey (account) {
return defaultWallet(account).getPrivateKey()
@ -57,7 +57,7 @@ function sendCoins (account, tx, settings, operatorId) {
.then(tx => {
if (!tx) return { txid }
const fee = BN(tx.gas).mul(BN(tx.gasPrice)).round()
const fee = new BN(tx.gas).times(new BN(tx.gasPrice)).decimalPlaces(0)
return { txid, fee }
})

View file

@ -35,13 +35,13 @@ function checkCryptoCode (cryptoCode) {
function accountBalance (cryptoCode) {
return checkCryptoCode(cryptoCode)
.then(() => fetch('getwalletinfo'))
.then(({ balance }) => BN(balance).shift(unitScale).round())
.then(({ balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
}
function accountUnconfirmedBalance (cryptoCode) {
return checkCryptoCode(cryptoCode)
.then(() => fetch('getwalletinfo'))
.then(({ unconfirmed_balance: balance }) => BN(balance).shift(unitScale).round())
.then(({ unconfirmed_balance: balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
}
// We want a balance that includes all spends (0 conf) but only deposits that
@ -52,7 +52,7 @@ function balance (account, cryptoCode, settings, operatorId) {
function sendCoins (account, tx, settings, operatorId) {
const { toAddress, cryptoAtoms, cryptoCode } = tx
const coins = cryptoAtoms.shift(-unitScale).toFixed(8)
const coins = cryptoAtoms.shiftedBy(-unitScale).toFixed(8)
return checkCryptoCode(cryptoCode)
.then(() => fetch('sendtoaddress', [toAddress, coins]))
@ -60,7 +60,7 @@ function sendCoins (account, tx, settings, operatorId) {
.then((res) => _.pick(['fee', 'txid'], res))
.then((pickedObj) => {
return {
fee: BN(pickedObj.fee).abs().shift(unitScale).round(),
fee: new BN(pickedObj.fee).abs().shiftedBy(unitScale).decimalPlaces(0),
txid: pickedObj.txid
}
})
@ -77,7 +77,7 @@ function newAddress (account, info, tx, settings, operatorId) {
function addressBalance (address, confs) {
return fetch('getreceivedbyaddress', [address, confs])
.then(r => BN(r).shift(unitScale).round())
.then(r => new BN(r).shiftedBy(unitScale).decimalPlaces(0))
}
function confirmedBalance (address, cryptoCode) {

View file

@ -38,7 +38,7 @@ function balance (acount, cryptoCode, settings, operatorId) {
.then(c => c.channelBalance({}))
.then(_.get('balance'))
.then(BN)
.then(r => r.shift(unitScale).round())
.then(r => r.shiftedBy(unitScale).decimalPlaces(0))
}
function sendCoins (account, tx, settings, operatorId) {

View file

@ -14,7 +14,7 @@ let t0
function _balance (cryptoCode) {
const cryptoRec = coinUtils.getCryptoCurrency(cryptoCode)
const unitScale = cryptoRec.unitScale
return BN(10).shift(unitScale).round()
return new BN(10).shiftedBy(unitScale).decimalPlaces(0)
}
function balance (account, cryptoCode, settings, operatorId) {
@ -24,7 +24,7 @@ function balance (account, cryptoCode, settings, operatorId) {
function pendingBalance (account, cryptoCode) {
return balance(account, cryptoCode)
.then(b => b.mul(1.1))
.then(b => b.times(1.1))
}
function confirmedBalance (account, cryptoCode) {
@ -36,7 +36,7 @@ let sendCount = 100
function isInsufficient (cryptoAtoms, cryptoCode) {
const b = _balance(cryptoCode)
return cryptoAtoms.gt(b.div(1000).mul(sendCount))
return cryptoAtoms.gt(b.div(1000).times(sendCount))
}
function sendCoins (account, tx, settings, operatorId) {
@ -52,7 +52,7 @@ function sendCoins (account, tx, settings, operatorId) {
console.log('[%s] DEBUG: Mock wallet sending %s cryptoAtoms to %s',
cryptoCode, cryptoAtoms.toString(), toAddress)
return resolve({ txid: '<txHash>', fee: BN(0) })
return resolve({ txid: '<txHash>', fee: new BN(0) })
}, 2000)
})
}
@ -81,7 +81,7 @@ function getStatus (account, tx, requested, settings, operatorId) {
const { toAddress, cryptoCode } = tx
const elapsed = Date.now() - t0
if (elapsed < PUBLISH_TIME) return Promise.resolve({ receivedCryptoAtoms: BN(0), status: 'notSeen' })
if (elapsed < PUBLISH_TIME) return Promise.resolve({ receivedCryptoAtoms: new BN(0), status: 'notSeen' })
if (elapsed < AUTHORIZE_TIME) return Promise.resolve({ receivedCryptoAtoms: requested, status: 'published' })
if (elapsed < CONFIRM_TIME) return Promise.resolve({ receivedCryptoAtoms: requested, status: 'authorized' })

View file

@ -30,7 +30,7 @@ function balance (account, cryptoCode, settings, operatorId) {
})
.then(({ data }) => {
if (data.error) throw new Error(JSON.stringify(data.error))
return BN(data.balance)
return new BN(data.balance)
})
}
@ -48,7 +48,7 @@ function sendCoins (account, tx, settings, operatorId) {
.then(({ data }) => {
if (data.error && data.error.errorCode === 'sc-001') throw new E.InsufficientFundsError()
else if (data.error) throw new Error(JSON.stringify(data.error))
const fee = BN(data.fee).round()
const fee = new BN(data.fee).decimalPlaces()
const txid = data.txid
return { txid, fee }
})
@ -74,8 +74,8 @@ function getStatus (account, tx, requested, settings, operatorId) {
.then(() => axios.get(`/balance/${tx.toAddress}?cryptoCode=${tx.cryptoCode}`))
.then(({ data }) => {
if (data.error) throw new Error(JSON.stringify(data.error))
const confirmed = BN(data.confirmedBalance)
const pending = BN(data.pendingBalance)
const confirmed = new BN(data.confirmedBalance)
const pending = new BN(data.pendingBalance)
if (confirmed.gte(requested)) return { receivedCryptoAtoms: confirmed, status: 'confirmed' }
if (pending.gte(requested)) return { receivedCryptoAtoms: pending, status: 'authorized' }
if (pending.gt(0)) return { receivedCryptoAtoms: pending, status: 'insufficientFunds' }

View file

@ -37,13 +37,13 @@ function checkCryptoCode (cryptoCode) {
function accountBalance (cryptoCode) {
return checkCryptoCode(cryptoCode)
.then(() => fetch('getwalletinfo'))
.then(({ balance }) => BN(balance).shift(unitScale).round())
.then(({ balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
}
function accountUnconfirmedBalance (cryptoCode) {
return checkCryptoCode(cryptoCode)
.then(() => fetch('getwalletinfo'))
.then(({ unconfirmed_balance: balance }) => BN(balance).shift(unitScale).round())
.then(({ unconfirmed_balance: balance }) => new BN(balance).shiftedBy(unitScale).decimalPlaces(0))
}
// We want a balance that includes all spends (0 conf) but only deposits that
@ -54,7 +54,7 @@ function balance (account, cryptoCode, settings, operatorId) {
function sendCoins (account, tx, settings, operatorId) {
const { toAddress, cryptoAtoms, cryptoCode } = tx
const coins = cryptoAtoms.shift(-unitScale).toFixed(8)
const coins = cryptoAtoms.shiftedBy(-unitScale).toFixed(8)
const checkSendStatus = function (opid) {
return new Promise((resolve, reject) => {
fetch('z_getoperationstatus', [[opid]])
@ -87,7 +87,7 @@ function sendCoins (account, tx, settings, operatorId) {
})
.then((pickedObj) => {
return {
fee: BN(pickedObj.fee).abs().shift(unitScale).round(),
fee: new BN(pickedObj.fee).abs().shiftedBy(unitScale).decimalPlaces(0),
txid: pickedObj.txid
}
})
@ -104,7 +104,7 @@ function newAddress (account, info, tx, settings, operatorId) {
function addressBalance (address, confs) {
return fetch('getreceivedbyaddress', [address, confs])
.then(r => BN(r).shift(unitScale).round())
.then(r => new BN(r).shiftedBy(unitScale).decimalPlaces(0))
}
function confirmedBalance (address, cryptoCode) {

View file

@ -35,7 +35,7 @@ function toCashOutTx (row) {
keys.forEach(key => {
const objKey = _.camelCase(key)
if (key === 'crypto_atoms' || key === 'fiat') {
newObj[objKey] = BN(row[key])
newObj[objKey] = new BN(row[key])
return
}

View file

@ -14,13 +14,13 @@ function verifyPromoCode (req, res, next) {
const transaction = req.body.tx
const commissions = configManager.getCommissions(transaction.cryptoCode, req.deviceId, req.settings.config)
const tickerRate = BN(transaction.rawTickerPrice)
const tickerRate = new BN(transaction.rawTickerPrice)
const discount = commissionMath.getDiscountRate(promoCode.discount, commissions[transaction.direction])
const rates = {
[transaction.cryptoCode]: {
[transaction.direction]: (transaction.direction === 'cashIn')
? tickerRate.mul(discount).round(5)
: tickerRate.div(discount).round(5)
? tickerRate.times(discount).decimalPlaces(5)
: tickerRate.div(discount).decimalPlaces(5)
}
}

View file

@ -25,19 +25,19 @@ function massage (tx, pi) {
const mapBN = r => {
const update = r.direction === 'cashIn'
? {
cryptoAtoms: BN(r.cryptoAtoms),
fiat: BN(r.fiat),
cashInFee: BN(r.cashInFee),
cashInFeeCrypto: BN(r.cashInFeeCrypto),
commissionPercentage: BN(r.commissionPercentage),
rawTickerPrice: r.rawTickerPrice ? BN(r.rawTickerPrice) : null,
minimumTx: BN(r.minimumTx)
cryptoAtoms: new BN(r.cryptoAtoms),
fiat: new BN(r.fiat),
cashInFee: new BN(r.cashInFee),
cashInFeeCrypto: new BN(r.cashInFeeCrypto),
commissionPercentage: new BN(r.commissionPercentage),
rawTickerPrice: r.rawTickerPrice ? new BN(r.rawTickerPrice) : null,
minimumTx: new BN(r.minimumTx)
}
: {
cryptoAtoms: BN(r.cryptoAtoms),
fiat: BN(r.fiat),
rawTickerPrice: r.rawTickerPrice ? BN(r.rawTickerPrice) : null,
commissionPercentage: BN(r.commissionPercentage)
cryptoAtoms: new BN(r.cryptoAtoms),
fiat: new BN(r.fiat),
rawTickerPrice: r.rawTickerPrice ? new BN(r.rawTickerPrice) : null,
commissionPercentage: new BN(r.commissionPercentage)
}
return _.assign(r, update)

67
package-lock.json generated
View file

@ -6423,9 +6423,9 @@
"integrity": "sha1-nGZalfiLiwj8Bc/XMfVhhZ1yWCU="
},
"bignumber.js": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz",
"integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA=="
"version": "9.0.1",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.1.tgz",
"integrity": "sha512-IdZR9mh6ahOBv/hYGiXyVuyCetmGJhtYkqLBpTStdhEGjegpPlUawydyaF3pbIOFynJTpllEs+NP+CS9jKFLjA=="
},
"binary-extensions": {
"version": "2.1.0",
@ -8897,6 +8897,11 @@
"array-find-index": "^1.0.1"
}
},
"cursor": {
"version": "0.1.5",
"resolved": "https://registry.npmjs.org/cursor/-/cursor-0.1.5.tgz",
"integrity": "sha1-6neMKwnTPC5WT9khRwdnUEg+uyw="
},
"cycle": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/cycle/-/cycle-1.0.3.tgz",
@ -14799,6 +14804,7 @@
"resolved": "https://registry.npmjs.org/js-xdr/-/js-xdr-1.2.0.tgz",
"integrity": "sha512-ziYlgwMofC0QK2K9M4Pwl3NNyfB5ObZxd86+vl2cWOxAVRhtB1xDnBV9nCxnA105c+lf3lfM0tvNtdm+FRpZOA==",
"requires": {
"cursor": "^0.1.5",
"lodash": "^4.17.5",
"long": "^2.2.3"
},
@ -18970,6 +18976,19 @@
"ripple-address-codec": "^4.1.0"
},
"dependencies": {
"base-x": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/base-x/-/base-x-3.0.4.tgz",
"integrity": "sha512-UYOadoSIkEI/VrRGSG6qp93rp2WdokiAiNYDfGW5qURAY8GiAQkvMbwNNSDYiVJopqv4gCna7xqf4rrNGp+5AA==",
"requires": {
"safe-buffer": "^5.0.1"
}
},
"bignumber.js": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz",
"integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA=="
},
"bn.js": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/bn.js/-/bn.js-5.2.0.tgz",
@ -19116,9 +19135,9 @@
}
},
"ripple-binary-codec": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/ripple-binary-codec/-/ripple-binary-codec-1.1.2.tgz",
"integrity": "sha512-BrsBkNic0F2++zEnCmWlHZEBNmMUJMN9xL2HL5I2fpmo0qlv+6g9oT7HrkxY3HCui52PJuKnkkrwBjqWvPBqpg==",
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/ripple-binary-codec/-/ripple-binary-codec-1.1.3.tgz",
"integrity": "sha512-NnFNZZ+225BxdDdHtcEn4GiGzup+V0DGAbtKygZIwbqA5116oZBt6uY3g43gYpdDMISsEbM7NewBij8+7jdlvA==",
"requires": {
"assert": "^2.0.0",
"big-integer": "^1.6.48",
@ -19141,9 +19160,9 @@
}
},
"ws": {
"version": "7.4.6",
"resolved": "https://registry.npmjs.org/ws/-/ws-7.4.6.tgz",
"integrity": "sha512-YmhHDO4MzaDLB+M9ym/mDA5z0naX8j7SIlT8f8z+I0VtzsRbekxEutHSme7NPS2qE8StCYQNUnfWdXta/Yu85A=="
"version": "7.5.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-7.5.0.tgz",
"integrity": "sha512-6ezXvzOZupqKj4jUqbQ9tXuJNo+BR2gU8fFRk3XCP3e0G6WT414u5ELe6Y0vtp7kmSJ3F7YWObSNr1ESsgi4vw=="
}
}
},
@ -19157,9 +19176,9 @@
},
"dependencies": {
"bignumber.js": {
"version": "9.0.1",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-9.0.1.tgz",
"integrity": "sha512-IdZR9mh6ahOBv/hYGiXyVuyCetmGJhtYkqLBpTStdhEGjegpPlUawydyaF3pbIOFynJTpllEs+NP+CS9jKFLjA=="
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz",
"integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA=="
}
}
},
@ -20643,6 +20662,11 @@
"tweetnacl": "^1.0.0"
},
"dependencies": {
"bignumber.js": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz",
"integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA=="
},
"tweetnacl": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
@ -20680,6 +20704,11 @@
"requires": {
"follow-redirects": "^1.10.0"
}
},
"bignumber.js": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz",
"integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA=="
}
}
},
@ -20991,6 +21020,20 @@
"supports-color": "^7.0.0"
},
"dependencies": {
"bignumber.js": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-4.1.0.tgz",
"integrity": "sha512-eJzYkFYy9L4JzXsbymsFn3p54D+llV27oTQ+ziJG7WFRheJcNZilgVXMG0LoZtlQSKBsJdWtLFqOD0u+U0jZKA=="
},
"ed25519": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/ed25519/-/ed25519-0.0.4.tgz",
"integrity": "sha1-5WIYrOL8kD0llZOu8LKpY59HW+s=",
"requires": {
"bindings": "^1.2.1",
"nan": "^2.0.9"
}
},
"has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",

View file

@ -11,7 +11,7 @@
"axios": "0.21.1",
"base-x": "3.0.8",
"bchaddrjs": "^0.3.0",
"bignumber.js": "^4.1.0",
"bignumber.js": "9.0.1",
"bip39": "^2.3.1",
"bitcoind-rpc": "^0.7.0",
"bitcore-lib": "^0.15.0",

View file

@ -28,7 +28,7 @@ test('should handle itbit error response', async t => {
const trade = rewireTrade(commonMock)
trade('buy', { walletId: 'id' }, BN('93410'), 'USD', 'BTC')
trade('buy', { walletId: 'id' }, new BN('93410'), 'USD', 'BTC')
.catch(err => {
t.regex(err.message, /wallet provided/g)
})