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 chain validation for swap #3271

Merged
merged 1 commit into from
Oct 11, 2024

Conversation

abtestingalpha
Copy link
Collaborator

@abtestingalpha abtestingalpha commented Oct 11, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new constant for supported swap chain IDs.
    • Added enhanced validation for swap operations, ensuring compatibility with specified chains.
  • Bug Fixes

    • Updated validation logic to improve accuracy in swap operations.
  • Tests

    • Added a new test case for validating swaps on unsupported chains.

Copy link
Contributor

coderabbitai bot commented Oct 11, 2024

Walkthrough

The changes involve updates to several files within the REST API package. A new constant SUPPORTED_SWAP_CHAIN_IDS has been added to index.ts, and the swap validation logic in swapRoute.ts has been enhanced by incorporating additional checks. A new function validSwapChain has been introduced to validate supported swap chains, while the existing validSwap function has been renamed to validSwapTokens. Additionally, tests in swapRoute.test.ts have been updated to include a new token and a test case for unsupported swaps.

Changes

File Path Change Summary
packages/rest-api/src/constants/index.ts Added constant SUPPORTED_SWAP_CHAIN_IDS; import for CHAINS updated.
packages/rest-api/src/routes/swapRoute.ts Updated imports for validation; added checks for swap support; modified validation logic for tokens.
packages/rest-api/src/tests/swapRoute.test.ts Added new token USDT and a test case for unsupported chain swaps.
packages/rest-api/src/validations/validSwapChain.ts Introduced function validSwapChain to validate chain IDs against SUPPORTED_SWAP_CHAIN_IDS.
packages/rest-api/src/validations/validSwapTokens.ts Renamed function validSwap to validSwapTokens, keeping parameters and logic unchanged.

Possibly related PRs

  • REST API Improvements [SLT-179] #3133: The changes in this PR involve adding a new parameter to the swaptxinfo function, which relates to the validation of token addresses, similar to the validation logic introduced in the main PR for the swap operations.
  • fix(rest-api): Adds validSwap validation [SLT-321] #3247: This PR introduces a validation mechanism for swap requests, ensuring that both tokens are valid and swappable, which directly relates to the changes made in the main PR regarding the validation logic for swap operations.

Suggested labels

size/m, Sol, Typescript, needs-yarn-install

Suggested reviewers

  • trajan0x
  • Defi-Moses
  • bigboydiamonds

🐰 In the code we hop and play,
New constants here to save the day!
With tokens swappable, chains in line,
Our validation's simply divine!
So let’s code and test, oh what a thrill,
For swaps that work, we’ve got the skill! 🌟


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

🧹 Outside diff range and nitpick comments (6)
packages/rest-api/src/validations/validSwapChain.ts (1)

3-5: Consider adding a JSDoc comment for better documentation.

To improve code readability and provide better documentation, consider adding a JSDoc comment above the function. This will help other developers understand the function's purpose, parameters, and return value at a glance.

Here's a suggested JSDoc comment:

/**
 * Checks if the given chain ID is supported for swaps.
 * @param {number | string} chain - The chain ID to validate.
 * @returns {boolean} True if the chain is supported, false otherwise.
 */
export const validSwapChain = (chain: number | string) => {
  // ... existing implementation
}
packages/rest-api/src/validations/validSwapTokens.ts (2)

Line range hint 3-16: Consider adding chain validation

The function doesn't validate the chain parameter. Consider adding a check to ensure the provided chain is supported before proceeding with token validation.

Here's a suggested improvement:

+ import { SUPPORTED_SWAP_CHAIN_IDS } from '../constants'

 export const validSwapTokens = (
   chain: number | string,
   fromToken: string,
   toToken: string
 ) => {
+  if (!SUPPORTED_SWAP_CHAIN_IDS.includes(Number(chain))) {
+    return false
+  }
   const fromTokenInfo = tokenAddressToToken(chain.toString(), fromToken)
   const toTokenInfo = tokenAddressToToken(chain.toString(), toToken)

   if (!fromTokenInfo || !toTokenInfo) {
     return false
   }

   return fromTokenInfo.swappable.includes(toToken)
 }

Line range hint 3-16: Enhance error handling

