Skip to content

Comments

fix: invalid value on send#555

Merged
gamalielhere merged 7 commits intodevelopfrom
fix/paste-invalid-white-screen
Nov 26, 2024
Merged

fix: invalid value on send#555
gamalielhere merged 7 commits intodevelopfrom
fix/paste-invalid-white-screen

Conversation

@gamalielhere
Copy link
Contributor

@gamalielhere gamalielhere commented Nov 14, 2024

Added value check on input to avoid white page issue.

Summary by CodeRabbit

  • New Features

    • Introduced a utility function for validating numeric input in the transaction sending process.
  • Improvements

    • Enhanced input validation to ensure only positive numeric values are accepted for transactions across multiple cryptocurrency components.
    • Updated balance calculations to prevent errors from invalid inputs.
    • Improved transaction handling logic for better user experience across various cryptocurrency components.
  • Bug Fixes

    • Improved error handling related to transaction logic and user input, ensuring a more seamless user experience.

@coderabbitai
Copy link

coderabbitai bot commented Nov 14, 2024

Walkthrough

The changes in the pull request focus on enhancing the send-transaction component within a Vue.js application across multiple blockchain implementations. A new utility function isNumericPositive has been introduced to validate that the input amount is a positive numeric value. This function is integrated into various computed properties and methods to ensure that only valid numeric values are processed for transactions. Additionally, error handling has been improved to prevent non-numeric values from interfering with transaction processing.

Changes

File Path Change Summary
packages/extension/src/providers/ethereum/ui/send-transaction/index.vue - Added isNumericPositive(value: string) method for positive numeric validation.
- Updated hasEnoughBalance to use isNumericPositive for validating sendAmount.value.
- Modified nativeBalanceAfterTransaction to use a local variable locAmount for numeric checks.
- Enhanced error handling related to non-numeric inputs.
packages/extension/src/libs/utils/number-formatter.ts - Introduced isNumericPositive function to check if a string represents a positive numeric value.
- Updated export statement to include the new function.
packages/extension/src/providers/bitcoin/ui/send-transaction/index.vue - Imported isNumericPositive for input validation.
- Updated nativeBalanceAfterTransaction to return zero for invalid amounts.
- Modified sendAction to handle token and NFT transactions correctly.
- Adjusted sendButtonTitle to format the send amount consistently.
packages/extension/src/providers/kadena/ui/send-transaction/index.vue - Imported isNumericPositive for validating input amounts in validateFields.
- Refined error handling in validateFields to prevent non-positive submissions.
packages/extension/src/providers/polkadot/ui/send-transaction/index.vue - Imported isNumericPositive to enhance validation logic.
- Updated edWarn and validateFields to use this function for checking amounts.
- Modified destinationBalanceCheck and isDisabled to incorporate positivity checks.
- Updated numerous functions and properties to include checks for positive numeric amounts.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SendTransactionComponent
    participant TransactionService

    User->>SendTransactionComponent: Input transaction amount
    SendTransactionComponent->>SendTransactionComponent: Call isNumericPositive(amount)
    alt Valid amount
        SendTransactionComponent->>TransactionService: Process transaction
    else Invalid amount
        SendTransactionComponent->>User: Show error message
    end
Loading

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9783587 and 299aae2.

