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

feat: twinned swap input hook #4026

Open
wants to merge 12 commits into
base: stage
Choose a base branch
from

Conversation

crnbarr93
Copy link
Contributor

@crnbarr93 crnbarr93 commented Dec 28, 2024

What is the purpose of the change:

These changes refactor the buy/sell tab inputs to use a new hook: useTwinnedSwapInput. This hook takes both a fiat and token input along with a price and adjusts the values of each depending on the input of the other in relation to the price. For example at a token price of $0.50 if the user input $1 then the token amount would be 2. This change was to make the code more readable/maintainable and to also prevent infinite rerendering caused by the use of useEffect. This hook now primarily makes use of callbacks instead of useEffect, with the exception of the price updating as that can occur with no input.

Linear Task

FE-1273
LIM-287

Brief Changelog

  • Added a new useTwinnedSwapInput hook
  • Refactored several sections of PlaceLimitTool
  • Moved several number functions out of PlaceLimitTool
  • Automatically swaps input/quote type when selecting "Max" on Buy/Sell tabs

Testing and Verifying

Manually tested and added unit tests for the new hook.

@crnbarr93 crnbarr93 requested a review from a team December 28, 2024 10:47
Copy link

vercel bot commented Dec 28, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
osmosis-frontend ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 28, 2024 11:26am
3 Skipped Deployments
Name Status Preview Comments Updated (UTC)
osmosis-frontend-datadog ⬜️ Ignored (Inspect) Visit Preview Dec 28, 2024 11:26am
osmosis-frontend-dev ⬜️ Ignored (Inspect) Visit Preview Dec 28, 2024 11:26am
osmosis-testnet ⬜️ Ignored (Inspect) Visit Preview Dec 28, 2024 11:26am

}

