Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve dust txs when sending max amount (#4979) #5472

Merged
merged 1 commit into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { BTC_P2WPKH_DUST_AMOUNT } from '@leather.io/constants';
import { createMoney, createNullArrayOfLength, sumNumbers } from '@leather.io/utils';

import { determineUtxosForSpend } from './local-coin-selection';
import { filterUneconomicalUtxos, getSizeInfo } from '../utils';
import { determineUtxosForSpend, determineUtxosForSpendAll } from './local-coin-selection';

const demoUtxos = [
{ value: 8200 },
Expand Down Expand Up @@ -168,4 +169,64 @@ describe(determineUtxosForSpend.name, () => {
.toString()
);
});

test('that spending all economical spendable utxos does not result in dust utxos', () => {
const feeRate = 3;
const recipients = [
{
address: 'tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m',
amount: createMoney(Number(1), 'BTC'),
},
];
const filteredUtxos = filterUneconomicalUtxos({
utxos: demoUtxos.sort((a, b) => b.value - a.value) as any,
feeRate,
recipients,
});
const amount = filteredUtxos.reduce((total, utxo) => total + utxo.value, 0) - 2251;
recipients[0].amount = createMoney(Number(amount), 'BTC');

const result = determineUtxosForSpend({
utxos: filteredUtxos as any,
recipients: [
{
address: 'tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m',
amount: createMoney(Number(amount), 'BTC'),
},
],
feeRate,
});
expect(result.inputs.length).toEqual(10);
expect(result.outputs.length).toEqual(1);
expect(result.fee).toEqual(2251);
});

test('that spending all utxos with sendMax does not result in dust utxos', () => {
const utxos = [{ value: 1000 }, { value: 2000 }, { value: 3000 }];
const recipients = [
{
address: 'tb1qt28eagxcl9gvhq2rpj5slg7dwgxae2dn2hk93m',
amount: createMoney(Number(1), 'BTC'),
},
];
const sizeInfo = getSizeInfo({
inputLength: utxos.length,
isSendMax: true,
recipients,
});
const feeRate = 3;
const fee = Math.floor(sizeInfo.txVBytes * feeRate);
const amount = utxos.reduce((total, utxo) => total + utxo.value, 0) - fee;
recipients[0].amount = createMoney(Number(amount), 'BTC');

const result = determineUtxosForSpendAll({
utxos: utxos as any,
recipients,
feeRate,
});
expect(result.inputs.length).toEqual(utxos.length);
expect(result.outputs.length).toEqual(1);
expect(result.fee).toEqual(735);
expect(fee).toEqual(735);
});
});
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import BigNumber from 'bignumber.js';
import { validate } from 'bitcoin-address-validation';

import { BTC_P2WPKH_DUST_AMOUNT } from '@leather.io/constants';
import type { UtxoResponseItem } from '@leather.io/query';
import { sumMoney, sumNumbers } from '@leather.io/utils';

Expand All @@ -14,6 +15,11 @@ export class InsufficientFundsError extends Error {
}
}

interface Output {
value: bigint;
address?: string;
}

