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

Merged
merged 42 commits into from
Oct 10, 2024
Merged

Conversation

trung2891
Copy link
Member

@trung2891 trung2891 commented Oct 9, 2024

[x] Generate msg from smartRoute

Summary by CodeRabbit

  • New Features

    • Introduced support for the Celestia network, including configuration details for token swaps.
    • Enhanced the UniversalSwapHandler for improved token swap functionality across multiple networks, including new methods for smart router swaps.
    • Updated the UniversalSwap package version to reflect recent changes and added new dependencies.
    • Added a new constant for test data related to valid paths in Cosmos messaging.
    • Introduced the CosmosMsg and OsmosisMsg classes for managing messages specific to their respective ecosystems.
  • Bug Fixes

    • Improved error handling in the UniversalSwapHandler and messaging classes to ensure robustness.
  • Documentation

    • Updated comments and documentation across various modules for clarity.
  • Tests

    • Expanded test coverage for new messaging classes and swap functionalities, ensuring comprehensive validation of features.
    • Added unit tests for the CosmosMsg, OraichainMsg, and OsmosisMsg classes to validate message handling and error scenarios.
    • Enhanced test cases for the UniversalSwapHelper and added tests for the generateMsgSwap function.

trung2891 and others added 30 commits October 1, 2024 16:38
…ain/oraidex-sdk into feat/support-swap-oraidex-osmosis
…ain/oraidex-sdk into feat/support-swap-oraidex-osmosis
…ain/oraidex-sdk into feat/support-swap-oraidex-osmosis
Copy link

github-actions bot commented Oct 9, 2024

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                                         1267     676  46.64%   81-82, 103-104, 119-121, 127-130, 152-157, 178-200, 280-310, 358-363, 414-434, 485-490, 537-548, 572, 574-578, 591-602, 609-624, 627-685, 696-706, 709-719, 726-733, 747-824, 828-859, 863-882, 885-902, 906-963, 968-1052, 1058-1150, 1153-1175, 1186-1193, 1211-1217, 1236-1239, 1243-1244, 1246-1247, 1253, 1318-1321, 1354-1357, 1364-1374, 1379-1399, 1440-1441, 1454-1497, 1560-1561
packages/universal-swap/src/helper.ts                                          1007     371  63.15%   90-92, 228-229, 275-280, 308-309, 320-321, 324-325, 335-345, 382-399, 405-430, 444-498, 539-541, 566-572, 598-600, 604-606, 613-643, 706-707, 740-747, 754-795, 808-867, 906-907, 922, 950, 957-980, 982-983, 1025-1026, 1030-1033, 1043-1085, 1093-1109, 1168-1178, 1189-1194, 1213, 1239-1251, 1369-1380
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                                         126      44  65.07%   22-23, 62-69, 84-89, 91-94, 100-101, 115-116, 131-153
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                             414      79  80.91%   39-40, 50-51, 73-96, 124-130, 147, 200, 289, 439-462, 494-513
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              32      32  0.00%    1-36
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                                    704      24  96.59%   378, 954-976
packages/universal-swap/tests/index.spec.ts                                    1750      30  98.28%   240-243, 283-284, 289-290, 292-293, 295-296, 1138-1157
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                                                                         17999    5657  68.57%

Diff against main

Filename                                                             Stmts    Miss  Cover
-----------------------------------------------------------------  -------  ------  --------
packages/oraidex-common/src/celestia-network.ts                        +52       0  +100.00%
packages/oraidex-common/src/constant.ts                                 +1       0  +100.00%
packages/oraidex-common/src/ibc-info.ts                                 +1      +1  +100.00%
packages/oraidex-common/src/index.ts                                    +1      +1  +100.00%
packages/oraidex-common/src/network.ts                                  +2       0  +100.00%
packages/universal-swap/src/handler.ts                                 +39     +14  +0.55%
packages/universal-swap/src/helper.ts                                  +59     +45  -2.46%
packages/universal-swap/src/types.ts                                    +4       0  +100.00%
packages/universal-swap/src/msg/common.ts                              +34     +12  +64.70%
packages/universal-swap/src/msg/index.ts                                +4       0  +100.00%
packages/universal-swap/src/msg/msgs.ts                               +126     +44  +65.07%
packages/universal-swap/src/msg/types.ts                                +6       0  +100.00%
packages/universal-swap/src/msg/chains/chain.ts                        +20      +4  +80.00%
packages/universal-swap/src/msg/chains/cosmos.ts                      +111     +14  +87.38%
packages/universal-swap/src/msg/chains/index.ts                         +3       0  +100.00%
packages/universal-swap/src/msg/chains/oraichain.ts                   +414     +79  +80.91%
packages/universal-swap/src/msg/chains/osmosis.ts                     +232    +117  +49.56%
packages/universal-swap/src/proto/universal_swap_memo.ts                 0     -91  +9.99%
packages/universal-swap/src/universal-demos/alpha-ibc-new.ts          +118    +118  +100.00%
packages/universal-swap/src/universal-demos/alpha-smart-router.ts       +3      +3  +100.00%
packages/universal-swap/src/universal-demos/decode-memo.ts             +13     +13  +100.00%
packages/universal-swap/tests/helper.spec.ts                            +7       0  +0.04%
packages/universal-swap/tests/index.spec.ts                             +7      -2  +0.12%
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%
packages/universal-swap/tests/msg/osmosis-msg.spec.ts                 +357       0  +100.00%
packages/universal-swap/tests/msg/test-data.ts                          +8      +8  +100.00%
TOTAL                                                                +3099    +382  +3.98%

Results for commit: 9eecca6

Minimum allowed coverage is 0%

♻️ This comment has been updated with latest results

Copy link

coderabbitai bot commented Oct 9, 2024

Walkthrough

The pull request introduces several changes across multiple files, primarily focusing on updates to the .gitignore file, version increments in package.json files, and the addition of new constants and classes related to the Celestia blockchain network. The UniversalSwapHandler class has been enhanced to improve token swap functionalities, and new messaging classes for Cosmos, Osmosis, and Oraichain have been added. Additionally, various utility functions and tests have been introduced or modified to support these changes.

Changes

File Path Change Summary
.gitignore Added entries for .yarn and demo-local, changed .yarn from excluded to included.
packages/oraidex-common/package.json Updated version from 1.1.21 to 1.1.23.
packages/oraidex-common/src/celestia-network.ts Introduced celestiaNetwork constant with configuration details for the Celestia blockchain.
packages/oraidex-common/src/constant.ts Added CELESTIA_CHAIN_ID to COSMOS_CHAIN_ID_COMMON enum and added a trailing comma.
packages/oraidex-common/src/ibc-info.ts Updated ibcInfos and ibcInfosOld to exclude the "celestia" key and adjusted mappings.
packages/oraidex-common/src/index.ts Added export statement for celestia-network.
packages/oraidex-common/src/network.ts Integrated celestiaNetwork into network configurations and updated types for network identification.
packages/universal-swap/package.json Updated version from 1.1.12 to 1.1.13 and added new dependency @oraichain/osor-api-contracts-sdk.
packages/universal-swap/src/handler.ts Enhanced UniversalSwapHandler with new methods and improved logic for token swaps and transfers.
packages/universal-swap/src/helper.ts Added new methods for address generation and updated existing methods for flexibility.
packages/universal-swap/src/universal-demos/alpha-ibc-new.ts Introduced functionality for executing universal swaps targeting Osmosis and Celestia.
packages/universal-swap/tests/helper.spec.ts Refactored tests for addOraiBridgeRoute function and enhanced coverage for swap routes.
packages/universal-swap/tests/msg/comos-msg.spec.ts Added unit tests for CosmosMsg class.
packages/universal-swap/tests/msg/msgs.spec.ts Established unit tests for generateMsgSwap function.
packages/universal-swap/tests/msg/oraichain-msg.spec.ts Created tests for OraichainMsg class.
packages/universal-swap/tests/msg/osmosis-msg.spec.ts Developed tests for OsmosisMsg class.
packages/universal-swap/tests/msg/test-data.ts Introduced cosmosTestData constant for testing.
tsconfig.json Confirmed esModuleInterop remains set to true.

Possibly related PRs

  • Feat/smart router osmosis pool #284: The changes in this PR involve updates to the .gitignore file, which is related to the management of ignored files in the repository, similar to the changes made in the main PR that also modifies the .gitignore file.
  • Feat/smart router osmosis pool #291: This PR includes changes to the UniversalSwapHandler class, which may relate to the handling of swap operations, similar to the modifications in the main PR that involve changes to the .gitignore file.
  • fix receipt address swap oraichain -> other chain #320: The changes in this PR involve updates to the UniversalSwapHandler class, specifically enhancing the logic for recipient address validation during a token swap operation, which could relate to the overall functionality being modified in the main PR.
  • update params smart route #324: This PR includes updates to the package.json file, which is also a file type modified in the main PR, indicating a potential connection in terms of project management and versioning.
  • Feat/add params smart route #325: The changes in this PR involve updates to the UniversalSwapHelper class, which may relate to the handling of swap operations, similar to the modifications in the main PR that involve changes to the .gitignore file.
  • Feat/add pepe cat #334: This PR introduces new constants related to blockchain contracts, which may connect to the overall functionality being modified in the main PR.
  • Feat/add pepe cat #335: This PR includes updates to the network.ts file, which may relate to the handling of token configurations, similar to the modifications in the main PR that involve changes to the .gitignore file.
  • bump: fix version #341: The changes in this PR involve updates to the package.json file, which is also a file type modified in the main PR, indicating a potential connection in terms of project management and versioning.
  • Fix/minimum receive ibc wasm #344: The changes in this PR involve updates to the UniversalSwapHandler class, which may relate to the handling of token swaps and transfers, similar to the modifications in the main PR that involve changes to the .gitignore file.

Suggested reviewers

  • quangdz1704

🐇 In the fields we hop and play,
New updates come to light today.
With swaps and chains, we dance around,
In code and tests, our joy is found!
Let's celebrate this code parade,
With every change, our path is laid! 🌟


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

🧹 Outside diff range and nitpick comments (25)
packages/oraidex-common/src/index.ts (1)

14-14: LGTM! Consider specific exports for better control.

The addition of the Celestia network module export aligns well with the PR objectives and fits the existing structure of the file. This change effectively expands the public API of the common package to include Celestia network functionality.

While the wildcard export is convenient, consider using specific exports if only certain parts of the Celestia network module are needed. This approach can provide better control over the public API and reduce the risk of unintended naming conflicts. For example:

export { CelestiaNetwork, CelestiaToken } from "./celestia-network";

This suggestion is optional and depends on your specific use case and project conventions.

packages/universal-swap/src/msg/chains/chain.ts (2)

4-11: LGTM: Class declaration is well-structured.

The ChainMsg class is properly declared with a descriptive name following PascalCase convention. The constructor parameters are clearly defined.

Consider using private access modifiers instead of protected if this class is not intended for inheritance. This would provide better encapsulation.


12-15: LGTM: Constructor includes important validations.

The constructor properly validates the path and receiver parameters, ensuring the object is always in a valid state.

Consider adding validations for minimumReceive to ensure it's a valid number string. Also, you might want to trim the memo to remove any leading or trailing whitespace.

packages/oraidex-common/src/celestia-network.ts (3)

4-14: LGTM: Bech32 configuration and BIP44 settings are correct.

The Bech32 address prefixes and BIP44 coin type are correctly set for the Celestia network. However, consider adding a comment explaining the significance of coin type 118 for better code documentation.

Consider adding a comment like this:

 bip44: {
+  // Coin type 118 is used for Cosmos-based chains
   coinType: 118
 },

20-28: LGTM: Currency information is correctly defined.

The TIA currency is properly configured with the correct denomination and other details. However, consider using a specific coin image if available, rather than reusing the chain symbol image.

If a specific TIA coin image exists, consider updating the coinImageUrl:

 coinImageUrl: "https://raw.githubusercontent.com/chainapsis/keplr-chain-registry/main/images/celestia/chain.png"
+// TODO: Replace with TIA-specific coin image if available

29-43: LGTM: Fee currencies are well-defined. Consider adding relevant features.

The fee currency (TIA) is correctly configured with appropriate gas price steps. However, the features array is empty, which might be a missed opportunity to specify network capabilities.

If there are any specific features or capabilities of the Celestia network, consider adding them to the features array. For example:

-features: [],
+features: [
+  // TODO: Add relevant Celestia network features
+  // "ibc-transfer",
+  // "ibc-go",
+  // Add any other applicable features
+],
packages/universal-swap/src/msg/common.ts (2)

5-26: LGTM: validatePath function is well-structured and covers important validations.

The function effectively validates the path structure, ensuring:

  1. At least one action is present
  2. Only one Bridge action is allowed
  3. If present, the Bridge action must be the last one
  4. Swap actions are controlled by the hasSwap parameter

Consider using early returns for improved readability:

 export const validatePath = (path: Path, hasSwap: boolean = true) => {
   if (path.actions.length == 0) {
     throw generateError("Require at least one action");
   }
   const numBridgeActions = path.actions.filter((action) => action.type === ActionType.Bridge).length;
 
   if (numBridgeActions > 1) {
     throw generateError("Only one Bridge action is allowed in the path");
   }
 
   if (numBridgeActions == 1 && path.actions[path.actions.length - 1].type !== ActionType.Bridge) {
     throw generateError("Bridge action must be the last in the path");
   }
 
   if (!hasSwap && path.actions.some((action) => action.type == ActionType.Convert || action.type == ActionType.Swap)) {
     throw generateError("Don't support swap action");
   }
+  // All validations passed
 };

28-35: LGTM: validateReceiver function performs necessary checks.

The function effectively ensures that both receiver and currentChainAddress are provided. However, consider adding input sanitization:

 export const validateReceiver = (receiver: string, currentChainAddress: string, chainId: string) => {
-  if (!receiver || receiver == "") {
+  if (!receiver || receiver.trim() === "") {
     throw generateError(`Missing receiver when build msg in ${chainId}`);
   }
-  if (!currentChainAddress || currentChainAddress == "") {
+  if (!currentChainAddress || currentChainAddress.trim() === "") {
     throw generateError(`Missing address of ${chainId}`);
   }
 };

This change will also catch inputs that are only whitespace.

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

269-269: LGTM: Addition of maxSplits, but needs documentation

The addition of the optional maxSplits property to the RouterConfigSmartRoute interface is a good enhancement. It allows for more granular control over the routing configuration while maintaining backward compatibility.

However, it would be beneficial to add a brief comment explaining the purpose and expected usage of this property. This will help other developers understand how to properly use this new configuration option.

Consider adding a JSDoc comment above the maxSplits property, like this:

/** The maximum number of splits allowed in the smart route. */
maxSplits?: number;

99-99: LGTM: Addition of isAlphaIbcWasm, but needs documentation and clarification

The addition of the optional isAlphaIbcWasm property to the SwapOptions interface is a good enhancement, allowing for more configuration options in swap operations while maintaining backward compatibility.

However, the purpose and implications of this flag are not immediately clear from its name. It would be beneficial to add documentation explaining:

  1. What does "Alpha" signify in this context?
  2. What behavior changes when this flag is set to true?
  3. Are there any risks or limitations associated with using this option?

Please add a comprehensive JSDoc comment above the isAlphaIbcWasm property. For example:

/**
 * Enables the alpha version of IBC WASM functionality.
 * @remarks
 * This is an experimental feature and may be subject to changes or instability.
 * Use with caution in production environments.
 */
isAlphaIbcWasm?: boolean;

Also, consider adding a brief comment in the PR description or commit message explaining the motivation behind adding this new option.

packages/oraidex-common/src/constant.ts (1)

182-183: LGTM! Consider adding a comment for the new Celestia chain ID.

The changes look good. The addition of the CELESTIA_CHAIN_ID entry to the COSMOS_CHAIN_ID_COMMON enum is consistent with the existing structure and naming conventions. The trailing comma after NOBLE_CHAIN_ID is a good practice for easier future additions.

Consider adding a brief comment above the CELESTIA_CHAIN_ID entry to explain its purpose or provide any relevant information about the Celestia chain, similar to comments you might have for other chain IDs in your codebase.

  NOBLE_CHAIN_ID = "noble-1",
+ // Celestia is a modular blockchain network
  CELESTIA_CHAIN_ID = "celestia"
packages/universal-swap/src/universal-demos/alpha-ibc-new.ts (1)

75-78: Remove or Clarify Commented-Out Code

The relayerFee configuration is currently commented out. Leaving commented-out code can clutter the codebase and may cause confusion about whether it's needed.

If the relayerFee is not required, consider removing it:

-      // relayerFee: {
-      //   relayerAmount: "100000",
-      //   relayerDecimals: 6
-      // },

If it's planned for future use, add a comment explaining its purpose:

// relayerFee is optional and may be used in future implementations.
// relayerFee: {
//   relayerAmount: "100000",
//   relayerDecimals: 6
// },
packages/universal-swap/src/msg/chains/cosmos.ts (2)

33-34: Correct typo in comment

In the comment on line 34, there's a typographical error. It should be "Cosmos-based ecosystem" instead of "Cosmos-base ecosystem."

Apply this diff to correct the typo:

  /**
-   * Function to get IBC info of Cosmos-base ecosystem
+   * Function to get IBC info of Cosmos-based ecosystem
    */

121-123: Update error message to reference Cosmos instead of Oraichain

In the genExecuteMsg method, the error message mentions Oraichain, which might be misleading since this method is within the CosmosMsg class. Updating the error message to reference Cosmos improves clarity and accuracy.

Apply this diff to correct the error message:

  if (bridgeInfo.sourcePort != "transfer") {
-   throw generateError("Error on generate executeMsg on Oraichain: Only support ibc transfer");
+   throw generateError("Error generating executeMsg on Cosmos: Only support IBC transfer");
  }
packages/universal-swap/src/msg/msgs.ts (2)

62-64: Improve error message for unsupported universal swap on EVM chains

The error message "Don't support universal swap in EVM" can be made more informative by including the currentChain value.

Enhance the error message as follows:

- throw generateError("Don't support universal swap in EVM");
+ throw generateError(`Universal swap is not supported on EVM chain: ${currentChain}`);

114-116: Enhance error message when route paths are empty

The current error message "Require at least 1 action" might be unclear to users.

Improve the error message for better clarity:

- throw generateError("Require at least 1 action");
+ throw generateError("Route must contain at least one path to perform a swap.");
packages/oraidex-common/src/ibc-info.ts (1)

Line range hint 9-9: Fix Typo in Import Statement

There is a typographical error in the import statement for ORAIB_ORAICHAIN_CHANNELS_TEST. It is misspelled as ORAIB_ORAICHIN_CHANNELS_TEST.

Apply this diff to correct the typo:

-import {
  ATOM_ORAICHAIN_CHANNELS,
  IBC_TRANSFER_TIMEOUT,
  IBC_WASM_CONTRACT,
  IBC_WASM_CONTRACT_TEST,
  INJECTIVE_ORAICHAIN_CHANNELS,
  KWT_ORAICHAIN_CHANNELS,
  NOBLE_ORAICHAIN_CHANNELS,
  NOBLE_ORAICHAIN_CHANNELS_TEST,
  ORAIB_ORAICHIN_CHANNELS_TEST,
  ORAIB_ORAICHAIN_CHANNELS,
  ORAIB_ORAICHAIN_CHANNELS_OLD,
  OSMOSIS_ORAICHAIN_CHANNELS,
  NEUTARO_ORAICHAIN_CHANNELS
} from "./constant";
+import {
  ATOM_ORAICHAIN_CHANNELS,
  IBC_TRANSFER_TIMEOUT,
  IBC_WASM_CONTRACT,
  IBC_WASM_CONTRACT_TEST,
  INJECTIVE_ORAICHAIN_CHANNELS,
  KWT_ORAICHAIN_CHANNELS,
  NOBLE_ORAICHAIN_CHANNELS,
  NOBLE_ORAICHAIN_CHANNELS_TEST,
  ORAIB_ORAICHAIN_CHANNELS_TEST,
  ORAIB_ORAICHAIN_CHANNELS,
  ORAIB_ORAICHAIN_CHANNELS_OLD,
  OSMOSIS_ORAICHAIN_CHANNELS,
  NEUTARO_ORAICHAIN_CHANNELS
} from "./constant";
packages/universal-swap/src/msg/chains/osmosis.ts (3)

59-67: Error Handling: Validate swapInfo before usage

In the loop over action.swapInfo, there is an assumption that swapInfo is defined and properly structured. Adding a validation step can prevent runtime errors if swapInfo is undefined or malformed.

Consider adding a check:

action.swapInfo.forEach((swapInfo) => {
+   if (!swapInfo || !swapInfo.poolId || !swapInfo.tokenOut) {
+       throw generateError("Invalid swapInfo data");
+   }
    swapOps.push({
        denom_in: denomIn,
        denom_out: swapInfo.tokenOut,
        pool: swapInfo.poolId
    });
    denomIn = swapInfo.tokenOut;
});

157-169: Code Consistency: Consolidate min_asset construction

The construction of min_asset for CW20 and native tokens could be simplified for readability.

Consider refactoring:

let assetType = isCw20Token(tokenOutOfSwap) ? 'cw20' : 'native';
let assetInfo = isCw20Token(tokenOutOfSwap)
    ? { address: tokenOutOfSwap }
    : { denom: tokenOutOfSwap };

let min_asset = {
    [assetType]: {
        amount: this.minimumReceive,
        ...assetInfo
    }
};

228-228: Error Message Clarification: Provide more detailed information

The error message "Only support ibc transfer" is generic. Providing more context can aid in debugging.

Enhance the error message:

throw generateError("Error generating executeMsg on Osmosis: Only IBC transfers are supported when no swap operations are provided.");
packages/universal-swap/src/msg/chains/oraichain.ts (1)

451-451: Improve clarity of error message

The error message can be rephrased for clarity and to adhere to standard grammatical conventions.

Apply this diff to enhance the error message:

-throw generateError("Error on generate executeMsg on Oraichain: Only support ibc or ibc wasm bridge");
+throw generateError("Error generating executeMsg on Oraichain: Only support IBC or IBC wasm bridge");
packages/universal-swap/tests/msg/msgs.spec.ts (2)

381-384: Check Indentation for Better Readability

Ensure consistent indentation for the bridgeInfo object at lines 381-384 to enhance code readability.


358-359: Add Description to Test Case

The test case starting at line 359 lacks a description. Adding a descriptive string will clarify the purpose of the test.

Apply this diff:

-describe("test build swap msg", () => {
+describe("Test building universal swap messages", () => {
packages/universal-swap/tests/msg/oraichain-msg.spec.ts (2)

630-630: Avoid hardcoding addresses for better flexibility and security

The bridge address oraiBridgeAddr is hardcoded in the test cases. While this may work for now, it can be problematic if the address changes or differs between environments (e.g., testnet vs. mainnet). Consider using configuration files or environment variables to manage such constants.

Also applies to: 700-700


49-83: Ensure all possible variations are tested in getPostAction

The test cases in it.each cover scenarios with and without bridgeInfo. Consider adding more variations, such as invalid bridgeInfo or edge cases, to thoroughly test the getPostAction method.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between fd9dc2b and d6bca87.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (29)
  • .gitignore (1 hunks)
  • packages/oraidex-common/package.json (1 hunks)
  • packages/oraidex-common/src/celestia-network.ts (1 hunks)
  • packages/oraidex-common/src/constant.ts (1 hunks)
  • packages/oraidex-common/src/ibc-info.ts (2 hunks)
  • packages/oraidex-common/src/index.ts (1 hunks)
  • packages/oraidex-common/src/network.ts (4 hunks)
  • packages/universal-swap/package.json (2 hunks)
  • packages/universal-swap/src/handler.ts (10 hunks)
  • packages/universal-swap/src/helper.ts (8 hunks)
  • packages/universal-swap/src/msg/chains/chain.ts (1 hunks)
  • packages/universal-swap/src/msg/chains/cosmos.ts (1 hunks)
  • packages/universal-swap/src/msg/chains/index.ts (1 hunks)
  • packages/universal-swap/src/msg/chains/oraichain.ts (1 hunks)
  • packages/universal-swap/src/msg/chains/osmosis.ts (1 hunks)
  • packages/universal-swap/src/msg/common.ts (1 hunks)
  • packages/universal-swap/src/msg/index.ts (1 hunks)
  • packages/universal-swap/src/msg/msgs.ts (1 hunks)
  • packages/universal-swap/src/msg/types.ts (1 hunks)
  • packages/universal-swap/src/types.ts (5 hunks)
  • packages/universal-swap/src/universal-demos/alpha-ibc-new.ts (1 hunks)
  • packages/universal-swap/src/universal-demos/alpha-smart-router.ts (3 hunks)
  • packages/universal-swap/tests/helper.spec.ts (2 hunks)
  • packages/universal-swap/tests/msg/comos-msg.spec.ts (1 hunks)
  • packages/universal-swap/tests/msg/msgs.spec.ts (1 hunks)
  • packages/universal-swap/tests/msg/oraichain-msg.spec.ts (1 hunks)
  • packages/universal-swap/tests/msg/osmosis-msg.spec.ts (1 hunks)
  • packages/universal-swap/tests/msg/test-data.ts (1 hunks)
  • tsconfig.json (1 hunks)
✅ Files skipped from review due to trivial changes (5)
  • .gitignore
  • packages/oraidex-common/package.json
  • packages/universal-swap/src/msg/chains/index.ts
  • packages/universal-swap/src/msg/index.ts
  • tsconfig.json
🧰 Additional context used
🪛 Gitleaks
packages/universal-swap/src/universal-demos/alpha-smart-router.ts

16-16: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


18-18: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


25-25: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


27-27: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


39-39: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


48-48: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


50-50: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


56-56: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


63-63: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

packages/universal-swap/tests/msg/msgs.spec.ts

230-230: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


253-253: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


368-368: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


377-377: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


389-389: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


391-391: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


398-398: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


400-400: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


406-406: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


471-471: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


480-480: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


492-492: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


494-494: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


501-501: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


517-517: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


522-522: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


529-529: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


531-531: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

packages/universal-swap/tests/msg/oraichain-msg.spec.ts

429-429: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


438-438: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


443-443: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


450-450: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


452-452: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


476-476: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


477-477: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


568-568: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


570-570: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


577-577: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


579-579: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


606-606: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


608-608: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


615-615: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


617-617: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


641-641: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


642-642: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


677-677: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


679-679: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


686-686: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


688-688: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

🔇 Additional comments (50)
packages/universal-swap/src/msg/chains/chain.ts (2)

1-2: LGTM: Import statements are appropriate.

The import statements are concise and import only the necessary components. The use of relative imports is suitable for the internal module structure.


21-23: LGTM: getMinimumReceive method is correctly implemented.

The method properly returns the minimumReceive property. Its implementation is simple and straightforward.

packages/universal-swap/package.json (3)

3-3: Version increment looks good.

The package version has been updated from 1.1.12 to 1.1.13, which is appropriate for adding new features or making minor changes.


20-20: Syntactical change approved.

The addition of a comma after the "ts-protoc-gen" dependency is correct and necessary for adding the new dependency.


21-21: New dependency added.

The addition of "@oraichain/osor-api-contracts-sdk" with version "^1.0.2" seems appropriate for the new feature.

Please ensure that this new dependency is necessary for the "support swap oraidex osmosis" feature mentioned in the PR title. You can verify its usage with the following script:

If the script doesn't return any results, consider removing the dependency to keep the package lean.

✅ Verification successful

Dependency Usage Verified

The new dependency "@oraichain/osor-api-contracts-sdk" is utilized in the following locations:

  • packages/universal-swap/src/msg/chains/osmosis.ts
  • packages/universal-swap/src/msg/chains/oraichain.ts
  • packages/universal-swap/src/msg/chains/cosmos.ts
  • packages/universal-swap/tests/msg/msgs.spec.ts
  • packages/universal-swap/tests/msg/comos-msg.spec.ts
  • packages/universal-swap/tests/msg/osmosis-msg.spec.ts
  • packages/universal-swap/tests/msg/oraichain-msg.spec.ts
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new dependency in the codebase

# Test: Search for import statements or usage of osor-api-contracts-sdk
rg --type typescript --type javascript 'from\s+[\'"]@oraichain/osor-api-contracts-sdk[\'"]'

Length of output: 93


Script:

#!/bin/bash
# Description: Verify the usage of the new dependency in the codebase using ast-grep

ast-grep --lang typescript --pattern '
import $_ from "@oraichain/osor-api-contracts-sdk"
'

Length of output: 93


Script:

#!/bin/bash
# Description: Verify the usage of the new dependency in the codebase using ast-grep

ast-grep --lang typescript --pattern "import $_ from '@oraichain/osor-api-contracts-sdk'"

Length of output: 592


Script:

#!/bin/bash
# Description: Broadly verify the usage of the new dependency in the codebase

# Search for any occurrence of "@oraichain/osor-api-contracts-sdk" in the codebase
rg "@oraichain/osor-api-contracts-sdk"

Length of output: 1554

packages/oraidex-common/src/celestia-network.ts (4)

1-3: LGTM: Import and constant declaration look good.

The import statement and the constant declaration are correctly implemented. The CustomChainInfo type is appropriately used for the celestiaNetwork constant.


53-54: LGTM: Wallet URL for staking is correctly set.

The wallet URL for staking is properly configured, pointing to the Keplr wallet for the Celestia chain.


15-19: LGTM: Network and chain information are correctly set.

The network type, chain ID, and chain name are accurately defined for the Celestia network. The chain symbol image URL appears to be from a reliable source.

Please verify that the chain symbol image URL is accessible and displays the correct image:

#!/bin/bash
# Description: Verify the accessibility and content type of the chain symbol image URL

# Test: Check if the URL is accessible and returns an image
curl -sI "https://raw.githubusercontent.com/chainapsis/keplr-chain-registry/main/images/celestia/chain.png" | grep -E "HTTP/2 200|Content-Type: image/"

44-52: LGTM: RPC, REST, and stake currency configurations look good.

The RPC and REST endpoints are provided, and the stake currency is correctly configured. However, it's important to verify that these endpoints are correct and operational.

Please verify that the RPC and REST endpoints are accessible and return valid responses:

✅ Verification successful

LGTM: RPC, REST, and stake currency configurations look good.

The RPC and REST endpoints are accessible and returning valid responses.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the accessibility of RPC and REST endpoints

# Test: Check if the RPC endpoint is accessible
curl -sI "https://celestia.rpc.orai.io" | grep "HTTP/2 200"

# Test: Check if the REST endpoint is accessible
curl -sI "https://celestia.lcd.orai.io" | grep "HTTP/2 200"

Length of output: 213


Script:

#!/bin/bash
# Description: Verify the accessibility of RPC and REST endpoints

# Test: Check if the RPC endpoint is accessible
curl -sI "https://celestia.rpc.orai.io" | grep "HTTP/2 200"

# Test: Check if the REST endpoint is accessible
curl -sI "https://celestia.lcd.orai.io" | grep "HTTP/2 200"

Length of output: 119


Script:

#!/bin/bash
# Description: Verify the accessibility of RPC and REST endpoints by retrieving HTTP status codes

# Test: Get HTTP status code for the RPC endpoint
echo "Checking RPC endpoint..."
status_rpc=$(curl -s -o /dev/null -w "%{http_code}" "https://celestia.rpc.orai.io")
echo "RPC endpoint status code: $status_rpc"

# Test: Get HTTP status code for the REST endpoint
echo "Checking REST endpoint..."
status_rest=$(curl -s -o /dev/null -w "%{http_code}" "https://celestia.lcd.orai.io")
echo "REST endpoint status code: $status_rest"

Length of output: 436

packages/universal-swap/src/msg/common.ts (2)

1-3: LGTM: Imports are appropriate and concise.

The import statements are relevant to the file's functionality, including necessary types, external libraries, and internal utilities.


1-48: Overall assessment: Well-structured utility functions with room for minor improvements.

The file common.ts provides essential utility functions for blockchain operations. The code is generally well-written and performs necessary validations. Consider implementing the suggested improvements for enhanced robustness and accuracy, particularly in the isCw20Token function and input sanitization in validateReceiver.

packages/universal-swap/src/types.ts (3)

14-18: LGTM: ActionType enum addition

The new ActionType enum is a good addition. It provides a clear and type-safe way to represent different action types (Bridge, Swap, Convert) in the system. The naming is self-explanatory and it's properly exported for use in other parts of the codebase.


Line range hint 1-269: Overall assessment: Good changes with minor improvements needed

The modifications to this file enhance the functionality and flexibility of the universal swap system while maintaining backward compatibility. The new ActionType enum, the exported Path interface, and the additions to RouterConfigSmartRoute and SwapOptions interfaces are all valuable improvements.

To further improve the code:

  1. Verify the impact of exporting the Path interface on the rest of the codebase.
  2. Add documentation for the new maxSplits property in RouterConfigSmartRoute.
  3. Provide comprehensive documentation for the isAlphaIbcWasm property in SwapOptions, explaining its purpose, implications, and any associated risks.

These minor enhancements will greatly improve the maintainability and usability of the code for other developers working on this project.


217-217: LGTM: Exporting Path interface, but verify impact

Exporting the Path interface is a good change as it allows for reuse in other modules and maintains a consistent type system. However, please verify that this change doesn't unintentionally expose this type in ways that could break existing code or violate encapsulation principles.

To ensure this change doesn't have unintended consequences, please run the following command to check for any new usages of the Path interface:

✅ Verification successful

Verified: Exporting Path interface does not introduce issues

The export of the Path interface has been successfully implemented and is being correctly utilized across multiple modules within the codebase. All existing imports and usages align with the intended changes, ensuring consistency and reusability without compromising encapsulation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for new usages of the Path interface
rg --type typescript -e "import.*Path" -e "Path\[" -e ": Path" -e "as Path"

Length of output: 112


Script:

#!/bin/bash
# Search for new usages of the Path interface without specifying the type
rg -t ts -e "import.*Path" -e "Path\[" -e ": Path" -e "as Path"

Length of output: 1847

packages/universal-swap/tests/helper.spec.ts (2)

589-593: Updated test case for addOraiBridgeRoute

The test case has been modified to use an object for the sourceReceiver and destReceiver parameters instead of separate arguments. This change aligns with the updated function signature of addOraiBridgeRoute.


602-611: Updated error test case for addOraiBridgeRoute

The error test case for addOraiBridgeRoute has been updated to use the new object parameter structure. This change correctly tests the function's behavior when an empty sourceReceiver is provided.

packages/universal-swap/src/msg/types.ts (3)

1-4: Imports are appropriate and necessary.

The imported modules are correctly specified and required for the interfaces and types defined in this file.


34-37: MiddlewareResponse interface is well-defined.

The properties memo and receiver are appropriately specified.


12-24: ⚠️ Potential issue

Verify the data types for amount and clarify units in BridgeMsgInfo.

The amount field is currently a string. If it represents a numeric value, consider using a numeric type or a dedicated class for handling currency amounts to improve type safety and prevent parsing errors.

Also, clarify the unit and format for the timeout field (e.g., seconds, milliseconds) to avoid potential misinterpretation.

Run the following script to check how BridgeMsgInfo is used in the codebase and ensure consistent handling of amount and timeout:

✅ Verification successful

Existing implementation for amount and timeout in BridgeMsgInfo is appropriate, but documentation can be improved.

The current implementation of BridgeMsgInfo uses appropriate data types for amount (string) and timeout (number). Here's why:

  1. amount as string:

    • Allows handling of large numbers without precision loss.
    • Consistent with common practices in financial applications and blockchain ecosystems.
    • No evidence of parsing errors or type safety issues in the codebase.
  2. timeout as number:

    • Consistently used throughout the codebase.
    • Set using calculateTimeoutTimestamp function, which returns a number.

To improve clarity, consider adding comments or documentation:

  1. For amount, explain that it's a string to preserve precision for large numbers.
  2. For timeout, specify the unit (e.g., milliseconds since epoch) in a comment.

These clarifications will help future developers understand the design choices without changing the current implementation.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of `BridgeMsgInfo` and examine how `amount` and `timeout` are handled.

# Search for all TypeScript files using `BridgeMsgInfo`
rg --type ts 'BridgeMsgInfo' -A 5

Length of output: 9430


Script:

#!/bin/bash
# Description: Find all assignments and manipulations of `amount` and `timeout` in `BridgeMsgInfo`.

# Search for assignments to `amount` and `timeout`
rg --type ts '(amount\s*:|timeout\s*:)' -A 10

Length of output: 421751

packages/universal-swap/src/universal-demos/alpha-ibc-new.ts (2)

85-85: Review Swap Options Configuration

In the swapOptions, isIbcWasm is set to false, and isAlphaIbcWasm is set to true. Ensure that this configuration aligns with the intended behavior of the swap operation.

If this configuration is intentional and necessary for interacting with alpha versions or specific protocols, no action is needed. Otherwise, review the settings to confirm they are correct.


62-63: Verify Token Identifiers for Accuracy

Ensure that the coinGeckoId and chainId used in the flattenTokens.find() methods accurately correspond to the intended tokens:

  • coinGeckoId: "osmosis" and chainId: "osmosis-1" for the original from token.
  • coinGeckoId: "celestia" and chainId: "celestia" for the original to token.

If coinGeckoId "celestia" correctly maps to the "utia" token on the Celestia network, this is acceptable. Otherwise, there might be a mismatch that could lead to incorrect token selection.

Run the following script to verify the token mappings:

This will help confirm that the tokens are correctly identified in the flattenTokens array.

packages/universal-swap/src/universal-demos/alpha-smart-router.ts (1)

Line range hint 7-112: Code changes are well-implemented

The modifications to the router configuration and the alphaSwapToOraichain function correctly implement the desired functionality. The updated swap amounts, token assignments, and swap options align with the intended behavior and appear consistent and accurate.

🧰 Tools
🪛 Gitleaks

16-16: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


18-18: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


25-25: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


27-27: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


39-39: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


48-48: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


50-50: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


56-56: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


63-63: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

packages/universal-swap/src/msg/chains/cosmos.ts (1)

81-89: Verify the use of recover_address in ibc_transfer action

The ibc_transfer action includes a recover_address field, but it's important to confirm that this field is supported in the IBC transfer specification for Cosmos SDK. Using an unsupported field could lead to transaction rejection or unexpected behavior.

Please check the IBC transfer module documentation or SDK specifications to ensure the recover_address field is valid in this context.

packages/universal-swap/src/msg/msgs.ts (2)

120-125: Ensure correct indices in memo generation loop

In the memo generation loop, verify that the indices and array accesses are correct to prevent off-by-one errors or undefined behavior when accessing elements with route.paths.at(-1).


109-128: Verify that receiver addresses are defined for all paths

In the generateMsgSwap function, the receiver is set based on the last path's tokenOutChainId. Ensure that the addresses object contains receiver addresses for all relevant chainId values to prevent undefined behavior.

Run the following script to check for missing receiver addresses:

packages/oraidex-common/src/ibc-info.ts (2)

183-186: Ensure "celestia" Exclusion from ibcInfosOld is Intentional

The ibcInfosOld constant now omits "celestia". Confirm that this change is deliberate and that there are no remaining dependencies on "celestia" within ibcInfosOld or related logic.

Run the following script to verify that "celestia" is not referenced in ibcInfosOld:

#!/bin/bash
# Description: Search for references to "celestia" in ibcInfosOld.

# Test: Find occurrences of "celestia" in ibcInfosOld definitions. Expect: No matches.
rg --type ts 'ibcInfosOld.*"celestia"'

44-44: Confirm the Exclusion of "celestia" from ibcInfos

The change excludes "celestia" from ibcInfos. Please verify that this exclusion is intentional and that there are no dependencies on "celestia" in the ibcInfos usage throughout the codebase.

Run the following script to check for references to "celestia" related to ibcInfos in the codebase:

✅ Verification successful

Exclusion of "celestia" from ibcInfos Verified

No dependencies on "celestia" were found in the usage of ibcInfos. The exclusion is intentional.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for references to "celestia" in ibcInfos usage.

# Test: Find occurrences of "celestia" in TypeScript files. Expect: No matches indicating dependency.
rg --type ts 'ibcInfos.*"celestia"'

Length of output: 134


Script:

#!/bin/bash
# Description: Search for references to "celestia" in ibcInfos usage.

# Test: Find occurrences of "celestia" in TypeScript files. Expect: No matches indicating dependency.
rg --type ts 'ibcInfos.*"celestia"'

Length of output: 133

packages/universal-swap/src/msg/chains/osmosis.ts (3)

122-122: Clarification Needed: Unreachable code path

The throw error at line 122 suggests a missing postAction, but given the cases handled, it's unclear under what circumstances this error would be triggered. Ensure all possible action types are accounted for.

Please review the logic to confirm that all action types are handled appropriately or adjust the error message to provide more context.


285-294: Security Concern: Validate Funds and Amounts

When constructing the funds array for native tokens, ensure that the amount and denom are correctly validated to prevent potential injection or tampering.

Consider adding validation for this.path.tokenInAmount and this.path.tokenIn to ensure they are in the expected format and safe to include.


73-73: ⚠️ Potential issue

Typo Correction: Fix typo in error message

There's a typo in the error message—"Only support IBC bridge on Osmosis" should replace "Only support IBC bridge on ${this.path.chainId}".

Correct the error message:

throw generateError(`Only support IBC bridge on Osmosis`);

Likely invalid or redundant comment.

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

185-186: Verify the Correct Usage of typeUrl in Assertions

In the assertions for executeMsg.typeUrl, you're checking for hard-coded string values. Ensure that these values are correct and up to date with the protobuf definitions.

Double-check that "/cosmwasm.wasm.v1.MsgExecuteContract" and "/ibc.applications.transfer.v1.MsgTransfer" are the correct typeUrl values for the respective messages. If these values are defined elsewhere in your codebase or in a dependency, consider importing and using the constants instead of hard-coding strings.

Example:

import { MsgExecuteContract } from "cosmjs-types/cosmwasm/wasm/v1/tx";

expect(executeMsg.typeUrl).toEqual(MsgExecuteContract.typeUrl);

This approach reduces the risk of typos and makes your tests more maintainable.

Also applies to: 338-339

packages/universal-swap/tests/msg/msgs.spec.ts (2)

501-510: Consistent Use of Swap Protocols

Ensure that the swap protocols used ("Oraidex" and "OraidexV3") are correctly implemented and consistently referenced throughout the tests.

Also applies to: 517-525

🧰 Tools
🪛 Gitleaks

501-501: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


190-210: ⚠️ Potential issue

Verify Token Denominations and Pool IDs

Ensure that the token denominations and pool IDs used in the swap operations are correct and up to date. Incorrect values may cause the swap to fail.

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

676-697: Validate test data to ensure correctness

In the validPath object, the tokenOutAmount is "306106", but in your bridgeInfo, the amount is "936043", which matches the tokenInAmount. Ensure that the tokenOutAmount accurately reflects the expected output after the bridge operation.

🧰 Tools
🪛 Gitleaks

677-677: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


679-679: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


686-686: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


688-688: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

packages/oraidex-common/src/network.ts (4)

80-81: Added "Celestia" to NetworkName type

The addition of "Celestia" to the NetworkName type is correct and consistent with existing entries.


91-92: Added "celestia" to CosmosChainId type

Including "celestia" in the CosmosChainId type aligns with the pattern of other Cosmos chain IDs.


547-547: Included celestiaNetwork in the chainInfos array

Adding celestiaNetwork to the chainInfos array correctly integrates the Celestia network into the supported networks.


66-66: Verify the existence and configuration of celestiaNetwork

Ensure that celestiaNetwork is properly defined in ./celestia-network.ts and includes all necessary configurations for the Celestia network.

Run the following script to check if celestia-network.ts exists and contains the expected export:

✅ Verification successful

celestiaNetwork is properly defined and exported in celestia-network.ts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `celestia-network.ts` exists and contains the export for `celestiaNetwork`.

# Test: Check for the existence of `celestia-network.ts`. Expect: The file path should be printed if it exists.
fd --type f --name "celestia-network.ts" src/

# Test: Confirm that `celestiaNetwork` is exported. Expect: Lines containing `export const celestiaNetwork` should be displayed.
if [ -f src/celestia-network.ts ]; then
  grep -E "export\s+const\s+celestiaNetwork" src/celestia-network.ts
fi

Length of output: 333


Script:

#!/bin/bash
# Description: Verify that `celestia-network.ts` exists and contains the export for `celestiaNetwork`.

# Test: Check for the existence of `celestia-network.ts`. Expect: The file path should be printed if it exists.
fd --type f "celestia-network.ts" src/

# Test: Confirm that `celestiaNetwork` is exported. Expect: Lines containing `export const celestiaNetwork` should be displayed.
if [ -f src/celestia-network.ts ]; then
  grep -E "export\s+const\s+celestiaNetwork" src/celestia-network.ts
fi

Length of output: 167


Script:

#!/bin/bash
# Description: Verify that `celestia-network.ts` exists and contains the export for `celestiaNetwork`.

# Test: Check for the existence of `celestia-network.ts`. Expect: The file path should be printed if it exists.
fd --type f "celestia-network.ts"

# Capture the file path if it exists
FILE_PATH=$(fd --type f "celestia-network.ts" | head -n 1)

# Test: Confirm that `celestiaNetwork` is exported. Expect: Lines containing `export const celestiaNetwork` should be displayed.
if [ -f "$FILE_PATH" ]; then
  grep -E "export\s+const\s+celestiaNetwork" "$FILE_PATH"
fi

Length of output: 393

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

63-64: Imports Added Correctly

The new imports for COSMOS_CHAIN_IDS and generateMsgSwap are appropriately added and will support the new functionalities introduced in the code.


335-338: Correct Usage of UniversalSwapHelper.getAddress

In getSwapAndActionInOsmosis, the to_address is correctly obtained using UniversalSwapHelper.getAddress, ensuring that the address format aligns with the target chain's requirements.


419-422: Appropriate Receiver Address Retrieval

The receiver field in getIbcTransferInfo is correctly assigned using UniversalSwapHelper.getAddress, which helps maintain consistency across different blockchain networks.


425-428: Proper Use of UniversalSwapHelper.getAddress for Recover Address

The recover_address is accurately generated using UniversalSwapHelper.getAddress, ensuring that any recovery operations can correctly identify the address across chains.


438-441: Accurate Address Generation in createForwardObject

The addressReceiver is correctly obtained using UniversalSwapHelper.getAddress, facilitating proper message forwarding in IBC transactions.


476-479: Consistent Address Assignment for Message Transfer

In getMsgTransfer, the addressReceiver is appropriately assigned using UniversalSwapHelper.getAddress, ensuring compatibility with the receiving chain's address format.


500-503: Correct Sender Address Construction

The sender address is accurately generated using UniversalSwapHelper.getAddress, which is crucial for transaction validation and processing.


1058-1067: Valid Destructuring of this.swapData Properties

The properties are properly destructured from this.swapData in swapCosmosToOtherNetwork, ensuring all necessary data is available for the operation.


1179-1180: Correct Extraction of Properties from this.swapData

The properties evm, tron, and others are accurately destructured from this.swapData and this.swapData.sender, ensuring the necessary data is readily available.


1201-1206: Efficient Retrieval of Addresses Using Promise.all

The concurrent fetching of oraiAddress and obridgeAddress with Promise.all optimizes the asynchronous operations, improving performance.


1211-1214: Potential Undefined alphaSmartRoutes Access

In processUniversalSwap, alphaSmartRoutes might be undefined, and accessing alphaSmartRoutes.routes without checking could cause a runtime error.

Refer to the previous comment on handling potential undefined alphaSmartRoutes in alphaSmartRouterSwapNewMsg.


1232-1238: Safe Execution with Optional Chaining

The condition checks alphaSmartRoutes?.routes?.length using optional chaining, which safely handles cases where alphaSmartRoutes might be undefined, preventing potential runtime errors.

packages/universal-swap/src/msg/common.ts Show resolved Hide resolved
packages/universal-swap/src/msg/types.ts Outdated Show resolved Hide resolved
packages/universal-swap/src/helper.ts Show resolved Hide resolved
packages/universal-swap/src/helper.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: 6

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

125-125: Correct error message to reflect the Cosmos network

The error message mentions "Oraichain," but since this is a CosmosMsg class, it should refer to "Cosmos-base network" for clarity.

Apply this diff to fix the issue:

- throw generateError("Error on generate executeMsg on Oraichain: Only support ibc transfer");
+ throw generateError("Error generating executeMsg on Cosmos-base network: Only support IBC transfer");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between d6bca87 and c9fe2fd.

📒 Files selected for processing (4)
  • packages/universal-swap/src/msg/chains/cosmos.ts (1 hunks)
  • packages/universal-swap/src/msg/chains/oraichain.ts (1 hunks)
  • packages/universal-swap/src/msg/chains/osmosis.ts (1 hunks)
  • packages/universal-swap/src/msg/index.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (10)
packages/universal-swap/src/msg/index.ts (1)

1-4: Consider the implications of exporting all entities from multiple modules.

The current approach of using export * for multiple modules provides a convenient single point of entry for imports. However, it may lead to potential issues:

  1. Naming conflicts: If different modules export entities with the same name, it could cause unexpected behavior.
  2. Reduced code clarity: It becomes harder to track which specific entities are being used where in the codebase.
  3. Potential bundle size increase: If tree-shaking is not properly implemented, this could lead to larger bundle sizes.

Consider the following improvements:

  1. Explicitly export only the necessary entities from each module to avoid potential conflicts and improve clarity.
  2. If wholesale exports are necessary, consider using namespaces to organize the exports, e.g.:
    import * as Common from "./common";
    import * as Chains from "./chains";
    import * as Types from "./types";
    import * as Msgs from "./msgs";
    
    export { Common, Chains, Types, Msgs };
  3. Add comments to explain the purpose of each module and its exports.

To check for potential naming conflicts, you can run the following script:

This script will help identify any naming conflicts across the exported entities.

packages/universal-swap/src/msg/chains/osmosis.ts (7)

109-134: LGTM: Post-action handling looks good

The getPostAction method correctly handles both transfer to receiver and IBC transfer cases. The logic is clear and appropriate for the given scenarios.


1-308: Consider adding unit tests

The OsmosisMsg class contains complex logic for handling various scenarios. To ensure reliability and catch potential issues early, it would be beneficial to add unit tests for the class methods.

Would you like assistance in setting up unit tests for this class?


19-29: 🛠️ Refactor suggestion

Use a constant for the Osmosis chain ID

To improve maintainability and reduce the risk of typos, consider using a constant for the Osmosis chain ID.

Apply this change:

+ const OSMOSIS_CHAIN_ID = "osmosis-1";

  constructor(path: Path, minimumReceive: string, receiver: string, currentChainAddress: string, memo: string = "") {
    super(path, minimumReceive, receiver, currentChainAddress, memo);
    // check chainId  = "osmosis-1"
-   if (path.chainId !== "osmosis-1") {
+   if (path.chainId !== OSMOSIS_CHAIN_ID) {
      throw generateError("This path must be on Osmosis");
    }
  }

36-48: ⚠️ Potential issue

Improve slippage validation and precision handling

  1. The slippage validation should also check for negative values.
  2. The current method of converting to an integer by splitting at the decimal point may lead to precision loss.

Consider these improvements:

  1. Enhance slippage validation:
- if (slippage > 1) {
+ if (slippage < 0 || slippage > 1) {
-   throw generateError("Slippage must be less than 1");
+   throw generateError("Slippage must be between 0 and 1");
  }
  1. Use a more precise method for rounding:
- if (minimumReceive.includes(".")) {
-   minimumReceive = minimumReceive.split(".")[0];
- }
+ minimumReceive = Math.floor(Number(minimumReceive)).toString();

53-101: ⚠️ Potential issue

Fix typo in error message

There's a typo in the error message for unsupported actions.

Apply this correction:

- throw generateError("Only support swap + bride on Osmosis");
+ throw generateError("Only support swap + bridge on Osmosis");

138-206: ⚠️ Potential issue

Ensure consistent timestamp handling

The use of the unary + operator to convert the timeout timestamp to a number might lead to precision loss for large values. It's safer to keep it as a string to prevent potential issues.

Consider this change:

- timeout: +calculateTimeoutTimestamp(IBC_TRANSFER_TIMEOUT),
+ timeout: calculateTimeoutTimestamp(IBC_TRANSFER_TIMEOUT).toString(),

Also, apply this change in other occurrences within the file.


212-307: ⚠️ Potential issue

Correct CW20 token message structure

In the CW20 token handling section, the message structure appears to be incorrect. The send field should not be nested twice.

Apply this correction:

msg: toUtf8(
  JSON.stringify({
    send: {
-     send: {
        contract: this.ENTRY_POINT_CONTRACT,
        amount: this.path.tokenInAmount,
        msg: toBinary(msg)
-     }
    }
  })
),
packages/universal-swap/src/msg/chains/oraichain.ts (1)

1-533: Overall implementation review

The OraichainMsg class provides a comprehensive implementation for handling various swap and bridge operations within the Oraichain ecosystem. The code is well-structured and handles different scenarios appropriately. However, there are a few minor issues that should be addressed:

  1. Fix the typo in the error message for unsupported actions.
  2. Improve the slippage validation in the setMinimumReceiveForSwap method.
  3. Correct the typo in the pasreConverterMsgToPoolId method name.
  4. Add validation for the sourcePort format in the getProtoForPostAction method.
  5. Correct the CW20 'send' message structure in the genExecuteMsg method.

After addressing these issues, the implementation will be more robust and less prone to potential errors.

packages/universal-swap/src/msg/chains/cosmos.ts (1)

20-30: Reconsider validation and rounding in setMinimumReceiveForSwap

Previous comments regarding the validation of negative slippage values and the use of proper rounding methods for minimumReceive are still applicable. Please address these to ensure numerical accuracy and input validation.

packages/universal-swap/src/msg/chains/oraichain.ts Outdated Show resolved Hide resolved
packages/universal-swap/src/msg/chains/oraichain.ts Outdated Show resolved Hide resolved
packages/universal-swap/src/msg/chains/oraichain.ts Outdated Show resolved Hide resolved
packages/universal-swap/src/msg/chains/oraichain.ts Outdated Show resolved Hide resolved
packages/universal-swap/src/msg/chains/cosmos.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: 5

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

1-308: Overall assessment: Comprehensive implementation with room for structural improvements

The OsmosisMsg class provides a comprehensive implementation for handling Osmosis blockchain operations. It covers various scenarios including swaps, bridges, and IBC transfers. The logic seems correct and well-thought-out.

Main points for improvement:

  1. Code structure: Several methods (e.g., getSwapAndBridgeInfo, genMemoAsMiddleware, genExecuteMsg) could benefit from being split into smaller, more focused functions for better readability and maintainability.

  2. Constants management: Consider moving hardcoded values (like chain IDs and contract addresses) to a centralized configuration file.

  3. Precision handling: Pay attention to precision issues, especially when dealing with timestamps and financial calculations. Consider using appropriate data types (like BigNumber) for such operations.

  4. Error handling: While error handling is present, it could be more consistent and informative across the class.

  5. Testing: Given the complexity of the operations, it would be beneficial to have comprehensive unit tests for this class to ensure reliability and catch potential issues early.

Consider implementing a more modular architecture, possibly using the Strategy pattern for different types of operations (swap, bridge, IBC transfer). This could make the code more extensible for future additions or modifications to the Osmosis protocol.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c9fe2fd and 1be1f92.

📒 Files selected for processing (4)
  • packages/universal-swap/src/msg/chains/cosmos.ts (1 hunks)
  • packages/universal-swap/src/msg/chains/oraichain.ts (1 hunks)
  • packages/universal-swap/src/msg/chains/osmosis.ts (1 hunks)
  • packages/universal-swap/src/msg/types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/universal-swap/src/msg/chains/cosmos.ts
  • packages/universal-swap/src/msg/chains/oraichain.ts
  • packages/universal-swap/src/msg/types.ts
🧰 Additional context used
🔇 Additional comments (1)
packages/universal-swap/src/msg/chains/osmosis.ts (1)

109-134: LGTM: getPostAction implementation is clear and correct

The getPostAction method effectively handles both transfer and IBC transfer cases. The logic is straightforward and easy to follow. Good job on providing clear error messages for unsupported scenarios.

packages/universal-swap/src/msg/chains/osmosis.ts Outdated Show resolved Hide resolved
packages/universal-swap/src/msg/chains/osmosis.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: 1

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

1179-1180: Updated processUniversalSwap method

The processUniversalSwap method has been updated to include new functionality for alpha smart router swaps and IBC wasm transfers. The changes look good, but there's a minor improvement that could be made:

The destructuring of this.swapData is split into two statements. It would be more concise to combine them.

Consider combining the destructuring statements:

- const { originalFromToken, originalToToken, simulateAmount, recipientAddress, userSlippage, alphaSmartRoutes } =
-   this.swapData;
- const { swapOptions } = this.config;
+ const { originalFromToken, originalToToken, simulateAmount, recipientAddress, userSlippage, alphaSmartRoutes } = this.swapData;
+ const { swapOptions } = this.config;

Also applies to: 1201-1204, 1210-1214, 1217-1228, 1231-1238

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1be1f92 and c20c33a.

📒 Files selected for processing (1)
  • packages/universal-swap/src/handler.ts (10 hunks)
🧰 Additional context used
🔇 Additional comments (7)
packages/universal-swap/src/handler.ts (7)

63-64: New imports added

The new imports COSMOS_CHAIN_IDS and generateMsgSwap have been added. This suggests new functionality related to Cosmos chain IDs and message generation for swaps.


Line range hint 335-339: Use of UniversalSwapHelper.getAddress

The getAddress method has been replaced with UniversalSwapHelper.getAddress. This change centralizes address generation logic, which is a good practice for maintainability.


419-428: Updated address generation in getIbcTransferInfo

Similar to the previous comment, UniversalSwapHelper.getAddress is now used for generating addresses. This consistent approach improves code maintainability.


Line range hint 438-442: Consistent use of UniversalSwapHelper.getAddress

The getAddress method has been replaced with UniversalSwapHelper.getAddress here as well, maintaining consistency throughout the code.


Line range hint 476-480: Consistent address generation in getMsgTransfer

The UniversalSwapHelper.getAddress method is used here too, further improving consistency in address generation across the codebase.


Line range hint 500-504: Consistent sender address generation

The UniversalSwapHelper.getAddress method is used for generating the sender address, maintaining consistency with previous changes.


Line range hint 1-1569: Overall code review summary

The changes to this file primarily focus on improving consistency in address generation and adding new functionality for alpha smart router swaps. Here's a summary of the key points:

  1. Address generation has been centralized using UniversalSwapHelper.getAddress, which improves maintainability.
  2. New imports and methods have been added to support alpha smart router swaps and IBC wasm transfers.
  3. The processUniversalSwap method has been updated to include the new functionality.

While the changes are generally positive, there are a couple of minor improvements that could be made:

  1. In the alphaSmartRouterSwapNewMsg method, add a null check for alphaSmartRoutes to prevent potential runtime errors.
  2. In the processUniversalSwap method, consider combining the destructuring statements for better readability.

Overall, the changes appear to enhance the functionality of the UniversalSwapHandler class while maintaining good coding practices.

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

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c20c33a and 03a28c0.

📒 Files selected for processing (1)
  • packages/universal-swap/src/msg/chains/osmosis.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (1)
packages/universal-swap/src/msg/chains/osmosis.ts (1)

23-29: 🛠️ Refactor suggestion

Use a constant for the chain ID check

The chain ID "osmosis-1" is hardcoded in the constructor. To improve maintainability and reduce the risk of typos, consider using a constant or importing the chain ID from a centralized configuration file.

Apply this change:

+ const OSMOSIS_CHAIN_ID = "osmosis-1";

  constructor(path: Path, minimumReceive: string, receiver: string, currentChainAddress: string, memo: string = "") {
    super(path, minimumReceive, receiver, currentChainAddress, memo);
    // check chainId  = "osmosis-1"
-   if (path.chainId !== "osmosis-1") {
+   if (path.chainId !== OSMOSIS_CHAIN_ID) {
-     throw generateError("This path must be on Osmosis");
+     throw generateError(`This path must be on Osmosis (${OSMOSIS_CHAIN_ID})`);
    }
  }

Likely invalid or redundant comment.

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 (4)

Line range hint 335-424: Improve error handling in isAlphaIbcWasm case

In the isAlphaIbcWasm case, there's a potential for uncaught errors if alphaSmartRoute or routes[0] is undefined. Consider adding more robust error checking to prevent potential runtime errors.

Apply this diff to improve error handling:

 if (swapOption.isAlphaIbcWasm) {
   if (!alphaSmartRoute) throw generateError(`Missing router with alpha ibc wasm!`);
+  if (!alphaSmartRoute.routes || alphaSmartRoute.routes.length === 0) {
+    throw generateError(`Invalid alphaSmartRoute: missing or empty routes`);
+  }
   const routes = alphaSmartRoute.routes;
   const alphaRoutes = routes[0];

   if (alphaSmartRoute.routes.length > 1) throw generateError(`Missing router with alpha ibc wasm max length!`);

+  if (!alphaRoutes || !alphaRoutes.paths) {
+    throw generateError(`Invalid alphaRoutes: missing or invalid structure`);
+  }
   const paths = alphaRoutes.paths.filter((_, index) => index > 0);

   // ... rest of the function
 }

This change adds checks for the existence and validity of alphaSmartRoute.routes and alphaRoutes.paths, which will help prevent potential runtime errors.


Line range hint 577-605: Plan for removal of deprecated methods

The generateSwapRoute method is marked as deprecated. Consider creating a plan to remove this and other deprecated methods in future versions of the codebase. This will help maintain a cleaner and more maintainable codebase.

  1. Identify all deprecated methods in the codebase.
  2. Determine if there are any current usages of these methods.
  3. If there are usages, plan to update them to use the new recommended alternatives.
  4. Set a timeline for when these deprecated methods will be removed.
  5. Update documentation to reflect these planned changes.
  6. In a future release, remove the deprecated methods and their associated exports.

798-798: Add comment explaining useAlphaIbcWasm option

The useAlphaIbcWasm option has been added to the routerOption parameter, but its purpose is not immediately clear. Consider adding a comment to explain what this option does and when it should be used.

Add a comment above the useAlphaIbcWasm property:

routerOption?: {
  useAlphaSmartRoute?: boolean;
  useIbcWasm?: boolean;
  // Controls whether to use the Alpha IBC WASM protocol for cross-chain swaps
  useAlphaIbcWasm?: boolean;
};

Line range hint 1268-1301: Improve type annotations and documentation for generateMsgsSmartRouterV2withV3

The generateMsgsSmartRouterV2withV3 method is a crucial part of the smart routing system, but it lacks proper type annotations and documentation. Consider adding TypeScript types and JSDoc comments to improve code readability and maintainability.

Apply these changes to improve the function:

/**
 * Generate message swap token in Oraichain of smart route (pool v2 + v3)
 * @param routes - Array of route information
 * @param offerInfo - Information about the offered token
 * @returns Array of swap operations with amounts
 */
static generateMsgsSmartRouterV2withV3(
  routes: Array<{ swapInfo: Array<{ poolId: string; tokenOut: string }>; tokenInAmount: string; tokenOutAmount: string }>,
  offerInfo: AssetInfo
): Array<{ swapAmount: string; returnAmount: string; swapOps: Array<{ swap_v3?: any; orai_swap?: any }> }> {
  return routes.map((route) => {
    let ops = [];
    let currTokenIn = offerInfo;
    for (let swap of route.swapInfo) {
      // ... (rest of the function remains the same)
    }
    return {
      swapAmount: route.tokenInAmount,
      returnAmount: route.tokenOutAmount,
      swapOps: ops
    };
  });
}

This change adds a JSDoc comment explaining the function's purpose and parameters, and includes type annotations for the function parameters and return value. These improvements will make the code more self-documenting and easier to use correctly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 03a28c0 and 7a534f1.

📒 Files selected for processing (1)
  • packages/universal-swap/src/helper.ts (8 hunks)
🧰 Additional context used
🔇 Additional comments (2)
packages/universal-swap/src/helper.ts (2)

622-625: ⚠️ Potential issue

Fix typo in default value for routerConfig

There's a typo in the default value for routerConfig. The property dontAlowSwapAfter should be dontAllowSwapAfter.

Apply this diff to correct the typo:

 routerConfig: RouterConfigSmartRoute = {
   url: "https://osor.oraidex.io",
   path: "/smart-router",
   protocols: ["Oraidex", "OraidexV3"],
-  dontAlowSwapAfter: routerConfig.dontAllowSwapAfter
+  dontAllowSwapAfter: routerConfig.dontAllowSwapAfter
 }

Likely invalid or redundant comment.


323-333: ⚠️ Potential issue

Fix typo in chain ID constant

There's a typo in the chain ID constant for Injective. It should be INJECTIVE_CHAIN_ID instead of INJECTVE_CHAIN_ID.

Apply this diff to correct the typo:

 static generateAddress = ({ oraiAddress, injAddress }) => {
   const addressFollowCoinType = { address60: injAddress, address118: oraiAddress };
   return {
     [COSMOS_CHAIN_ID_COMMON.ORAICHAIN_CHAIN_ID]: oraiAddress,
-    [COSMOS_CHAIN_ID_COMMON.INJECTVE_CHAIN_ID]: injAddress,
+    [COSMOS_CHAIN_ID_COMMON.INJECTIVE_CHAIN_ID]: injAddress,
     [COSMOS_CHAIN_ID_COMMON.COSMOSHUB_CHAIN_ID]: UniversalSwapHelper.getAddress("cosmos", addressFollowCoinType),
     [COSMOS_CHAIN_ID_COMMON.OSMOSIS_CHAIN_ID]: UniversalSwapHelper.getAddress("osmo", addressFollowCoinType),
     [COSMOS_CHAIN_ID_COMMON.NOBLE_CHAIN_ID]: UniversalSwapHelper.getAddress("noble", addressFollowCoinType),
     [COSMOS_CHAIN_ID_COMMON.CELESTIA_CHAIN_ID]: UniversalSwapHelper.getAddress("celestia", addressFollowCoinType)
   };
 };

Likely invalid or redundant comment.

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

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

Line range hint 335-412: Consider refactoring for improved maintainability

The addOraiBridgeRoute function has grown quite complex, which may make it difficult to maintain and understand. Consider the following improvements:

  1. Split the function into smaller, more focused functions. For example:

    • generateSourceReceiver
    • handleAlphaIbcWasm
    • generateSwapRoute
  2. Add more comments explaining the complex logic, especially around the different swap options and routing scenarios.

  3. Use early returns to reduce nesting and improve readability.

Here's a simplified example of how you might start refactoring:

static addOraiBridgeRoute = async (params) => {
  const source = UniversalSwapHelper.generateSourceReceiver(params);
  let { swapRoute, universalSwapType, isSmartRouter } = UniversalSwapHelper.getRoute(params);

  if (isSmartRouter && params.swapOption.isIbcWasm && !params.swapOption.isAlphaIbcWasm) {
    swapRoute = await UniversalSwapHelper.handleIbcWasmRoute(params);
  }

  if (params.swapOption.isAlphaIbcWasm) {
    swapRoute = UniversalSwapHelper.handleAlphaIbcWasmRoute(params);
  }

  return UniversalSwapHelper.finalizeSwapRoute(source, swapRoute, universalSwapType, isSmartRouter);
};

This refactoring will make the function easier to understand, test, and maintain.


Line range hint 422-495: Refactor for improved readability and maintainability

The getRouteV2 function is quite complex and handles multiple scenarios. Consider the following improvements:

  1. Break down the function into smaller, more focused functions. For example:

    • determineDestinationDetails
    • buildIbcWasmBridge
    • buildIbcTransfer
  2. Use constants for hardcoded values. For example:

    const NOBLE_CHAIN_ID = "noble-1";
  3. Consider using a configuration object or enum for chain-specific logic instead of if-else statements.

Here's a simplified example of how you might start refactoring:

static getRouteV2 = (basic, userSwap, ibcInfoTestMode) => {
  const destDetails = UniversalSwapHelper.determineDestinationDetails(basic, userSwap);
  const ibcInfo = UniversalSwapHelper.getIbcInfo(userSwap.destChainId, ibcInfoTestMode);
  
  const useIbcWasm = UniversalSwapHelper.shouldUseIbcWasm(userSwap.destChainId);

  return buildUniversalSwapMemo(
    basic,
    userSwap,
    useIbcWasm ? UniversalSwapHelper.buildIbcWasmBridge(destDetails, ibcInfo) : undefined,
    undefined,
    !useIbcWasm ? UniversalSwapHelper.buildIbcTransfer(destDetails, ibcInfo) : undefined,
    userSwap.destChainId === "Oraichain" ? { toAddress: basic.recoveryAddr } : undefined
  );
};

This refactoring will make the function easier to understand, test, and maintain.


Line range hint 502-534: Enhance parsing logic and error handling

The unmarshalOraiBridgeRoute function could benefit from the following improvements:

  1. Use regular expressions for more robust parsing. This can handle various formats more efficiently and with less code.

  2. Improve error messages to provide more context, making debugging easier.

  3. Add input validation to ensure the input string is not empty or malformed before processing.

Here's an example of how you might refactor this function:

static unmarshalOraiBridgeRoute = (destination: string): OraiBridgeRouteData => {
  if (!destination || typeof destination !== 'string') {
    throw new Error(`Invalid destination: ${destination}`);
  }

  const routeData: OraiBridgeRouteData = {
    oraiBridgeChannel: "",
    oraiReceiver: "",
    finalDestinationChannel: "",
    finalReceiver: "",
    tokenIdentifier: ""
  };

  const regex = /^(?:([^\/]+)\/)?([^:]+)(?::(?:([^\/]+)\/)?([^:]+)(?::(.+))?)?$/;
  const match = destination.match(regex);

  if (!match) {
    throw new Error(`Unable to parse destination: ${destination}`);
  }

  [, routeData.oraiBridgeChannel, routeData.oraiReceiver, routeData.finalDestinationChannel, routeData.finalReceiver, routeData.tokenIdentifier] = match;

  return routeData;
};

This refactored version uses a single regular expression to parse the input string, simplifying the logic and making it more robust. It also includes better error handling and input validation.


Line range hint 1203-1236: Enhance robustness and readability

The generateMsgsSmartRouterV2withV3 function could be improved in several ways:

  1. Add input validation to ensure routes and offerInfo are valid before processing.

  2. Implement error handling to gracefully manage unexpected scenarios.

  3. Use more descriptive variable names and add comments to explain the logic, especially for the pool ID parsing.

  4. Consider using TypeScript interfaces to define the structure of the input and output objects.

Here's an example of how you might start refactoring this function:

interface SwapOperation {
  swap_v3?: {
    pool_key: {
      token_x: string;
      token_y: string;
      fee_tier: {
        fee: number;
        tick_spacing: number;
      }
    };
    x_to_y: boolean;
  };
  orai_swap?: {
    offer_asset_info: any;
    ask_asset_info: any;
  };
}

interface SwapRoute {
  swapAmount: string;
  returnAmount: string;
  swapOps: SwapOperation[];
}

static generateMsgsSmartRouterV2withV3(routes: any[], offerInfo: any): SwapRoute[] {
  if (!Array.isArray(routes) || !offerInfo) {
    throw new Error('Invalid input: routes must be an array and offerInfo must be provided');
  }

  return routes.map(route => {
    let operations: SwapOperation[] = [];
    let currentTokenIn = offerInfo;

    for (let swap of route.swapInfo) {
      const [tokenX, tokenY, fee, tickSpacing] = swap.poolId.split('-');
      const tokenOut = parseAssetInfoFromContractAddrOrDenom(swap.tokenOut);

      if (tokenX && tokenY && fee && tickSpacing) {
        // This is a V3 pool
        operations.push({
          swap_v3: {
            pool_key: {
              token_x: tokenX,
              token_y: tokenY,
              fee_tier: {
                fee: Number(fee),
                tick_spacing: Number(tickSpacing)
              }
            },
            x_to_y: tokenY === swap.tokenOut
          }
        });
      } else {
        // This is a V2 pool
        operations.push({
          orai_swap: {
            offer_asset_info: currentTokenIn,
            ask_asset_info: tokenOut
          }
        });
      }

      currentTokenIn = tokenOut;
    }

    return {
      swapAmount: route.tokenInAmount,
      returnAmount: route.tokenOutAmount,
      swapOps: operations
    };
  });
}

This refactored version includes input validation, uses TypeScript interfaces for better type checking, and includes comments to explain the logic. It also uses more descriptive variable names to improve readability.


Line range hint 1321-1363: Enhance robustness, readability, and precision

The buildSwapMsgsFromSmartRoute function could be improved in several ways:

  1. Add input validation to ensure all required parameters are provided and valid.

  2. Implement error handling to gracefully manage unexpected scenarios.

  3. Use more descriptive variable names and add comments to explain the logic, especially for the swap operation construction.

  4. Use a more precise method for calculating minimumReceive to avoid potential precision loss.

  5. Consider using TypeScript interfaces to define the structure of the input and output objects.

Here's an example of how you might start refactoring this function:

interface SwapRoute {
  swapAmount: string;
  returnAmount: string;
  swapOps: any[]; // Define a more specific type if possible
}

interface TokenInfo {
  contractAddress?: string;
  denom?: string;
}

static buildSwapMsgsFromSmartRoute(
  routes: SwapRoute[],
  fromTokenOnOrai: TokenInfo,
  to: string,
  routerContract: string,
  userSlippage: number,
  affiliates?: Affiliate[]
): ExecuteInstruction[] {
  if (!Array.isArray(routes) || !fromTokenOnOrai || !to || !routerContract || typeof userSlippage !== 'number') {
    throw new Error('Invalid input parameters');
  }

  return routes.map(route => {
    const slippageMultiplier = new BigDecimal(100 - userSlippage).div(100);
    const minimumReceive = new BigDecimal(route.returnAmount).mul(slippageMultiplier).round(0, BigDecimal.ROUND_DOWN).toString();

    const swapOperations = {
      execute_swap_operations: {
        operations: route.swapOps,
        minimum_receive: minimumReceive,
        to,
        affiliates
      }
    };

    if (fromTokenOnOrai.contractAddress) {
      // CW20 token swap
      return {
        contractAddress: fromTokenOnOrai.contractAddress,
        msg: {
          send: {
            contract: routerContract,
            amount: route.swapAmount,
            msg: toBinary(swapOperations)
          }
        },
        funds: []
      };
    } else {
      // Native token swap
      return {
        contractAddress: routerContract,
        msg: swapOperations,
        funds: handleSentFunds(parseTokenInfo(fromTokenOnOrai, route.swapAmount).fund)
      };
    }
  });
}

This refactored version includes input validation, uses a BigDecimal library for more precise calculations, and includes comments to explain the logic. It also uses more descriptive variable names and a TypeScript interface to improve readability and type safety.


Line range hint 1-1363: Overall code quality improvements needed

After reviewing the entire helper.ts file, here are some general observations and suggestions for improvement:

  1. Deprecation Management: The file contains many deprecated functions. Consider removing these deprecated functions if they are no longer in use, or create a separate file for legacy code if they're still needed for backwards compatibility.

  2. Error Handling: Implement consistent error handling across all functions. Use custom error types to provide more context and make debugging easier.

  3. Input Validation: Add thorough input validation at the beginning of each function to ensure that all required parameters are provided and of the correct type.

  4. Code Complexity: Some functions, like addOraiBridgeRoute and getRouteV2, have grown quite complex. Consider breaking these down into smaller, more focused functions to improve readability and maintainability.

  5. Type Safety: Make better use of TypeScript's type system. Define interfaces for complex objects and use them consistently throughout the code.

  6. Comments and Documentation: Add more inline comments explaining complex logic, and consider using JSDoc comments for better documentation.

  7. Constants: Move hardcoded values (like chain IDs) into a constants file or configuration object.

  8. Testing: Ensure that unit tests are updated or added for any new or modified functionality.

  9. Performance: Review the use of string manipulations and consider more efficient alternatives where appropriate.

  10. Naming Conventions: Ensure consistent naming conventions throughout the file. For example, some functions use camelCase while others use snake_case.

Implementing these suggestions will greatly improve the overall quality, maintainability, and reliability of the code.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7a534f1 and 7282679.

📒 Files selected for processing (2)
  • packages/universal-swap/src/helper.ts (8 hunks)
  • packages/universal-swap/src/universal-demos/alpha-ibc-new.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (4)
packages/universal-swap/src/universal-demos/alpha-ibc-new.ts (4)

1-4: LGTM: Import statements are appropriate and concise.

The import statements are well-organized and relevant to the file's functionality. They include necessary modules for environment configuration, wallet implementation, swap handling, and utility functions.


6-81: LGTM: Well-structured router object with comprehensive swap information.

The router object is well-defined and provides detailed information about the swap operation, including amounts, routes, and specific actions. The structure is clear and easy to follow, which will facilitate the swap process.


1-129: Overall Assessment: Solid implementation with room for improvements.

The file successfully implements a universal swap operation focusing on the Osmosis and Celestia ecosystems. The structure is well-organized, with clear separation of concerns between the router configuration and the swap execution logic.

Key strengths:

  1. Comprehensive router object with detailed swap information.
  2. Use of appropriate libraries and utility functions.
  3. Implementation of error handling (though it can be improved).

Areas for improvement:

  1. Function naming to accurately reflect its purpose.
  2. Security enhancements for handling sensitive information.
  3. Avoiding hardcoded values for better flexibility.
  4. More robust error handling and logging.
  5. Consideration of module reusability.

Addressing these points will significantly enhance the code's quality, security, and maintainability. Despite these areas for improvement, the core functionality appears to be implemented correctly.


101-101: 🛠️ Refactor suggestion

Avoid hardcoding EVM addresses.

The EVM address "0x8c7E0A841269a01c0Ab389Ce8Fb3Cf150A94E797" is hardcoded in the sender object. This practice can lead to issues if the address changes or when the code is run in different environments.

Consider retrieving the EVM address dynamically or storing it in a configuration file. For example:

-    sender: { cosmos: sender, evm: "0x8c7E0A841269a01c0Ab389Ce8Fb3Cf150A94E797" },
+    sender: { cosmos: sender, evm: config.defaultEvmAddress },

Ensure that you add defaultEvmAddress to your configuration file or retrieve it from a secure source.

Likely invalid or redundant comment.

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 (4)
packages/universal-swap/src/helper.ts (2)

314-329: LGTM! Consider adding a type for the address object

The getAddress function is well-implemented with proper error handling. It correctly handles address conversion between different formats based on the coin type.

As a minor improvement, consider defining a type for the address object parameter to enhance code readability and maintainability:

type AddressObject = {
  address60: string;
  address118: string;
};

static getAddress = (prefix: string, addressObject: AddressObject, coinType: number = 118) => {
  // ... rest of the function
};

This change would make the function signature more explicit about the expected input structure.


Line range hint 347-433: LGTM! Consider adding null check for swapOption

The updates to addOraiBridgeRoute function enhance its capabilities to handle more complex routing scenarios, including support for alpha IBC wasm. The new structure with the addresses object improves the function's flexibility.

However, there's a potential issue when accessing swapOption.isIbcWasm:

if (isSmartRouter && swapOption.isIbcWasm && !swapOption?.isAlphaIbcWasm) {
  // ...
}

Consider adding a null check for swapOption to prevent potential runtime errors:

if (isSmartRouter && swapOption?.isIbcWasm && !swapOption?.isAlphaIbcWasm) {
  // ...
}

This change will ensure that the function doesn't throw an error if swapOption is undefined.

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

Line range hint 335-339: Ensure injAddress and oraiAddress are Defined Before Use

In multiple instances, injAddress and oraiAddress are used in calls to UniversalSwapHelper.getAddress without prior checks for their existence. If either of these variables is undefined, it could lead to runtime errors when the getAddress function attempts to process them.

Consider adding checks to ensure that injAddress and oraiAddress are defined before using them in these calls. Alternatively, modify the getAddress method to handle undefined values gracefully.

Apply this diff to add checks before the calls:

+ if (!oraiAddress) {
+   throw generateError('oraiAddress is undefined');
+ }
+ if (!injAddress) {
+   // Handle cases where injAddress might be undefined or assign a default value if appropriate
+ }

UniversalSwapHelper.getAddress(
  prefixReceiver,
  { address60: injAddress, address118: oraiAddress },
  chainInfoReceiver.bip44.coinType
);

Also applies to: 419-423, 425-429, 438-442, 476-480, 500-504


Line range hint 335-339: Refactor Repeated getAddress Calls into a Helper Function

The code has multiple instances where UniversalSwapHelper.getAddress is called with similar parameters:

UniversalSwapHelper.getAddress(
  prefixReceiver,
  { address60: injAddress, address118: oraiAddress },
  chainInfoReceiver.bip44.coinType
);

Consider creating a helper function to encapsulate this repeated logic. This refactoring will improve code maintainability and reduce duplication.

Apply this diff to create a helper function:

+ private getUnifiedAddress(prefix, chainInfo) {
+   return UniversalSwapHelper.getAddress(
+     prefix,
+     { address60: this.injAddress, address118: this.oraiAddress },
+     chainInfo.bip44.coinType
+   );
+ }

And replace the repeated calls with:

- UniversalSwapHelper.getAddress(
-   prefixReceiver,
-   { address60: injAddress, address118: oraiAddress },
-   chainInfoReceiver.bip44.coinType
- );

+ this.getUnifiedAddress(prefixReceiver, chainInfoReceiver);

Also applies to: 419-423, 425-429, 438-442, 476-480, 500-504

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7282679 and 9986a13.

📒 Files selected for processing (2)
  • packages/universal-swap/src/handler.ts (10 hunks)
  • packages/universal-swap/src/helper.ts (8 hunks)
🧰 Additional context used
🔇 Additional comments (6)
packages/universal-swap/src/helper.ts (4)

Line range hint 646-657: LGTM! Good addition of default values

The updates to generateSmartRouteForSwap function improve its usability by providing default values for the routerConfig parameter. The addition of maxSplits and dontAllowSwapAfter in the default configuration aligns well with the changes made to the querySmartRoute function.

These default values provide a good starting point for users while still allowing for customization when needed. The implementation correctly passes these values to the querySmartRoute function.


Line range hint 1255-1391: LGTM! Useful additions for smart routing

The new functions generateMsgsSmartRouterV2withV3 and flattenSmartRouters are valuable additions to the UniversalSwapHelper class. They provide essential functionality for processing smart router data and generating appropriate swap messages.

Key points:

  1. generateMsgsSmartRouterV2withV3 correctly handles both V2 and V3 pool swaps, generating the appropriate swap operations based on the pool type.
  2. flattenSmartRouters effectively simplifies the complex route structure, making it easier to process in other parts of the system.

These functions will greatly enhance the capabilities of the smart routing system, allowing for more efficient and flexible swap operations across different pool types.


Line range hint 1-1391: Overall, good improvements with minor issues to address

The changes to packages/universal-swap/src/helper.ts significantly enhance the functionality and flexibility of the universal swap system. The additions and modifications support more complex swap scenarios, improve smart routing capabilities, and add support for alpha IBC wasm.

Key improvements:

  1. New address generation and conversion functions.
  2. Enhanced support for complex routing scenarios in addOraiBridgeRoute.
  3. Improved smart routing with the addition of maxSplits and support for V3 pools.
  4. New functions for flattening and processing smart router data.

Minor issues to address:

  1. Typo in the Injective chain ID constant name.
  2. Typo in the dontAllowSwapAfter property name.
  3. Potential null reference when accessing swapOption properties.

These issues are easily fixable and don't detract from the overall quality of the improvements. Once addressed, the updated helper file will provide a robust foundation for handling complex swap operations across various chains and pool types.


628-632: ⚠️ Potential issue

LGTM! Fix typo in swapConfig property

The updates to querySmartRoute function enhance its capabilities by adding support for maxSplits in the router configuration. This allows for more granular control over the routing process.

However, there's a typo in the swapConfig property:

swapConfig: {
-  dontAlowSwapAfter: routerConfig.dontAllowSwapAfter
+  dontAllowSwapAfter: routerConfig.dontAllowSwapAfter
}

Please correct this typo to ensure consistency with the routerConfig property name and prevent potential issues.

Likely invalid or redundant comment.

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

1058-1067: Avoid Accessing alphaSmartRoutes Without Null Checks

The alphaSmartRoutes property is destructured from this.swapData without verifying its existence. Accessing alphaSmartRoutes or its properties when it is undefined will cause runtime errors.


1210-1217: Add Null Check for alphaSmartRoutes Before Accessing Properties

In the processUniversalSwap method, alphaSmartRoutes is accessed without verifying that it is defined. This can lead to runtime errors if alphaSmartRoutes is undefined.

packages/universal-swap/src/helper.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: 4

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

Line range hint 476-480: Validate injAddress before use

When creating addressReceiver, injAddress could be undefined. This may cause unexpected behavior in UniversalSwapHelper.getAddress.

Suggestion:

const addressReceiver = UniversalSwapHelper.getAddress(
  prefixReceiver,
- { address60: injAddress, address118: oraiAddress },
+ { address60: injAddress || '', address118: oraiAddress },
  chainInfoReceiver.bip44.coinType
);

Line range hint 500-505: Handle potential undefined injAddress in sender address

When generating the sender address, injAddress may be undefined. Ensure that this is properly handled to avoid errors.

Possible modification:

sender: UniversalSwapHelper.getAddress(
  prefixRecover,
- { address60: injAddress, address118: oraiAddress },
+ { address60: injAddress || '', address118: oraiAddress },
  chainInfoRecover.bip44.coinType
),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9986a13 and 9eecca6.

📒 Files selected for processing (1)
  • packages/universal-swap/src/handler.ts (10 hunks)
🧰 Additional context used
🔇 Additional comments (1)
packages/universal-swap/src/handler.ts (1)

63-64: New imports are appropriate

The addition of COSMOS_CHAIN_IDS and generateMsgSwap imports enhances the code and appears necessary for the new functionality.

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
packages/universal-swap/src/handler.ts Show resolved Hide resolved
@haunv3 haunv3 merged commit 2f20b38 into main Oct 10, 2024
4 checks passed
@haunv3 haunv3 deleted the feat/support-swap-oraidex-osmosis branch October 10, 2024 07:48
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