if (price.isNegative()) {
console.error("INPUT WARNING: Price is negative");
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Should this throw an error?

Copy link
Contributor

coderabbitai bot commented Dec 28, 2024

Warning

Rate limit exceeded

@crnbarr93 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 0 minutes and 57 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between b9b583f and b15ad6c.

📒 Files selected for processing (4)
  • packages/web/components/place-limit-tool/index.tsx (2 hunks)
  • packages/web/hooks/input/use-amount-input.ts (1 hunks)
  • packages/web/hooks/use-twinned-swap-input.ts (1 hunks)
  • packages/web/utils/number.ts (1 hunks)

Walkthrough

This pull request introduces significant modifications to the token and fiat amount management in the swap interface. The primary focus is on the new custom hook useTwinnedSwapInput, which centralizes the logic for handling numerical inputs for both token and fiat amounts. The implementation removes outdated utility functions and streamlines the input handling in the PlaceLimitTool component. Additionally, a new test suite is added to validate the functionality of the new hook.

Changes

File Change Summary
packages/web/components/place-limit-tool/index.tsx Removed isValidNumericalRawInput utility, replaced transformAmount with new implementation, removed roundUpToDecimal and fixDecimalCount, simplified setAmountSafe, integrated useTwinnedSwapInput hook.
packages/web/hooks/use-twinned-swap-input.ts New hook added to manage synchronization of token and fiat amounts, including input handling and validation logic.
packages/web/utils/number.ts Added new utility functions: roundUpToDecimal, fixDecimalCount, and transformAmount for enhanced number handling.
packages/web/hooks/__tests__/use-twinned-swap-input.spec.ts New test suite for useTwinnedSwapInput hook with comprehensive test cases covering various input scenarios.

Possibly related PRs

Suggested reviewers

  • jonator
  • JoseRFelix

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 3

🧹 Nitpick comments (7)
packages/web/hooks/use-twinned-swap-input.ts (3)

8-10: Consider simplifying or inlining isEmptyString.

This helper function merely checks that the string is defined and non-whitespace. Inlining it or using a more concise check (e.g., !value?.trim()) might reduce indirection if it’s only used in a few places.


53-59: Improve error handling for reset logic.

reset silently clears values without indicating the cause in the UI or logs. Consider providing feedback or logs when a reset happens, especially if it's triggered by invalid user input.


129-152: Avoid code duplication when setting quote type.

setAllFiatAmounts and setAllTokenAmounts share logic to update quoteType based on market order scenarios. Extracting this logic into a shared helper function could improve maintainability and consistency.

packages/web/utils/number.ts (1)

119-139: Streamline decimal transformations in transformAmount.

While this function covers multiple edge cases (“.” prefix, trailing zeros), consider using a single, clearly commented flow to handle each scenario. This will make the function easier to maintain and extend for new edge cases.

packages/web/hooks/__tests__/use-twinned-swap-input.spec.ts (2)

58-179: Parametric test coverage is thorough.

Testing “buy” vs. “sell” and “fiat” vs. “token” input scenarios ensures robust coverage of user interactions. Consider adding tests for boundary conditions, such as extremely large decimals or invalid inputs with partial decimal format (e.g., “0.”), if not already covered.


180-235: Excellent validation of price-change scenarios.

The tests correctly assert that the focused input remains the same and the non-focused input updates predictably. Include additional checks for corner cases (e.g., price transitioning from zero to a positive number) to further minimize regressions.

packages/web/components/place-limit-tool/index.tsx (1)

279-313: Enhance clarity in the inputValue memo.

The combination of focused, tab, and type logic can be tricky to follow. Adding inline comments or simplifying the conditions would facilitate maintenance. Consider separating the logic for “market” vs. “limit” into separate helper functions.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7b03c95 and a90ab85.

📒 Files selected for processing (4)
  • packages/web/components/place-limit-tool/index.tsx (3 hunks)
  • packages/web/hooks/__tests__/use-twinned-swap-input.spec.ts (1 hunks)
  • packages/web/hooks/use-twinned-swap-input.ts (1 hunks)
  • packages/web/utils/number.ts (1 hunks)
🔇 Additional comments (5)
packages/web/hooks/use-twinned-swap-input.ts (1)

91-121: Check for negative or zero prices earlier.

Currently, the code prints a console error at lines 98 and 163 if the price is negative or zero, then returns. Consider surfacing these states in the UI or applying stricter input validation before the user enters the editing flow to reduce confusion.

packages/web/utils/number.ts (1)

88-94: Be mindful of floating-point limitations in roundUpToDecimal.

Using Math.ceil with floating multipliers can produce unexpected results for very large or small numbers. If extreme precision is required, consider using a decimal library to handle these operations reliably.

packages/web/hooks/__tests__/use-twinned-swap-input.spec.ts (1)

8-37: Good use of an internal test component.

Wrapping the hook in a small test component simplifies state management for each test scenario and keeps tests readable. This approach helps ensure that multiple states and transitions are thoroughly covered.

packages/web/components/place-limit-tool/index.tsx (2)

47-52: Imports for the new hook and revised number utilities look good.

Leveraging centralized logic from useTwinnedSwapInput and transformAmount keeps the component lean and promotes reusability.


215-228: Appropriate usage of useTwinnedSwapInput.

Injecting the hook’s handlers into the existing state flow simplifies swap logic. Just ensure that any new parameters added to useTwinnedSwapInput are properly documented and tested here.

packages/web/hooks/use-twinned-swap-input.ts Outdated Show resolved Hide resolved
packages/web/utils/number.ts Outdated Show resolved Hide resolved
packages/web/components/place-limit-tool/index.tsx Outdated Show resolved Hide resolved
crnbarr93 and others added 3 commits December 28, 2024 10:52
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: 0

🧹 Nitpick comments (4)
packages/web/utils/number.ts (4)

91-94: Add input validation for edge cases.

The function should handle edge cases such as NaN, Infinity, or negative precision values to prevent unexpected behavior.

Consider this implementation:

 export function roundUpToDecimal(value: number, precision: number) {
+  if (!Number.isFinite(value)) return value;
+  if (precision < 0) precision = 0;
   const multiplier = Math.pow(10, precision || 0);
   return Math.ceil(value * multiplier) / multiplier;
 }

100-114: Add input validation and handle negative decimal counts.

The function should validate the input string format and handle negative decimal counts to prevent unexpected behavior.

Consider this implementation:

 export function fixDecimalCount(
   value: string,
   decimalCount = 18,
   rounding = false
 ) {
+  if (!isNumeric(value)) return "0";
+  if (decimalCount < 0) decimalCount = 0;
   if (rounding) {
     return roundUpToDecimal(parseFloat(value), decimalCount).toString();
   }
   const split = value.split(".");
   const integerPart = split[0];
   const fractionalPart = split[1] ? split[1].substring(0, decimalCount) : "";
   const result =
     integerPart + (decimalCount > 0 ? "." + fractionalPart : "");
   return result;
 }

120-140: Optimize period handling and add input validation.

The function can be optimized by:

  1. Adding input validation
  2. Combining period handling conditions
  3. Removing redundant trim() as proper input handling should prevent whitespace

Consider this implementation:

 export function transformAmount(
   value: string,
   decimalCount = 18,
   rounding = false
 ) {
+  if (!value || !isNumeric(value.replace(/\.$/, '0'))) return "0";
   let updatedValue = value;
-  if (value.endsWith(".") && value.length === 1) {
-    updatedValue = value + "0";
-  }
-
-  if (value.startsWith(".")) {
-    updatedValue = "0" + value;
-  }
+  // Handle both leading and trailing periods
+  updatedValue = updatedValue.replace(/^\./, '0.').replace(/\.$/, '.0');

   const decimals = countDecimals(updatedValue);
   return decimals > decimalCount
     ? fixDecimalCount(updatedValue, decimalCount, rounding)
-    : updatedValue
-  ).trim();
+    : updatedValue;
 }