📒 Files selected for processing (1)
  • packages/extension/src/providers/kadena/ui/send-transaction/index.vue (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/extension/src/providers/kadena/ui/send-transaction/index.vue

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.

@github-actions
Copy link

github-actions bot commented Nov 14, 2024

💼 Build Files
chrome: enkrypt-chrome-299aae22.zip
firefox: enkrypt-firefox-299aae22.zip

💉 Virus total analysis
chrome: 299aae22
firefox: 299aae22

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 (1)
packages/extension/src/providers/ethereum/ui/send-transaction/index.vue (1)

222-225: Consider adding maximum decimal places validation

While the numeric validation is good, cryptocurrency amounts often have restrictions on the maximum number of decimal places allowed.

Consider enhancing the validation to include a maximum decimal places check:

   // check if valid sendAmount.value
   if (!isNumeric(sendAmount.value)) {
     return false;
   }
+  const [, decimals] = sendAmount.value.split('.');
+  if (decimals && decimals.length > selectedAsset.value.decimals!) {
+    return false;
+  }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 76fb11b and 6f1d4c9.

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

222-225: Verify the validation coverage

Let's verify that numeric validation is consistently applied across all transaction-related computations.

Also applies to: 353-355, 540-542

✅ Verification successful

Numeric validation is consistently applied across transaction flows

The verification shows that numeric validation is properly implemented across all transaction providers:

  • Ethereum provider validates using both isNumeric and isValidDecimals checks
  • Solana, Polkadot, Kadena, and Bitcoin providers all implement isValidDecimals checks
  • All providers use BigNumber for safe numeric operations after validation
  • Amount values are properly validated before being used in calculations or transactions

The current implementation in the Ethereum provider at lines 222-225 follows the established pattern across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential missing numeric validations in transaction-related computations

# Look for direct usage of amount.value without validation
rg -A 5 "amount\.value" --type vue

# Look for potential arithmetic operations that might need validation
ast-grep --pattern 'computed(() => {
  $$$
  return $_ + $_;
})'

# Look for BigNumber operations that might need validation
rg "new BigNumber\(" --type vue

Length of output: 193


Script:

#!/bin/bash
# Search for numeric validation patterns and amount-related computations
rg -g '*.{vue,js,ts}' -A 5 "amount\.value|sendAmount\.value"

# Look for BigNumber operations
rg -g '*.{vue,js,ts}' "new BigNumber\("

# Look for isNumeric usage
rg -g '*.{vue,js,ts}' "isNumeric"

Length of output: 51698

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

🧹 Outside diff range and nitpick comments (2)
packages/extension/src/providers/ethereum/ui/send-transaction/index.vue (2)

222-226: Add user feedback for invalid amount inputs

While the validation is correct, consider providing user feedback when an invalid amount is entered.

 if (!isNumericPositive(sendAmount.value)) {
+  emit('error', 'Please enter a valid positive number');
   return false;
 }

Line range hint 583-597: Prevent race conditions in name resolution

