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/support swap oraidex osmosis #349

Merged
merged 11 commits into from
Oct 23, 2024
Merged

Conversation

haunv3
Copy link
Contributor

@haunv3 haunv3 commented Oct 16, 2024

Summary by CodeRabbit

  • New Features

    • Updated version of the @oraichain/oraidex-universal-swap package to 1.1.15.
    • Enhanced handling of EVM and Tron addresses in the swap processing logic.
    • Improved address generation and routing capabilities for cross-chain operations.
    • Added new methods for address validation and error handling in the UniversalSwapHelper.
  • Bug Fixes

    • Adjusted logic for token swaps to ensure better compatibility and routing checks.
    • Improved error messages for invalid recipient addresses.
    • Corrected typographical error in method name for calculating minimum receive.
  • Chores

    • Retained deprecated methods for backward compatibility.

Copy link

coderabbitai bot commented Oct 16, 2024

Walkthrough

The pull request includes updates to the @oraichain/oraidex-universal-swap package, specifically changing the version number from 1.1.14 to 1.1.15 in the package.json file. Additionally, the UniversalSwapHandler and UniversalSwapHelper classes have been modified to enhance functionality related to EVM address handling, including updates to several methods to accommodate new parameters and logic for managing addresses across different blockchain networks. The test suite has also been updated to reflect these changes.

Changes

File Change Summary
packages/universal-swap/package.json Version updated from 1.1.14 to 1.1.15.
packages/universal-swap/src/handler.ts Added import of EVM_CHAIN_IDS, refactored processUniversalSwap into getToAddressUniversalSwap and processUniversalSwap, enhanced address validation and handling for EVM and Tron addresses.
packages/universal-swap/src/helper.ts Updated generateAddress, getSourceReceiver, and addOraiBridgeRoute methods to include EVM address handling and parameters, improved error handling, and deprecated outdated methods.
packages/universal-swap/tests/helper.spec.ts Added new test cases and updated existing tests to reflect changes in address handling and validation.
packages/universal-swap/tests/index.spec.ts Updated StubCosmosWallet and test cases to reflect new default addresses and ensure accurate message generation.
packages/universal-swap/src/msg/chains/oraichain.ts Refined genExecuteMsg method to ensure correct message structure for contract execution on Oraichain.

Possibly related PRs

Suggested reviewers

  • ducphamle2
  • trung2891
  • quangdz1704
  • trungbach

Poem

🐇 In the land of code where rabbits play,
A version jumps up, hip-hip-hooray!
With EVM magic, our swaps now shine,
Addressing all chains, oh so fine!
Hopping through logic, swift and bright,
Universal swaps, a coder's delight! 🌟


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.

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

🧹 Outside diff range and nitpick comments (1)
packages/universal-swap/src/handler.ts (1)

1202-1203: Nitpick: Remove redundant initialization of evmAddress to undefined

Variables declared with let are initialized to undefined by default in JavaScript/TypeScript. You can omit the = undefined for brevity and clarity.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 09c7db1 and 236d83b.