87-140: Well-structured number handling system.

The three new functions form a well-designed hierarchy for handling numerical inputs in the context of the new useTwinnedSwapInput hook:

  1. roundUpToDecimal provides the foundational rounding logic
  2. fixDecimalCount builds on it to ensure consistent decimal places
  3. transformAmount handles user input edge cases

This layered approach promotes code reuse and separation of concerns.

Consider extracting these number handling utilities into a separate package that can be shared across different parts of the application, as precise number handling is crucial for financial calculations.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a90ab85 and b9b583f.

📒 Files selected for processing (1)
  • packages/web/utils/number.ts (1 hunks)
🔇 Additional comments (1)
packages/web/utils/number.ts (1)

120-140: Verify usage in PlaceLimitTool component.

The function is used in the PlaceLimitTool component. Let's verify its integration to ensure it's properly handling all input cases.

✅ Verification successful

transformAmount usage in PlaceLimitTool is properly integrated with appropriate error handling

The verification shows that:

  • transformAmount is used correctly in PlaceLimitTool with proper decimal handling (using 2 and 10 decimal places depending on the context)
  • The function is well-tested through its dependencies (countDecimals, fixDecimalCount, trimPlaceholderZeros)
  • Error handling is in place for various scenarios including zero amounts, empty amounts, and insufficient funds
  • The component properly handles input validation and displays appropriate error messages

Key integration points:

  • Used for both sell and buy scenarios with market tab handling
  • Integrated with getTrimmedAmount for proper input formatting
  • Connected to the swap state error handling system
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of transformAmount in PlaceLimitTool

# Find all usages of transformAmount in the codebase
echo "Searching for transformAmount usage..."
rg -A 5 "transformAmount" packages/web/components/place-limit-tool/

# Find test coverage for transformAmount
echo "Searching for transformAmount tests..."
rg -A 5 "transformAmount" "packages/web/**/*.spec.ts" "packages/web/**/*.test.ts"

Length of output: 2892


Script:

#!/bin/bash
# Let's verify the test coverage and implementation details

# Search for test files with different extensions
echo "Searching for test files..."
rg -A 5 "transformAmount" "packages/web/**/*test*" "packages/web/**/*spec*"

# Check the implementation details of getTrimmedAmount
echo "Checking getTrimmedAmount implementation..."
rg -A 5 "getTrimmedAmount" packages/web/components/place-limit-tool/

# Check for any error handling or validation related to transformAmount
echo "Checking error handling..."
rg -A 5 "catch|error.*transformAmount" packages/web/components/place-limit-tool/

# Look for any related utility functions
echo "Checking related utilities..."
rg -A 5 "countDecimals|fixDecimalCount" packages/web/utils/

Length of output: 4184


Script:

#!/bin/bash
# Let's check the test coverage for transformAmount and its dependencies

# Search for test files specifically for number utils
echo "Checking number utils tests..."
cat packages/web/utils/__tests__/number.spec.ts

# Check for any validation or error states in PlaceLimitTool
echo "Checking validation in PlaceLimitTool..."
rg "validation|error|invalid" packages/web/components/place-limit-tool/index.tsx

# Look for any other components using transformAmount
echo "Checking other usages of transformAmount..."
rg -l "transformAmount" packages/web/

Length of output: 8878

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.

1 participant