Skip to content

Comments

fix/PRO-3405/exchange-max-value-blocker#328

Merged
RanaBug merged 1 commit intostagingfrom
fix/PRO-3405/exchange-max-value-blocker
Jun 3, 2025
Merged

fix/PRO-3405/exchange-max-value-blocker#328
RanaBug merged 1 commit intostagingfrom
fix/PRO-3405/exchange-max-value-blocker

Conversation

@RanaBug
Copy link
Collaborator

@RanaBug RanaBug commented Jun 3, 2025

Description

  • Blocking value to max including deployment cost FIX

How Has This Been Tested?

  • Unit tests and manual testing

Screenshots (if appropriate):

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to change)

Summary by CodeRabbit

  • New Features
    • Added a mechanism to prevent offer fetching and display an error when the entered token amount exceeds the spendable balance after deployment cost is deducted.
  • Bug Fixes
    • Improved error message formatting for balance limits.
  • Other
    • Introduced a utility to convert numbers in exponential notation to standard decimal string format.

@RanaBug RanaBug requested review from IAmKio and vignesha22 June 3, 2025 11:24
@RanaBug RanaBug self-assigned this Jun 3, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 3, 2025

Walkthrough

This update introduces a new isAboveLimit flag in the Redux store to track if a user's entered token amount exceeds their available balance after deployment costs. The EnterAmount component is updated to use this flag, preventing offer fetching and displaying an error state when the limit is surpassed. Additionally, a utility function for formatting exponential numbers is added.

Changes

File(s) Change Summary
src/apps/the-exchange/components/EnterAmount/EnterAmount.tsx Integrates isAboveLimit Redux flag, updates input validation, error messaging, and offer-fetching logic.
src/apps/the-exchange/reducer/theExchangeSlice.ts Adds isAboveLimit state, corresponding reducer, and action creator to the Redux slice.
src/utils/number.tsx Adds formatExponential function to convert exponential numbers to full decimal strings; updates import statements.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant EnterAmount Component
    participant Redux Store
    participant OfferFetcher

    User->>EnterAmount Component: Inputs token amount
    EnterAmount Component->>Redux Store: Dispatch setIsAboveLimit (true/false)
    EnterAmount Component->>Redux Store: Update input value
    EnterAmount Component->>EnterAmount Component: Check isAboveLimit
    alt isAboveLimit is false
        EnterAmount Component->>OfferFetcher: Fetch best swap offer
    else isAboveLimit is true
        EnterAmount Component--xOfferFetcher: Prevent offer fetch
        EnterAmount Component->>User: Show above-limit error
    end
Loading

Possibly related PRs

  • fix/PRO-3382/undeployed-wallet-cost #321: Implements deployment cost adjustments and error messaging logic, which is directly extended by the new isAboveLimit state and related input validation in this PR.

Suggested reviewers

  • IAmKio
  • vignesha22

Poem

In the field of numbers, a rabbit leaps,
Guarding your balance, no bounds it keeps.
If you hop too far, a warning appears,
Saving your tokens, allaying your fears.
With numbers now clear, exponential no more,
The Exchange is safer than ever before!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-03T11_26_33_554Z-debug-0.log

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

CodeRabbit Configuration 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.

Copy link
Contributor

@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

🧹 Nitpick comments (1)
src/apps/the-exchange/components/EnterAmount/EnterAmount.tsx (1)

201-206: Simplify the conditional logic for better maintainability.

The current implementation uses two separate if statements that could be consolidated for better readability and maintainability.

Consider refactoring to a single conditional:

