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

fix: send input ui breaking with multiple periods #567

Merged

Conversation

NickKelly1
Copy link
Contributor

@NickKelly1 NickKelly1 commented Nov 22, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced input validation for sending transactions across Bitcoin, Ethereum, and Solana wallets.
    • Improved handling of invalid numerical inputs to prevent errors during transaction processing.
  • Bug Fixes

    • Resolved potential issues with invalid inputs by implementing robust checks for numeric values.
  • Documentation

    • Updated descriptions of validation logic for clarity and user understanding.

@NickKelly1 NickKelly1 requested a review from kvhnuke November 22, 2024 01:02
Copy link

coderabbitai bot commented Nov 22, 2024

Walkthrough

The pull request introduces enhancements to the input validation logic across multiple send transaction components for Bitcoin, Ethereum, and Solana wallet applications. Each component now employs a more robust validation process using the BigNumber library to check for valid numerical inputs, specifically addressing NaN values. The changes ensure that invalid inputs are effectively managed before further processing, while the overall structure and functionality of the components remain consistent.

Changes

File Path Change Summary
packages/extension/src/providers/bitcoin/ui/send-transaction/index.vue Enhanced validation logic for sendAmount using BigNumber to check for NaN before comparing with assetMaxValue.
packages/extension/src/providers/common/ui/send-transaction/send-input-amount.vue Updated onlyNumber method to allow valid numeric input and a single period; modified amount computed property to emit '0.' for empty input.
packages/extension/src/providers/ethereum/ui/send-transaction/index.vue Updated validation logic to check for NaN values when parsing sendAmount, using BigNumber for enhanced robustness.
packages/extension/src/providers/solana/ui/send-transaction/index.vue Improved validation in isInputsValid by checking for NaN before comparing sendAmount with assetMaxValue; updated inputAmount to set empty input to '0'.

Possibly related PRs

  • fix: test pass always on and ff csp #547: The changes in the main PR regarding input validation in the Bitcoin wallet's send transaction component are related to the modifications in the Ethereum send transaction component, which also updated its input validation logic to include checks for NaN values and utilize the BigNumber library.

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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 using 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.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

Copy link

github-actions bot commented Nov 22, 2024

💼 Build Files
chrome: enkrypt-chrome-f7ef55d2.zip
firefox: enkrypt-firefox-f7ef55d2.zip

💉 Virus total analysis
chrome: f7ef55d2
firefox: f7ef55d2

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: 2

🧹 Outside diff range and nitpick comments (5)
packages/extension/src/providers/common/ui/send-transaction/send-input-amount.vue (1)

Line range hint 51-60: Add error handling for BigNumber calculations

The fiatEquivalent computed property should handle invalid numerical inputs gracefully to prevent potential errors.

Consider adding error handling:

 const fiatEquivalent = computed(() => {
-  return new BigNumber(props.fiatValue).times(props.amount).toString();
+  try {
+    if (!props.amount || !props.fiatValue) return '0';
+    const value = new BigNumber(props.fiatValue).times(props.amount);
+    return value.isNaN() ? '0' : value.toString();
+  } catch (error) {
+    console.error('Error calculating fiat equivalent:', error);
+    return '0';
+  }
 });
packages/extension/src/providers/bitcoin/ui/send-transaction/index.vue (2)

308-311: Consider enhancing user feedback for invalid inputs

While the validation logic is solid, consider providing more specific feedback to users when their input is invalid. This could help users understand why the send button is disabled.

Consider adding computed properties for specific error states:

+const inputErrors = computed(() => {
+  const errors = [];
+  const sendAmountBigNumber = new BigNumber(sendAmount.value);
+  
+  if (sendAmountBigNumber.isNaN()) {
+    errors.push('Invalid number format');
+  } else if (sendAmountBigNumber.gt(assetMaxValue.value)) {
+    errors.push('Amount exceeds available balance');
+  }
+  return errors;
+});

Then use these errors to display feedback in the template.


308-311: Consider synchronizing validation logic with inputAmount method

The inputAmount method (around line 400) also uses BigNumber for validation but handles it differently. Consider unifying the validation approach for consistency.

Extract the validation logic into a reusable function:

