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

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from
Open

Conversation

friedger
Copy link
Contributor

@friedger friedger commented May 31, 2024

Building Leather at commit 100184a

This PR

Summary by CodeRabbit

  • Refactor

    • Improved clarity and modularity in Bitcoin transaction handling by refactoring output handling and removing redundant parameters.
  • Bug Fixes

    • Removed unnecessary amount prop from BitcoinCustomFee components and hooks, streamlining the fee calculation process.
  • Chores

    • Updated import statements and interfaces for better code organization and maintainability.

Copy link

coderabbitai bot commented May 31, 2024

Walkthrough

The changes aim to prevent remaining dust when sending the maximum amount of Bitcoin. This involves refactoring the determineUtxosForSpend function to handle change outputs more clearly, removing the amount prop from custom fee components, and updating the fee calculation logic. These changes ensure that when sending max BTC, the wallet avoids leaving dust by correctly adjusting the spendable amount based on the selected fee.

Changes

File Path Change Summary
src/app/common/transactions/bitcoin/coinselect/local-coin-selection.spec.ts Imported filterUneconomicalUtxos and getSizeInfo functions; added determineUtxosForSpendAll to exports.
src/app/common/transactions/bitcoin/coinselect/local-coin-selection.ts Imported BTC_P2WPKH_DUST_AMOUNT; refactored determineUtxosForSpend to handle change outputs more clearly.
src/app/components/bitcoin-custom-fee/bitcoin-custom-fee-input.tsx Removed amount prop from Props interface and corresponding function usage.
src/app/components/bitcoin-custom-fee/bitcoin-custom-fee.tsx Removed amount prop and parameter from BitcoinCustomFee and BitcoinCustomFeeInput components.
src/app/components/bitcoin-custom-fee/hooks/use-bitcoin-custom-fee.tsx Removed amount parameter from useBitcoinCustomFee function signature and updated related fee calculation logic.
src/app/features/dialogs/increase-fee-dialog/increase-btc-fee-dialog.tsx Removed calculation of Bitcoin transaction value using btcToSat function.

Sequence Diagram(s) (Beta)

sequenceDiagram
    participant User
    participant BitcoinCustomFee
    participant UseBitcoinCustomFee
    participant DetermineUtxosForSpend
    
    User->>BitcoinCustomFee: Select send max
    BitcoinCustomFee->>UseBitcoinCustomFee: Calculate custom fee without amount
    UseBitcoinCustomFee->>DetermineUtxosForSpend: Determine UTXOs
    DetermineUtxosForSpend->>UseBitcoinCustomFee: Return UTXOs and change
    UseBitcoinCustomFee->>BitcoinCustomFee: Return fee and UTXOs
    BitcoinCustomFee->>User: Display fee and UTXOs
Loading

Assessment against linked issues

Objective (Issue #4979) Addressed Explanation
Prevent remaining dust when sending max BTC
Adjust send amount based on selected fee in send-max mode
Remove amount parameter from custom fee calculations

Poem

In the world of Bitcoin's grand array,
We tweaked the code to pave the way,
For max sends without dust's dismay,
A cleaner path for coins to sway.
With fees adjusted, clear and bright,
Your transactions now take flight! 🚀


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

},
];
}[] =
changeAmount <= BTC_P2WPKH_DUST_AMOUNT
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Is it ok to leave the dust amount in the wallet? @fbwoolf

Copy link
Contributor

Choose a reason for hiding this comment

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

@alter-eggo, thoughts on these changes? It looks like you've made the most recent changes to this code?


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

@fbwoolf
Copy link
Contributor

fbwoolf commented May 31, 2024

@alter-eggo it might make sense for you to review these changes? I think this touches code you've worked on recently adding multiple recipients?

@alter-eggo
Copy link
Contributor

@fbwoolf yeah will take a look, @kyranjamie and me refactored it not so long ago

@kyranjamie
Copy link
Collaborator

Thanks a lot @friedger, great improvement! Taking a look at implementation now, may tidy commits

@kyranjamie
Copy link
Collaborator

Rewrote logic a little to make more readable, but otherwise think this is good. @friedger to verify changed logic.

@kyranjamie kyranjamie marked this pull request as ready for review June 3, 2024 11:11
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Outside diff range and nitpick comments (6)
src/app/components/bitcoin-custom-fee/hooks/use-bitcoin-custom-fee.tsx (1)

Line range hint 23-47: Refactor to improve readability and maintainability.

The useBitcoinCustomFee function could be refactored for better readability by separating the logic into smaller, more manageable functions. This would make the code easier to understand and maintain, especially as it grows in complexity.

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

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

    const determineUtxosArgs: DetermineUtxosForSpendArgs = {
      recipients,
      utxos,
      feeRate,
    };
    const { fee } = isSendingMax
      ? determineUtxosForSpendAll(determineUtxosArgs)
      : determineUtxosForSpend(determineUtxosArgs);

    return {
      fee,
      fiatFeeValue: `~ ${i18nFormatCurrency(
        baseCurrencyAmountInQuote(createMoney(Math.ceil(fee), 'BTC'), btcMarketData)
      )}`,
    };
  }, [utxos, isSendingMax, recipients, btcMarketData]);

  return calculateFee;
}
src/app/components/bitcoin-custom-fee/bitcoin-custom-fee-input.tsx (1)

