-
Notifications
You must be signed in to change notification settings - Fork 195
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
chore: cw20 to bank convert docs #516
Conversation
Caution Review failedThe pull request is closed. WalkthroughThe pull request introduces updates to the documentation for the Injective blockchain, specifically enhancing the guidance on converting CW20 tokens to bank tokens and executing market orders in a single transaction. Key changes include the addition of a new entry in the Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant CW20Service
participant BankService
participant MarketOrderService
User->>CW20Service: Check CW20 token balance
CW20Service-->>User: Return balance
User->>CW20Service: Create conversion message
CW20Service-->>User: Return convertMsg
User->>BankService: Convert CW20 to bank tokens
BankService-->>User: Confirm conversion
User->>MarketOrderService: Create market order
MarketOrderService-->>User: Confirm market order
Possibly related PRs
Warning There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure. 🔧 eslint
packages/sdk-ts/src/core/accounts/PrivateKey.spec.tsOops! Something went wrong! :( ESLint: 7.32.0 ESLint couldn't find the config "./../../eslintrc.js" to extend from. Please check that the name of the config is correct. The config "./../../eslintrc.js" was referenced from the config file in "/packages/sdk-ts/.eslintrc.js". If you still have problems, please stop by https://eslint.org/chat/help to chat with the team. 🪧 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: 2
🧹 Outside diff range and nitpick comments (8)
.gitbook/contracts/README.md (1)
13-13
: Consider enhancing the description for clarity.While "Convert Cw20 Example" is concise, it could be more descriptive to help users understand the full capability being documented.
Consider this alternative:
-| [CW20 to Bank & Market Order in One Transaction](cw20-convert-and-market-order-example.md) | Convert Cw20 Example | +| [CW20 to Bank & Market Order in One Transaction](cw20-convert-and-market-order-example.md) | Example of converting CW20 tokens to bank and executing market orders atomically |.gitbook/readme/application-concepts.md (3)
28-32
: Consider adding type information to improve documentation.While the syntax improvements are good, consider adding type information for
actualAmount
to make the example more complete.+// actualAmount: BigNumber amount: actualAmount.toFixed(),
38-38
: Remove trailing colon from heading.According to markdown best practices, headings should not end with punctuation.
-### Example on how to convert CW20 to a factory denom: +### Example on how to convert CW20 to a factory denom🧰 Tools
🪛 Markdownlint (0.35.0)
38-38: Punctuation: ':'
Trailing punctuation in heading(MD026, no-trailing-punctuation)
56-57
: Consider adding a comment about the expected outcome.While the syntax improvements are good, consider adding a comment explaining what happens after successful execution.
contractAddress: CW20_ADAPTER_CONTRACT, +// After successful execution, the CW20 tokens will be converted to factory/{CW20_ADAPTER_CONTRACT}/{contractCw20Address}
.gitbook/contracts/cw20-convert-and-market-order-example.md (4)
3-4
: Add security considerations and prerequisitesWhile the introduction explains the purpose well, consider adding important security considerations and prerequisites, such as:
- Warning about transaction finality and irreversibility
- Recommendation to test with small amounts first
- Prerequisites like minimum balance requirements or gas fees
27-31
: Add type definitions to the code exampleThe TypeScript example would be more helpful with proper type definitions.
Consider updating the example:
-const order = { +interface SpotOrder { + price: number; + quantity: number; +} + +const order: SpotOrder = { price: 1, quantity: 10, }
33-33
: Clarify the balance calculation exampleThe balance explanation could be more explicit about the mathematics involved.
Consider rephrasing to: "For example, if you have 5 CW20 tokens and 5 bank tokens at $1 each, the total available balance after conversion would be 10 tokens ($10 total), which is sufficient for the order quantity of 10 at price of $1 each."
54-54
: Add troubleshooting sectionConsider adding a troubleshooting section after the implementation example that covers:
- Common error messages and their solutions
- Network-specific considerations
- Links to support resources
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (4)
.gitbook/SUMMARY.md
(1 hunks).gitbook/contracts/README.md
(1 hunks).gitbook/contracts/cw20-convert-and-market-order-example.md
(1 hunks).gitbook/readme/application-concepts.md
(3 hunks)
🧰 Additional context used
🪛 LanguageTool
.gitbook/contracts/cw20-convert-and-market-order-example.md
[style] ~19-~19: Consider a shorter alternative to avoid wordiness.
Context: ...how-to-convert-cw20-to-a-factory-denom) in order to convert your cw20 token to a bank facto...
(IN_ORDER_TO_PREMIUM)
🪛 Markdownlint (0.35.0)
.gitbook/readme/application-concepts.md
38-38: Punctuation: ':'
Trailing punctuation in heading
(MD026, no-trailing-punctuation)
🔇 Additional comments (4)
.gitbook/contracts/README.md (1)
9-10
: LGTM! Clean and consistent table formatting.
The table header is well-structured with proper markdown syntax and alignment.
.gitbook/readme/application-concepts.md (2)
14-17
: LGTM! Import statements are well-formatted.
The multi-line import statement improves readability.
41-44
: LGTM! Import statements are consistently formatted.
The formatting matches the style used in the previous example.
.gitbook/SUMMARY.md (1)
89-89
: LGTM! Verify the linked documentation file exists.
The new entry is logically placed under the "Contracts" section and the title clearly describes its purpose.
Let's verify the existence of the referenced documentation file:
✅ Verification successful
Documentation file exists and is correctly referenced ✅
The linked documentation file contracts/cw20-convert-and-market-order-example.md
exists in the repository, confirming that the table of contents entry is valid and properly connected to its content.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if the referenced documentation file exists
# Expected: File should exist since it's referenced in the table of contents
if [ -f ".gitbook/contracts/cw20-convert-and-market-order-example.md" ]; then
echo "Documentation file exists"
else
echo "Warning: Referenced documentation file is missing"
fi
Length of output: 133
const privateKey = '0x...' | ||
const injectiveAddress = 'inj1...' |
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.
🛠️ Refactor suggestion
Improve security practices in code examples
The example shows sensitive information directly in the code. Consider:
- Adding a comment about secure key management
- Mentioning environment variables for private keys
Update the example:
-const privateKey = '0x...'
-const injectiveAddress = 'inj1...'
+// IMPORTANT: Never hardcode private keys in your code
+// Use secure environment variables or key management solutions
+const privateKey = process.env.INJECTIVE_PRIVATE_KEY
+const injectiveAddress = process.env.INJECTIVE_ADDRESS
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const privateKey = '0x...' | |
const injectiveAddress = 'inj1...' | |
// IMPORTANT: Never hardcode private keys in your code | |
// Use secure environment variables or key management solutions | |
const privateKey = process.env.INJECTIVE_PRIVATE_KEY | |
const injectiveAddress = process.env.INJECTIVE_ADDRESS |
const txHash = await new MsgBroadcasterWithPk({ | ||
privateKey, | ||
network: Network.MainnetSentry, | ||
}).broadcast({ | ||
msgs: [convertMsg, msg], // the convert to bank message executes first, Then, you will have that additional balance to complete your market order in the following msg | ||
}) | ||
|
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.
🛠️ Refactor suggestion
Add error handling and gas estimation details
The broadcast example should include error handling and information about gas estimation.
Consider updating the example:
const txHash = await new MsgBroadcasterWithPk({
privateKey,
network: Network.MainnetSentry,
-}).broadcast({
- msgs: [convertMsg, msg],
-})
+}).broadcast({
+ msgs: [convertMsg, msg],
+ // Add comment explaining gas estimation strategy
+ gasMultiplier: 1.2 // Adjust gas limit by 20% to ensure transaction success
+}).catch(error => {
+ console.error('Transaction failed:', error);
+ // Handle specific error cases (insufficient funds, slippage, etc.)
+ throw error;
+});
Committable suggestion skipped: line range outside the PR's diff.
fix: update link to Cosmos SDK Transactions documentation
fix: fix links to main docs portal
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)
.gitbook/core-modules/auction.md (1)
Line range hint
73-119
: Consider adding a cross-reference to CW20 conversion documentationSince this PR introduces new documentation about CW20 to bank conversion, consider adding a note in the external transfer section that points users to the new CW20 conversion guide if they're working with CW20 tokens.
Add a note like this before the code example:
+ Note: If you're working with CW20 tokens, please refer to our guide on [CW20 to Bank & Market Order in One Transaction](../contracts/cw20-convert-and-market-order-example.md). ```ts import { DenomClient, MsgExternalTransfer, ...
🧰 Tools
🪛 Markdownlint (0.35.0)
68-68: null
Spaces inside link text(MD039, no-space-in-links)
68-68: null
Spaces inside link text(MD039, no-space-in-links)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (3)
.gitbook/contracts/README.md
(1 hunks).gitbook/core-modules/auction.md
(1 hunks).gitbook/transactions/README.md
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- .gitbook/transactions/README.md
🚧 Files skipped from review as they are similar to previous changes (1)
- .gitbook/contracts/README.md
@@ -68,7 +68,7 @@ How to use funds that are currently associated with your Injective Address in ba | |||
- If you have existing non-default subaccounts, you'll want to do a[ MsgDeposit ](exchange.md#msgdeposit)to one of your existing non-default subaccountIds and use that subaccountId as the `srcSubaccountId` below. | |||
- If you don't have existing non-default subaccounts, you can do a [MsgDeposit](exchange.md#msgdeposit) to a new default subaccountId, which would be done via importing `getSubaccountId` from `sdk-ts` and setting the `subaccountId` field in [MsgDeposit](exchange.md#msgdeposit) to `getSubaccountId(injectiveAddress, 1)`. | |||
|
|||
For more info, check out the [burn auction pool docs](https://docs.injective.network/develop/tech-concepts/auction_pool/). | |||
For more info, check out the [burn auction pool docs](https://docs.injective.network/developers/modules/injective/auction). |
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.
💡 Codebase verification
Documentation links need to be updated consistently
There's an inconsistency in the documentation links. While the burn auction pool link has been updated to the new docs.injective.network domain, there's still an old reference to hub.injective.network in the same file:
- Line 7:
[auction](https://hub.injective.network/auction/)
should be updated to use the new documentation domain pattern
🔗 Analysis chain
Verify the updated documentation link
The link to the burn auction pool documentation has been updated. While the change itself is straightforward, let's verify the link's validity.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify if the new documentation link is accessible
# and check for any other references to the old link pattern
# Check for any other instances of the old documentation pattern that might need updating
rg -i "hub\.injective\.network/auction"
# Note: The actual URL verification would typically be done via curl,
# but since this is an internal documentation site, we'll focus on consistency
Length of output: 41
Script:
#!/bin/bash
# Let's search for any references to documentation links about auction
rg -i "docs.*auction|hub.*auction" .gitbook/
# Also check for any other potential documentation links in the auction.md file
cat .gitbook/core-modules/auction.md
Length of output: 4786
…ncement Chore: wallet strategy enhancement
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 (19)
packages/wallets/wallet-cosmostation/src/index.ts (1)
1-3
: Consider documenting the public API changes.Since we're exposing new utilities through the package's public API, it would be helpful to document these changes in the package's README or API documentation.
packages/wallets/wallet-cosmos/src/data/index.ts (1)
3-8
: Add documentation for maintainabilityConsider adding JSDoc comments to document:
- The purpose of this array
- The significance of the wallet order (if any)
- The criteria for inclusion in this list
+/** + * List of supported Cosmos wallets. + * Used for wallet validation and installation checks. + */ export const cosmosWallets = [packages/wallets/wallet-cosmostation/src/utils/index.ts (1)
3-3
: Consider adding JSDoc documentationAdding documentation would improve developer experience by providing usage examples and explaining the function's purpose.
+/** + * Checks if the Cosmostation wallet extension is installed in the browser. + * @returns {boolean} True if the Cosmostation wallet is installed, false otherwise. + * @example + * if (isCosmosStationWalletInstalled()) { + * // Proceed with wallet connection + * } + */ export const isCosmosStationWalletInstalled = () => {packages/wallets/wallet-cosmos/src/cosmos.d.ts (1)
Line range hint
3-11
: Consider adding JSDoc documentation for better maintainability.Adding documentation comments would help other developers understand the purpose of each wallet integration and any specific considerations.
declare global { // eslint-disable-next-line @typescript-eslint/no-empty-interface + /** + * Extends the Window interface to include various Cosmos ecosystem wallet providers. + * Each wallet property provides access to its respective wallet's functionality. + */ interface Window extends KeplrWindow { + /** Leap Cosmos wallet provider */ leap: KeplrWindow['keplr'] + /** Keplr wallet provider */ keplr: KeplrWindow['keplr'] + /** Ninji wallet provider */ ninji: KeplrWindow['ninji'] + /** OWallet provider (optional) */ owallet?: KeplrWindow['owallet'] } }packages/wallets/wallet-base/src/utils/wallet.ts (3)
20-20
: Consider future extensibility of wallet types.The current implementation assumes wallets are either EVM or Cosmos. This might need revision if new wallet types are introduced that don't fit either category.
Consider maintaining explicit lists for each wallet type instead of using negation:
-export const isCosmosWallet = (wallet: Wallet): boolean => !isEvmWallet(wallet) +export const isCosmosWallet = (wallet: Wallet): boolean => [ + Wallet.Leap, + Wallet.Ninji, + Wallet.Keplr, + Wallet.OWallet, + Wallet.Cosmostation, + Wallet.LedgerCosmos, +].includes(wallet)
29-30
: Remove extra empty line.There's an unnecessary empty line that can be removed for better code formatting.
Issues found: Function rename requires coordinated changes across packages
The rename from
isEthWallet
toisEvmWallet
inpackages/wallets/wallet-base/src/utils/wallet.ts
requires corresponding changes inpackages/wallet-ts
where the old function name is still being used:
packages/wallet-ts/src/strategies/wallet-strategy/utils.ts
: Function definition and usagepackages/wallet-ts/src/strategies/wallet-strategy/WalletStrategy.ts
: Multiple imports and usages🔗 Analysis chain
Line range hint
3-16
: LGTM! Verify the function rename impact.The rename from
isEthWallet
toisEvmWallet
better represents the broader category of EVM-compatible wallets.Let's verify all usages of the old function name have been updated:
Let me generate additional verification scripts to check for any remaining references to
isEthWallet
in the codebase:🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check for any remaining references to isEthWallet # Expect: No results as all occurrences should have been renamed rg "isEthWallet"Length of output: 109605
Script:
#!/bin/bash # Description: Check for any imports of isEthWallet from wallet-base package # This will help verify if other packages are importing the old function name rg "from.*wallet-base.*isEthWallet" rg "import.*wallet-base.*isEthWallet" # Check for any references to isEthWallet in TypeScript type definitions ast-grep --pattern 'isEthWallet' --lang tsLength of output: 856
packages/wallets/wallet-cosmos/src/utils/index.ts (2)
10-30
: Consider enhancing type safety and maintainabilityWhile the function works correctly, here are some suggestions for improvement:
+const WALLET_WINDOW_KEYS = { + [Wallet.Keplr]: 'keplr', + [Wallet.Ninji]: 'ninji', + [Wallet.Leap]: 'leap', + [Wallet.OWallet]: 'oWallet', +} as const; export const isCosmosWalletInstalled = (wallet: Wallet) => { - const $window = (typeof window !== 'undefined' ? window : {}) as Window & { + if (typeof window === 'undefined') { + return false; + } + + const $window = window as Window & { leap?: CosmosBrowserWallet keplr?: CosmosBrowserWallet ninji?: CosmosBrowserWallet oWallet?: CosmosBrowserWallet } - switch (wallet) { - case Wallet.Keplr: - return $window.keplr !== undefined - case Wallet.Ninji: - return $window.ninji !== undefined - case Wallet.Leap: - return $window.leap !== undefined - case Wallet.OWallet: - return $window.oWallet !== undefined - default: - return false - } + const key = WALLET_WINDOW_KEYS[wallet]; + return key ? $window[key] !== undefined : false; }These changes:
- Improve type safety with explicit non-browser environment handling
- Replace the switch statement with an object lookup for better maintainability
- Make it easier to add new wallet types in the future
1-64
: Consider adding rate limiting and cachingSince this code interacts with browser extensions and performs cryptographic operations:
- Consider implementing rate limiting for the
confirmCosmosAddress
function to prevent potential DoS attacks- Consider caching the wallet installation status for a short period to improve performance
packages/wallets/wallet-core/src/strategy/BaseWalletStrategy.ts (1)
Line range hint
210-214
: Consider improving error message clarityWhile the logic is correct, the error message could be more specific about supported wallets.
- if (![Wallet.Keplr, Wallet.Leap].includes(this.getWallet())) { - throw new WalletException( - new Error(`You can't use this method outside of Keplr/Leap wallet`), - ) + const supportedWallets = [Wallet.Keplr, Wallet.Leap]; + if (!supportedWallets.includes(this.getWallet())) { + throw new WalletException( + new Error(`This method only supports ${supportedWallets.join(' and ')} wallets. Current wallet: ${this.getWallet()}`), + )packages/wallets/wallet-evm/src/strategy/strategy.ts (3)
2-2
: LGTM! Consider standardizing error message format.The changes improve maintainability by using
isEvmBrowserWallet
instead of a hardcoded list. The error message formatting withcapitalize
is a good addition.Consider using template literals consistently across error messages in the class:
- `Evm Wallet for ${capitalize(args.wallet)} is not supported.` + `EVM Wallet for ${capitalize(args.wallet)} is not supported.`Also applies to: 36-36, 59-63
Line range hint
70-86
: Fix incorrect exception type for Phantom wallet.The Phantom wallet case incorrectly returns a MetamaskException instead of a wallet-specific exception.
Consider creating a PhantomException class and using it here:
if (this.wallet === Wallet.Phantom) { - return new MetamaskException(error, context) + return new PhantomException(error, context) }
Line range hint
214-223
: Consider standardizing error handling across methods.Some methods use direct
WalletException
while others useEvmWalletException
. For consistency and better error context, consider usingEvmWalletException
throughout the class.Example for signCosmosTransaction:
- throw new WalletException( + throw this.EvmWalletException( new Error('This wallet does not support signing Cosmos transactions'), { code: UnspecifiedErrorCode, type: ErrorType.WalletError, contextModule: WalletAction.SignTransaction, }, )Also applies to: 249-257
packages/wallets/wallet-cosmos/src/wallet.ts (1)
143-145
: Improve grammar in error messages.The error messages have inconsistent grammar. The word "support" should be "supported" in error messages.
Apply these changes for consistency:
- `getOfflineAminoSigner is not support on ${capitalize(wallet)}`, + `getOfflineAminoSigner is not supported on ${capitalize(wallet)}`,- `signAndBroadcastAminoUsingCosmjs is not support on ${capitalize( + `signAndBroadcastAminoUsingCosmjs is not supported on ${capitalize(- new Error(`disableGasCheck is not support on ${capitalize(wallet)}`), + new Error(`disableGasCheck is not supported on ${capitalize(wallet)}`),- new Error(`enableGasCheck is not support on ${capitalize(wallet)}`), + new Error(`enableGasCheck is not supported on ${capitalize(wallet)}`),Also applies to: 252-254, 403-403, 423-423
packages/wallets/wallet-evm/src/utils/index.ts (5)
25-45
: Simplify provider selection logic with a mappingTo enhance code maintainability and scalability, consider refactoring the multiple
if
statements into a mapping of wallet types to provider functions. This approach simplifies the addition of new wallets and improves readability.Apply this diff to refactor the code:
export const getEvmProvider = async ( wallet: Wallet, ): Promise<BrowserEip1993Provider> => { if (!isEvmBrowserWallet(wallet)) { throw new WalletException( new Error(`Evm Wallet for ${capitalize(wallet)} is not supported.`), ) } try { - let provider - - if (wallet === Wallet.Metamask) { - provider = (await getMetamaskProvider()) as BrowserEip1993Provider - } - - if (wallet === Wallet.BitGet) { - provider = (await getBitGetProvider()) as BrowserEip1993Provider - } - - if (wallet === Wallet.Phantom) { - provider = (await getPhantomProvider()) as BrowserEip1993Provider - } - - if (wallet === Wallet.TrustWallet) { - provider = (await getTrustWalletProvider()) as BrowserEip1993Provider - } - - if (wallet === Wallet.OkxWallet) { - provider = (await getOkxWalletProvider()) as BrowserEip1993Provider - } + const walletProviderMap: { [key in Wallet]?: () => Promise<BrowserEip1993Provider> } = { + [Wallet.Metamask]: getMetamaskProvider, + [Wallet.BitGet]: getBitGetProvider, + [Wallet.Phantom]: getPhantomProvider, + [Wallet.TrustWallet]: getTrustWalletProvider, + [Wallet.OkxWallet]: getOkxWalletProvider, + } + + const providerFunction = walletProviderMap[wallet] + + if (!providerFunction) { + throw new WalletException( + new Error(`Evm Wallet for ${capitalize(wallet)} is not supported.`), + ) + } + + const provider = (await providerFunction()) as BrowserEip1993Provider if (!provider) { throw new WalletException( new Error(`Please install ${capitalize(wallet)} Extension`), ) } return provider } catch (e) { throw new WalletException( new Error(`Please install ${capitalize(wallet)} Extension`), ) } }
55-57
: Include original error details in exceptionWhen rethrowing an exception, consider including the original error message to provide more context for debugging and troubleshooting.
Apply this diff to include the original error:
} catch (e) { throw new WalletException( - new Error(`Please install ${capitalize(wallet)} Extension`), + new Error(`Failed to get ${capitalize(wallet)} provider: ${e.message}`), ) }
96-98
: Provide detailed error information when network update failsIncluding the original error message when throwing an exception can help identify the underlying issue during network updates.
Apply this diff to enhance the error message:
} catch (e) { throw new WalletException( - new Error(`Please update your ${capitalize(wallet)} network`), + new Error(`Failed to update ${capitalize(wallet)} network: ${e.message}`), ) }
71-77
: Redundant null check forprovider
Since
getEvmProvider
already throws an exception if the provider is not obtained, the null check forprovider
here may be redundant.Consider removing the unnecessary null check:
export const updateEvmNetwork = async ( wallet: Wallet, chainId: EthereumChainId, ) => { if (!isEvmBrowserWallet(wallet)) { throw new WalletException( new Error(`Evm Wallet for ${capitalize(wallet)} is not supported.`), ) } const provider = (await getEvmProvider(wallet)) as BrowserEip1993Provider - if (!provider) { - throw new WalletException( - new Error(`Please install ${capitalize(wallet)} Extension`), - ) - } try { const chainIdToHex = chainId.toString(16)
Add error handling for chain switching operations
Based on the code analysis, there are several issues that need to be addressed:
- The chain switching implementation is identical across all EVM wallets (MetaMask, BitGet, OKX, TrustWallet) without any wallet-specific error handling.
- While the wallets have error handling for installation and connection, there's no try-catch block around the
wallet_switchEthereumChain
operation.- The code uses
Promise.race
without a timeout, which could lead to hanging if thechange
event is never emitted.Required changes:
- Wrap the chain switching operation in a try-catch block to handle potential unsupported method errors
- Add a timeout to the Promise.race to prevent indefinite waiting
- Consider implementing wallet_addEthereumChain as a fallback when switching fails
🔗 Analysis chain
Line range hint
83-94
: Verify support forwallet_switchEthereumChain
method across walletsNot all EVM wallets may support the
wallet_switchEthereumChain
method or emit a'change'
event in the same way. Ensure that the wallets integrated support these features, or handle exceptions where they do not.Run the following script to check if each wallet's provider supports the
wallet_switchEthereumChain
method:Note: This script provides guidance but cannot be executed in the current sandbox environment. Manual verification or unit tests within the development environment are recommended.
Let me search for any error handling or wallet-specific implementations in the codebase.
Let me check for any error handling or fallback mechanisms in these wallet implementations.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Check if the `wallet_switchEthereumChain` method is supported by each EVM wallet provider. # List of wallets to check wallets=("Metamask" "BitGet" "Phantom" "TrustWallet" "OkxWallet") for wallet in "${wallets[@]}"; do echo "Checking wallet: $wallet" # Simulate provider method check (This is a placeholder for actual implementation) # In practice, you would need a test harness or environment where you can load each provider and check for method support. echo "Please verify manually if $wallet supports 'wallet_switchEthereumChain' method." doneLength of output: 1421
Script:
#!/bin/bash # Search for wallet-specific implementations and error handling related to chain switching rg -A 5 "wallet_switchEthereumChain" --type ts # Search for any try-catch blocks around chain switching ast-grep --pattern 'try { $$$ wallet_switchEthereumChain $$$ } catch' # Look for any fallback methods or alternative chain switching implementations rg -A 5 "wallet_addEthereumChain" --type ts # Check if there's any wallet provider type definitions or interfaces fd "provider|wallet" -e ts -x cat {} | rg -A 3 "interface|type.*Provider"Length of output: 3525
Script:
#!/bin/bash # Check for error handling in the wallet implementations rg -B 5 -A 10 "switchEthereumChain" packages/wallet-ts/src/utils/wallets/ --type ts # Look for any try-catch blocks in the wallet implementations ast-grep --pattern 'try { $$$ provider.request $$$ } catch' # Check for any error handling utilities or types rg "catch|error|throw" packages/wallet-ts/src/utils/wallets/ --type tsLength of output: 15135
📜 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 (19)
packages/utils/src/formatters.ts
(1 hunks)packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/Base.ts
(1 hunks)packages/wallets/wallet-base/src/utils/wallet.ts
(2 hunks)packages/wallets/wallet-core/package.json
(1 hunks)packages/wallets/wallet-core/src/strategy/BaseWalletStrategy.ts
(4 hunks)packages/wallets/wallet-cosmos/src/cosmos.d.ts
(1 hunks)packages/wallets/wallet-cosmos/src/data/index.ts
(1 hunks)packages/wallets/wallet-cosmos/src/index.ts
(1 hunks)packages/wallets/wallet-cosmos/src/strategy/strategy.ts
(6 hunks)packages/wallets/wallet-cosmos/src/utils/index.ts
(1 hunks)packages/wallets/wallet-cosmos/src/wallet.ts
(11 hunks)packages/wallets/wallet-cosmostation/src/index.ts
(1 hunks)packages/wallets/wallet-cosmostation/src/utils/index.ts
(1 hunks)packages/wallets/wallet-evm/package.json
(1 hunks)packages/wallets/wallet-evm/src/index.ts
(1 hunks)packages/wallets/wallet-evm/src/strategy/strategy.ts
(3 hunks)packages/wallets/wallet-evm/src/utils/index.ts
(2 hunks)packages/wallets/wallet-strategy/src/strategy/WalletStrategy.ts
(0 hunks)packages/wallets/wallet-strategy/src/strategy/index.ts
(1 hunks)
💤 Files with no reviewable changes (1)
- packages/wallets/wallet-strategy/src/strategy/WalletStrategy.ts
✅ Files skipped from review due to trivial changes (1)
- packages/wallet-ts/src/strategies/wallet-strategy/strategies/Ledger/Base.ts
🧰 Additional context used
🪛 Biome (1.9.4)
packages/wallets/wallet-strategy/src/strategy/index.ts
[error] 136-136: Avoid the use of spread (...
) syntax on accumulators.
Spread syntax should be avoided on accumulators (like those in .reduce
) because it causes a time complexity of O(n^2)
.
Consider methods such as .splice or .push instead.
(lint/performance/noAccumulatingSpread)
🔇 Additional comments (28)
packages/wallets/wallet-cosmos/src/index.ts (2)
3-3
: LGTM! The export statement is correctly structured.
The syntax is correct and follows ES module conventions with proper file extensions.
3-3
: Verify the intended public API surface.
Using export *
exposes all exports from the utils module. Consider being more explicit about which utilities should be public by using named exports instead.
Let's check what utilities are being exposed:
✅ Verification successful
The export *
is acceptable in this case
The utils module exports only two specific utility functions that are clearly related to Cosmos wallet functionality:
isCosmosWalletInstalled
: Checks if specific Cosmos wallets are installedconfirmCosmosAddress
: Validates Cosmos wallet addresses
These utilities are part of the public API surface and their exposure is intentional as they provide essential wallet-specific functionality. The wild-card export is not causing any unintended exposure of internal utilities.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Analyze the utilities being exposed from the utils module
# Expected: List of exported utilities to review for intended public exposure
# Check the exports from utils/index.js
ast-grep --pattern 'export { $$$ }' packages/wallets/wallet-cosmos/src/utils/index.js
# Check for direct exports in utils/index.js
ast-grep --pattern 'export function $_($$$) { $$$ }' packages/wallets/wallet-cosmos/src/utils/index.js
ast-grep --pattern 'export const $_ = $$$' packages/wallets/wallet-cosmos/src/utils/index.js
Length of output: 578
Script:
#!/bin/bash
# Let's first check if the utils directory exists and find the correct path
fd -t f "index.js" packages/wallets/wallet-cosmos/src/utils
# Let's also check all exported items from any .ts files in the utils directory
fd -e ts . packages/wallets/wallet-cosmos/src/utils --exec ast-grep --pattern 'export $_'
# Additionally, let's check if there are any re-exports
fd -e ts . packages/wallets/wallet-cosmos/src/utils --exec ast-grep --pattern 'export \* from'
Length of output: 248
Script:
#!/bin/bash
# Let's check the directory structure first to understand what we're working with
fd . packages/wallets/wallet-cosmos/src/utils
# Let's also check for any TypeScript files in the utils directory
fd -e ts . packages/wallets/wallet-cosmos/src
# Let's examine the content of the main index.ts file to understand the export
cat packages/wallets/wallet-cosmos/src/index.ts
Length of output: 624
Script:
#!/bin/bash
# Let's examine the content of utils/index.ts to see what's being exported
cat packages/wallets/wallet-cosmos/src/utils/index.ts
# Also check if these utilities are used within the wallet implementation
rg -l "utils" packages/wallets/wallet-cosmos/src/wallet.ts
Length of output: 2027
packages/wallets/wallet-evm/src/index.ts (1)
1-1
: Verify impact of new EvmWalletStrategy export
Adding a new strategy export could be a breaking change. Let's verify its usage across the codebase.
packages/wallets/wallet-cosmostation/src/index.ts (1)
3-3
: LGTM! Let's verify the exported utilities.
The export statement follows TypeScript best practices for barrel files.
Let's check what utilities are being exposed:
✅ Verification successful
Let me verify the contents of the utils directory in the wallet-cosmostation package.
LGTM! The utility export is safe and well-scoped.
The export from utils/index.js
only exposes a single utility function isCosmosStationWalletInstalled
which is a simple browser check for Cosmostation wallet installation. This is a safe and focused utility that:
- Follows TypeScript best practices
- Handles browser vs non-browser environments safely
- Has proper type definitions
- Serves a single, clear purpose
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify the contents of the utils/index.js file
# and its potential usage in the codebase
# Check the contents of the utils index file
rg -l "utils/index\.(ts|js)" --type ts
rg "from.*utils" --type ts -A 3
Length of output: 101625
Script:
#!/bin/bash
# Check the contents of the utils directory in wallet-cosmostation package
fd . packages/wallets/wallet-cosmostation/src/utils -t f --full-path
cat packages/wallets/wallet-cosmostation/src/utils/index.ts
Length of output: 454
packages/wallets/wallet-cosmos/src/data/index.ts (2)
1-1
: LGTM: Clean and specific import
The import statement is appropriately scoped to only bring in the Wallet enum from the base package.
3-8
: Verify wallet support completeness
The implementation looks correct, but let's verify if this list includes all supported Cosmos wallets and if the order is intentional.
✅ Verification successful
Based on the search results, I can now provide a definitive response about the completeness of the Cosmos wallet list.
Cosmos wallet list is complete and order appears intentional
The current list in cosmosWallets
includes all supported Cosmos wallets:
- Leap
- Ninji
- Keplr
- OWallet
This is verified by:
- All wallet implementations found in the codebase match the list
- The order appears intentional, following the same pattern in other parts of the codebase
- Each listed wallet has corresponding strategy implementations confirming their support
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for any other Cosmos wallet references in the codebase
# that might need to be included in this list
# Search for Wallet enum usage related to Cosmos
rg -A 2 "Wallet\.(Leap|Ninji|Keplr|OWallet)" --type typescript
# Search for potential missing wallet implementations
ast-grep --pattern 'class $_ implements CosmosWallet {
$$$
}'
Length of output: 165
Script:
#!/bin/bash
# Let's try different approaches to find wallet implementations and references
# Search for wallet-related files
fd -e ts wallet
# Search for Wallet enum definition and usage
rg "enum.*Wallet" -A 5
# Search for class implementations with 'Wallet' in the name
rg "class.*Wallet" -A 5
# Search for cosmos wallet-related imports and configurations
rg -i "cosmos.*wallet" -A 2
Length of output: 132518
Script:
#!/bin/bash
# Let's try a different approach to find wallet implementations
# Search for wallet class implementations
rg "class.*Wallet" -t ts
# Search for wallet-related imports and exports
rg "import.*Wallet|export.*Wallet" -t ts
# Search for wallet enum definition
rg "enum.*Wallet" -t ts
# Search for cosmos wallet strategy implementations
rg "implements.*CosmosWallet" -t ts
Length of output: 37159
packages/wallets/wallet-cosmostation/src/utils/index.ts (2)
1-1
: LGTM: Clean import statement
The import statement correctly imports the required type from the Cosmostation extension client package.
3-9
: Implementation looks good, verifying similar patterns
The function correctly handles SSR compatibility and provides a type-safe way to check for wallet installation.
Let's verify this implementation against other wallet detection patterns in the codebase:
✅ Verification successful
Let's examine the actual implementation patterns in these files to ensure consistency.
Implementation is consistent with established patterns
The implementation of isCosmosStationWalletInstalled
follows the same robust pattern used across the codebase for wallet detection:
- Cosmos-based wallets (Keplr, Leap) use the same type-safe window casting approach
- EVM wallets follow a similar SSR-safe check pattern
- The implementation maintains consistency with other wallet detection utilities in the repository
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for similar wallet detection patterns across the codebase
rg -l "typeof window !== 'undefined'" packages/wallets/
Length of output: 504
Script:
#!/bin/bash
# Check implementation patterns of wallet detection across files
rg "typeof window !== 'undefined'" packages/wallets/ -A 3 -B 1
Length of output: 3655
packages/wallets/wallet-cosmos/src/cosmos.d.ts (1)
9-9
: LGTM! Type definition is correct and safely integrated.
The optional owallet
property is properly typed and follows the existing pattern while maintaining backward compatibility.
packages/wallets/wallet-base/src/utils/wallet.ts (2)
22-28
: LGTM! The implementation correctly identifies EVM browser wallets.
The function properly categorizes browser-specific EVM wallets.
31-38
: LGTM! The implementation correctly identifies Cosmos browser wallets.
The function properly categorizes Cosmos-specific browser wallets and maintains consistency with the isEvmBrowserWallet
implementation.
packages/wallets/wallet-cosmos/src/utils/index.ts (1)
1-8
: LGTM! Well-structured imports
The imports are properly organized, typed, and follow ES module conventions.
packages/wallets/wallet-core/package.json (1)
63-63
: Verify the major version upgrade and beta dependency.
The @injectivelabs/wallet-base
dependency has been upgraded from ^0.0.6
to ^1.14.33-beta.2
. This represents a significant version jump that could introduce breaking changes.
Consider:
- Testing the integration thoroughly due to the major version upgrade
- Evaluating if using a beta version (
1.14.33-beta.2
) in production is appropriate - Ensuring all dependent packages are compatible with this version
✅ Verification successful
Let me gather more information about the dependency and its usage to better assess the situation.
Let me check the actual usage of the wallet-base package to understand the impact of this upgrade.
Based on the gathered information, I can now provide a final response:
Version upgrade appears to be part of an aligned release strategy
The version upgrade from ^0.0.6
to ^1.14.33-beta.2
is part of a coordinated version alignment across the @InjectiveLabs ecosystem:
- The
wallet-core
package itself is at version1.14.33-beta.2
- Other dependencies like
sdk-ts
are also at version1.14.33-beta.2
- The
wallet-base
package is used as a core dependency providing essential interfaces and types - The upgrade maintains version parity across the monorepo packages
The beta version is consistently used across related packages, indicating this is an intentional pre-release state for the entire ecosystem rather than an isolated risky upgrade.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check for breaking changes and verify the dependency upgrade
# Check if there are any TypeScript compilation issues after the upgrade
tsc --noEmit
# Check if there are any package-lock.json or yarn.lock changes that might affect other dependencies
git diff origin/main -- '**/package-lock.json' '**/yarn.lock'
# Look for any migration guides or breaking changes in the repository
rg -i "BREAKING|MIGRATION" --type md
Length of output: 401
Script:
#!/bin/bash
# Check the current package version and its dependencies
cat packages/wallets/wallet-core/package.json
# Find files that import or use wallet-base
rg -l "@injectivelabs/wallet-base" --type ts
# Look for any breaking changes in recent commits
git log --oneline -n 20 | grep -i "break"
Length of output: 4728
Script:
#!/bin/bash
# Check the actual imports and usage of wallet-base in a few key files
cat packages/wallets/wallet-core/src/strategy/BaseWalletStrategy.ts
# Check if there are any recent changes to wallet-base package
fd -e ts -e js wallet-base
# Look for any migration guides or documentation
fd -e md -e txt . | xargs rg -l "wallet-base"
Length of output: 6550
packages/wallets/wallet-evm/package.json (1)
63-63
: Verify if this dependency update is intentional
This change updates @injectivelabs/wallet-base
from ^0.0.6
to ^1.14.33-beta.2
, which represents a significant version jump and introduces a beta version. A few concerns:
- This seems unrelated to the PR's documentation focus
- The major version change (0.x.x to 1.x.x) could introduce breaking changes
- The beta version might not be stable enough for production use
Let's check for related changes and potential impacts:
✅ Verification successful
Dependency update appears to be part of coordinated versioning
The version update of @injectivelabs/wallet-base
to ^1.14.33-beta.2
is consistent across all wallet packages in the monorepo:
- All 11 wallet-related packages use the exact same version
^1.14.33-beta.2
- Related dependencies like
@injectivelabs/utils
are also consistently versioned - The package itself (
@injectivelabs/wallet-base
) is the source package being referenced
This indicates a coordinated version bump across the monorepo rather than an unintended change, making it safe to proceed with this update.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check for other package.json files with similar dependencies
echo "Checking other package.json files for wallet-base dependency..."
rg -A 1 -B 1 '"@injectivelabs/wallet-base"' -g 'package.json'
# Check for breaking changes in git history
echo "Checking for breaking changes in recent commits..."
git log --oneline -n 10 | rg -i "break|major|wallet-base"
Length of output: 3559
packages/wallets/wallet-core/src/strategy/BaseWalletStrategy.ts (3)
15-15
: LGTM: Import reflects broader EVM wallet support
The change from isEthWallet
to isEvmWallet
better represents the broader category of Ethereum Virtual Machine compatible wallets.
Line range hint 169-173
: Consistent with amino transaction check
The check is consistent with the amino transaction check above, maintaining uniform validation across different signing methods.
Line range hint 154-158
: Verify wallet type checks across the codebase
The check prevents EVM wallets from signing Cosmos transactions, which is correct. Let's verify the consistency of these checks across the codebase.
✅ Verification successful
Let me generate another script to check for wallet type validations more comprehensively.
Wallet type validations are consistently implemented across the codebase
The validation checks for wallet types are properly implemented and consistent across the codebase:
- EVM wallet checks prevent signing Cosmos transactions in both
BaseWalletStrategy
andWalletStrategy
- Cosmos wallet checks prevent signing Ethereum transactions
- The wallet type checks are used consistently in broadcasters to route transactions to appropriate handlers (Cosmos vs Web3)
- The utility functions
isEvmWallet
andisCosmosWallet
are used consistently for type checking
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify consistent wallet type checks across the codebase
# Look for any remaining instances of isEthWallet and verify all wallet type checks
# Check for any remaining isEthWallet references
echo "Checking for remaining isEthWallet references:"
rg "isEthWallet"
# Check all wallet type validation patterns
echo "Checking wallet type validation patterns:"
rg -A 2 "You can't sign Cosmos Transaction using"
Length of output: 132117
Script:
#!/bin/bash
# Search for wallet type validations across the codebase
echo "Checking wallet type validations:"
# Look for isEvmWallet checks
echo "Checking isEvmWallet validations:"
rg "isEvmWallet\(" -A 2
# Look for isCosmosWallet checks
echo "Checking isCosmosWallet validations:"
rg "isCosmosWallet\(" -A 2
# Look for transaction signing validations
echo "Checking transaction signing validations:"
rg "can't sign .* Transaction using" -A 2
Length of output: 7047
packages/wallets/wallet-cosmos/src/strategy/strategy.ts (4)
34-34
: LGTM: Import of capitalize utility function
The addition of the capitalize
utility function import is appropriate for improving error message formatting consistency.
64-67
: LGTM: Improved constructor parameter handling
The refactoring to use object parameters for CosmosWallet
instantiation improves code clarity and maintainability.
56-58
: LGTM: Consistent error message formatting
Error messages have been standardized to properly capitalize wallet names using the capitalize
utility function, improving user-facing error messages consistency.
Also applies to: 146-148, 263-263, 275-279, 333-333
325-325
: LGTM: Consistent parameter handling in getCosmosWallet
The update to use object parameters in getCosmosWallet
maintains consistency with the constructor changes.
packages/wallets/wallet-evm/src/strategy/strategy.ts (2)
Line range hint 169-178
: LGTM! Good addition of endpoints validation.
The addition of endpoints validation is necessary and well-implemented. The error message clearly explains the requirement for EVM native wallets.
Line range hint 1-363
: Verify if these changes should be included in this PR.
The changes in this file appear to be unrelated to the PR's stated objective of updating CW20 to bank conversion documentation. Please verify if these changes should be part of a separate PR.
packages/wallets/wallet-cosmos/src/wallet.ts (2)
21-24
: LGTM! Constructor signature and imports are well structured.
The changes improve code readability by:
- Using object destructuring for constructor parameters
- Adding the
capitalize
utility for consistent error message formatting
Also applies to: 39-45
39-45
: Verify all instantiations of CosmosWallet.
The constructor signature has changed to use object destructuring. Let's verify that all instantiations of CosmosWallet
have been updated accordingly.
✅ Verification successful
The previous search showed many references to CosmosWalletException
and some instantiations, but we need to specifically look at the constructor patterns to verify they match the new object destructuring format. Let's use ast-grep to find these patterns more precisely.
All instantiations of CosmosWallet are using the correct object destructuring format
The verification shows that all instances of CosmosWallet
constructor calls in the codebase are already using the object destructuring pattern with the correct parameters (wallet
and chainId
):
new CosmosWallet({ chainId, wallet })
in wallet.tsnew CosmosWallet({ chainId, wallet })
in utils/index.tsnew CosmosWallet({ wallet: args.wallet, chainId: args.chainId })
in strategy/strategy.tsnew CosmosWallet({ chainId, wallet })
in strategy/strategy.ts (conditional instantiation)
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Find all instantiations of CosmosWallet to verify they use the new constructor signature
# Search for new CosmosWallet instantiations
rg -A 2 "new CosmosWallet"
# Search for potential class extensions
rg -A 2 "extends CosmosWallet"
Length of output: 57871
Script:
#!/bin/bash
# Search for instantiations of CosmosWallet class with constructor arguments
ast-grep --pattern 'new CosmosWallet({ $$$, $$$, $$$ })'
# Search for instantiations of CosmosWallet class with any pattern
ast-grep --pattern 'new CosmosWallet($$$)'
Length of output: 1533
packages/wallets/wallet-strategy/src/strategy/index.ts (3)
25-39
: Function ethereumWalletsDisabled
logic is clear and correct
The function accurately determines if Ethereum wallets should be disabled based on the provided arguments.
41-129
: createStrategy
function correctly initializes wallet strategies
The createStrategy
function effectively handles various wallet types and initializes the appropriate strategies. The use of type checks and switch cases enhances the extensibility and maintainability of the code.
143-176
: Class WalletStrategy
implementation is robust and well-structured
The WalletStrategy
class correctly initializes strategies and provides a setOptions
method for dynamic updates. The implementation follows good practices and enhances the modularity of wallet strategies.
export const capitalize = (str: string): string => | ||
str[0].toUpperCase() + str.slice(1) |
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.
🛠️ Refactor suggestion
Add input validation to prevent runtime errors
The capitalize
function could throw an error when given an empty string. Since this is used in error messages for wallets, we should make it more robust.
Consider adding input validation:
-export const capitalize = (str: string): string =>
- str[0].toUpperCase() + str.slice(1)
+export const capitalize = (str: string): string => {
+ if (!str) return ''
+ return str[0].toUpperCase() + str.slice(1)
+}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
export const capitalize = (str: string): string => | |
str[0].toUpperCase() + str.slice(1) | |
export const capitalize = (str: string): string => { | |
if (!str) return '' | |
return str[0].toUpperCase() + str.slice(1) | |
} |
export const confirmCosmosAddress = async ({ | ||
wallet, | ||
chainId, | ||
injectiveAddress, | ||
}: { | ||
wallet: Wallet | ||
chainId: ChainId | ||
injectiveAddress: string | ||
}) => { | ||
if (!cosmosWallets.includes(wallet)) { | ||
throw new CosmosWalletException( | ||
new Error(`Cosmos Wallet for ${capitalize(wallet)} is not supported.`), | ||
) | ||
} | ||
|
||
const cosmosWallet = new CosmosWallet({ chainId, wallet }) | ||
const key = await cosmosWallet.getKey() | ||
const publicKey = PublicKey.fromBase64( | ||
Buffer.from(key.pubKey).toString('base64'), | ||
) | ||
|
||
const { address: derivedAddress } = publicKey.toAddress() | ||
|
||
if (derivedAddress !== injectiveAddress) { | ||
throw new CosmosWalletException( | ||
new Error( | ||
`Connected ${capitalize( | ||
wallet, | ||
)} address is wrong. Please update Injective on ${capitalize(wallet)}.`, | ||
), | ||
) | ||
} | ||
} |
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.
💡 Codebase verification
🛠️ Refactor suggestion
Based on the search results, I can now provide a final response regarding the review comment:
Suggested improvements are valid but need refinement
The suggested error handling improvements are good but should be adjusted:
- The input validation for
injectiveAddress
is valid since the code already throwsCosmosWalletException
for unsupported wallets - The error message enhancement for unsupported wallets is already handled consistently across the codebase with similar patterns
- The key retrieval error handling is good but should maintain consistency with other wallet implementations
- The address mismatch error message should be adjusted to match the existing pattern
export const confirmCosmosAddress = async ({
wallet,
chainId,
injectiveAddress,
}: {
wallet: Wallet
chainId: ChainId
injectiveAddress: string
}) => {
+ if (!injectiveAddress) {
+ throw new CosmosWalletException(
+ new Error('Injective address is required'),
+ )
+ }
if (!cosmosWallets.includes(wallet)) {
throw new CosmosWalletException(
new Error(`Cosmos Wallet for ${capitalize(wallet)} is not supported.`),
)
}
const cosmosWallet = new CosmosWallet({ chainId, wallet })
+ let key;
+ try {
+ key = await cosmosWallet.getKey()
+ } catch (error) {
+ throw new CosmosWalletException(
+ new Error(`Failed to get public key: ${error.message}`),
+ )
+ }
const publicKey = PublicKey.fromBase64(
Buffer.from(key.pubKey).toString('base64'),
)
const { address: derivedAddress } = publicKey.toAddress()
if (derivedAddress !== injectiveAddress) {
throw new CosmosWalletException(
new Error(
`Connected ${capitalize(wallet)} address is wrong. Please update Injective on ${capitalize(wallet)}.`,
),
)
}
}
The error messages are kept consistent with the existing patterns found in the codebase, while adding the necessary input validation and error handling.
🔗 Analysis chain
Add input validation and enhance error handling
The function works correctly but could benefit from some improvements:
export const confirmCosmosAddress = async ({
wallet,
chainId,
injectiveAddress,
}: {
wallet: Wallet
chainId: ChainId
injectiveAddress: string
}) => {
+ if (!injectiveAddress) {
+ throw new CosmosWalletException(
+ new Error('Injective address is required'),
+ )
+ }
if (!cosmosWallets.includes(wallet)) {
throw new CosmosWalletException(
- new Error(`Cosmos Wallet for ${capitalize(wallet)} is not supported.`),
+ new Error(`${capitalize(wallet)} is not supported. Supported wallets: ${cosmosWallets.join(', ')}`),
)
}
const cosmosWallet = new CosmosWallet({ chainId, wallet })
- const key = await cosmosWallet.getKey()
+ let key;
+ try {
+ key = await cosmosWallet.getKey()
+ } catch (error) {
+ throw new CosmosWalletException(
+ new Error(`Failed to get public key from ${capitalize(wallet)}: ${error.message}`),
+ )
+ }
const publicKey = PublicKey.fromBase64(
Buffer.from(key.pubKey).toString('base64'),
)
const { address: derivedAddress } = publicKey.toAddress()
if (derivedAddress !== injectiveAddress) {
throw new CosmosWalletException(
new Error(
- `Connected ${capitalize(
- wallet,
- )} address is wrong. Please update Injective on ${capitalize(wallet)}.`,
+ `Address mismatch. Expected: ${injectiveAddress}, Got: ${derivedAddress}. Please update Injective on ${capitalize(wallet)}.`,
),
)
}
}
These changes:
- Add input validation for required parameters
- Enhance error messages with more context
- Add proper error handling for key retrieval
- Provide more detailed address mismatch information
Let's verify the wallet implementation:
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check for consistent wallet handling across the codebase
# Look for other wallet validation implementations
rg -A 5 "confirmCosmosAddress|isCosmosWalletInstalled"
# Check for potential error handling patterns
ast-grep --pattern 'throw new CosmosWalletException'
Length of output: 112844
Script:
#!/bin/bash
# Let's try a more focused search for wallet validation and error handling patterns
# Search for CosmosWalletException usage
rg -A 2 "CosmosWalletException" --type ts
# Look for wallet validation patterns
rg -A 3 "cosmosWallets.includes" --type ts
# Check for other address validation patterns
rg -A 3 "address.*wrong|address.*mismatch" --type ts
Length of output: 64654
if (![Wallet.Keplr, Wallet.OWallet].includes(wallet)) { | ||
throw new CosmosWalletException( | ||
new Error(`disableGasCheck is not support on ${wallet}`), | ||
new Error(`disableGasCheck is not support on ${capitalize(wallet)}`), |
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.
Fix inconsistent wallet support checks in gas check methods.
There's a logical inconsistency in the wallet support checks:
disableGasCheck
throws for non-Keplr/OWallet walletsenableGasCheck
throws for Keplr/OWallet wallets
This means these methods have opposite wallet support checks, which seems incorrect.
Both methods should have the same wallet support check. Suggest applying this fix:
- if (![Wallet.Keplr, Wallet.OWallet].includes(wallet)) {
+ if ([Wallet.Keplr, Wallet.OWallet].includes(wallet)) {
throw new CosmosWalletException(
new Error(`disableGasCheck is not supported on ${capitalize(wallet)}`),
)
}
- if ([Wallet.Keplr, Wallet.OWallet].includes(wallet)) {
+ if (![Wallet.Keplr, Wallet.OWallet].includes(wallet)) {
throw new CosmosWalletException(
new Error(`enableGasCheck is not supported on ${capitalize(wallet)}`),
)
}
Also applies to: 419-423
let provider | ||
|
||
if (wallet === Wallet.Metamask) { | ||
provider = (await getMetamaskProvider()) as BrowserEip1993Provider |
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.
Missing import for getMetamaskProvider
The function getMetamaskProvider()
is used but not imported. Please add the missing import statement to prevent a ReferenceError
.
Apply this diff to add the missing import:
+import { getMetamaskProvider } from '../strategy/utils/metamask.js'
Committable suggestion skipped: line range outside the PR's diff.
return Object.values(Wallet).reduce( | ||
(strategies, wallet) => ({ | ||
...strategies, | ||
[wallet]: createStrategy({ args, wallet: wallet as Wallet }), | ||
}), | ||
{} as ConcreteStrategiesArg, | ||
) |
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.
🛠️ Refactor suggestion
Avoid using spread syntax on accumulators in reduce
to improve performance
Using spread syntax on accumulators within a reduce
function can lead to O(n^2)
time complexity due to the creation of a new object at each iteration. This can impact performance, especially with larger datasets.
Apply the following refactor to avoid using spread syntax and improve performance:
- return Object.values(Wallet).reduce(
- (strategies, wallet) => ({
- ...strategies,
- [wallet]: createStrategy({ args, wallet: wallet as Wallet }),
- }),
- {} as ConcreteStrategiesArg,
- )
+ const strategies = {} as ConcreteStrategiesArg
+ Object.values(Wallet).forEach((wallet) => {
+ strategies[wallet] = createStrategy({ args, wallet: wallet as Wallet })
+ })
+ return strategies
Alternatively, refactor the reduce
function to mutate the accumulator:
return Object.values(Wallet).reduce(
- (strategies, wallet) => ({
- ...strategies,
- [wallet]: createStrategy({ args, wallet: wallet as Wallet }),
- }),
+ (strategies, wallet) => {
+ strategies[wallet] = createStrategy({ args, wallet: wallet as Wallet })
+ return strategies
+ },
{} as ConcreteStrategiesArg,
)
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
return Object.values(Wallet).reduce( | |
(strategies, wallet) => ({ | |
...strategies, | |
[wallet]: createStrategy({ args, wallet: wallet as Wallet }), | |
}), | |
{} as ConcreteStrategiesArg, | |
) | |
const strategies = {} as ConcreteStrategiesArg | |
Object.values(Wallet).forEach((wallet) => { | |
strategies[wallet] = createStrategy({ args, wallet: wallet as Wallet }) | |
}) | |
return strategies |
return Object.values(Wallet).reduce( | |
(strategies, wallet) => ({ | |
...strategies, | |
[wallet]: createStrategy({ args, wallet: wallet as Wallet }), | |
}), | |
{} as ConcreteStrategiesArg, | |
) | |
return Object.values(Wallet).reduce( | |
(strategies, wallet) => { | |
strategies[wallet] = createStrategy({ args, wallet: wallet as Wallet }) | |
return strategies | |
}, | |
{} as ConcreteStrategiesArg, | |
) |
🧰 Tools
🪛 Biome (1.9.4)
[error] 136-136: Avoid the use of spread (...
) syntax on accumulators.
Spread syntax should be avoided on accumulators (like those in .reduce
) because it causes a time complexity of O(n^2)
.
Consider methods such as .splice or .push instead.
(lint/performance/noAccumulatingSpread)
jira
Summary by CodeRabbit
New Features
Documentation