+const isValidAmount = (amount: string): boolean => {
+  const amountBN = new BigNumber(amount);
+  return !amountBN.isNaN() && !amountBN.gt(assetMaxValue.value);
+};

 const inputAmount = (inputAmount: string) => {
   if (inputAmount === '') {
     inputAmount = '0';
   }
-  const inputAmountBn = new BigNumber(inputAmount);
-  isMaxSelected.value = false;
-  amount.value = inputAmountBn.lt(0) ? '0' : inputAmount;
+  isMaxSelected.value = false;
+  amount.value = isValidAmount(inputAmount) ? inputAmount : '0';
 };
packages/extension/src/providers/solana/ui/send-transaction/index.vue (1)

402-404: LGTM! The BigNumber validation fixes the multiple periods issue.

The new validation logic properly handles invalid numeric inputs, including cases with multiple periods, by using BigNumber's isNaN check.

Consider enhancing the validation with explicit checks and user feedback:

 const sendAmountBigNumber = new BigNumber(sendAmount.value);
 if (sendAmountBigNumber.isNaN()) return false;
+if (sendAmountBigNumber.isNegative()) return false;
 if (sendAmountBigNumber.gt(assetMaxValue.value)) return false;

Additionally, consider emitting validation errors to show helpful messages to users when validation fails:

const getValidationError = computed(() => {
  const amount = new BigNumber(sendAmount.value);
  if (amount.isNaN()) return 'Please enter a valid number';
  if (amount.isNegative()) return 'Amount cannot be negative';
  if (amount.gt(assetMaxValue.value)) return 'Insufficient balance';
  return null;
});
packages/extension/src/providers/ethereum/ui/send-transaction/index.vue (1)

489-491: Consider adding user feedback for invalid inputs

The validation silently fails when encountering invalid numbers. Consider providing feedback to help users understand why their input was rejected.

+  const isValidAmount = computed(() => {
+    if ((sendAmount.value.match(/\./g) || []).length > 1) {
+      return { valid: false, error: 'Multiple decimal points are not allowed' };
+    }
+    const sendAmountBigNumber = new BigNumber(sendAmount.value);
+    if (sendAmountBigNumber.isNaN()) {
+      return { valid: false, error: 'Invalid number format' };
+    }
+    if (sendAmountBigNumber.gt(assetMaxValue.value)) {
+      return { valid: false, error: 'Amount exceeds maximum value' };
+    }
+    return { valid: true, error: null };
+  });

   const isInputsValid = computed<boolean>(() => {
     if (!props.network.isAddress(addressTo.value)) return false;
     if (
       isSendToken.value &&
       !isValidDecimals(sendAmount.value, selectedAsset.value.decimals!)
     ) {
       return false;
     }
     if (!isSendToken.value && !selectedNft.value.id) {
       return false;
     }
-    const sendAmountBigNumber = new BigNumber(sendAmount.value)
-    if (sendAmountBigNumber.isNaN()) return false
-    if (sendAmountBigNumber.gt(assetMaxValue.value)) return false;
+    if (!isValidAmount.value.valid) return false;
     if (gasCostValues.value.REGULAR.nativeValue === '0') return false;
     return true;
   });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between abf56be and f7ef55d.

📒 Files selected for processing (4)
  • packages/extension/src/providers/bitcoin/ui/send-transaction/index.vue (1 hunks)
  • packages/extension/src/providers/common/ui/send-transaction/send-input-amount.vue (1 hunks)
  • packages/extension/src/providers/ethereum/ui/send-transaction/index.vue (1 hunks)
  • packages/extension/src/providers/solana/ui/send-transaction/index.vue (1 hunks)
🔇 Additional comments (3)
packages/extension/src/providers/common/ui/send-transaction/send-input-amount.vue (1)

76-85: Verify the fix for multiple periods across different scenarios

While the implementation prevents multiple periods, we should verify it handles all edge cases correctly.

✅ Verification successful

Implementation correctly handles decimal input validation

The code implements proper validation for numeric input with decimals:

  • Allows single decimal point entry
  • Prevents multiple decimal points
  • Handles edge case where decimal is first character by converting it to "0."
  • Consistent with standard numeric input patterns
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar input validation patterns across the codebase
# to ensure consistent handling of decimal inputs