The debounced name resolution could lead to race conditions where a later request completes before an earlier one, potentially setting an incorrect address.

 const inputAddressTo = async (text: string) => {
+  let currentRequest = Date.now();
   const debounceResolve = debounce(() => {
     nameResolver
       .resolveName(text, [props.network.name as CoinType, 'ETH'])
       .then(resolved => {
-        if (resolved) {
+        // Only update if this is the most recent request
+        if (resolved && currentRequest === mostRecentRequest) {
           addressTo.value = resolved;
         }
       });
   }, 500);
+  mostRecentRequest = currentRequest;
   debounceResolve();
   addressTo.value = text;
 };
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6f1d4c9 and cece01e.

📒 Files selected for processing (1)
  • packages/extension/src/providers/ethereum/ui/send-transaction/index.vue (3 hunks)

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 (11)
packages/extension/src/providers/bitcoin/ui/send-transaction/index.vue (2)

224-227: Consider adding explicit error handling

While the validation using isNumericPositive is good, silently returning 0 for invalid values might mask errors from users. Consider adding explicit error feedback through the UI.

 if (!isNumericPositive(sendAmount.value)) {
+  // Emit an error event or update an error state
+  emit('update:error', 'Please enter a valid positive number');
   return toBN(0);
 }

Line range hint 441-557: Consider refactoring sendAction for better maintainability

The sendAction method is handling multiple responsibilities including:

  1. Transaction preparation
  2. Fee calculation
  3. Hardware wallet detection
  4. Navigation logic

Consider breaking this down into smaller, focused methods for better maintainability and testing.

Example refactor:

+ const prepareTxInfo = (accountUTXOs, isSendToken) => {
+   // Extract transaction preparation logic
+ }

+ const calculateOutputs = (txInfo, toAmount, remainder) => {
+   // Extract output calculation logic
+ }

+ const handleHardwareWallet = async (txVerifyInfo) => {
+   // Extract hardware wallet logic
+ }

 const sendAction = async () => {
   const keyring = new PublicKeyRing();
   const fromAccountInfo = await keyring.getAccount(addressFrom.value);
   
   // Use extracted methods
   const txInfo = await prepareTxInfo(accountUTXOs.value, isSendToken.value);
   const outputs = calculateOutputs(txInfo, toAmount, remainder);
   
   if (fromAccountInfo.isHardware) {
     await handleHardwareWallet(txVerifyInfo);
   } else {
     router.push(routedRoute);
   }
 };
packages/extension/src/providers/kadena/ui/send-transaction/index.vue (3)

241-246: Remove debugging console.log statement

The console.log statement appears to be debugging code that should be removed before merging.

  if (!isNumericPositive(amount.value)) {
-   console.log('amount', amount.value, !isNumericPositive(amount.value));
    fieldsValidation.value.amount = false;
    errorMsg.value = 'Invalid amount. Amount has to be greater than 0';
    return;
  }

241-246: Consider reordering validation checks

The positive number validation should come after the decimal places validation to provide more accurate error messages. If a user enters a negative number with too many decimal places, they'll first see the "greater than 0" error before seeing the decimal places error.

- if (!isNumericPositive(amount.value)) {
-   fieldsValidation.value.amount = false;
-   errorMsg.value = 'Invalid amount. Amount has to be greater than 0';
-   return;
- }

  if (!isValidDecimals(amount.value, selectedAsset.value.decimals!)) {
    fieldsValidation.value.amount = false;
    errorMsg.value = `Amount cannot have more than ${selectedAsset.value.decimals} decimals`;
    return;
  }

+ if (!isNumericPositive(amount.value)) {
+   fieldsValidation.value.amount = false;
+   errorMsg.value = 'Invalid amount. Amount has to be greater than 0';
+   return;
+ }

241-246: Enhance error message clarity

The error message could be more specific about acceptable values, especially since there's a minimum amount check later in the code (0.000001).

  if (!isNumericPositive(amount.value)) {
    fieldsValidation.value.amount = false;
-   errorMsg.value = 'Invalid amount. Amount has to be greater than 0';
+   errorMsg.value = 'Invalid amount. Please enter a positive number (minimum 0.000001)';
    return;
  }
packages/extension/src/providers/polkadot/ui/send-transaction/index.vue (3)

462-465: Consider simplifying the amount validation

The current implementation can be made more concise while maintaining the same functionality.

-      const checkedValue = amount.value?.toString() ?? '0';
-      const rawAmount = toBN(
-        toBase(
-          isNumericPositive(checkedValue) ? checkedValue : '0',
-          selectedAsset.value.decimals ?? 0,
-        ),
+      const rawAmount = toBN(
+        toBase(
+          isNumericPositive(amount.value?.toString() ?? '0') ? amount.value : '0',
+          selectedAsset.value.decimals ?? 0,
+        ),

489-491: Consider optimizing validation order

The current validation might attempt to check isNumericPositive on an undefined value. Consider reordering the conditions for better efficiency.

   if (
-    amount.value !== undefined &&
     amount.value !== '' &&
+    amount.value !== undefined &&
     isNumericPositive(amount.value) &&

Line range hint 202-490: Consider centralizing validation logic

The validation for positive numeric values is currently duplicated across multiple computed properties and methods. Consider extracting this into a single computed property that other parts of the component can reference.

Example approach:

const isValidAmount = computed(() => {
  return amount.value !== undefined && 
         amount.value !== '' && 
         isNumericPositive(amount.value);
});

This would:

  1. Reduce code duplication
  2. Make validation changes easier to maintain
  3. Ensure consistent validation behavior
packages/extension/src/providers/ethereum/ui/send-transaction/index.vue (3)

356-358: Ensure consistent validation approach.

The validation in nativeBalanceAfterTransaction uses a local variable as a fallback, which is good. However, this approach differs from other validations in the component.

Consider extracting a common validation function:

+const getValidAmount = (value: string) => {
+  return isNumericPositive(value) ? value : '0';
+};

 // In nativeBalanceAfterTransaction
-const locAmount = isNumericPositive(amount.value) ? amount.value : '0';
+const locAmount = getValidAmount(amount.value);

500-500: Verify validation order in isInputsValid.

The numeric validation is placed at the end of the validation chain. Consider moving it earlier to fail fast and avoid unnecessary validations.

 const isInputsValid = computed<boolean>(() => {
+  if (!isNumericPositive(sendAmount.value)) return false;
   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;
   }
   if (new BigNumber(sendAmount.value).gt(assetMaxValue.value)) return false;
   if (gasCostValues.value.REGULAR.nativeValue === '0') return false;
-  if (!isNumericPositive(sendAmount.value)) return false;
   return true;
 });

Line range hint 1-800: Consider adding error messages for validation failures.

The component performs various validations but doesn't provide specific error messages to users when validation fails. This could impact user experience.

Consider adding a computed property for validation error messages:

const validationError = computed(() => {
  if (!isNumericPositive(sendAmount.value)) 
    return 'Please enter a valid positive amount';
  if (!props.network.isAddress(addressTo.value))
    return 'Invalid address';
  if (new BigNumber(sendAmount.value).gt(assetMaxValue.value))
    return 'Insufficient balance';
  return '';
});
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4a368ff and 31bb64b.

📒 Files selected for processing (5)
  • packages/extension/src/libs/utils/number-formatter.ts (2 hunks)
  • packages/extension/src/providers/bitcoin/ui/send-transaction/index.vue (2 hunks)
  • packages/extension/src/providers/ethereum/ui/send-transaction/index.vue (4 hunks)
  • packages/extension/src/providers/kadena/ui/send-transaction/index.vue (2 hunks)
  • packages/extension/src/providers/polkadot/ui/send-transaction/index.vue (6 hunks)
🔇 Additional comments (9)
packages/extension/src/libs/utils/number-formatter.ts (2)

Line range hint 525-535: LGTM!

The export statement is correctly updated to include the new function while maintaining consistent formatting.


520-523: Verify integration with transaction components

The function implementation aligns with the PR objectives for preventing white page issues. Let's verify its integration across different blockchain implementations.

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

152-155: LGTM: Clean import of validation utilities

The addition of formatFloatingPointValue and isNumericPositive utilities aligns well with the PR's objective of preventing issues with invalid values.

packages/extension/src/providers/kadena/ui/send-transaction/index.vue (2)

113-116: LGTM: Clean import addition

The import statement is properly structured to include the new isNumericPositive utility function.


241-246: LGTM: Core validation functionality

The added validation successfully prevents processing of invalid values, which addresses the PR objective of preventing white page issues on invalid input.

packages/extension/src/providers/polkadot/ui/send-transaction/index.vue (2)

202-207: LGTM: Enhanced amount validation

The addition of isNumericPositive check ensures that only valid positive numeric values are processed when calculating existential deposit warnings.


258-260: LGTM: Consistent amount validation

The addition of isNumericPositive check maintains consistent validation behavior across the component.

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

171-174: LGTM: Import statement is correctly structured.

The import statement correctly includes both formatFloatingPointValue and isNumericPositive from the number formatter utility.


225-229: Verify edge cases in amount validation.

The numeric validation is good, but consider these edge cases:

  1. Scientific notation (e.g., "1e18")
  2. Numbers larger than Number.MAX_SAFE_INTEGER
  3. Extremely small numbers that could lead to precision loss

Consider using BigNumber.js for comprehensive validation:

-  if (!isNumericPositive(sendAmount.value)) {
+  const amount = new BigNumber(sendAmount.value);
+  if (amount.isNaN() || !amount.isPositive() || amount.gt(new BigNumber(2).pow(256))) {
     return false;
   }

@gamalielhere gamalielhere requested a review from kvhnuke November 15, 2024 01:12
@gamalielhere gamalielhere merged commit 2f67395 into develop Nov 26, 2024
@gamalielhere gamalielhere deleted the fix/paste-invalid-white-screen branch November 26, 2024 21:28
@coderabbitai coderabbitai bot mentioned this pull request Dec 4, 2024
@coderabbitai coderabbitai bot mentioned this pull request Feb 27, 2025
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.

3 participants