📒 Files selected for processing (3)
  • packages/universal-swap/package.json (1 hunks)
  • packages/universal-swap/src/handler.ts (5 hunks)
  • packages/universal-swap/src/helper.ts (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/universal-swap/package.json
🧰 Additional context used
🔇 Additional comments (8)
packages/universal-swap/src/helper.ts (2)

331-341: Update generateAddress Method to Include evmInfo: Approved

The changes to the generateAddress method correctly add the optional evmInfo parameter, enhancing its functionality to handle EVM addresses. The types are properly specified, and the implementation is sound.


373-373: Addition of evmAddress Parameter in addOraiBridgeRoute: Approved

The addition of the optional evmAddress parameter to the addresses object enhances flexibility in managing EVM addresses during route addition. No issues found.

packages/universal-swap/src/handler.ts (6)

1218-1223: Code logic for detecting EVM chains appears correct

The implementation correctly identifies routes involving Ethereum and BSC chains using the hasEvm flag.


1224-1227: Code logic for detecting TRON chain appears correct

The hasTron flag correctly checks if any route involves the TRON chain.


1230-1235: Assignment of evmAddress based on EVM flags is appropriate

The code correctly assigns evmAddress when either hasEvm or hasTron is true.


1243-1245: Passing recipientAddress and evmAddress to addOraiBridgeRoute

The parameters recipientAddress and evmAddress are correctly passed to the addOraiBridgeRoute function to facilitate address handling.


1255-1265: Conditional assignment of evmInfo in addressParams is correct

The addressParams object properly sets evmInfo based on whether the originalToToken is not cosmos-based and evmAddress is defined.


1266-1268: Updating receiverAddresses with recipientAddress

The code correctly updates receiverAddresses with the recipientAddress for the current network when a recipient address is provided.

packages/universal-swap/src/helper.ts Show resolved Hide resolved
packages/universal-swap/src/helper.ts Outdated Show resolved Hide resolved
packages/universal-swap/src/helper.ts Outdated Show resolved Hide resolved
packages/universal-swap/src/handler.ts Outdated Show resolved Hide resolved
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: 4

🧹 Outside diff range and nitpick comments (11)
packages/universal-swap/tests/helper.spec.ts (3)

Line range hint 630-641: LGTM! Consider adding an assertion for the universalSwapType.

The changes improve the readability of the test case by introducing the sourceReceiver variable. The test now correctly checks the behavior of addOraiBridgeRoute when the swap route is empty.

As a minor improvement, consider adding an assertion for the universalSwapType property of the result to ensure it's set correctly.

You could add the following assertion:

expect(result.universalSwapType).toEqual("other-networks-to-oraichain");

Line range hint 660-717: LGTM! Consider adding edge cases to the test suite.

The updates to the unmarshalOraiBridgeRoute test cases improve their accuracy and realism by using more specific oraiReceiver values. This change reflects the expected behavior of the function more closely.

To further enhance the test suite, consider adding edge cases such as:

  1. An empty string input
  2. A malformed input string
  3. A string with extra delimiters

These additional test cases would help ensure the robustness of the unmarshalOraiBridgeRoute function.


Line range hint 1-1004: Overall improvements to test cases, but some areas need attention.

The changes in this file generally improve the test suite for the universal swap helper functions. The test cases are now more specific and realistic, particularly in the unmarshalOraiBridgeRoute tests. However, there are a few areas that could use attention:

  1. There's a commented-out test case for generateAddress that should either be implemented or removed.
  2. Some test cases could benefit from additional assertions to ensure all aspects of the function behavior are covered.
  3. Consider adding more edge cases to improve the robustness of the test suite.

Additionally, it might be helpful to add more descriptive comments for complex test cases to explain the purpose and expected behavior of each test.

packages/universal-swap/tests/index.spec.ts (3)

260-267: LGTM! Consider adding a comment explaining the address format.

The changes to the getKeplrAddr method improve test coverage by adding support for the Osmosis chain and updating the default Oraichain address. This is a good improvement for testing different chain scenarios.

Consider adding a brief comment explaining the format of these test addresses (e.g., why they end with "1234" for test chains). This would improve code readability and make it easier for other developers to understand the test setup.


349-349: LGTM! Consider using a constant for test addresses.

The receiver address in the IBC transfer messages has been correctly updated to use the Osmosis address ("osmo1234") instead of the previous Oraichain address. This change aligns with the modifications in the StubCosmosWallet class and improves the accuracy of the test cases for Osmosis-related transfers.

For better maintainability and consistency, consider defining these test addresses (e.g., "osmo1234", "orai1234") as constants at the top of the file or in a separate test utilities file. This would make it easier to update all test cases if the addresses need to change in the future.

Also applies to: 438-438


993-993: LGTM! Consider grouping chain-specific test data.

The receiver addresses in various IBC transfer and swap messages have been correctly updated to use the appropriate addresses for different chains (Oraichain, Osmosis, Cosmos, Noble). These changes improve the accuracy and coverage of the test cases for multi-chain scenarios.

To improve code organization and readability, consider grouping all chain-specific test data (addresses, chain IDs, etc.) into a single object or constant. This would make it easier to manage and update test data for different chains in the future. For example:

const TEST_CHAIN_DATA = {
  Oraichain: { address: "orai1g4h64yjt0fvzv5v2j8tyfnpe5kmnetejvfgs7g", chainId: "Oraichain" },
  Osmosis: { address: "osmo1234", chainId: "osmosis-1" },
  Cosmos: { address: "cosmos12zyu8w93h0q2lcnt50g3fn0w3yqnhy4flwc7p3", chainId: "cosmoshub-4" },
  Noble: { address: "noble12zyu8w93h0q2lcnt50g3fn0w3yqnhy4fhddkel", chainId: "noble-1" }
};

Then use this object throughout the test file for consistency and easier maintenance.

Also applies to: 1054-1054

packages/universal-swap/src/helper.ts (1)

227-228: Enhance error message for invalid recipient address

The current error message "orai Address get source receiver invalid!" may not be clear to users. Consider rephrasing it to "Invalid Oraichain recipient address provided." for better clarity.

Apply this diff to improve the error message:

- if (!isValidRecipient.isValid) throw generateError("orai Address get source receiver invalid!");
+ if (!isValidRecipient.isValid) throw generateError("Invalid Oraichain recipient address provided!");
packages/universal-swap/src/handler.ts (4)

Line range hint 1283-1283: Typo in method name 'caculateMinimumReceive'

The method caculateMinimumReceive is misspelled. It should be calculateMinimumReceive.

Apply this diff to fix the method name:

-   async caculateMinimumReceive() {
+   async calculateMinimumReceive() {

Remember to update all references to this method accordingly.


Line range hint 1193-1270: Consider refactoring 'processUniversalSwap' into smaller methods

The processUniversalSwap method spans numerous lines and contains complex logic, which can make it hard to read and maintain. Consider refactoring it into smaller, well-named helper methods to improve readability and maintainability.


1242-1245: Use 'evmAddress' variable consistently

You have already assigned this.swapData.sender.evm to evmAddress, so you can use evmAddress instead when setting addressParams.evmInfo.

Apply this diff:

      addressParams.evmInfo = {
        ...addressParams.evmInfo,
-       [EVM_CHAIN_IDS.ETH]: this.swapData.sender.evm,
-       [EVM_CHAIN_IDS.BSC]: this.swapData.sender.evm
+       [EVM_CHAIN_IDS.ETH]: evmAddress,
+       [EVM_CHAIN_IDS.BSC]: evmAddress
      };

1250-1253: Use 'tronAddress' variable consistently

After assigning tronAddress, you can use it instead of recomputing tronToEthAddress(this.swapData.sender.tron) when setting addressParams.evmInfo.

Apply this diff:

      addressParams.evmInfo = {
        ...addressParams.evmInfo,
-       [EVM_CHAIN_IDS.TRON]: tronToEthAddress(this.swapData.sender.tron)
+       [EVM_CHAIN_IDS.TRON]: tronAddress
      };
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 236d83b and 34d9924.

📒 Files selected for processing (4)
  • packages/universal-swap/src/handler.ts (4 hunks)
  • packages/universal-swap/src/helper.ts (6 hunks)
  • packages/universal-swap/tests/helper.spec.ts (4 hunks)
  • packages/universal-swap/tests/index.spec.ts (6 hunks)
🧰 Additional context used
🪛 Biome
packages/universal-swap/src/helper.ts

[error] 353-353: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

🔇 Additional comments (3)
packages/universal-swap/tests/helper.spec.ts (1)

395-435: Consider enabling or removing the commented-out test case.

This test case for UniversalSwapHelper.generateAddress is currently disabled. If the functionality is not yet implemented or there are unresolved issues, consider adding a TODO comment explaining why it's commented out and when it should be addressed. If the test is no longer relevant, it would be better to remove it entirely to keep the test suite clean.

To check if there are any other commented-out tests in the file, you can run:

✅ Verification successful

No additional commented-out tests found in packages/universal-swap/tests/helper.spec.ts.

The only commented-out test case for UniversalSwapHelper.generateAddress has been addressed. Ensure it is either enabled with necessary fixes or removed if obsolete to maintain a clean test suite.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other commented-out tests in the file
rg '^\s*//\s*it\.' packages/universal-swap/tests/helper.spec.ts

Length of output: 131

packages/universal-swap/tests/index.spec.ts (1)

524-524: LGTM! Test case updated correctly.

The expected result for the "cosmoshub-4" chain ID has been updated to match the new default address set in the StubCosmosWallet class. This ensures consistency between the implementation and the test case.

packages/universal-swap/src/handler.ts (1)

63-63: LGTM!

The import statement is correct and necessary for the functionality.

packages/universal-swap/src/helper.ts Outdated Show resolved Hide resolved
packages/universal-swap/src/handler.ts Show resolved Hide resolved
packages/universal-swap/src/handler.ts Show resolved Hide resolved
packages/universal-swap/src/handler.ts Show resolved Hide resolved
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: 2

🧹 Outside diff range and nitpick comments (8)
packages/universal-swap/src/handler.ts (6)

1176-1191: Improved address handling and validation

The getToAddressUniversalSwap method has been enhanced to properly validate recipient addresses and handle different chain scenarios, including the special case for Tron. This is a good improvement for robustness and security.

Consider extracting the chain-specific logic (e.g., Tron address handling) into a separate method for better maintainability.


1216-1247: Improved support for alpha IBC wasm swaps

The new code block enhances support for alpha IBC wasm swaps, handling various chain types including EVM and Tron. The use of array destructuring for boolean checks is efficient and readable.

Consider extracting the chain-specific logic into separate methods to improve maintainability and reduce the complexity of this method.


Line range hint 1288-1330: Enhanced minimum receive calculation

The calculateMinimumReceive method has been significantly improved to handle various scenarios, including relayer fees and different token types. The changes enhance the accuracy of the calculation and provide better support for complex swap operations.

Consider breaking down this method into smaller, more focused functions to improve readability and maintainability. For example, you could extract the relayer fee calculation into a separate method.


Line range hint 1364-1483: Enhanced swap message generation

The generateMsgsSwap method has been significantly improved to handle various swap scenarios, including IBC wasm swaps. The additions in error handling, recipient address validation, and support for complex swap operations enhance the robustness and flexibility of the method.

Consider extracting the IBC wasm specific logic into a separate method to improve readability and maintainability of this method.


Line range hint 1526-1589: Enhanced IBC Wasm transfer message generation

The generateMsgsIbcWasm method has been improved to handle IBC Wasm transfers for both native and CW20 tokens. The additions enhance support for cross-network transfers and include proper error handling for invalid IBC Wasm source ports.

Consider adding more detailed error messages or logging to aid in debugging potential issues with IBC Wasm transfers.


Line range hint 1-1589: Overall improvements with opportunities for further refinement

The UniversalSwapHandler class has been significantly enhanced to support a wider range of swap scenarios, including cross-chain swaps, smart routing, and IBC Wasm transfers. The additions improve error handling, address validation, and support for various token types and network configurations.

While these changes greatly improve the functionality and robustness of the class, there are opportunities for further refinement:

  1. Consider breaking down some of the larger methods (e.g., processUniversalSwap, generateMsgsSwap) into smaller, more focused functions to improve readability and maintainability.
  2. Implement more comprehensive error handling and logging throughout the class to aid in debugging and improve the developer experience.
  3. Consider creating separate classes or modules for handling specific network types (e.g., EVM, Cosmos, Tron) to better organize the network-specific logic.
  4. Add more inline documentation or comments explaining the purpose and functionality of complex code blocks, especially in areas dealing with cross-chain operations.

These suggestions could help improve the long-term maintainability and scalability of the codebase.

packages/universal-swap/src/helper.ts (2)

228-228: Clarify the error message for invalid recipient address

The error message "orai Address get source receiver invalid!" is a bit unclear. Consider rephrasing it to make it more understandable to users.

Apply this diff to improve the error message:

- if (!isValidRecipient.isValid) throw generateError("orai Address get source receiver invalid!");
+ if (!isValidRecipient.isValid) throw generateError("Invalid Oraichain recipient address provided!");

470-470: Remove debug console.log statement

The console.log statement appears to be used for debugging purposes. Consider removing it or replacing it with appropriate logging if necessary.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 34d9924 and 4c8c953.

📒 Files selected for processing (3)
  • packages/universal-swap/src/handler.ts (5 hunks)
  • packages/universal-swap/src/helper.ts (6 hunks)
  • packages/universal-swap/tests/index.spec.ts (7 hunks)
🧰 Additional context used
🪛 Biome
packages/universal-swap/src/helper.ts

[error] 354-354: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

🔇 Additional comments (10)
packages/universal-swap/src/handler.ts (4)

63-63: New import added

The addition of EVM_CHAIN_IDS from @oraichain/common suggests that the code now handles EVM-specific chain IDs. This is a good practice for maintaining consistency and avoiding hardcoded values.


1193-1214: Enhanced cross-chain swap handling

The processUniversalSwap method has been significantly improved to handle various address types and chain scenarios. This enhancement increases the flexibility and robustness of the swap process across different networks.


Line range hint 1331-1363: Improved smart router swap message generation

The generateMsgsSmartRouterSwap method has been enhanced to better handle smart router swaps, including support for affiliates and proper slippage handling. The addition of error checking for missing simulate price or user slippage improves the robustness of the method.


Line range hint 1484-1525: Improved smart route swap message building

The buildSwapMsgsFromSmartRoute method has been enhanced to better handle smart route swap operations. The addition of minimum receive calculation using user-defined slippage and proper handling of both native and CW20 tokens improves the flexibility and accuracy of the swap process.

packages/universal-swap/tests/index.spec.ts (6)

349-349: Update to receiver address in test case

The receiver address has been changed from "orai1234" to "osmo1234".

This change is consistent with the updates made to the StubCosmosWallet class and appears to be intentional.


438-438: Update to receiver address in another test case

Similar to the previous change, the receiver address has been updated from "orai1234" to "osmo1234".

This change is consistent with the updates made to the StubCosmosWallet class and appears to be intentional.


524-524: Update to expected address in getUniversalSwapToAddress test

The expected address for the "Oraichain" chain ID has been updated to "orai1g4h64yjt0fvzv5v2j8tyfnpe5kmnetejvfgs7g".

This change is consistent with the updates made to the StubCosmosWallet class and appears to be intentional.


993-995: Update to remote address in test case

The remote address has been changed from "orai1234" to "orai1g4h64yjt0fvzv5v2j8tyfnpe5kmnetejvfgs7g".

This change is consistent with the updates made to the StubCosmosWallet class and appears to be intentional.


1054-1056: Update to remote address in another test case

Similar to the previous change, the remote address has been updated from "orai1234" to "orai1g4h64yjt0fvzv5v2j8tyfnpe5kmnetejvfgs7g".

This change is consistent with the updates made to the StubCosmosWallet class and appears to be intentional.


1887-1887: Rename method from caculateMinimumReceive to calculateMinimumReceive

The method name has been corrected from caculateMinimumReceive to calculateMinimumReceive.

This is a good correction that fixes a typo in the method name. It improves code readability and consistency.

To ensure this change is applied consistently across the codebase, you may want to run the following check:

packages/universal-swap/src/handler.ts Show resolved Hide resolved
packages/universal-swap/tests/index.spec.ts Show resolved Hide resolved
Copy link

badge

Code Coverage Summary

Filename                                                                      Stmts    Miss  Cover    Missing
--------------------------------------------------------------------------  -------  ------  -------  --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
docs/assets/main.js                                                              58      58  0.00%    1-58
docs/assets/search.js                                                             1       1  0.00%    1
packages/ibc-routing/hardhat.config.ts                                           59      59  0.00%    1-75
packages/ibc-routing/src/db.ts                                                  158     158  0.00%    1-263
packages/ibc-routing/src/event.ts                                                85      85  0.00%    1-122
packages/ibc-routing/src/index.ts                                                31      31  0.00%    1-56
packages/ibc-routing/src/machine.ts                                              30      30  0.00%    1-34
packages/ibc-routing/test/mock-eth-ws.ts                                         52      52  0.00%    1-55
packages/ibc-routing/test/mock-tendermint-ws.spec.ts                             25      17  32.00%   7-24
packages/oraidex-common/src/alpha-network.ts                                     61       0  100.00%
packages/oraidex-common/src/axios-request.ts                                     11      11  0.00%    1-20
packages/oraidex-common/src/bigdecimal.ts                                       139      50  64.02%   23-24, 30-33, 40-41, 45-54, 63-65, 71-73, 120-124, 127-146, 149-150, 153-154, 180-181, 184-185
packages/oraidex-common/src/celestia-network.ts                                  52       0  100.00%
packages/oraidex-common/src/constant.ts                                         170       0  100.00%
packages/oraidex-common/src/helper.ts                                           466     142  69.52%   141-142, 145-156, 159-169, 267-269, 286-293, 296-309, 319-325, 335-350, 353-360, 363-393, 396-404, 407-409, 412-414, 418-427, 436-450, 456-458, 543-544, 569-572
packages/oraidex-common/src/ibc-info.ts                                         184     184  0.00%    1-218
packages/oraidex-common/src/index.ts                                             14      14  0.00%    1-14
packages/oraidex-common/src/network.ts                                         1024       0  100.00%
packages/oraidex-common/src/pairs.ts                                            154       4  97.40%   151-152, 157-158
packages/oraidex-common/src/token.ts                                             71       0  100.00%
packages/oraidex-common/src/wallet.ts                                           146     146  0.00%    1-236
packages/oraidex-common/src/config/chainInfosWithIcon.ts                        208     208  0.00%    1-222
packages/oraidex-common/src/interface/index.ts                                    1       1  0.00%    1
packages/oraidex-common/src/interface/wallet.ts                                  19      19  0.00%    1-20
packages/oraidex-common/tests/bigdecimal.spec.ts                                220       0  100.00%
packages/oraidex-common/tests/helper.spec.ts                                    560       8  98.57%   97-98, 337-338, 628-629, 659-660
packages/oraidex-common/tests/pairs.spec.ts                                      24       0  100.00%
packages/oraiswap-v3/src/const.ts                                                11       0  100.00%
packages/oraiswap-v3/src/error.ts                                                 5       2  60.00%   3-4
packages/oraiswap-v3/src/handler.ts                                             292      28  90.41%   63-64, 100-101, 216-217, 341-355, 358-366
packages/oraiswap-v3/src/helpers.ts                                             444     234  47.29%   122-123, 133-134, 159-160, 188-189, 199-200, 283-287, 290-297, 300-356, 359-364, 367-376, 380-436, 439-447, 450-481, 484-497, 500-523, 526-532, 535-549
packages/oraiswap-v3/src/index.ts                                                 7       0  100.00%
packages/oraiswap-v3/src/main.ts                                                 37      37  0.00%    1-72
packages/oraiswap-v3/src/types.ts                                                13       0  100.00%
packages/oraiswap-v3/src/zap-consumer.ts                                        496     478  3.62%    54-58, 61-62, 65-98, 101-143, 146-165, 168-186, 189-219, 222-331, 334-567, 570-608
packages/oraiswap-v3/src/wasm/oraiswap_v3_wasm.d.ts                              32      32  0.00%    469-500
packages/oraiswap-v3/src/wasm/oraiswap_v3_wasm.js                              1543     710  53.98%   32-34, 92-94, 100-101, 103-108, 113-120, 136-145, 160-223, 233-255, 264-284, 293-313, 322-342, 351-371, 380-400, 409-429, 463-464, 480-502, 508-511, 518-530, 536-548, 555-558, 565-579, 587-590, 595-598, 611-614, 620-623, 636-639, 660-663, 668-671, 688-729, 736-754, 762-776, 783-786, 793-807, 817-838, 848-869, 884-885, 910-911, 929-953, 958-961, 966-969, 976-979, 984-987, 992-995, 1002-1005, 1010-1013, 1028-1031, 1036-1039, 1044-1047, 1062-1065, 1080-1083, 1088-1091, 1096-1099, 1106-1109, 1114-1117, 1122-1125, 1132-1135, 1149-1150, 1161-1164, 1170-1173, 1179-1182, 1188-1191, 1196-1199, 1204-1207, 1214-1217, 1219-1225, 1300-1301, 1329-1330, 1333-1335, 1356-1361, 1364-1365, 1368-1372, 1386-1387, 1390-1391, 1394-1395, 1398-1399, 1402-1403, 1406-1407, 1410-1413, 1416-1417, 1420-1421, 1424-1425, 1428-1431, 1434-1437, 1444, 1447-1448, 1451-1458, 1465-1466, 1469-1470, 1473-1474, 1477, 1480-1481, 1484-1491, 1500-1504, 1507, 1510-1511
packages/oraiswap-v3/tests/handler.spec.ts                                      276       0  100.00%
packages/oraiswap-v3/tests/helpers.spec.ts                                      577       0  100.00%
packages/oraiswap-v3/tests/test-common.ts                                        32       0  100.00%
packages/oraiswap-v3/tests/zap-consumer.spec.ts                                  50       0  100.00%
packages/universal-swap/src/handler.ts                                         1294     695  46.29%   81-82, 103-104, 119-121, 127-130, 152-157, 178-200, 280-309, 357-362, 413-433, 484-489, 536-547, 571, 573-577, 590-601, 608-623, 626-684, 695-705, 708-718, 725-732, 746-823, 827-858, 862-881, 884-901, 905-962, 967-1051, 1057-1146, 1149-1171, 1175-1181, 1214-1246, 1266-1269, 1273-1274, 1276-1277, 1283, 1347-1350, 1383-1386, 1393-1403, 1408-1428, 1469-1470, 1483-1526, 1589-1590
packages/universal-swap/src/helper.ts                                          1043     411  60.59%   92-94, 233-234, 280-285, 313-314, 325-326, 329-330, 337-378, 416-437, 445-482, 496-550, 591-593, 618-624, 650-652, 656-658, 665-696, 753-754, 787-794, 801-842, 854-914, 953-954, 969, 997, 1004-1027, 1029-1030, 1072-1073, 1077-1080, 1090-1132, 1140-1156, 1215-1225, 1236-1241, 1260, 1286-1298, 1416-1427
packages/universal-swap/src/index.ts                                              6       6  0.00%    1-6
packages/universal-swap/src/swap-filter.ts                                       40       0  100.00%
packages/universal-swap/src/types.ts                                             14       0  100.00%
packages/universal-swap/src/wrapper.ts                                           79      79  0.00%    1-117
packages/universal-swap/src/msg/common.ts                                        34      12  64.70%   11-12, 16-17, 20-21, 24-25, 30-31, 33-34
packages/universal-swap/src/msg/index.ts                                          4       0  100.00%
packages/universal-swap/src/msg/msgs.ts                                         134      50  62.68%   22-23, 43-44, 67-74, 89-99, 101-104, 110-111, 125-126, 141-163
packages/universal-swap/src/msg/types.ts                                          6       0  100.00%
packages/universal-swap/src/msg/chains/chain.ts                                  20       4  80.00%   18-19, 22-23
packages/universal-swap/src/msg/chains/cosmos.ts                                111      14  87.38%   22-23, 27-28, 54-55, 59-60, 64-65, 102-103, 127-128
packages/universal-swap/src/msg/chains/index.ts                                   3       0  100.00%
packages/universal-swap/src/msg/chains/oraichain.ts                             412      77  81.31%   39-40, 50-51, 73-96, 124-130, 147, 200, 289, 439-462, 494-511
packages/universal-swap/src/msg/chains/osmosis.ts                               232     117  49.56%   27-28, 38-39, 78-79, 96, 112-117, 133, 147-165, 169-174, 213-305
packages/universal-swap/src/proto/index.ts                                        1       1  0.00%    1
packages/universal-swap/src/proto/universal-swap-memo-proto-handler.ts           66      60  9.09%    21-46, 50-91
packages/universal-swap/src/proto/universal_swap_memo.ts                        911     727  20.19%   110-112, 135-183, 186-193, 196-213, 216-217, 219-230, 233-235, 246-266, 269-274, 277-282, 285-286, 288-291, 294-296, 300-304, 307-327, 330-333, 336-341, 344-345, 347-350, 353-355, 359-366, 369-396, 399-405, 408-416, 419-420, 422-426, 429-431, 448-482, 485-490, 493-504, 507-508, 510-515, 518-520, 531-532, 537-571, 574-583, 586-597, 600-601, 603-613, 616-618, 629-630, 638-679, 682-690, 693-707, 710-711, 713-727, 730-732, 755-803, 806-813, 816-833, 836-837, 839-846, 849-851, 865-866, 874-922, 925-932, 935-952, 955-956, 958-965, 968-970, 974-981, 984-1011, 1014-1018, 1021-1029, 1032-1033, 1035-1039, 1042-1044, 1055-1075, 1078-1079, 1082-1087, 1090-1091, 1093-1096, 1111-1119, 1122-1128
packages/universal-swap/src/universal-demos/alpha-ibc-new.ts                    118     118  0.00%    1-129
packages/universal-swap/src/universal-demos/alpha-smart-router.ts               117     117  0.00%    1-126
packages/universal-swap/src/universal-demos/decode-memo.ts                       13      13  0.00%    1-14
packages/universal-swap/src/universal-demos/evm-to-evm.ts                        52      52  0.00%    1-68
packages/universal-swap/src/universal-demos/from-cosmos-to-evm.ts                41      41  0.00%    1-53
packages/universal-swap/src/universal-demos/from-oraichain-to-evm.ts             42      42  0.00%    1-62
packages/universal-swap/src/universal-demos/from-oraichain-to-oraichain.ts       49      49  0.00%    1-66
packages/universal-swap/src/universal-demos/handle-simulate-swap.ts              31      31  0.00%    1-35
packages/universal-swap/src/universal-demos/ibc-hooks-demo.ts                    40      40  0.00%    1-55
packages/universal-swap/src/universal-demos/neutaro-ibc-demo.ts                  40      40  0.00%    1-47
packages/universal-swap/src/universal-demos/noble-ibc-demo.ts                    41      41  0.00%    1-45
packages/universal-swap/src/universal-demos/offline-wallet.ts                    19      19  0.00%    1-21
packages/universal-swap/tests/helper.spec.ts                                    705      24  96.59%   378, 997-1019
packages/universal-swap/tests/index.spec.ts                                    1753      30  98.28%   240-243, 286-287, 292-293, 295-296, 298-299, 1141-1160
packages/universal-swap/tests/smart-router-common.ts                            864       0  100.00%
packages/universal-swap/tests/test-common.ts                                     56       0  100.00%
packages/universal-swap/tests/msg/comos-msg.spec.ts                             208       0  100.00%
packages/universal-swap/tests/msg/msgs.spec.ts                                  580       0  100.00%
packages/universal-swap/tests/msg/oraichain-msg.spec.ts                         689       2  99.70%   115-116
packages/universal-swap/tests/msg/osmosis-msg.spec.ts                           357       0  100.00%
packages/universal-swap/tests/msg/test-data.ts                                    8       8  0.00%    1-9
TOTAL                                                                         18071    5719  68.35%

Diff against main

Filename                                                               Stmts    Miss  Cover
-------------------------------------------------------------------  -------  ------  --------
packages/universal-swap/src/handler.ts                                   +27     +19  -0.35%
packages/universal-swap/src/helper.ts                                    +36     +40  -2.56%
packages/universal-swap/src/msg/msgs.ts                                   +8      +6  -2.39%
packages/universal-swap/src/msg/chains/oraichain.ts                       -2      -2  +0.40%
packages/universal-swap/src/universal-demos/handle-simulate-swap.ts       -1      -1  +100.00%
packages/universal-swap/tests/helper.spec.ts                              +1       0  +100.00%
packages/universal-swap/tests/index.spec.ts                               +3       0  +100.00%
TOTAL                                                                    +72     +62  -0.22%

Results for commit: f2e61b8

Minimum allowed coverage is 0%

♻️ This comment has been updated with latest results

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

🧹 Outside diff range and nitpick comments (4)
packages/universal-swap/src/helper.ts (2)

452-454: Improve error message clarity.

The current error message "Missing router with alpha ibc wasm max length!" could be more descriptive about the actual limitation.

Apply this diff to improve the error message:

-        throw generateError(`Missing router with alpha ibc wasm max length!`);
+        throw generateError(`EVM tokens with Alpha IBC Wasm only support single route operations.`);

456-458: Add comment explaining path filtering requirement.

The path filtering logic for EVM tokens would benefit from a comment explaining why the first path is excluded.

Apply this diff to improve code documentation:

      if (fromTokenIsEvm) {
+        // Skip the first path for EVM tokens as it represents the initial bridge operation
        paths = alphaRoutes.paths.filter((_, index) => index > 0);
      }
packages/universal-swap/src/handler.ts (2)

Line range hint 1190-1267: Consider enhancing type safety for address parameters

The address parameter handling could benefit from stronger typing to prevent potential errors. Consider creating an interface for the address parameters.

Add a type definition:

interface AddressParams {
  oraiAddress: string;
  injAddress?: string;
  evmInfo: {
    [key: string]: string;
  };
}

Then use it in the code:

-    let addressParams = {
+    let addressParams: AddressParams = {
       oraiAddress,
       injAddress,
       evmInfo: {}
     };

Line range hint 1286-1334: Enhance readability of minimum receive calculation

The calculation logic could be more readable by extracting the fee calculations into separate helper functions.

Consider refactoring like this:

private calculateBridgeFeeAdjustment(amount: string, bridgeFee: number): number {
  return (bridgeFee * Number(amount)) / 100;
}

private calculateSlippageAdjustment(amount: string, slippage: number): number {
  return (slippage * Number(amount)) / 100;
}

async calculateMinimumReceive() {
  const { relayerFee, simulateAmount, originalToToken, bridgeFee = 1, userSlippage = 0 } = this.swapData;
  const convertSimulateAmount = simulateAmount;
  
  // Calculate relayer fee
  let subRelayerFee = await this.calculateRelayerFee(relayerFee, originalToToken);
  
  // Calculate adjustments
  const bridgeFeeAdjustment = this.calculateBridgeFeeAdjustment(convertSimulateAmount, bridgeFee);
  const slippageAdjustment = this.calculateSlippageAdjustment(convertSimulateAmount, userSlippage);
  
  // Calculate final amount
  const minimumReceive = new BigDecimal(convertSimulateAmount)
    .sub(bridgeFeeAdjustment)
    .sub(slippageAdjustment)
    .sub(subRelayerFee)
    .toString();
    
  return Math.max(0, Math.floor(Number(minimumReceive))).toLocaleString("fullwide", {
    useGrouping: false
  });
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0ae5aab and f2e61b8.

📒 Files selected for processing (2)
  • packages/universal-swap/src/handler.ts (5 hunks)
  • packages/universal-swap/src/helper.ts (6 hunks)
🧰 Additional context used
🪛 Biome
packages/universal-swap/src/helper.ts

[error] 354-354: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

🔇 Additional comments (6)
packages/universal-swap/src/helper.ts (5)

51-53: LGTM! Good addition of address validation imports.

The new imports enhance the security of the codebase by adding proper address validation functionality.


227-229: LGTM! Proper address validation implementation.

The added validation ensures that only valid Oraichain addresses are processed, enhancing security.


386-387: LGTM! Good implementation of cross-chain address handling.

The changes properly handle EVM and Tron addresses while maintaining compatibility with the OraiBridge protocol.

Also applies to: 417-420, 427-427


440-443: LGTM! Good documentation of supported routes.

The comment clearly documents the supported cross-chain routes for Alpha IBC Wasm.


370-376: Verify evmInfo merge behavior.

The current implementation merges evmInfo directly into cosmosAddress which could potentially overwrite existing keys. Consider adding a check to prevent unintended overwrites.

✅ Verification successful

Let me gather more information about the structure of evmInfo and cosmosAddress to better understand potential key conflicts.


Let me gather more information about the structure and usage of cosmosAddress and evmInfo to better understand the merge behavior.


Let me try a different search pattern to understand the context better.


Let me try one more search pattern to understand the context of the merge operation.


Based on the code context, I can now provide a final response about the evmInfo merge behavior.

The merge of evmInfo into cosmosAddress is safe and intentional

The merge operation is part of the generateAddress helper method that combines different address types into a single address mapping. Here's why the merge is safe:

  1. cosmosAddress is initially populated with Cosmos-based addresses (Oraichain and Injective)
  2. evmInfo is an optional parameter containing EVM chain addresses as a simple key-value mapping
  3. The merge is additive - it adds EVM addresses under their respective chain IDs without risk of overwriting Cosmos addresses because:
    • Cosmos chain IDs use string names (e.g., "Oraichain", "injective-1")
    • EVM chain IDs use hex format (e.g., "0x01", "0x38")

Therefore, there is no risk of key collisions between Cosmos and EVM addresses in the merged object.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any potential key conflicts between cosmos addresses and EVM addresses
rg -A 2 "chainId.*[\"'](?:0x38|0x01|0x2b6653dc)[\"']" 

Length of output: 7619


Script:

#!/bin/bash
# Search for the structure and usage of evmInfo and cosmosAddress
ast-grep --pattern 'interface $_ {
  $$$
}'

# Also search for type definitions and assignments
rg -A 5 "type.*cosmosAddress|interface.*cosmosAddress|evmInfo.*=|cosmosAddress.*=" 

Length of output: 355442


Script:

#!/bin/bash
# Search for the structure and usage of cosmosAddress and evmInfo
ast-grep --pattern 'interface $_ {
  evmInfo?: $_
}'

# Also search for any type definitions and assignments related to these objects
rg -A 5 "type.*evmInfo|interface.*evmInfo|type.*cosmosAddress|cosmosAddress.*type"

Length of output: 139


Script:

#!/bin/bash
# Search for the context around where cosmosAddress and evmInfo are used
rg -B 5 -A 10 "cosmosAddress.*evmInfo" 

# Also search for any type definitions or interfaces that might contain these fields
ast-grep --pattern 'type $_ = {
  $$$
  evmInfo?: $_
  $$$
}'

# Look for the broader context of the file
rg -l "cosmosAddress.*evmInfo" | xargs cat

Length of output: 149


Script:

#!/bin/bash
# Search for the broader context of the file where the merge happens
rg -B 10 -A 10 "cosmosAddress.*=.*\{.*\.\.\.cosmosAddress" 

# Also look for any type definitions or interfaces in the helper.ts file
rg -A 5 "interface|type" packages/universal-swap/src/helper.ts

# Get the full content of the helper.ts file around this merge
rg -B 20 -A 20 "evmInfo" packages/universal-swap/src/helper.ts

Length of output: 6258

packages/universal-swap/src/handler.ts (1)

1173-1188: ⚠️ Potential issue

Inconsistent use of recipientAddress parameter

The function uses both the recipientAddress parameter and this.swapData.recipientAddress, which can lead to confusion. Consider using the parameter consistently throughout the method.

Apply this diff:

-  if (this.swapData.recipientAddress) {
+  if (recipientAddress) {
     const isValidRecipient = checkValidateAddressWithNetwork(recipientAddress, originalToToken.chainId);

     if (!isValidRecipient.isValid) throw generateError("Recipient address invalid!");

     return originalToToken.chainId === ChainIdEnum.TRON
-      ? tronToEthAddress(recipientAddress)
-      : this.swapData.recipientAddress;
+      ? tronToEthAddress(recipientAddress)
+      : recipientAddress;
   } else {

Likely invalid or redundant comment.

packages/universal-swap/src/helper.ts Show resolved Hide resolved
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)
packages/universal-swap/tests/helper.spec.ts (3)

396-441: Enhance error handling assertions in generateAddress test.

The test case has good coverage but could benefit from more specific error assertions.

Consider modifying the error handling to verify the specific error type and message:

    } catch (error) {
-     expect(willThrow).toEqual(false);
+     if (willThrow) {
+       expect(error).toBeInstanceOf(Error);
+       expect(error.message).toMatch(/invalid address/i);
+     } else {
+       throw error;
+     }
    }

Line range hint 636-647: Add test cases for additional edge scenarios.

While the basic functionality is covered, consider adding test cases for:

  • Invalid receiver addresses
  • Maximum amount limits
  • Contract address validation

Would you like me to help generate additional test cases for these scenarios?


Line range hint 666-723: LGTM! Consider adding negative test cases.

The test data is comprehensive and well-structured, covering various route formats and combinations.

Consider adding negative test cases for:

  • Malformed route strings
  • Invalid channel formats
  • Missing separators
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f2e61b8 and 1e2b60e.

📒 Files selected for processing (1)
  • packages/universal-swap/tests/helper.spec.ts (5 hunks)
🧰 Additional context used

@haunv3 haunv3 merged commit 9df748d into main Oct 23, 2024
3 of 4 checks passed
@haunv3 haunv3 deleted the feat/support-swap-oraidex-osmosis branch October 23, 2024 08:55
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