Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: user added chains price id #1571

Merged
merged 1 commit into from
Oct 1, 2024
Merged

Conversation

Nick-1979
Copy link
Member

@Nick-1979 Nick-1979 commented Oct 1, 2024

closes #1569

Summary by CodeRabbit

  • New Features

    • Introduced a new hook for retrieving token prices, enhancing accuracy and user-specific data handling.
    • Improved asset selection logic to reset appropriately when the chain changes.
  • Bug Fixes

    • Enhanced error handling for balance retrieval, preventing runtime errors related to undefined properties.
    • Improved error reporting during asset fetching on relay chains.
  • Documentation

    • Updated method signatures and added new utility functions for better functionality and error handling.

Copy link
Contributor

coderabbitai bot commented Oct 1, 2024

Walkthrough

The changes introduce a new useTokenPrice hook for simplified asset price retrieval in the AccountDetails component, enhancing logic for asset selection and balance display. The useBalances hook is modified for improved error handling when fetching existential deposits. The getPriceIdByChainName function is updated to consider user-added price IDs, while utility functions for array comparison and recent chain updates are added. Overall, the modifications streamline price retrieval and enhance robustness across several components.

Changes

Files Change Summary
packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx, packages/extension-polkagate/src/hooks/useTokenPrice.ts Introduced useTokenPrice hook for simplified asset price retrieval in AccountDetails, replacing complex logic with a direct hook call. Adjusted useEffect for asset selection based on URL parameters.
packages/extension-polkagate/src/hooks/useBalances.ts Modified getBalances function to include a conditional check for existential deposit retrieval, improving error handling and robustness in fetching balances.
packages/extension-polkagate/src/util/utils.ts Added UserAddedChains type and updated getPriceIdByChainName to accept an optional parameter for user-added price IDs. Introduced areArraysEqual function for array comparison and improved error handling in updateRecentChains.
packages/extension-polkagate/src/util/workers/getAssetOnRelayChain.js Updated getPriceIdByChainName function call to include user-added endpoints, enhancing price ID retrieval. Improved error logging in the asset fetching process.
packages/extension-polkagate/src/util/workers/utils/getChainEndpoints.js Replaced sanitizeChainName with direct string manipulation for chain comparison, maintaining functionality while simplifying the logic.

Possibly related PRs

Suggested labels

new feature

Suggested reviewers

  • AMIRKHANEF

🐇 In the code, we hop and play,
With prices fetched in a simpler way.
Balances checked, no need to fret,
User-added chains, a new asset bet!
So let’s rejoice, with a joyful cheer,
For clearer code, we hold so dear! 🎉


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Outside diff range and nitpick comments (3)
packages/extension-polkagate/src/hooks/useBalances.ts (1)

103-103: Approve: Improved robustness in retrieving existential deposit

The change enhances the code's resilience by adding a safety check before accessing api.consts['balances']['existentialDeposit']. This prevents potential runtime errors if the 'balances' module is not available in the API.

Consider using optional chaining for slightly improved readability:

const ED = api.consts?.['balances']?.['existentialDeposit'] as unknown as BN ?? BN_ZERO;

This achieves the same result with a more concise syntax.

packages/extension-polkagate/src/util/utils.ts (2)

379-385: Avoid deep nesting and improve readability in conditionals

The nested optional chaining and destructuring in the find method make the code harder to read and maintain. Consider breaking down the logic into smaller, clearer steps or using intermediate variables for better readability.

Refactored example:

if (useAddedChains) {
  const entries = Object.entries(useAddedChains);
  const matchedEntry = entries.find(([_, chainData]) => {
    const chainNameCleaned = chainData.chain?.replace(/\s/g, '')?.toLowerCase();
    return chainNameCleaned === chainName.toLowerCase();
  });

  const maybeUserAddedPriceId = matchedEntry?.[1]?.priceId;

  if (maybeUserAddedPriceId) {
    return maybeUserAddedPriceId;
  }
}

Line range hint 388-402: Prevent mutation of input arrays in areArraysEqual function

The areArraysEqual function currently sorts the input arrays in place using array.sort(), which mutates the original arrays. This side effect can lead to unexpected behavior elsewhere in the code where these arrays are used.

To fix this, create copies of the arrays before sorting:

-  const sortedArrays = arrays.map((array) => array.sort());
+  const sortedArrays = arrays.map((array) => [...array].sort());

Additionally, be aware that Array.prototype.sort() without a compare function may not sort numbers correctly and won't work as expected for complex types. If the arrays contain numbers or custom objects, consider providing a compare function:

const sortedArrays = arrays.map((array) => [...array].sort((a, b) => a - b));
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 5a2f0cc and 9151371.

📒 Files selected for processing (6)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (2 hunks)
  • packages/extension-polkagate/src/hooks/useBalances.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useTokenPrice.ts (4 hunks)
  • packages/extension-polkagate/src/util/utils.ts (2 hunks)
  • packages/extension-polkagate/src/util/workers/getAssetOnRelayChain.js (1 hunks)
  • packages/extension-polkagate/src/util/workers/utils/getChainEndpoints.js (1 hunks)
🔇 Additional comments (9)
packages/extension-polkagate/src/util/workers/utils/getChainEndpoints.js (1)

19-19: 🛠️ Refactor suggestion

Verify the impact of replacing sanitizeChainName with direct string manipulation.

The change from sanitizeChainName(chain)?.toLowerCase() to chain?.replace(/\s/g, '')?.toLowerCase() might have some implications:

  1. It could potentially improve performance by avoiding an external function call.
  2. The new method removes all whitespace, which might change behavior in edge cases compared to the previous sanitizeChainName function.
  3. The inline regex might be less readable than a named function.