# Look for other Vue components with number input validation
rg -l "keypress.*onlyNumber" --type vue

# Check for other BigNumber usage patterns
rg "new BigNumber.*toString" --type vue -A 2

# Look for related test files
fd -e spec.ts -e test.ts send-input

Length of output: 182


Script:

#!/bin/bash
# Search for similar input validation patterns across the codebase
# Look for keypress event handlers and number validation
rg -t js -t ts -t vue "keypress|keyCode.*preventDefault" -A 3

# Check for BigNumber usage patterns
rg -t js -t ts -t vue "BigNumber.*toString" -A 2

# Look for test files related to send-input
find . -type f -name "*send-input*.spec.ts" -o -name "*send-input*.test.ts"

# Look for similar numeric input validation in other files
rg -t js -t ts -t vue "indexOf\('\.'\)|indexOf\(\"\.\"\)" -A 2

Length of output: 345


Script:

#!/bin/bash
# Search without specifying file types to catch all relevant files
rg "keypress.*preventDefault" -A 3

# Look for decimal point validation patterns
rg "indexOf\\(\\.\\)" -A 2

# Find all Vue files first to understand the structure
fd -e vue

# Look for numeric input validation patterns
rg "keyCode.*[0-9].*preventDefault" -A 3

Length of output: 25627


Script:

#!/bin/bash
# Look at the specific file content to understand the validation logic
cat "packages/extension/src/providers/common/ui/send-transaction/send-input-amount.vue"

# Search for similar numeric input validation patterns in the codebase
rg "keyCode.*[0-9].*preventDefault|indexOf\\(\"\\.\"\\)|indexOf\\('\\.'\\)" -A 3 -B 1

Length of output: 4822

packages/extension/src/providers/bitcoin/ui/send-transaction/index.vue (1)

308-311: Approve the enhanced input validation logic

The new validation using BigNumber effectively addresses the issue with multiple periods in the input by:

  1. Properly handling invalid numeric inputs through isNaN() check
  2. Correctly comparing the amount against maximum value using gt()

Let's verify the fix handles the multiple periods case correctly:

✅ Verification successful

Based on the search results, I can now generate the final response since I have enough information to verify the review comment. The search shows that similar BigNumber validation is consistently implemented across different wallet providers (Bitcoin, Ethereum, Solana, etc.) for handling send amounts, and specifically confirms that the Bitcoin implementation follows the same pattern as other providers.

Approve the BigNumber validation implementation

The validation using BigNumber is correctly implemented and consistent with the codebase patterns. The code:

  • Properly validates numeric input through isNaN() check
  • Correctly compares against maximum value using gt()
  • Follows the same validation pattern used in other providers (Ethereum, Solana) for handling send amounts
  • Is part of a broader input validation strategy across the wallet
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if similar validation is consistently applied across the codebase
# Look for other instances where we might need similar BigNumber validation

# Search for numeric input validation patterns
rg -A 3 'new BigNumber\(' --type vue

# Search for potential places handling decimal input
rg -A 3 'inputAmount|sendAmount|amount\.value' --type vue

Length of output: 154


Script:

#!/bin/bash
# Let's try without file type filtering since .vue might not be recognized
# Search for BigNumber validation patterns
rg -A 3 'new BigNumber\('

# Search for amount validation patterns
rg -A 3 'inputAmount|sendAmount|amount\.value'

# Also check for similar files in the bitcoin provider directory
fd -e vue . packages/extension/src/providers/bitcoin

Length of output: 79855

packages/extension/src/providers/ethereum/ui/send-transaction/index.vue (1)

489-491: Verify the fix addresses multiple periods across components

The PR title suggests this is a UI breaking issue with multiple periods, but the changes only handle NaN values. Let's verify if similar fixes are needed in other components.

@kvhnuke kvhnuke changed the base branch from develop to prep/release December 4, 2024 18:56
@kvhnuke kvhnuke merged commit b5b9fb0 into prep/release Dec 4, 2024
4 checks passed
@kvhnuke kvhnuke deleted the fix/send-input-ui-breaking-with-multiple-periods branch December 4, 2024 18:58
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.

2 participants