export interface DetermineUtxosForSpendArgs {
feeRate: number;
recipients: TransferRecipient[];
Expand Down Expand Up @@ -101,20 +107,24 @@ export function determineUtxosForSpend({ feeRate, recipients, utxos }: Determine
new BigNumber(estimateTransactionSize().txVBytes).multipliedBy(feeRate).toNumber()
);

const outputs: {
value: bigint;
address?: string;
}[] = [
const changeAmount =
BigInt(getUtxoTotal(neededUtxos).toString()) - BigInt(amount.amount.toNumber()) - BigInt(fee);

const changeUtxos: Output[] =
changeAmount > BTC_P2WPKH_DUST_AMOUNT
? [
{
value: changeAmount,
},
]
: [];

const outputs: Output[] = [
...recipients.map(({ address, amount }) => ({
value: BigInt(amount.amount.toNumber()),
address,
})),
{
value:
BigInt(getUtxoTotal(neededUtxos).toString()) -
BigInt(amount.amount.toNumber()) -
BigInt(fee),
},
...changeUtxos,
];

return {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useField } from 'formik';
import { Stack } from 'leather-styles/jsx';

import { Input } from '@leather.io/ui';
import { createMoney, satToBtc } from '@leather.io/utils';
import { satToBtc } from '@leather.io/utils';

import type { TransferRecipient } from '@shared/models/form.model';

Expand All @@ -19,7 +19,6 @@ const feeInputLabel = 'sats/vB';

interface Props {
onClick?(): void;
amount: number;
isSendingMax: boolean;
recipients: TransferRecipient[];
hasInsufficientBalanceError: boolean;
Expand All @@ -30,7 +29,6 @@ interface Props {

export function BitcoinCustomFeeInput({
onClick,
amount,
isSendingMax,
recipients,
hasInsufficientBalanceError,
Expand All @@ -45,7 +43,6 @@ export function BitcoinCustomFeeInput({
}>(null);

const getCustomFeeValues = useBitcoinCustomFee({
amount: createMoney(amount, 'BTC'),
isSendingMax,
recipients,
});
Expand Down
4 changes: 0 additions & 4 deletions src/app/components/bitcoin-custom-fee/bitcoin-custom-fee.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import * as yup from 'yup';

import type { BtcFeeType } from '@leather.io/models';
import { Button, Link } from '@leather.io/ui';
import { createMoney } from '@leather.io/utils';

import type { TransferRecipient } from '@shared/models/form.model';

Expand All @@ -31,7 +30,6 @@ interface BitcoinCustomFeeProps {
}

export function BitcoinCustomFee({
amount,
customFeeInitialValue,
hasInsufficientBalanceError,
isSendingMax,
Expand All @@ -44,7 +42,6 @@ export function BitcoinCustomFee({
}: BitcoinCustomFeeProps) {
const feeInputRef = useRef<HTMLInputElement | null>(null);
const getCustomFeeValues = useBitcoinCustomFee({
amount: createMoney(amount, 'BTC'),
isSendingMax,
recipients,
});
Expand Down Expand Up @@ -97,7 +94,6 @@ export function BitcoinCustomFee({
</Link>
</styled.span>
<BitcoinCustomFeeInput
amount={amount}
isSendingMax={isSendingMax}
onClick={async () => {
feeInputRef.current?.focus();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,33 @@
import { useCallback } from 'react';

import type { Money } from '@leather.io/models';
import { useCryptoCurrencyMarketDataMeanAverage } from '@leather.io/query';
import { baseCurrencyAmountInQuote, createMoney, i18nFormatCurrency } from '@leather.io/utils';

import type { TransferRecipient } from '@shared/models/form.model';

import {
type DetermineUtxosForSpendArgs,
determineUtxosForSpend,
determineUtxosForSpendAll,
} from '@app/common/transactions/bitcoin/coinselect/local-coin-selection';
import { useCurrentNativeSegwitUtxos } from '@app/query/bitcoin/address/utxos-by-address.hooks';
import { useCurrentBtcCryptoAssetBalanceNativeSegwit } from '@app/query/bitcoin/balance/btc-balance-native-segwit.hooks';

export const MAX_FEE_RATE_MULTIPLIER = 50;

interface UseBitcoinCustomFeeArgs {
amount: Money;
isSendingMax: boolean;
recipients: TransferRecipient[];
}

export function useBitcoinCustomFee({ amount, isSendingMax, recipients }: UseBitcoinCustomFeeArgs) {
const { balance } = useCurrentBtcCryptoAssetBalanceNativeSegwit();
export function useBitcoinCustomFee({ isSendingMax, recipients }: UseBitcoinCustomFeeArgs) {
const { data: utxos = [] } = useCurrentNativeSegwitUtxos();
const btcMarketData = useCryptoCurrencyMarketDataMeanAverage('BTC');

return useCallback(
(feeRate: number) => {
if (!feeRate || !utxos.length) return { fee: 0, fiatFeeValue: '' };

const satAmount = isSendingMax
? balance.availableBalance.amount.toNumber()
: amount.amount.toNumber();

const determineUtxosArgs = {
amount: satAmount,
const determineUtxosArgs: DetermineUtxosForSpendArgs = {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

satAmount is not used in determineUtxosForSpendArgs. Is the amount provided for other reasons? Is it ok to remove it? Is this the source of this issue?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, it's ok to remove it since we provide amounts in recipient model

recipients,
utxos,
feeRate,
Expand All @@ -51,6 +43,6 @@ export function useBitcoinCustomFee({ amount, isSendingMax, recipients }: UseBit
)}`,
};
},
[utxos, isSendingMax, balance.availableBalance.amount, amount.amount, recipients, btcMarketData]
[utxos, isSendingMax, recipients, btcMarketData]
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,6 @@ export function IncreaseBtcFeeDialog() {
<Stack gap="space.04">
<Stack gap="space.01">
<BitcoinCustomFeeInput
amount={Math.abs(
btcToSat(getBitcoinTxValue(currentBitcoinAddress, btcTx)).toNumber()
)}
isSendingMax={false}
recipients={recipients}
hasInsufficientBalanceError={false}
Expand Down
Loading