Line range hint 3-3: Remove unused import to clean up the code.

- import { createMoney, satToBtc } from '@leather-wallet/utils';
+ import { satToBtc } from '@leather-wallet/utils';
src/app/common/transactions/bitcoin/coinselect/local-coin-selection.ts (1)

Line range hint 37-40: Replace forEach with for...of for better performance and readability.

- recipients.forEach(recipient => {
+ for (const recipient of recipients) {
    if (!validate(recipient.address))
      throw new Error('Cannot calculate spend of invalid address type');
  });

Also applies to: 66-69

src/app/components/bitcoin-custom-fee/bitcoin-custom-fee.tsx (1)

Line range hint 1-1: Optimize imports by removing unused ones.

- import { Dispatch, SetStateAction, useCallback, useRef } from 'react';
+ import { Dispatch, SetStateAction, useCallback, useRef } from 'react'; // Assuming these are used elsewhere in the file
- import { createMoney } from '@leather-wallet/utils';
- import { SendCryptoAssetSelectors } from '@tests/selectors/send.selectors';
- import { Form, Formik } from 'formik';
- import { Stack, styled } from 'leather-styles/jsx';
- import * as yup from 'yup';

Also applies to: 8-9, 15-16

src/app/features/dialogs/increase-fee-dialog/increase-btc-fee-dialog.tsx (1)

Line range hint 7-8: Remove unused imports to clean up the code.

- import { btcToSat, createMoney, formatMoney } from '@leather-wallet/utils';
+ import { btcToSat, formatMoney } from '@leather-wallet/utils'; // Assuming createMoney is not used elsewhere in the file
src/app/common/transactions/bitcoin/coinselect/local-coin-selection.spec.ts (1)

Line range hint 26-26: Specify a more appropriate type instead of any.

In several places in the test file, any is used where a more specific type could be applied. This would improve type safety and code clarity.

- const demoUtxos = [{ value: 8200 }, { value: 8490 }, ...] as any;
+ const demoUtxos: UtxoResponseItem[] = [{ value: 8200 }, { value: 8490 }, ...];

Also applies to: 36-36, 52-52, 79-79, 155-155, 183-183, 191-191, 224-224

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ab7fb16 and 100184a.

Files selected for processing (6)
  • src/app/common/transactions/bitcoin/coinselect/local-coin-selection.spec.ts (2 hunks)
  • src/app/common/transactions/bitcoin/coinselect/local-coin-selection.ts (3 hunks)
  • src/app/components/bitcoin-custom-fee/bitcoin-custom-fee-input.tsx (3 hunks)
  • src/app/components/bitcoin-custom-fee/bitcoin-custom-fee.tsx (3 hunks)
  • src/app/components/bitcoin-custom-fee/hooks/use-bitcoin-custom-fee.tsx (2 hunks)
  • src/app/features/dialogs/increase-fee-dialog/increase-btc-fee-dialog.tsx (1 hunks)
Additional context used
GitHub Check: typecheck
src/app/components/bitcoin-custom-fee/bitcoin-custom-fee-input.tsx

[failure] 3-3:
'createMoney' is declared but its value is never read.

src/app/components/bitcoin-custom-fee/bitcoin-custom-fee.tsx

[failure] 3-3:
'createMoney' is declared but its value is never read.

Biome
src/app/common/transactions/bitcoin/coinselect/local-coin-selection.ts

[error] 37-40: Prefer for...of instead of forEach.


[error] 66-69: Prefer for...of instead of forEach.

src/app/components/bitcoin-custom-fee/bitcoin-custom-fee.tsx

[error] 1-1: Some named imports are only used as types.


[error] 8-9: All these imports are only used as types.


[error] 15-16: All these imports are only used as types.

src/app/features/dialogs/increase-fee-dialog/increase-btc-fee-dialog.tsx

[error] 7-8: All these imports are only used as types.

src/app/common/transactions/bitcoin/coinselect/local-coin-selection.spec.ts

[error] 26-26: Unexpected any. Specify a different type.


[error] 36-36: Unexpected any. Specify a different type.


[error] 52-52: Unexpected any. Specify a different type.


[error] 79-79: Unexpected any. Specify a different type.


[error] 155-155: Unexpected any. Specify a different type.


[error] 183-183: Unexpected any. Specify a different type.


[error] 191-191: Unexpected any. Specify a different type.


[error] 224-224: Unexpected any. Specify a different type.

@markmhendrickson
Copy link
Collaborator

@alter-eggo want to review this PR before we merge in? @kyranjamie has already approved

@alter-eggo
Copy link
Contributor

@markmhendrickson from the code side - lgtm
but there are merging conflicts and not all checks have passed

@markmhendrickson
Copy link
Collaborator

@alter-eggo to fix conflicts and merge

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Prevent remaining dust when sending max BTC
5 participants