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(rest-api): Adds validSwap validation [SLT-321] #3247

Merged
merged 4 commits into from
Oct 9, 2024

Conversation

abtestingalpha
Copy link
Collaborator

@abtestingalpha abtestingalpha commented Oct 7, 2024

Description
When a user requests an invalid swap through the api, the response is a 500 instead of a 400 with error message. This adds a validation to the swapRoute to check tha the from and to token are swappable.

Summary by CodeRabbit

  • New Features

    • Introduced a validation step for swap operations to ensure supported token swaps.
    • Added a new function to check if a swap between specified tokens is valid based on their swappability.
  • Bug Fixes

    • Enhanced test coverage for invalid token swap scenarios, ensuring proper error handling.
  • Improvements

    • Updated token information output to include swappability details, providing users with more comprehensive data.

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

Walkthrough

The changes in this pull request enhance the swap route functionality within an Express application by introducing a new validation step for token swaps. A new function, validSwap, is added to validate the compatibility of token swaps based on the provided parameters. Additionally, the test suite for the swap route is updated to include tests for the newly introduced validation logic and the handling of the ETH token. The output of the tokenAddressToToken function is also modified to include a swappable property, providing more detailed token information.

Changes

File Path Change Summary
packages/rest-api/src/routes/swapRoute.ts Added import for validSwap. Included validation check using validSwap in the GET request handler.
packages/rest-api/src/tests/swapRoute.test.ts Added ETH to bridgeable tokens imports. Introduced new test case for invalid token swap combinations.
packages/rest-api/src/utils/tokenAddressToToken.ts Updated tokenAddressToToken to include swappable property in the returned object.
packages/rest-api/src/validations/validSwap.ts Introduced validSwap function to validate token swaps based on chain, fromToken, and toToken.

Possibly related PRs

Suggested labels

size/m

Suggested reviewers

  • trajan0x
  • bigboydiamonds

🐰 In the land of swaps, where tokens play,
A new check was added to brighten the day.
With validSwap in hand, the routes now gleam,
Ensuring each trade is more than a dream.
So hop along, friends, let’s celebrate right,
For swaps are now safer, and futures are bright! 🌟


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 11824e8 and a674a21.

📒 Files selected for processing (2)
  • packages/rest-api/src/routes/swapRoute.ts (2 hunks)
  • packages/rest-api/src/tests/swapRoute.test.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/rest-api/src/routes/swapRoute.ts
  • packages/rest-api/src/tests/swapRoute.test.ts

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

cloudflare-workers-and-pages bot commented Oct 7, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: a674a21
Status: ✅  Deploy successful!
Preview URL: https://1232df0c.sanguine-fe.pages.dev
Branch Preview URL: https://rest-api-valid-swap-path.sanguine-fe.pages.dev

View logs

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

🧹 Outside diff range and nitpick comments (3)
packages/rest-api/src/utils/tokenAddressToToken.ts (1)

19-19: Approve the addition of the swappable property with a suggestion for type safety.

The addition of the swappable property enhances the token information and aligns well with the PR objectives. This change will support the new validation mechanism for swap requests.

To improve type safety, consider defining an interface for the token info structure:

interface TokenInfo {
  symbol: string;
  decimals: number;
  swappable: boolean;
}

// Then use it in the function:
const tokenInfo: TokenInfo = chainData[tokenAddress];

This will ensure type consistency and make the code more robust against future changes.

packages/rest-api/src/tests/swapRoute.test.ts (1)

81-94: LGTM: New test case for invalid token combo

The new test case effectively validates the handling of invalid swap requests, which aligns with the PR objectives. It provides good coverage for the edge case where ETH to USDC swap is not supported.

Consider adding a comment explaining why this specific combination (ETH to USDC) is invalid. This would enhance the test's readability and provide context for future developers. For example:

// ETH to USDC direct swap is not supported in this implementation
it('should return 400 for invalid fromToken + toToken combo', async () => {
  // ... (rest of the test case)
})
packages/rest-api/src/routes/swapRoute.ts (1)

Line range hint 1-172: Summary: New validation enhances API robustness for swap requests.

The addition of the validSwap check significantly improves the API's ability to handle invalid swap requests. This change directly addresses the PR objective of returning a 400 error with a relevant message instead of a 500 error for unsupported swaps. The implementation is clean, modular, and follows good practices.

To fully validate this change, ensure that:

  1. The validSwap function in '../validations/validSwap' is correctly implemented.
  2. Appropriate unit tests are added or updated to cover this new validation scenario.
  3. The error handling middleware correctly processes this new validation error.

Consider adding logging for failed validations to help with monitoring and debugging in production.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4b49879 and dae2cdd.

📒 Files selected for processing (4)
  • packages/rest-api/src/routes/swapRoute.ts (2 hunks)
  • packages/rest-api/src/tests/swapRoute.test.ts (2 hunks)
  • packages/rest-api/src/utils/tokenAddressToToken.ts (1 hunks)
  • packages/rest-api/src/validations/validSwap.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (7)
packages/rest-api/src/validations/validSwap.ts (2)

1-1: LGTM: Import statement is correct and follows best practices.

The import of tokenAddressToToken from a relative path suggests good organization of the project structure.


7-9: LGTM: Validation logic is clear and prevents potential errors.

The check for both fromTokenInfo and toTokenInfo being truthy is a good safeguard against potential errors if token information couldn't be retrieved. This simple validation enhances the function's robustness.

packages/rest-api/src/tests/swapRoute.test.ts (2)

6-6: LGTM: ETH import added

The addition of ETH to the import statement is consistent with the PR objectives and necessary for the new test case.


Line range hint 1-124: Overall assessment: Changes improve test coverage

The modifications to this test file are well-aligned with the PR objectives. The addition of the ETH import and the new test case for invalid token combinations enhance the test coverage for the swap route functionality. The changes are minimal, focused, and maintain consistency with the existing code style and structure.

packages/rest-api/src/routes/swapRoute.ts (3)

11-11: LGTM: Import statement for validSwap is correctly added.

The import statement is properly placed and follows good practices for modularity by importing the validSwap function from a separate file.


166-172: LGTM: New validation check for swap support is well-implemented.

The new validation check is correctly placed within the existing array of checks and uses the appropriate methods from express-validator. The error message is clear and concise, and the use of destructuring to extract query parameters is a good practice.


166-172: Verify the implementation of the validSwap function.

The new validation relies on the validSwap function, which is imported from another file. To ensure the correctness of this validation, we should verify the implementation of the validSwap function.

Please run the following script to check the implementation of the validSwap function:

packages/rest-api/src/validations/validSwap.ts Outdated Show resolved Hide resolved
Copy link

codecov bot commented Oct 7, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 90.43902%. Comparing base (4b49879) to head (a674a21).
Report is 8 commits behind head on master.

Additional details and impacted files
@@                 Coverage Diff                 @@
##              master       #3247         +/-   ##
===================================================
- Coverage   91.00237%   90.43902%   -0.56335%     
===================================================
  Files             60          54          -6     
  Lines           1267        1025        -242     
  Branches         154          82         -72     
===================================================
- Hits            1153         927        -226     
+ Misses           111          95         -16     
  Partials           3           3                 
Flag Coverage Δ
packages 90.43902% <ø> (ø)
solidity ?

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@abtestingalpha abtestingalpha changed the title fix(rest-api): Adds validSwap validation fix(rest-api): Adds validSwap validation [SLT-321] Oct 8, 2024
@abtestingalpha abtestingalpha merged commit 0738536 into master Oct 9, 2024
36 checks passed
@abtestingalpha abtestingalpha deleted the rest-api/valid-swap-path branch October 9, 2024 14:21
This was referenced Nov 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant