-
Notifications
You must be signed in to change notification settings - Fork 10
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
Conversation
…port-swap-oraidex-osmosis
…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
Code Coverage Summary
Diff against main
Results for commit: 9eecca6 Minimum allowed coverage is ♻️ This comment has been updated with latest results |
WalkthroughThe pull request introduces several changes across multiple files, primarily focusing on updates to the Changes
Possibly related PRs
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 ofprotected
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
andreceiver
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 thememo
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:
- At least one action is present
- Only one Bridge action is allowed
- If present, the Bridge action must be the last one
- 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 documentationThe addition of the optional
maxSplits
property to theRouterConfigSmartRoute
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 clarificationThe addition of the optional
isAlphaIbcWasm
property to theSwapOptions
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:
- What does "Alpha" signify in this context?
- What behavior changes when this flag is set to true?
- 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 theCOSMOS_CHAIN_ID_COMMON
enum is consistent with the existing structure and naming conventions. The trailing comma afterNOBLE_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 CodeThe
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 commentIn 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 OraichainIn the
genExecuteMsg
method, the error message mentions Oraichain, which might be misleading since this method is within theCosmosMsg
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 chainsThe error message
"Don't support universal swap in EVM"
can be made more informative by including thecurrentChain
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 emptyThe 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 StatementThere is a typographical error in the import statement for
ORAIB_ORAICHAIN_CHANNELS_TEST
. It is misspelled asORAIB_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 usageIn the loop over
action.swapInfo
, there is an assumption thatswapInfo
is defined and properly structured. Adding a validation step can prevent runtime errors ifswapInfo
isundefined
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: Consolidatemin_asset
constructionThe 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 informationThe 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 messageThe 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 ReadabilityEnsure consistent indentation for the
bridgeInfo
object at lines 381-384 to enhance code readability.
358-359
: Add Description to Test CaseThe 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 securityThe 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 ingetPostAction
The test cases in
it.each
cover scenarios with and withoutbridgeInfo
. Consider adding more variations, such as invalidbridgeInfo
or edge cases, to thoroughly test thegetPostAction
method.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ 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 thecelestiaNetwork
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 theisCw20Token
function and input sanitization invalidateReceiver
.packages/universal-swap/src/types.ts (3)
14-18
: LGTM: ActionType enum additionThe 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 neededThe modifications to this file enhance the functionality and flexibility of the universal swap system while maintaining backward compatibility. The new
ActionType
enum, the exportedPath
interface, and the additions toRouterConfigSmartRoute
andSwapOptions
interfaces are all valuable improvements.To further improve the code:
- Verify the impact of exporting the
Path
interface on the rest of the codebase.- Add documentation for the new
maxSplits
property inRouterConfigSmartRoute
.- Provide comprehensive documentation for the
isAlphaIbcWasm
property inSwapOptions
, 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 impactExporting 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 issuesThe 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 foraddOraiBridgeRoute
The test case has been modified to use an object for the
sourceReceiver
anddestReceiver
parameters instead of separate arguments. This change aligns with the updated function signature ofaddOraiBridgeRoute
.
602-611
: Updated error test case foraddOraiBridgeRoute
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 emptysourceReceiver
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
andreceiver
are appropriately specified.
12-24
:⚠️ Potential issueVerify the data types for
amount
and clarify units inBridgeMsgInfo
.The
amount
field is currently astring
. 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 ofamount
andtimeout
:✅ Verification successful
Existing implementation for
amount
andtimeout
inBridgeMsgInfo
is appropriate, but documentation can be improved.The current implementation of
BridgeMsgInfo
uses appropriate data types foramount
(string) andtimeout
(number). Here's why:
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.
timeout
as number:
- Consistently used throughout the codebase.
- Set using
calculateTimeoutTimestamp
function, which returns a number.To improve clarity, consider adding comments or documentation:
- For
amount
, explain that it's a string to preserve precision for large numbers.- 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 5Length 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 10Length of output: 421751
packages/universal-swap/src/universal-demos/alpha-ibc-new.ts (2)
85-85
: Review Swap Options ConfigurationIn the
swapOptions
,isIbcWasm
is set tofalse
, andisAlphaIbcWasm
is set totrue
. 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 AccuracyEnsure that the
coinGeckoId
andchainId
used in theflattenTokens.find()
methods accurately correspond to the intended tokens:
coinGeckoId: "osmosis"
andchainId: "osmosis-1"
for the original from token.coinGeckoId: "celestia"
andchainId: "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-implementedThe 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 ofrecover_address
inibc_transfer
actionThe
ibc_transfer
action includes arecover_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 loopIn 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 pathsIn the
generateMsgSwap
function, thereceiver
is set based on the last path'stokenOutChainId
. Ensure that theaddresses
object contains receiver addresses for all relevantchainId
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 IntentionalThe
ibcInfosOld
constant now omits"celestia"
. Confirm that this change is deliberate and that there are no remaining dependencies on"celestia"
withinibcInfosOld
or related logic.Run the following script to verify that
"celestia"
is not referenced inibcInfosOld
:#!/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 ibcInfosThe change excludes
"celestia"
fromibcInfos
. Please verify that this exclusion is intentional and that there are no dependencies on"celestia"
in theibcInfos
usage throughout the codebase.Run the following script to check for references to
"celestia"
related toibcInfos
in the codebase:✅ Verification successful
Exclusion of "celestia" from ibcInfos Verified
No dependencies on
"celestia"
were found in the usage ofibcInfos
. 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 pathThe 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 AmountsWhen constructing the
funds
array for native tokens, ensure that theamount
anddenom
are correctly validated to prevent potential injection or tampering.Consider adding validation for
this.path.tokenInAmount
andthis.path.tokenIn
to ensure they are in the expected format and safe to include.
73-73
:⚠️ Potential issueTypo 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 oftypeUrl
in AssertionsIn 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 correcttypeUrl
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 ProtocolsEnsure 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 issueVerify 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 correctnessIn the
validPath
object, thetokenOutAmount
is"306106"
, but in yourbridgeInfo
, theamount
is"936043"
, which matches thetokenInAmount
. Ensure that thetokenOutAmount
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" toNetworkName
typeThe addition of
"Celestia"
to theNetworkName
type is correct and consistent with existing entries.
91-92
: Added "celestia" toCosmosChainId
typeIncluding
"celestia"
in theCosmosChainId
type aligns with the pattern of other Cosmos chain IDs.
547-547
: IncludedcelestiaNetwork
in thechainInfos
arrayAdding
celestiaNetwork
to thechainInfos
array correctly integrates the Celestia network into the supported networks.
66-66
: Verify the existence and configuration ofcelestiaNetwork
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 fiLength 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 fiLength 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" fiLength of output: 393
packages/universal-swap/src/handler.ts (12)
63-64
: Imports Added CorrectlyThe new imports for
COSMOS_CHAIN_IDS
andgenerateMsgSwap
are appropriately added and will support the new functionalities introduced in the code.
335-338
: Correct Usage ofUniversalSwapHelper.getAddress
In
getSwapAndActionInOsmosis
, theto_address
is correctly obtained usingUniversalSwapHelper.getAddress
, ensuring that the address format aligns with the target chain's requirements.
419-422
: Appropriate Receiver Address RetrievalThe
receiver
field ingetIbcTransferInfo
is correctly assigned usingUniversalSwapHelper.getAddress
, which helps maintain consistency across different blockchain networks.
425-428
: Proper Use ofUniversalSwapHelper.getAddress
for Recover AddressThe
recover_address
is accurately generated usingUniversalSwapHelper.getAddress
, ensuring that any recovery operations can correctly identify the address across chains.
438-441
: Accurate Address Generation increateForwardObject
The
addressReceiver
is correctly obtained usingUniversalSwapHelper.getAddress
, facilitating proper message forwarding in IBC transactions.
476-479
: Consistent Address Assignment for Message TransferIn
getMsgTransfer
, theaddressReceiver
is appropriately assigned usingUniversalSwapHelper.getAddress
, ensuring compatibility with the receiving chain's address format.
500-503
: Correct Sender Address ConstructionThe
sender
address is accurately generated usingUniversalSwapHelper.getAddress
, which is crucial for transaction validation and processing.
1058-1067
: Valid Destructuring ofthis.swapData
PropertiesThe properties are properly destructured from
this.swapData
inswapCosmosToOtherNetwork
, ensuring all necessary data is available for the operation.
1179-1180
: Correct Extraction of Properties fromthis.swapData
The properties
evm
,tron
, and others are accurately destructured fromthis.swapData
andthis.swapData.sender
, ensuring the necessary data is readily available.
1201-1206
: Efficient Retrieval of Addresses UsingPromise.all
The concurrent fetching of
oraiAddress
andobridgeAddress
withPromise.all
optimizes the asynchronous operations, improving performance.
1211-1214
: Potential UndefinedalphaSmartRoutes
AccessIn
processUniversalSwap
,alphaSmartRoutes
might be undefined, and accessingalphaSmartRoutes.routes
without checking could cause a runtime error.Refer to the previous comment on handling potential undefined
alphaSmartRoutes
inalphaSmartRouterSwapNewMsg
.
1232-1238
: Safe Execution with Optional ChainingThe condition checks
alphaSmartRoutes?.routes?.length
using optional chaining, which safely handles cases wherealphaSmartRoutes
might be undefined, preventing potential runtime errors.
There was a problem hiding this 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 networkThe 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
📒 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:
- Naming conflicts: If different modules export entities with the same name, it could cause unexpected behavior.
- Reduced code clarity: It becomes harder to track which specific entities are being used where in the codebase.
- Potential bundle size increase: If tree-shaking is not properly implemented, this could lead to larger bundle sizes.
Consider the following improvements:
- Explicitly export only the necessary entities from each module to avoid potential conflicts and improve clarity.
- 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 };- 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 goodThe
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 testsThe
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 suggestionUse 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 issueImprove slippage validation and precision handling
- The slippage validation should also check for negative values.
- The current method of converting to an integer by splitting at the decimal point may lead to precision loss.
Consider these improvements:
- 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"); }
- Use a more precise method for rounding:
- if (minimumReceive.includes(".")) { - minimumReceive = minimumReceive.split(".")[0]; - } + minimumReceive = Math.floor(Number(minimumReceive)).toString();
53-101
:⚠️ Potential issueFix 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 issueEnsure 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 issueCorrect 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 reviewThe
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:
- Fix the typo in the error message for unsupported actions.
- Improve the slippage validation in the
setMinimumReceiveForSwap
method.- Correct the typo in the
pasreConverterMsgToPoolId
method name.- Add validation for the
sourcePort
format in thegetProtoForPostAction
method.- 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 insetMinimumReceiveForSwap
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.
There was a problem hiding this 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 improvementsThe
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:
Code structure: Several methods (e.g.,
getSwapAndBridgeInfo
,genMemoAsMiddleware
,genExecuteMsg
) could benefit from being split into smaller, more focused functions for better readability and maintainability.Constants management: Consider moving hardcoded values (like chain IDs and contract addresses) to a centralized configuration file.
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.Error handling: While error handling is present, it could be more consistent and informative across the class.
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
📒 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 correctThe
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.
There was a problem hiding this 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 methodThe
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
📒 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 addedThe new imports
COSMOS_CHAIN_IDS
andgenerateMsgSwap
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.getAddressThe
getAddress
method has been replaced withUniversalSwapHelper.getAddress
. This change centralizes address generation logic, which is a good practice for maintainability.
419-428
: Updated address generation in getIbcTransferInfoSimilar 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.getAddressThe
getAddress
method has been replaced withUniversalSwapHelper.getAddress
here as well, maintaining consistency throughout the code.
Line range hint
476-480
: Consistent address generation in getMsgTransferThe
UniversalSwapHelper.getAddress
method is used here too, further improving consistency in address generation across the codebase.
Line range hint
500-504
: Consistent sender address generationThe
UniversalSwapHelper.getAddress
method is used for generating the sender address, maintaining consistency with previous changes.
Line range hint
1-1569
: Overall code review summaryThe 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:
- Address generation has been centralized using
UniversalSwapHelper.getAddress
, which improves maintainability.- New imports and methods have been added to support alpha smart router swaps and IBC wasm transfers.
- 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:
- In the
alphaSmartRouterSwapNewMsg
method, add a null check foralphaSmartRoutes
to prevent potential runtime errors.- 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.
…ain/oraidex-sdk into feat/support-swap-oraidex-osmosis
There was a problem hiding this 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
📒 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 suggestionUse 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.
There was a problem hiding this 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 inisAlphaIbcWasm
caseIn the
isAlphaIbcWasm
case, there's a potential for uncaught errors ifalphaSmartRoute
orroutes[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
andalphaRoutes.paths
, which will help prevent potential runtime errors.
Line range hint
577-605
: Plan for removal of deprecated methodsThe
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.
- Identify all deprecated methods in the codebase.
- Determine if there are any current usages of these methods.
- If there are usages, plan to update them to use the new recommended alternatives.
- Set a timeline for when these deprecated methods will be removed.
- Update documentation to reflect these planned changes.
- In a future release, remove the deprecated methods and their associated exports.
798-798
: Add comment explaininguseAlphaIbcWasm
optionThe
useAlphaIbcWasm
option has been added to therouterOption
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 forgenerateMsgsSmartRouterV2withV3
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
📒 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 issueFix typo in default value for
routerConfig
There's a typo in the default value for
routerConfig
. The propertydontAlowSwapAfter
should bedontAllowSwapAfter
.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 issueFix typo in chain ID constant
There's a typo in the chain ID constant for Injective. It should be
INJECTIVE_CHAIN_ID
instead ofINJECTVE_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.
There was a problem hiding this 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 maintainabilityThe
addOraiBridgeRoute
function has grown quite complex, which may make it difficult to maintain and understand. Consider the following improvements:
Split the function into smaller, more focused functions. For example:
generateSourceReceiver
handleAlphaIbcWasm
generateSwapRoute
Add more comments explaining the complex logic, especially around the different swap options and routing scenarios.
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 maintainabilityThe
getRouteV2
function is quite complex and handles multiple scenarios. Consider the following improvements:
Break down the function into smaller, more focused functions. For example:
determineDestinationDetails
buildIbcWasmBridge
buildIbcTransfer
Use constants for hardcoded values. For example:
const NOBLE_CHAIN_ID = "noble-1";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 handlingThe
unmarshalOraiBridgeRoute
function could benefit from the following improvements:
Use regular expressions for more robust parsing. This can handle various formats more efficiently and with less code.
Improve error messages to provide more context, making debugging easier.
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 readabilityThe
generateMsgsSmartRouterV2withV3
function could be improved in several ways:
Add input validation to ensure
routes
andofferInfo
are valid before processing.Implement error handling to gracefully manage unexpected scenarios.
Use more descriptive variable names and add comments to explain the logic, especially for the pool ID parsing.
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 precisionThe
buildSwapMsgsFromSmartRoute
function could be improved in several ways:
Add input validation to ensure all required parameters are provided and valid.
Implement error handling to gracefully manage unexpected scenarios.
Use more descriptive variable names and add comments to explain the logic, especially for the swap operation construction.
Use a more precise method for calculating
minimumReceive
to avoid potential precision loss.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 neededAfter reviewing the entire
helper.ts
file, here are some general observations and suggestions for improvement:
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.
Error Handling: Implement consistent error handling across all functions. Use custom error types to provide more context and make debugging easier.
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.
Code Complexity: Some functions, like
addOraiBridgeRoute
andgetRouteV2
, have grown quite complex. Consider breaking these down into smaller, more focused functions to improve readability and maintainability.Type Safety: Make better use of TypeScript's type system. Define interfaces for complex objects and use them consistently throughout the code.
Comments and Documentation: Add more inline comments explaining complex logic, and consider using JSDoc comments for better documentation.
Constants: Move hardcoded values (like chain IDs) into a constants file or configuration object.
Testing: Ensure that unit tests are updated or added for any new or modified functionality.
Performance: Review the use of string manipulations and consider more efficient alternatives where appropriate.
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
📒 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:
- Comprehensive router object with detailed swap information.
- Use of appropriate libraries and utility functions.
- Implementation of error handling (though it can be improved).
Areas for improvement:
- Function naming to accurately reflect its purpose.
- Security enhancements for handling sensitive information.
- Avoiding hardcoded values for better flexibility.
- More robust error handling and logging.
- 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 suggestionAvoid hardcoding EVM addresses.
The EVM address
"0x8c7E0A841269a01c0Ab389Ce8Fb3Cf150A94E797"
is hardcoded in thesender
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.
There was a problem hiding this 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 objectThe
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 swapOptionThe updates to
addOraiBridgeRoute
function enhance its capabilities to handle more complex routing scenarios, including support for alpha IBC wasm. The new structure with theaddresses
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
: EnsureinjAddress
andoraiAddress
are Defined Before UseIn multiple instances,
injAddress
andoraiAddress
are used in calls toUniversalSwapHelper.getAddress
without prior checks for their existence. If either of these variables isundefined
, it could lead to runtime errors when thegetAddress
function attempts to process them.Consider adding checks to ensure that
injAddress
andoraiAddress
are defined before using them in these calls. Alternatively, modify thegetAddress
method to handleundefined
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 RepeatedgetAddress
Calls into a Helper FunctionThe 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
📒 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 valuesThe updates to
generateSmartRouteForSwap
function improve its usability by providing default values for therouterConfig
parameter. The addition ofmaxSplits
anddontAllowSwapAfter
in the default configuration aligns well with the changes made to thequerySmartRoute
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 routingThe new functions
generateMsgsSmartRouterV2withV3
andflattenSmartRouters
are valuable additions to theUniversalSwapHelper
class. They provide essential functionality for processing smart router data and generating appropriate swap messages.Key points:
generateMsgsSmartRouterV2withV3
correctly handles both V2 and V3 pool swaps, generating the appropriate swap operations based on the pool type.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 addressThe 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:
- New address generation and conversion functions.
- Enhanced support for complex routing scenarios in
addOraiBridgeRoute
.- Improved smart routing with the addition of
maxSplits
and support for V3 pools.- New functions for flattening and processing smart router data.
Minor issues to address:
- Typo in the Injective chain ID constant name.
- Typo in the
dontAllowSwapAfter
property name.- 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 issueLGTM! Fix typo in swapConfig property
The updates to
querySmartRoute
function enhance its capabilities by adding support formaxSplits
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 AccessingalphaSmartRoutes
Without Null ChecksThe
alphaSmartRoutes
property is destructured fromthis.swapData
without verifying its existence. AccessingalphaSmartRoutes
or its properties when it isundefined
will cause runtime errors.
1210-1217
: Add Null Check foralphaSmartRoutes
Before Accessing PropertiesIn the
processUniversalSwap
method,alphaSmartRoutes
is accessed without verifying that it is defined. This can lead to runtime errors ifalphaSmartRoutes
isundefined
.
There was a problem hiding this 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
: ValidateinjAddress
before useWhen creating
addressReceiver
,injAddress
could beundefined
. This may cause unexpected behavior inUniversalSwapHelper.getAddress
.Suggestion:
const addressReceiver = UniversalSwapHelper.getAddress( prefixReceiver, - { address60: injAddress, address118: oraiAddress }, + { address60: injAddress || '', address118: oraiAddress }, chainInfoReceiver.bip44.coinType );
Line range hint
500-505
: Handle potentialundefined
injAddress
insender
addressWhen generating the
sender
address,injAddress
may beundefined
. 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
📒 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 appropriateThe addition of
COSMOS_CHAIN_IDS
andgenerateMsgSwap
imports enhances the code and appears necessary for the new functionality.
[x] Generate msg from smartRoute
Summary by CodeRabbit
New Features
CosmosMsg
andOsmosisMsg
classes for managing messages specific to their respective ecosystems.Bug Fixes
Documentation
Tests