diff --git a/web/cashtab/src/hooks/__tests__/migrations.test.js b/web/cashtab/src/hooks/__tests__/migrations.test.js --- a/web/cashtab/src/hooks/__tests__/migrations.test.js +++ b/web/cashtab/src/hooks/__tests__/migrations.test.js @@ -1,5 +1,7 @@ import { currency } from '../../components/Common/Ticker'; import BigNumber from 'bignumber.js'; +import BCHJS from '@psf/bch-js'; +import useBCH from '../useBCH'; describe('Testing functions for upgrading Cashtab', () => { it('Replacement currency.dust parameter parsing matches legacy DUST parameter', () => { @@ -7,4 +9,16 @@ 0.00000546, ); }); + it('For strings with 8 decimal places, toBaseUnit() outputs a BigNumber equivalent to the toSatoshi() integer output', () => { + const BCH = new BCHJS(); + const testAmount = 0.12345678; + const { toSmallestDenomination } = useBCH(); + const dustLimitInSatoshis = BCH.BitcoinCash.toSatoshi( + new BigNumber(testAmount).toFixed(8), + ); + const dustLimitInCashDecimalsDenomination = parseInt( + toSmallestDenomination(new BigNumber(testAmount)).toString(), + ); + expect(dustLimitInSatoshis).toBe(dustLimitInCashDecimalsDenomination); + }); }); diff --git a/web/cashtab/src/hooks/useBCH.js b/web/cashtab/src/hooks/useBCH.js --- a/web/cashtab/src/hooks/useBCH.js +++ b/web/cashtab/src/hooks/useBCH.js @@ -406,6 +406,18 @@ return link; }; + const toSmallestDenomination = sendAmount => { + // Replace the BCH.toSatoshi method with an equivalent function that works for arbitrary decimal places + // Example, for an 8 decimal place currency like Bitcoin + // Input: a BigNumber of the amount of Bitcoin to be sent + // Output: a BigNumber of the amount of satoshis to be sent + const conversionFactor = new BigNumber(10 ** currency.cashDecimals); + const sendAmountSmallestDenomination = sendAmount.times( + conversionFactor, + ); + return sendAmountSmallestDenomination; + }; + const sendBch = async ( BCH, wallet, @@ -440,7 +452,7 @@ transactionBuilder = new BCH.TransactionBuilder(); else transactionBuilder = new BCH.TransactionBuilder('testnet'); - const satoshisToSend = BCH.BitcoinCash.toSatoshi(value.toFixed(8)); + const satoshisToSend = toSmallestDenomination(value); let originalAmount = new BigNumber(0); let txFee = 0; for (let i = 0; i < utxos.length; i++) { @@ -574,6 +586,7 @@ getSlpBalancesAndUtxos, getTxHistory, getRestUrl, + toSmallestDenomination, sendBch, sendToken, };