-    if (tokenBalance && Number(value) > tokenBalance - (deploymentCost ?? 0)) {
-      dispatch(setIsAboveLimit(true));
-    }
-    if (tokenBalance && Number(value) <= tokenBalance - (deploymentCost ?? 0)) {
-      dispatch(setIsAboveLimit(false));
-    }
+    if (tokenBalance) {
+      const isAboveBalanceLimit = Number(value) > tokenBalance - (deploymentCost ?? 0);
+      dispatch(setIsAboveLimit(isAboveBalanceLimit));
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f184be5 and adf40fc.

⛔ Files ignored due to path filters (1)
  • src/apps/pillarx-app/components/MediaGridCollection/tests/__snapshots__/DisplayCollectionImage.test.tsx.snap is excluded by !**/*.snap
📒 Files selected for processing (3)
  • src/apps/the-exchange/components/EnterAmount/EnterAmount.tsx (6 hunks)
  • src/apps/the-exchange/reducer/theExchangeSlice.ts (4 hunks)
  • src/utils/number.tsx (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/apps/the-exchange/components/EnterAmount/EnterAmount.tsx (3)
src/apps/the-exchange/hooks/useReducerHooks.tsx (1)
  • useAppSelector (6-6)
src/utils/number.tsx (1)
  • formatExponential (77-111)
src/apps/the-exchange/reducer/theExchangeSlice.ts (1)
  • setIsAboveLimit (115-117)
🪛 Biome (1.9.4)
src/utils/number.tsx

[error] 1-1: Do not shadow the global "parseInt" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: unit-tests
  • GitHub Check: build
🔇 Additional comments (5)
src/apps/the-exchange/reducer/theExchangeSlice.ts (1)

27-27: LGTM! Clean Redux state management implementation.

The isAboveLimit flag is properly integrated into the Redux slice with correct typing, initialization, and action creators. This follows Redux Toolkit best practices perfectly.

Also applies to: 54-54, 115-117, 139-139

src/apps/the-exchange/components/EnterAmount/EnterAmount.tsx (3)

9-9: Good integration of the isAboveLimit state.

The Redux state integration is clean and follows the established patterns in the component.

Also applies to: 77-79


163-165: Excellent deployment cost integration in balance validation.

The logic correctly accounts for deployment costs when validating token limits, and the enhanced error message using formatExponential provides clear feedback to users about their spendable balance.


180-180: Smart optimization to prevent unnecessary API calls.

Preventing offer fetching when isAboveLimit is true is an excellent optimization that avoids wasted API calls. The cleanup to set isOfferLoading(false) is also good practice.

Also applies to: 186-186

src/utils/number.tsx (1)

77-111:

Details

✅ Verification successful

Verify the formatExponential function with edge cases.

The function logic appears correct for converting exponential notation to decimal strings, but given its complexity, it should be thoroughly tested with various edge cases.

Please test this function with edge cases to ensure correctness:


🏁 Script executed:

#!/bin/bash
# Test formatExponential function with various edge cases

cat > test_format_exponential.js << 'EOF'
// Import the function (assuming it can be imported in Node.js context)
const formatExponential = (num) => {
  const str = num.toString();
  if (!str.includes('e') && !str.includes('E')) {
    return str;
  }
  const [mantissa, exponent] = str.toLowerCase().split('e');
  const exp = parseInt(exponent, 10);
  const [intPart, fracPart = ''] = mantissa.split('.');
  const decimalPlaces = exp > 0 ? exp : -exp;
  if (exp > 0) {
    const newIntPart = intPart + (fracPart + '0'.repeat(decimalPlaces)).slice(0, decimalPlaces);
    const newFracPart = (fracPart + '0'.repeat(decimalPlaces)).slice(decimalPlaces);
    const final = newFracPart ? `${newIntPart}.${newFracPart}` : newIntPart;
    return final;
  }
  const newIntPart = '0'.repeat(decimalPlaces - intPart.length) + intPart;
  const final = `0.${newIntPart}${fracPart}`;
  return final;
};

// Test cases
const testCases = [
  1.23e-4,     // Small positive number
  1.23e4,      // Large positive number  
  1.23e-10,    // Very small number
  1.23e10,     // Very large number
  1e-5,        // No fractional part in mantissa
  1.2345e-3,   // Multiple decimal places
  0,           // Zero
  123,         // Regular number (no exponential)
  -1.23e-4     // Negative number
];

testCases.forEach(num => {
  console.log(`Input: ${num}, Output: "${formatExponential(num)}"`);
});
EOF

node test_format_exponential.js

Length of output: 347


formatExponential passes all tested edge cases

All tried inputs—including very small/large exponents (positive & negative), zero, and non-exponential numbers—produce the correct decimal strings. No further changes needed.

@@ -1,4 +1,4 @@
import { parseInt as parseIntLodash } from 'lodash';
import { parseInt, parseInt as parseIntLodash } from 'lodash';
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the shadowed global parseInt import.

The static analysis tool correctly identifies that importing parseInt shadows the global parseInt property, which can lead to confusion about variable origins.

Apply this fix to remove the shadowed import:

-import { parseInt, parseInt as parseIntLodash } from 'lodash';
+import { parseInt as parseIntLodash } from 'lodash';

Then update line 88 to use the native parseInt:

-  const exp = parseInt(exponent);
+  const exp = parseInt(exponent, 10);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import { parseInt, parseInt as parseIntLodash } from 'lodash';
// In src/utils/number.tsx
// --- Update the import to avoid shadowing the global parseInt
-import { parseInt, parseInt as parseIntLodash } from 'lodash';
+import { parseInt as parseIntLodash } from 'lodash';
// … other code …
// --- At line 88, use the native parseInt with an explicit radix
- const exp = parseInt(exponent);
+ const exp = parseInt(exponent, 10);
🧰 Tools
🪛 Biome (1.9.4)

[error] 1-1: Do not shadow the global "parseInt" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

🤖 Prompt for AI Agents
In src/utils/number.tsx at line 1, the import statement imports `parseInt` from
lodash, which shadows the global `parseInt` function and causes confusion.
Remove the import of `parseInt` from lodash entirely to avoid shadowing. Then,
at line 88, update the code to use the native global `parseInt` function instead
of the lodash version.

@cloudflare-workers-and-pages
Copy link

Deploying x with  Cloudflare Pages  Cloudflare Pages

Latest commit: adf40fc
Status: ✅  Deploy successful!
Preview URL: https://504fae3f.x-e62.pages.dev
Branch Preview URL: https://fix-pro-3405-exchange-max-va.x-e62.pages.dev

View logs

Copy link
Contributor

@vignesha22 vignesha22 left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Collaborator

@IAmKio IAmKio left a comment

Choose a reason for hiding this comment

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

LGTM

@RanaBug RanaBug merged commit 4101bd8 into staging Jun 3, 2025
7 of 8 checks passed
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