To ensure consistency and prevent potential issues:

  1. Verify that this change doesn't break consistency with other parts of the codebase that might still be using sanitizeChainName.
  2. Consider extracting this logic into a new named function for better readability and reusability.

Run the following script to check for other usages of sanitizeChainName in the codebase:

Consider extracting the string manipulation into a new function for better readability and consistency:

const sanitizeChainName = (chain) => chain?.replace(/\s/g, '')?.toLowerCase();

// Then use it in the function:
const maybeEndpoint = Object.entries(userAddedEndpoints).find(([_, { chain }]) => sanitizeChainName(chain) === chainName.toLowerCase());

This approach maintains the performance improvement while enhancing code readability and maintainability.

packages/extension-polkagate/src/util/workers/getAssetOnRelayChain.js (1)

98-98: LGTM! Verify the getPriceIdByChainName function update.

The addition of the userAddedEndpoints parameter to the getPriceIdByChainName function call enhances flexibility by allowing custom endpoints. This change aligns with the PR objective of fixing user-added chains price ID.

Please run the following script to verify that the getPriceIdByChainName function has been updated to handle the new parameter:

packages/extension-polkagate/src/hooks/useBalances.ts (1)

Line range hint 1-385: Overall impact: Localized improvement with no negative side effects

The change to the existential deposit retrieval is a targeted improvement that enhances the robustness of the useBalances hook. It aligns well with the existing error-handling patterns in the file and doesn't introduce any new risks or alter the core functionality.

To ensure the change is consistent with the rest of the file, let's verify the usage of ED:

This will help confirm that the change doesn't introduce any inconsistencies in how the existential deposit is used throughout the file.

packages/extension-polkagate/src/hooks/useTokenPrice.ts (3)

9-13: Imports are correctly updated and organized.

The added imports for useUserAddedPriceId, toCamelCase, ASSET_HUBS, NATIVE_TOKEN_ASSET_ID, useInfo, and usePrices are appropriate and the paths appear to be correct.


59-59: Dependency array in useMemo updated correctly.

Including userAddedPriceId in the dependency array ensures that the memoized value updates when userAddedPriceId changes, preventing potential stale data issues.


50-50: Verify the logic for determining priceId.

The updated logic prioritizes _assetId when it's defined and greater than NATIVE_TOKEN_ASSET_ID. Otherwise, it uses userAddedPriceId or falls back to getPriceIdByChainName(chainName). Ensure that this order of precedence aligns with the intended functionality, especially in cases where userAddedPriceId and getPriceIdByChainName(chainName) might return different results.

To confirm that userAddedPriceId is correctly fetched and utilized, you can run the following script:

✅ Verification successful

Let's run an updated verification to ensure userAddedPriceId and genesisHash are correctly utilized.


Let's run an updated verification to ensure userAddedPriceId and genesisHash are correctly utilized.


Price ID Logic Verified

The userAddedPriceId and genesisHash are correctly fetched and utilized, ensuring the order of precedence aligns with the intended functionality.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that user-added price IDs are correctly associated with the genesisHash.

# Test: Search for all occurrences of useUserAddedPriceId to ensure it's implemented correctly.
rg --type javascript 'useUserAddedPriceId\((.*?)\)' -A 5

# Check if genesisHash values are consistently defined and used.
rg --type javascript 'genesisHash' -A 2

Length of output: 168


Script:

#!/bin/bash
# Description: Verify that user-added price IDs are correctly associated with the genesisHash.

# Test: Search for all occurrences of useUserAddedPriceId to ensure it's implemented correctly.
rg --type typescript 'useUserAddedPriceId\((.*?)\)' -A 5

# Check if genesisHash values are consistently defined and used.
rg --type typescript 'genesisHash' -A 2

Length of output: 168


Script:

#!/bin/bash
# Description: Verify that user-added price IDs are correctly associated with the genesisHash.

# Test: Search for all occurrences of useUserAddedPriceId to ensure it's implemented correctly within TypeScript files.
rg 'useUserAddedPriceId\((.*?)\)' -A 5 -g '*.ts'

# Check if genesisHash values are consistently defined and used within TypeScript files.
rg 'genesisHash' -A 2 -g '*.ts'

Length of output: 103623

packages/extension-polkagate/src/util/utils.ts (1)

11-11: Importing UserAddedChains type is appropriate

The addition of UserAddedChains to the import statement ensures that the new type is available for use in the updated function. This is necessary for the changes made below.

packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (2)

18-18: Importing useTokenPrice Hook

The useTokenPrice hook is correctly imported from '../../hooks', allowing you to access token price data within the component.


72-72: Obtaining currentPrice Using useTokenPrice

The currentPrice is now obtained by destructuring the price from the useTokenPrice(address, assetId) hook. This simplifies the logic for retrieving the current price based on the account address and asset ID.

@Nick-1979 Nick-1979 merged commit 0db1976 into main Oct 1, 2024
11 checks passed
@Nick-1979 Nick-1979 deleted the fixPriceIdIssuesForUserAddedChains branch October 1, 2024 12:59
github-actions bot pushed a commit that referenced this pull request Oct 1, 2024
# [0.15.0](v0.14.1...v0.15.0) (2024-10-01)

### Bug Fixes

* user added chains price id ([#1571](#1571)) ([0db1976](0db1976))

### Features

* add profile tab tooltip in FS ([#1567](#1567)) ([929b519](929b519)), closes [#1572](#1572)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

no show for price of user added chain
2 participants