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: use normalized decimal count for fromAmount calculation #164

Merged
merged 2 commits into from
Nov 4, 2024

Conversation

jjramirezn
Copy link
Contributor

When the fromToken has fewer decimals than toToken, the amount returned by prepareXchainFromAmountCalculation was wrong because of mismatch in the decimals used for slippage calculation and the final decimals used to format the amount.

Afther packaging, get package in peanut-ui: peanutprotocol/peanut-ui#508

Copy link

coderabbitai bot commented Nov 4, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes primarily involve modifications to the src/util.ts file, specifically the prepareXchainFromAmountCalculation function, which now returns a string formatted to a fixed number of decimal places based on fromToken.decimals. A new utility function, stringToFixed, has been added to handle the formatting. Minor adjustments include improved error handling. Additionally, a new test suite was created in test/unit/util.test.ts to enhance coverage for the modified function, including mocking of the fetch function to simulate responses.

Changes

File Change Summary
src/util.ts - Modified prepareXchainFromAmountCalculation to return a string formatted to fixed decimal places.
- Added new function stringToFixed for formatting strings.
- Improved error handling in prepareXchainFromAmountCalculation.
test/unit/util.test.ts - Added a new test suite for prepareXchainFromAmountCalculation, including setup for mocking fetch and verifying calculation correctness.

Possibly related PRs

  • Request Links #147: This PR introduces the getStringAmount function, which enhances the handling of token amounts, similar to the stringToFixed function added in the main PR for formatting numbers as strings.
  • fix: resolve ens when preparing request xchain #154: This PR modifies the prepareXchainRequestFulfillmentTransaction function to include ENS resolution, which is relevant to the changes made in prepareXchainFromAmountCalculation in the main PR, as both involve transaction preparation logic.
  • fix: don't send double amount for native xchain requests #162: This PR updates the prepareXchainRequestFulfillmentTransaction function to include a slippagePercentage parameter, which aligns with the changes in the main PR that also involve calculations related to slippage in token transactions.

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.

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.

@jjramirezn jjramirezn requested a review from Hugo0 November 4, 2024 12:49
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 (3)
test/unit/util.test.ts (2)

21-28: Consider simplifying mock cleanup.

Using both restoreAllMocks and clearAllMocks is redundant here. restoreAllMocks already resets the mock's implementation, while clearAllMocks only clears the mock's history. You can safely remove clearAllMocks.

 afterEach(() => {
   jest.restoreAllMocks()
-  jest.clearAllMocks()
 })

29-69: Consider adding more test cases for comprehensive coverage.

While the current test case validates the happy path with different decimal places (which aligns with the PR's objective), consider adding the following test cases:

  1. Error cases:
    • Invalid token addresses
    • API failures
    • Invalid decimal values
  2. Edge cases:
    • Same number of decimals for both tokens
    • Maximum possible decimal difference
    • Zero amount handling
  3. Slippage calculation verification:
    • Verify that the returned amount includes the correct slippage adjustment
  4. API request validation:
    • Verify the correct URLs are being called for price fetching

Here's an example of an additional test case for API validation:

it('should call API with correct URLs', async () => {
  // ... setup code ...
  
  await prepareXchainFromAmountCalculation({
    fromToken,
    toToken,
    toAmount,
    slippagePercentage,
  })

  expect(mockFetch).toHaveBeenNthCalledWith(
    1,
    expect.stringContaining(`tokenAddress=${fromToken.address}`)
  )
  expect(mockFetch).toHaveBeenNthCalledWith(
    2,
    expect.stringContaining(`tokenAddress=${toToken.address}`)
  )
})
src/util.ts (1)

745-745: Consider adding test cases for decimal normalization.

To ensure the decimal normalization remains correct, consider adding test cases that cover:

  1. Source token with more decimals than target token
  2. Source token with fewer decimals than target token
  3. Tokens with equal decimals

Would you like me to help generate these test cases?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 59df5ee and b7add12.

📒 Files selected for processing (2)
  • src/util.ts (1 hunks)
  • test/unit/util.test.ts (2 hunks)
🔇 Additional comments (3)
test/unit/util.test.ts (2)

1-3: LGTM! Clean import setup with proper mocking.

The import statements are clear and the mock setup follows Jest best practices.


60-65: Verify integration with peanut-ui repository.

Since this change will be used in the peanut-ui repository (PR #508), consider adding integration tests that simulate the exact usage patterns from the UI to ensure compatibility.

src/util.ts (1)

745-745: LGTM! The decimal normalization fix looks correct.

The change to use fromToken.decimals instead of normalizedDecimalCount in the final formatting ensures that the returned amount matches the decimal precision of the source token, which is the expected behavior for cross-chain token swaps.

Let's verify the decimal normalization with different token combinations:

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 (1)
src/util.ts (1)

768-768: Remove unused variable from destructuring.

The _ variable is assigned but never used. Consider removing it from the destructuring assignment.

-const [_, intPart, decimals] = match
+const [, intPart, decimals] = match
🧰 Tools
🪛 eslint

[error] 768-768: '_' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b7add12 and a3f5205.

📒 Files selected for processing (2)
  • src/util.ts (2 hunks)
  • test/unit/util.test.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/unit/util.test.ts
🧰 Additional context used
🪛 eslint
src/util.ts

[error] 768-768: '_' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)

🔇 Additional comments (2)
src/util.ts (2)

745-746: LGTM! Decimal normalization looks correct.

The changes properly handle decimal precision by first formatting with the normalized decimal count and then adjusting to match the source token's decimals.


764-771: LGTM! Well-implemented string formatting utility.

The stringToFixed function:

  • Correctly handles decimal string formatting
  • Properly manages edge cases (no decimal point, empty decimal part)
  • Uses appropriate padding and slicing for precision control
🧰 Tools
🪛 eslint

[error] 768-768: '_' is assigned a value but never used.

(@typescript-eslint/no-unused-vars)

@Hugo0 Hugo0 merged commit baf05ab into develop Nov 4, 2024
@coderabbitai coderabbitai bot mentioned this pull request Nov 4, 2024
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