The current implementation returns a boolean value, which doesn't provide detailed information about why a swap might be invalid. Consider enhancing the error handling to provide more specific error messages.

Here's a suggested improvement:

 export const validSwapTokens = (
   chain: number | string,
   fromToken: string,
   toToken: string
-) => {
+): { valid: boolean; reason?: string } => {
+  if (!SUPPORTED_SWAP_CHAIN_IDS.includes(Number(chain))) {
+    return { valid: false, reason: 'Unsupported chain' }
+  }
   const fromTokenInfo = tokenAddressToToken(chain.toString(), fromToken)
   const toTokenInfo = tokenAddressToToken(chain.toString(), toToken)

   if (!fromTokenInfo || !toTokenInfo) {
-    return false
+    return { valid: false, reason: 'Invalid token information' }
   }

-  return fromTokenInfo.swappable.includes(toToken)
+  return {
+    valid: fromTokenInfo.swappable.includes(toToken),
+    reason: fromTokenInfo.swappable.includes(toToken) ? undefined : 'Tokens not swappable'
+  }
 }
packages/rest-api/src/constants/index.ts (1)

12-29: Approved: New constant added correctly, but consider adding a comment.

The new SUPPORTED_SWAP_CHAIN_IDS constant is well-structured and uses the CHAINS object consistently. However, to improve maintainability and clarity, consider adding a brief comment explaining the purpose of this constant and any criteria for inclusion in this list.

Consider adding a comment above the constant, like this:

/**
 * List of chain IDs that support swap functionality.
 * This constant is used for validating swap requests across supported networks.
 */
export const SUPPORTED_SWAP_CHAIN_IDS = [
  // ... (existing chain IDs)
]

Also, it might be helpful to document the process for updating this list if new chains need to be added or removed in the future.

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

81-94: LGTM: New test case for unsupported chain swap

The new test case effectively validates the behavior for swap attempts on unsupported chains, which aligns with the PR objectives. The test structure and assertions are appropriate.

Suggestion for improvement:
Consider using a constant for the unsupported chain ID (59144) to enhance maintainability. This could be defined at the top of the file or imported from a constants file if it's used elsewhere.

Example:

const UNSUPPORTED_CHAIN_ID = '59144';

// In the test case
chain: UNSUPPORTED_CHAIN_ID,

This change would make it easier to update the unsupported chain ID if needed in the future.

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

167-173: LGTM: New validation for supported swap chains.

The addition of validSwapChain check improves the API's robustness by ensuring only supported chains are used for swaps. This is a valuable safeguard against potential errors.

Consider extracting the error message to a constant for consistency and easier maintenance:

+const UNSUPPORTED_SWAP_CHAIN_ERROR = 'Swap not supported for given chain';

 check()
   .custom((_value, { req }) => {
     const { chain } = req.query
     return validSwapChain(chain)
   })
-  .withMessage('Swap not supported for given chain'),
+  .withMessage(UNSUPPORTED_SWAP_CHAIN_ERROR),
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9e5340b and 7ce97d8.

📒 Files selected for processing (5)
  • packages/rest-api/src/constants/index.ts (2 hunks)
  • packages/rest-api/src/routes/swapRoute.ts (2 hunks)
  • packages/rest-api/src/tests/swapRoute.test.ts (2 hunks)
  • packages/rest-api/src/validations/validSwapChain.ts (1 hunks)
  • packages/rest-api/src/validations/validSwapTokens.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (9)
packages/rest-api/src/validations/validSwapChain.ts (1)

1-5: LGTM! The implementation looks correct and concise.

The validSwapChain function effectively validates if a given chain ID is supported for swaps. It handles both number and string inputs, which provides good flexibility.

packages/rest-api/src/validations/validSwapTokens.ts (2)

3-3: Approve function name change

The renaming of the function from validSwap to validSwapTokens is a good improvement. The new name is more descriptive and accurately reflects the function's purpose of validating swap tokens.


3-3: Verify impact of function name change

The function name has been changed from validSwap to validSwapTokens. Ensure that all imports and usages of this function have been updated accordingly throughout the codebase.

Run the following script to check for any remaining usages of the old function name:

✅ Verification successful

Impact of Function Name Change Verified

All imports and usages of the old function name validSwap have been successfully updated to validSwapTokens and validSwapChain. No remaining usages of validSwap found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for any remaining usages of the old function name 'validSwap'

# Test: Search for 'validSwap' in all TypeScript and JavaScript files
rg --type-add 'ts:*.{ts,tsx}' --type-add 'js:*.{js,jsx}' --type ts --type js 'validSwap'

Length of output: 677

packages/rest-api/src/constants/index.ts (2)

1-1: LGTM: Import statement is correct and necessary.

The new import statement for CHAINS is correctly added and is required for the new constant SUPPORTED_SWAP_CHAIN_IDS. This change follows good practices by importing only the necessary module.


Line range hint 1-29: Summary: Changes align with PR objective, minor improvement suggested.

The addition of the SUPPORTED_SWAP_CHAIN_IDS constant aligns well with the PR objective of adding chain validation for swap functionality. This constant will likely be used in the swap route validation logic mentioned in the PR summary. The implementation is correct and follows good practices.

To further improve the code:

  1. Consider adding a comment explaining the purpose and usage of the SUPPORTED_SWAP_CHAIN_IDS constant.
  2. Document the process for maintaining this list of supported chains.

These improvements will enhance the maintainability and clarity of the codebase for future developers working on swap functionality across different chains.

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

6-6: LGTM: Import statement updated correctly

The addition of USDT to the import statement is consistent with the new test case and aligns with the PR objectives.

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

11-12: LGTM: New imports for improved validation.

The addition of validSwapTokens and validSwapChain imports indicates a good separation of concerns for validation logic. This change aligns with best practices for modular code organization.


178-178: LGTM: Updated token validation function.

The change from validSwap to validSwapTokens improves code clarity by using a more specific function name. This modification aligns well with the principle of having clear and focused function names.


Line range hint 1-190: Summary: Improved swap validation enhances API robustness.

The changes in this file significantly improve the swap validation process by:

  1. Introducing separate validations for swap chains and tokens.
  2. Using more specific function names for better code clarity.
  3. Adding an additional layer of validation to ensure only supported chains are used for swaps.

These enhancements align well with the PR objectives and contribute to a more robust and maintainable API.

Comment on lines +3 to +5
export const validSwapChain = (chain: number | string) => {
return SUPPORTED_SWAP_CHAIN_IDS.includes(Number(chain))
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding error handling for invalid inputs.

While the current implementation works for valid numeric inputs, it doesn't explicitly handle non-numeric string inputs. Consider adding error handling to improve robustness.

Here's a suggested implementation with error handling:

export const validSwapChain = (chain: number | string): boolean => {
  const chainId = Number(chain);
  if (isNaN(chainId)) {
    throw new Error('Invalid chain ID: must be a number or numeric string');
  }
  return SUPPORTED_SWAP_CHAIN_IDS.includes(chainId);
}

This change will throw an error for non-numeric inputs, making it easier to debug issues related to invalid chain IDs.

Copy link

codecov bot commented Oct 11, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 31.76937%. Comparing base (2c90cf7) to head (7ce97d8).
Report is 2 commits behind head on master.

Additional details and impacted files
@@              Coverage Diff              @@
##              master       #3271   +/-   ##
=============================================
  Coverage   31.76937%   31.76937%           
=============================================
  Files            427         427           
  Lines          28496       28496           
  Branches          82          82           
=============================================
  Hits            9053        9053           
  Misses         18597       18597           
  Partials         846         846           
Flag Coverage Δ
packages 90.43902% <ø> (ø)

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.

Copy link

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 7ce97d8
Status: ✅  Deploy successful!
Preview URL: https://5a57fae9.sanguine-fe.pages.dev
Branch Preview URL: https://rest-api-validates-swap-chai.sanguine-fe.pages.dev

View logs

@abtestingalpha abtestingalpha merged commit 12fb1e5 into master Oct 11, 2024
36 checks passed
@abtestingalpha abtestingalpha deleted the rest-api/validates-swap-chain branch October 11, 2024 13:03
@coderabbitai coderabbitai bot mentioned this pull request 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