Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: add some Asset hubs reserved amount #1394

Open
wants to merge 24 commits into
base: main
Choose a base branch
from

Conversation

AMIRKHANEF
Copy link
Member

@AMIRKHANEF AMIRKHANEF commented Jun 26, 2024

Works Done

  1. Add creating assets deposit amount.
  2. Add creating NFT deposit amount.
  3. Add creating uniques NFT deposit amount.
  4. refactor useReservedDetails.
  5. refactor ReservedDisplayBalance.
  6. Update translations.

Summary by CodeRabbit

  • New Features

    • Enhanced the ReservedDisplayBalance component to require assetId and assetToken for improved functionality.
    • Introduced new state logic in ReservedDetails to track data fetching and conditionally render messages based on asset parameters.
  • Improvements

    • Updated the AccountDetails component to better manage and display reserved balances with specific asset context.
    • Refined logic for displaying balances based on asset genesis hash and ID, ensuring consistency during asset changes.
    • Improved error handling and state management in the useReservedDetails hook, enhancing type safety and robustness.

Copy link
Contributor

coderabbitai bot commented Jun 26, 2024

Walkthrough

The updates enhance the ReservedDisplayBalance component to incorporate new props assetId and assetToken, which are now required for its functionality. The component's state management has been improved with the addition of a stillFetching variable and refined rendering logic to provide better user feedback. The AccountDetails component has been modified to pass these new props to ReservedDisplayBalance, ensuring accurate display of asset information and handling of asset changes effectively. Additionally, the useReservedDetails hook has undergone significant restructuring to improve type safety and state management.

Changes

File Path Change Summary
.../ReservedDisplayBalance.tsx Added new props assetId and assetToken; utilized useMemo for notOnNativeAsset and filtered reservedDetails; added stillFetching state; updated useEffect dependencies; memoized component export.
.../accountDetails/index.tsx Updated ReservedDisplayBalance to accept assetId and assetToken; refined logic for balancesToShow and asset handling during state changes.
.../DisplayBalance.tsx Modified control flow for ArrowForwardIosRoundedIcon to consider both openCollapse and disabled states.
.../useReservedDetails.ts Enhanced type safety with new types; updated function signature to include decimal; improved error handling and state management with setValue.

Possibly related PRs

Suggested labels

new feature

Poem

In the code where balance shows its might,
With assetId and tokens gleaming bright,
Now reasons filtered, clear as day,
Hooked to details in a brand-new way. 🌟
State updated, features fine,
In our app, the sun will shine. 🌞


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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a6d4f63 and d206c68.

Files selected for processing (7)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (4 hunks)
  • packages/extension-polkagate/src/hooks/useReservedDetails.ts (8 hunks)
  • packages/extension/public/locales/en/translation.json (1 hunks)
  • packages/extension/public/locales/fr/translation.json (1 hunks)
  • packages/extension/public/locales/hi/translation.json (1 hunks)
  • packages/extension/public/locales/ru/translation.json (1 hunks)
  • packages/extension/public/locales/zh/translation.json (1 hunks)
Files skipped from review due to trivial changes (3)
  • packages/extension/public/locales/en/translation.json
  • packages/extension/public/locales/fr/translation.json
  • packages/extension/public/locales/hi/translation.json
Additional context used
Biome
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx

[error] 73-90: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 79-89: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 86-88: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 136-138: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 134-134: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead. (lint/suspicious/noGlobalIsNan)

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

Additional comments not posted (9)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (3)

9-9: Addition of React hooks is appropriate for the new functionality.

The addition of useMemo, useState, and useParams aligns with the new functionality related to handling dynamic UI states and parameters.


15-15: Use of useParams from React Router is correctly implemented.

This hook is essential for retrieving route parameters, which is necessary for the new feature of handling asset-specific displays.


125-159: Ensure proper conditional rendering based on genesisHash and notOnNativeAsset.

This logic effectively prevents the component from rendering irrelevant data based on the asset context, which is crucial for user experience and data integrity.
[APROVED]

Tools
Biome

[error] 136-138: This else clause can be omitted because previous branches break early. (lint/style/noUselessElse)

Unsafe fix: Omit the else clause.


[error] 134-134: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead. (lint/suspicious/noGlobalIsNan)

See the MDN documentation for more details.
Unsafe fix: Use Number.isNaN instead.

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

14-14: Addition of constants for asset hubs and proxy chains.

This addition supports the new functionality for handling different asset types and proxy chains, which is crucial for the expanded capabilities of the hook.


17-17: Utility functions for human-readable and machine-readable conversions are correctly implemented.

These utility functions are essential for handling the display and calculation of asset values, improving the flexibility and readability of the code.


Line range hint 69-374: Ensure robust error handling in asynchronous operations.

The extensive use of .catch blocks for handling API call errors is well implemented, ensuring that the UI can gracefully handle failures.

packages/extension/public/locales/zh/translation.json (2)

1289-1289: Added new translation key "No reasons found!"

This change aligns with the PR objectives to add new language translations. The translation is correctly formatted and matches the provided English text.


Line range hint 1-1288: General Review of the File

The existing translations in the file appear to be consistent and correctly formatted. No syntax errors or missing values were detected.

packages/extension/public/locales/ru/translation.json (1)

1280-1280: Translation for "No reasons found!" is correct and appropriate.

The translation "Причины не найдены!" accurately conveys the meaning of the original English phrase and is grammatically correct.

@Nick-1979
Copy link
Member

@AMIRKHANEF
Please check Codrabbit's suggestions, resolve them even if some are unrelated.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d206c68 and 79c7384.

Files selected for processing (3)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (4 hunks)
  • packages/extension-polkagate/src/popup/account/ReservedReasons.tsx (5 hunks)
  • packages/extension-polkagate/src/popup/account/index.tsx (2 hunks)
Additional context used
Biome
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx

[error] 134-136: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

packages/extension-polkagate/src/popup/account/index.tsx

[error] 60-62: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

Eliminate // @ts-nocheck

Apply code rabit suggestions
@AMIRKHANEF AMIRKHANEF force-pushed the AssetHubsReservedAmount branch from 4c3d72a to 230133e Compare July 1, 2024 09:40
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/components/Assets.tsx (3)

Line range hint 23-23: Fix the type of setAssetId prop.

The setAssetId prop should be typed as React.Dispatch<React.SetStateAction<number | undefined>> instead of React.Dispatch<React.SetStateAction<number | undefined>>.

- setAssetId: React.Dispatch<React.SetStateAction<number | undefined>>
+ setAssetId: React.Dispatch<React.SetStateAction<number | undefined>>;

Line range hint 28-28: Handle missing address gracefully.

The address prop is used directly without checking if it's defined. Add a check to handle cases where address is null or undefined.

- const tokens = useTokens(address as string);
- const chain = useChain(address);
- const assetHubOptions = useAssetHubAssets(address as string);
- const multiChainAssetsOptions = useAccountAssetsOptions(address as string);
+ const tokens = useTokens(address ?? '');
+ const chain = useChain(address ?? '');
+ const assetHubOptions = useAssetHubAssets(address ?? '');
+ const multiChainAssetsOptions = useAccountAssetsOptions(address ?? '');

Line range hint 37-37: Initialize isLoading state properly.

The isLoading state is declared but not initialized. Initialize it to false.

- const [isLoading, setLoading] = useState<boolean>();
+ const [isLoading, setLoading] = useState<boolean>(false);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d206c68 and 4c3d72a.

Files selected for processing (5)
  • packages/extension-polkagate/src/components/Assets.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (4 hunks)
  • packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/account/ReservedReasons.tsx (5 hunks)
  • packages/extension-polkagate/src/popup/account/index.tsx (2 hunks)
Files not summarized due to errors (4)
  • packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx: Error: Server error. Please try again later.
  • packages/extension-polkagate/src/components/Assets.tsx: Error: Server error. Please try again later.
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx: Error: Server error. Please try again later.
  • packages/extension-polkagate/src/popup/account/ReservedReasons.tsx: Error: Server error. Please try again later.
Additional context used
Learnings (1)
packages/extension-polkagate/src/popup/account/index.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-07-01T09:27:24.482Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
Biome
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx

[error] 134-136: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

packages/extension-polkagate/src/popup/account/index.tsx

[error] 60-62: This else clause can be omitted because previous branches break early.

Unsafe fix: Omit the else clause.

(lint/style/noUselessElse)

Additional comments not posted (6)
packages/extension-polkagate/src/components/Assets.tsx (2)

1-4: Remove unnecessary ESLint disable comment.

The react/jsx-max-props-per-line rule is disabled but not needed in this context.

- /* eslint-disable react/jsx-max-props-per-line */

Line range hint 5-6: Remove unnecessary type import.

The SxProps and Theme types are imported but not used in the file.

- import { Grid, type SxProps, type Theme } from '@mui/material;
+ import { Grid } from '@mui/material;
packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx (1)

3-4: Remove unnecessary ESLint disable comment.

The header/header rule is disabled but not needed in this context.

- /* eslint-disable header/header */
packages/extension-polkagate/src/popup/account/ReservedReasons.tsx (1)

14-14: Remove unnecessary useCallback import.

The useCallback hook is imported but not used in the file.

- import React, { useCallback, useMemo } from 'react';
+ import React, { useMemo } from 'react';
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (2)

9-10: Remove unnecessary useCallback import.

The useCallback hook is imported but not used in the file.

- import React, { useCallback, useEffect, useMemo, useState } from 'react';
+ import React, { useEffect, useMemo, useState } from 'react';

13-13: Remove unnecessary BN import.

The BN class is imported but not used in the file.

- import { BN } from '@polkadot/util';

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

Outside diff range and nitpick comments (1)
packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx (1)

Line range hint 14-14: Consider adding TypeScript type annotations for better type safety.

The component uses TypeScript, but not all functions and variables are fully typed. Adding explicit types can improve maintainability and reduce the risk of bugs.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d206c68 and 230133e.

Files selected for processing (5)
  • packages/extension-polkagate/src/components/Assets.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (4 hunks)
  • packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/account/ReservedReasons.tsx (5 hunks)
  • packages/extension-polkagate/src/popup/account/index.tsx (2 hunks)
Files not summarized due to errors (3)
  • packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx: Error: Server error. Please try again later.
  • packages/extension-polkagate/src/popup/account/index.tsx: Error: Server error. Please try again later.
  • packages/extension-polkagate/src/popup/account/ReservedReasons.tsx: Error: Server error. Please try again later.
Files skipped from review due to trivial changes (1)
  • packages/extension-polkagate/src/components/Assets.tsx
Additional context used
Learnings (1)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-07-01T09:27:24.482Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
Additional comments not posted (6)
packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx (1)

Line range hint 19-19: Ensure consistent use of theme colors.

It appears that the theme is used inconsistently. For example, theme.palette.secondary.light is used without checking if it exists. This could lead to runtime errors if the theme structure changes.

#!/bin/bash
# Description: Check for consistent use of theme across the project.

# Test: Search for theme usage. Expect: Consistent theme structure usage.
rg --type typescript 'theme.palette'
packages/extension-polkagate/src/popup/account/ReservedReasons.tsx (2)

Line range hint 105-143: Ensure proper handling of null and undefined states.

The rendering logic based on reasonsToShow should explicitly handle undefined and null to avoid rendering issues or errors in edge cases.


57-77: Revisit the conditional logic in useMemo.

The logic inside useMemo has been a point of contention. The conditions details.length === 0 and details.every((deposit) => deposit === null) are indeed different and should not be combined as they check for different scenarios. It's important to maintain clear and separate checks for these conditions to avoid logic errors.

#!/bin/bash
# Description: Verify the logic of useMemo in other similar components for consistency.

# Test: Search for similar useMemo usage. Expect: Consistent handling of similar conditions.
rg --type typescript 'useMemo'
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (2)

129-133: Good use of Number.isNaN for NaN checking.

This is a good practice and aligns with previous learnings to avoid type coercion issues.


69-89: Simplify conditional logic in useMemo.

The nested conditional logic can be streamlined for better readability and performance, especially since similar suggestions have been made in the past.

-    if (details.length === 0) {
-      return undefined
-    }
-    const noReason = details.every((deposit) => deposit === null);
-    if (noReason) {
-      return null;
-    }
-    const filteredReservedDetails = Object.fromEntries(
-      Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
-    );
-    return Object.values(filteredReservedDetails).length > 0 ? filteredReservedDetails : undefined;
+    if (details.length === 0 || details.every((deposit) => deposit === null)) return null;
+    const filteredReservedDetails = Object.fromEntries(
+      Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
+    );
+    return Object.values(filteredReservedDetails).length > 0 ? filteredReservedDetails : null;

Likely invalid or redundant comment.

packages/extension-polkagate/src/popup/account/index.tsx (1)

55-60: Simplify the conditional logic.

The previous comment about omitting redundant else clauses is still relevant. Simplifying this logic can improve readability and performance.

-    if (assetIdNumber > 0) {
-      return true;
-    } else {
-      return false;
-    }
+    return assetIdNumber > 0;

Likely invalid or redundant comment.

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 (5)
packages/extension-polkagate/src/components/Assets.tsx (1)

Line range hint 9-9: Ensure proper handling of undefined addresses.

The useTokens, useChain, and useAssetHubAssets hooks are called with address cast to a string without checking if address is defined. This could lead to runtime errors if address is null or undefined.

-  const tokens = useTokens(address as string);
-  const chain = useChain(address);
-  const assetHubOptions = useAssetHubAssets(address as string);
+  const tokens = useTokens(address ?? '');
+  const chain = useChain(address ?? '');
+  const assetHubOptions = useAssetHubAssets(address ?? '');
packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx (2)

Line range hint 41-41: Ensure proper handling of undefined addresses.

The useApi and useTokenPrice hooks are called with address cast to a string without checking if address is defined. This could lead to runtime errors if address is undefined.

-  const api = useApi(address);
-  const { price } = useTokenPrice(address as string, balances?.assetId);
+  const api = useApi(address ?? '');
+  const { price } = useTokenPrice(address ?? '', balances?.assetId);

Line range hint 107-107: Avoid using index as key in lists.

Using the index as a key in lists can lead to issues with component re-rendering and state management. Consider using a unique identifier instead.

-  {Object.entries(reasonsToShow)?.map(([key, value], index) => (
-    <Grid container item key={index}>
+  {Object.entries(reasonsToShow)?.map(([key, value]) => (
+    <Grid container item key={key}>
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (2)

Line range hint 57-77: Optimize the conditional logic in useMemo.

The nested conditional logic can be simplified to improve readability and maintainability.

-  if (details.length === 0) {
-    return undefined;
-  }
-  const noReason = details.every((deposit) => deposit === null);
-  if (noReason) {
-    return null;
-  }
-  const filteredReservedDetails = Object.fromEntries(
-    Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
-  );
-  return Object.values(filteredReservedDetails).length > 0 ? filteredReservedDetails : undefined;
+  if (details.length === 0) {
+    return undefined;
+  }
+  if (details.every((deposit) => deposit === null)) {
+    return null;
+  }
+  const filteredReservedDetails = Object.fromEntries(
+    Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
+  );
+  return Object.values(filteredReservedDetails).length > 0 ? filteredReservedDetails : undefined;

Line range hint 107-107: Avoid using index as key in lists.

Using the index as a key in lists can lead to issues with component re-rendering and state management. Consider using a unique identifier instead.

-  {Object.entries(reasonsToShow)?.map(([key, value], index) => (
-    <Grid container item key={index}>
+  {Object.entries(reasonsToShow)?.map(([key, value]) => (
+    <Grid container item key={key}>
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d206c68 and 0c23779.

Files selected for processing (5)
  • packages/extension-polkagate/src/components/Assets.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (4 hunks)
  • packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx (1 hunks)
  • packages/extension-polkagate/src/popup/account/ReservedReasons.tsx (5 hunks)
  • packages/extension-polkagate/src/popup/account/index.tsx (2 hunks)
Files not summarized due to errors (5)
  • packages/extension-polkagate/src/popup/account/index.tsx: Error: Server error. Please try again later.
  • packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx: Error: Server error. Please try again later.
  • packages/extension-polkagate/src/components/Assets.tsx: Error: Server error. Please try again later.
  • packages/extension-polkagate/src/popup/account/ReservedReasons.tsx: Error: Server error. Please try again later.
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx: Error: Server error. Please try again later.
Additional context used
Learnings (1)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-07-01T09:27:24.482Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
Additional comments not posted (7)
packages/extension-polkagate/src/components/Assets.tsx (2)

Line range hint 20-20: Consider adding a loading state for chain switch.

When the chain changes, the setAssetId is called, but there is no indication to the user that the assets are being reloaded. Consider adding a loading state to improve user experience.

useEffect(() => {
  setAssetId(undefined); // this will set the asset to the native asset on chain switch
+  setLoading(true);
}, [chain]);

Line range hint 24-24: Verify the logic for setting loading state.

The setLoading function is called with true if both assetHubOptions and multiChainAssetsOptions are undefined, and false otherwise. Ensure this logic correctly reflects the loading state.

useEffect(() => {
  if (assetHubOptions === undefined && multiChainAssetsOptions === undefined) {
    setAssetId(undefined);
    return setLoading(true);
  }
  setLoading(false);
}, [assetHubOptions, multiChainAssetsOptions, setAssetId]);
packages/extension-polkagate/src/popup/account/LabelBalancePrice.tsx (1)

3-3: Remove unnecessary ESLint disable directive.

The header/header ESLint directive is not necessary and can be removed to maintain cleaner code.

/* eslint-disable header/header */
packages/extension-polkagate/src/popup/account/ReservedReasons.tsx (1)

57-77: Optimize the conditional logic in useMemo.

The nested conditional logic can be simplified to improve readability and maintainability.

-  if (details.length === 0) {
-    return undefined;
-  }
-  const noReason = details.every((deposit) => deposit === null);
-  if (noReason) {
-    return null;
-  }
-  const filteredReservedDetails = Object.fromEntries(
-    Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
-  );
-  return Object.values(filteredReservedDetails).length > 0 ? filteredReservedDetails : undefined;
+  if (details.length === 0) {
+    return undefined;
+  }
+  if (details.every((deposit) => deposit === null)) {
+    return null;
+  }
+  const filteredReservedDetails = Object.fromEntries(
+    Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
+  );
+  return Object.values(filteredReservedDetails).length > 0 ? filteredReservedDetails : undefined;

Likely invalid or redundant comment.

packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)

129-133: Omit the redundant else clause in notOnNativeAsset.

The else clause is redundant because the previous branch returns early.

-    if (Number.isNaN(assetIdNumber) || assetIdNumber > 0) {
-      return true;
-    } else {
-      return false;
-    }
+    return Number.isNaN(assetIdNumber) || assetIdNumber > 0;

Likely invalid or redundant comment.

packages/extension-polkagate/src/popup/account/index.tsx (2)

55-59: Omit the redundant else clause in notOnNativeAsset.

The else clause is redundant because the previous branch returns early.

-    if (assetIdNumber > 0) {
-      return true;
-    } else {
-      return false;
-    }
+    return assetIdNumber > 0;

60-60: LGTM!

The memoization for showReservedChevron is well-implemented and improves performance by avoiding unnecessary recalculations.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0c23779 and 997e2dc.

Files selected for processing (2)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (4 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (1 hunks)
Additional context used
Learnings (2)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-07-01T09:27:24.482Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-07-01T09:27:24.482Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
GitHub Check: build
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx

[failure] 15-15:
'useParams' is declared but its value is never read.

Additional comments not posted (6)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (5)

23-23: LGTM!

The addition of the assetId parameter in the Props interface is appropriate.


Line range hint 99-117: LGTM!

The conditional rendering logic for reasonsToShow is correct and handles all possible states.


124-149: LGTM!

The updates to the ReservedDisplayBalance component, including the assetId parameter and related logic, are correct and well-integrated.


129-129: LGTM!

The notOnNativeAsset useMemo hook logic is correct and efficient.


70-90: Optimize conditional logic in useMemo.

The nested conditional logic can be simplified to improve readability and maintainability.

-    if (details.length === 0) {
-      return undefined;
-    }
-    const noReason = details.every((deposit) => deposit === null);
-    if (noReason) {
-      return null;
-    }
-    const filteredReservedDetails = Object.fromEntries(
-      Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
-    );
-    return Object.values(filteredReservedDetails).length > 0 ? filteredReservedDetails : undefined;
+    if (details.length === 0 || details.every((deposit) => deposit === null)) return null;
+    const filteredReservedDetails = Object.fromEntries(
+      Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
+    );
+    return Object.values(filteredReservedDetails).length > 0 ? filteredReservedDetails : undefined;

Likely invalid or redundant comment.

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

258-258: LGTM!

The updates to the ReservedDisplayBalance component usage, including the assetId parameter, are correct and well-integrated.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0c23779 and 997e2dc.

Files selected for processing (2)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (4 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (1 hunks)
Additional context used
Learnings (2)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-07-01T09:27:24.482Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-07-01T09:27:24.482Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
GitHub Check: build
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx

[failure] 15-15:
'useParams' is declared but its value is never read.

Additional comments not posted (3)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (3)

Line range hint 42-61: LGTM!

The WaitForReserved function component is implemented correctly and uses props effectively to render skeletons.


Line range hint 124-153: LGTM!

The ReservedDisplayBalance function component is implemented correctly and uses hooks and conditional rendering effectively.


70-90: Optimize the conditional logic in useMemo.

The nested conditional logic can be simplified to improve readability and maintainability.

-    if (details.length === 0) {
-      return undefined;
-    }
-    const noReason = details.every((deposit) => deposit === null);
-    if (noReason) {
-      return null;
-    }
-    const filteredReservedDetails = Object.fromEntries(
-      Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
-    );
-    return Object.values(filteredReservedDetails).length > 0 ? filteredReservedDetails : undefined;
+    if (details.length === 0 || details.every((deposit) => deposit === null)) return null;
+    const filteredReservedDetails = Object.fromEntries(
+      Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
+    );
+    return Object.values(filteredReservedDetails).length > 0 ? filteredReservedDetails : undefined;

Likely invalid or redundant comment.

@Nick-1979
Copy link
Member

address #1360

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 997e2dc and 5ce3a47.

Files selected for processing (1)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (5 hunks)
Additional context used
Learnings (1)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-07-01T09:27:24.482Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
Additional comments not posted (7)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (7)

9-9: LGTM! The import of useMemo is appropriate.

The useMemo hook is necessary for memoizing values that depend on dependencies.


13-13: LGTM! The import of isOnRelayChain is appropriate.

The isOnRelayChain function is necessary for checking if the current chain is a relay chain.


22-22: LGTM! The addition of the assetId property to the Props interface is appropriate.

This change is necessary for handling asset IDs in the component.


112-116: LGTM! The addition of the translation key "No reasons found!" is appropriate.

This change adds a new translation key for localization purposes.


128-129: LGTM! The use of useMemo for notOnNativeAsset is appropriate.

This change memoizes the calculation of notOnNativeAsset based on the assetId.


134-134: LGTM! The addition of address and genesisHash as dependencies for the useEffect hook is appropriate.

This change ensures that the effect runs whenever address or genesisHash changes.


140-148: LGTM! The conditional rendering logic for ReservedDisplayBalance is appropriate.

This change ensures that the component renders correctly based on genesisHash and notOnNativeAsset.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5ce3a47 and baba7b2.

Files selected for processing (1)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (5 hunks)
Additional context used
Learnings (1)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-07-01T09:27:24.482Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
Additional comments not posted (1)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)

41-41: LGTM!

The WaitForReserved function component is well-implemented and does not need any changes.

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

Outside diff range and nitpick comments (6)
packages/extension-polkagate/src/hooks/useReservedDetails.ts (6)

Line range hint 121-162: Improve error handling for referenda fetch.

Consider adding more specific error messages to identify the source of the error.

- console.error(error);
+ console.error('Error fetching referenda:', error);

Line range hint 167-188: Improve error handling for bounty fetch.

Consider adding more specific error messages to identify the source of the error.

- console.error(error);
+ console.error('Error fetching bounty:', error);

Line range hint 193-214: Improve error handling for index fetch.

Consider adding more specific error messages to identify the source of the error.

- console.error(error);
+ console.error('Error fetching index:', error);

Line range hint 219-240: Improve error handling for multisig fetch.

Consider adding more specific error messages to identify the source of the error.

- console.error(error);
+ console.error('Error fetching multisig:', error);

Line range hint 245-272: Improve error handling for preimage fetch.

Consider adding more specific error messages to identify the source of the error.

- console.error(error);
+ console.error('Error fetching preimage:', error);

Line range hint 277-306: Improve error handling for society fetch.

Consider adding more specific error messages to identify the source of the error.

- console.error(error);
+ console.error('Error fetching society:', error);
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between baba7b2 and 7e37bed.

Files selected for processing (1)
  • packages/extension-polkagate/src/hooks/useReservedDetails.ts (8 hunks)
Additional comments not posted (2)
packages/extension-polkagate/src/hooks/useReservedDetails.ts (2)

14-14: Unused Import: Consider removing PROXY_CHAINS if not used.

The import statement includes PROXY_CHAINS, but it is not used in the provided code.

- import { ASSET_HUBS, PROXY_CHAINS } from '../util/constants';
+ import { ASSET_HUBS } from '../util/constants';

17-17: Unused Import: Consider removing amountToHuman if not used.

The import statement includes amountToHuman, but it is not used in the provided code.

- import { amountToHuman, amountToMachine } from '../util/utils';
+ import { amountToMachine } from '../util/utils';

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 7e37bed and 563ace5.

Files selected for processing (1)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 563ace5 and 25c00eb.

Files selected for processing (2)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (5 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (2 hunks)
Files skipped from review as they are similar to previous changes (1)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx
Additional context used
Learnings (1)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-07-01T09:27:24.482Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
Additional comments not posted (4)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (4)

13-13: Ensure the imported function isOnRelayChain is necessary.

Verify that isOnRelayChain is used in the code to avoid unnecessary imports.

Verification successful

The imported function isOnRelayChain is necessary and is used in the code.

  • The function is used in the onClick handler within the file.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify usage of `isOnRelayChain` in the file.

# Test: Search for `isOnRelayChain` usage. Expect: At least one usage.
rg --type js 'isOnRelayChain' packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx

Length of output: 314


129-129: Simplify the useMemo logic for notOnNativeAsset.

The useMemo logic for notOnNativeAsset can be simplified by removing the redundant typeof check.

-  const notOnNativeAsset = useMemo(() => (assetId !== undefined && assetId > 0) || assetToken?.toLowerCase() !== token?.toLowerCase() , [assetId, assetToken, token]);
+  const notOnNativeAsset = useMemo(() => assetId !== undefined && assetId > 0, [assetId, assetToken, token]);

Likely invalid or redundant comment.


9-9: Ensure all imports are necessary.

Verify that useMemo and useCallback are indeed used in the code to avoid unnecessary imports.

Verification successful

Imports are necessary and used in the code.

Both useMemo and useCallback are utilized in ReservedDisplayBalance.tsx, validating their presence in the import statement.

  • useMemo: Lines showing usage.
  • useCallback: Lines showing usage.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify usage of `useMemo` and `useCallback` in the file.

# Test: Search for `useMemo` and `useCallback` usage. Expect: At least one usage for each.
rg --type js 'useMemo|useCallback' packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx

Length of output: 470


22-25: Ensure the new properties assetId and assetToken are used appropriately.

Verify that assetId and assetToken are used correctly in the code to ensure they serve their intended purpose.

Verification successful

The properties assetId and assetToken are used appropriately in the ReservedDisplayBalance component.

  • assetId and assetToken are included in the function signature of ReservedDisplayBalance.
  • They are used in a useMemo hook to determine the value of notOnNativeAsset.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify usage of `assetId` and `assetToken` in the file.

# Test: Search for `assetId` and `assetToken` usage. Expect: At least one usage for each.
rg --type js 'assetId|assetToken' packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx

Length of output: 539

@Nick-1979
Copy link
Member

I was on Westend, and then switch to People chain:

Screenshot 2024-07-08 at 11 36 53

@AMIRKHANEF AMIRKHANEF marked this pull request as draft July 21, 2024 07:43
@AMIRKHANEF AMIRKHANEF closed this Sep 8, 2024
@AMIRKHANEF AMIRKHANEF force-pushed the AssetHubsReservedAmount branch from 579ba40 to f734a4a Compare September 8, 2024 05:07
@Nick-1979 Nick-1979 reopened this Oct 14, 2024
@Nick-1979 Nick-1979 added the WIP Work In Progress label Oct 14, 2024
@Nick-1979 Nick-1979 self-assigned this Oct 14, 2024
@AMIRKHANEF AMIRKHANEF closed this Nov 12, 2024
@AMIRKHANEF AMIRKHANEF force-pushed the AssetHubsReservedAmount branch from b7cc69d to a845d45 Compare November 12, 2024 07:11
@AMIRKHANEF AMIRKHANEF reopened this Nov 20, 2024
@AMIRKHANEF AMIRKHANEF changed the title Add some Asset hubs reserved amount feat: add some Asset hubs reserved amount Nov 20, 2024
@Nick-1979 Nick-1979 marked this pull request as ready for review November 30, 2024 11:54
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: 1

🧹 Outside diff range and nitpick comments (3)
packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (3)

Line range hint 89-106: Consider simplifying the balance selection logic

The current implementation of balancesToShow is complex and handles multiple edge cases, making it harder to maintain and understand. Consider breaking it down into smaller, more focused functions.

Here's a suggested refactoring:

- const balancesToShow = useMemo(() => {
-   if ((selectedAsset === undefined && balances) || (selectedAsset && balances === undefined)) {
-     return selectedAsset || balances;
-   }
-   if (selectedAsset && balances && (selectedAsset.genesisHash !== balances.genesisHash || (selectedAsset.genesisHash === balances.genesisHash && selectedAsset.assetId !== balances.assetId))) {
-     return selectedAsset?.assetId === assetId ? selectedAsset : balances;
-   }
-   if (!chainName || (balances?.genesisHash && selectedAsset?.genesisHash && balances.genesisHash !== selectedAsset.genesisHash)) {
-     return;
-   }
-   return balances?.date && selectedAsset?.date && balances.date > selectedAsset.date
-     ? { ...(selectedAsset || {}), ...(balances || {}) }
-     : { ...(balances || {}), ...(selectedAsset || {}) };
- }, [assetId, balances, chainName, selectedAsset]);
+ const balancesToShow = useMemo(() => {
+   const handleSingleBalance = () => {
+     if ((selectedAsset === undefined && balances) || (selectedAsset && balances === undefined)) {
+       return selectedAsset || balances;
+     }
+     return null;
+   };
+
+   const handleInconsistentBalances = () => {
+     if (selectedAsset && balances && (
+       selectedAsset.genesisHash !== balances.genesisHash || 
+       (selectedAsset.genesisHash === balances.genesisHash && selectedAsset.assetId !== balances.assetId)
+     )) {
+       return selectedAsset?.assetId === assetId ? selectedAsset : balances;
+     }
+     return null;
+   };
+
+   const handleChainMismatch = () => {
+     if (!chainName || (
+       balances?.genesisHash && 
+       selectedAsset?.genesisHash && 
+       balances.genesisHash !== selectedAsset.genesisHash
+     )) {
+       return undefined;
+     }
+     return null;
+   };
+
+   const handleMergedBalances = () => {
+     return balances?.date && selectedAsset?.date && balances.date > selectedAsset.date
+       ? { ...(selectedAsset || {}), ...(balances || {}) }
+       : { ...(balances || {}), ...(selectedAsset || {}) };
+   };
+
+   return handleSingleBalance() ?? 
+          handleInconsistentBalances() ?? 
+          handleChainMismatch() ?? 
+          handleMergedBalances();
+ }, [assetId, balances, chainName, selectedAsset]);

Line range hint 108-142: Consider consolidating asset selection logic

The current implementation uses multiple useEffect hooks to handle asset selection and chain switching. This could lead to potential race conditions and makes the logic harder to follow.

Consider consolidating the asset selection logic into a custom hook:

function useAssetSelection({
  genesisHash,
  paramAssetId,
  accountAssets,
  selectedAsset,
  assetId
}) {
  const [assetIdOnAssetHub, setAssetIdOnAssetHub] = useState<number | string>();

  // Handle chain switching
  useEffect(() => {
    if (genesisHash !== selectedAsset?.genesisHash) {
      setAssetIdOnAssetHub(undefined);
      setSelectedAsset(undefined);
    }
  }, [genesisHash, selectedAsset?.genesisHash]);

  // Handle asset selection from URL params
  useEffect(() => {
    if (!paramAssetId || !genesisHash || selectedAsset) {
      return;
    }

    const targetAssetId = assetId ?? paramAssetId;
    
    if (accountAssets && targetAssetId >= 0) {
      const asset = accountAssets.find(
        ({ assetId, genesisHash: _genesisHash }) => 
          String(assetId) === String(targetAssetId) && 
          genesisHash === _genesisHash
      );

      asset && setSelectedAsset(asset);
    }
  }, [genesisHash, accountAssets, assetId, paramAssetId, selectedAsset]);

  return {
    assetIdOnAssetHub,
    setAssetIdOnAssetHub
  };
}

This refactoring:

  1. Encapsulates asset selection logic in a reusable hook
  2. Makes the logic easier to test and maintain
  3. Reduces the risk of race conditions

Line range hint 43-435: Consider breaking down AccountDetails into smaller components

The AccountDetails component has grown to handle multiple responsibilities including:

  • Asset management
  • Balance display
  • Staking functionality
  • Account operations

This makes it harder to maintain and test. Consider splitting it into smaller, more focused components.

Suggested architecture:

  1. Create separate components for:
    • AssetManagement (handling asset selection and balance display)
    • StakingSection (handling staking-related functionality)
    • AccountOperations (handling account-related operations)
  2. Create custom hooks for:
    • useAssetSelection (as suggested above)
    • useBalanceManagement
    • useStakingOperations

This would improve:

  • Code maintainability
  • Testing capabilities
  • Reusability
  • Performance (through more granular rendering)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 25c00eb and 6fc6c8f.

📒 Files selected for processing (2)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (5 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (1 hunks)
🧰 Additional context used
📓 Learnings (1)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-11-12T04:57:59.388Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
🔇 Additional comments (2)
packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (1)

267-271: Verify prop types for ReservedDisplayBalance

New props assetId and assetToken have been added to ReservedDisplayBalance. Ensure these props are properly typed in the component's interface.

✅ Verification successful

Props are properly typed for ReservedDisplayBalance

The Props interface is correctly defined with proper types for both new props:

  • assetId is typed as string | number | undefined
  • assetToken is typed as string | undefined
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check ReservedDisplayBalance component prop types

# Search for ReservedDisplayBalance component definition
ast-grep --pattern 'interface $interface {
  $$$
  assetId?: $type
  assetToken?: $type
  $$$
}'

# Search for ReservedDisplayBalance component implementation
ast-grep --pattern 'function ReservedDisplayBalance({ assetId, assetToken, $$$ }: $props) {
  $$$
}'

Length of output: 201


Script:

#!/bin/bash
# Let's try a different approach to find the ReservedDisplayBalance component and its type definitions

# First, let's find the file containing ReservedDisplayBalance
rg -l "ReservedDisplayBalance"

# Then let's look at the content of files containing this component
rg -A 10 -B 10 "ReservedDisplayBalance" 

Length of output: 9230


Script:

#!/bin/bash
# Let's look at the Props interface definition for ReservedDisplayBalance
cat packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx | rg -B 10 "function ReservedDisplayBalance"

Length of output: 498


Script:

#!/bin/bash
# Let's look at the entire file content to find the Props interface
cat packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx

Length of output: 6189

packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)

136-136: Ensure proper handling of undefined address

The useReservedDetails hook is called with address which may be undefined. This could lead to runtime errors if address is undefined.

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

🧹 Outside diff range and nitpick comments (7)
packages/extension-polkagate/src/fullscreen/accountDetails/components/DisplayBalance.tsx (1)

Line range hint 67-71: Fix incorrect logical condition affecting icon rotation

The current condition openCollapse !== undefined || disabled could cause unintended icon rotations when the component is disabled but openCollapse is undefined. The disabled state should not affect the rotation logic.

Apply this fix to correctly handle the icon rotation:

-                  transform:
-                    openCollapse !== undefined || disabled
-                      ? openCollapse
-                        ? 'rotate(-90deg)'
-                        : 'rotate(90deg)'
-                      : 'none',
+                  transform:
+                    openCollapse !== undefined
+                      ? openCollapse
+                        ? 'rotate(-90deg)'
+                        : 'rotate(90deg)'
+                      : 'none',
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (5)

22-25: Consider refining the assetId type for better type safety.

The assetId prop accepts multiple types (string | number | undefined), which could lead to inconsistent comparisons. Consider using a single type, preferably number, and handling the type conversion at the component's boundary.

-  assetId: string | number | undefined,
+  assetId: number | undefined,

69-77: Extract common computation to avoid duplication.

The reasons computation is duplicated in both useEffect and useMemo. Consider extracting it into a separate useMemo to improve maintainability and performance.

+const reasons = useMemo(() => Object.values(reservedDetails), [reservedDetails]);
+
 useEffect(() => {
-  const reasons = Object.values(reservedDetails);
   const isStillFetchingSomething = reasons.some((reason) => reason === undefined);
   setStillFetching(isStillFetchingSomething);
-}, [reservedDetails]);
+}, [reasons]);

79-102: Enhance code readability with more descriptive comments and type annotations.

While the logic is correct, the code could benefit from:

  1. More descriptive comments explaining the business logic
  2. Type annotations for intermediate variables
  3. Consistent return type annotation
-const reasonsToShow = useMemo(() => {
+const reasonsToShow = useMemo((): Reserved | null | undefined => {
   const reasons = Object.values(reservedDetails);

-  // details are still fetching
+  // Return undefined while details are being fetched
   if (reasons.length === 0) {
     return undefined;
   }

   const noReason = reasons.every((reason) => reason === null);

-  // no reasons found
+  // Return null when all reasons are explicitly null (no reserved amounts)
   if (noReason) {
     return null;
   }

-  // filter fetched reasons
+  // Return only non-zero reserved amounts
   const filteredReservedDetails = Object.fromEntries(
     Object.entries(reservedDetails).filter(([_key, value]) => value && !value.isZero())
   );

   return Object.values(filteredReservedDetails).length > 0
     ? filteredReservedDetails
     : undefined;
 }, [reservedDetails]);

Line range hint 111-130: Simplify conditional rendering logic.

The current implementation has redundant checks and could be simplified:

  1. Remove unnecessary optional chaining
  2. Use early returns for better readability
-{reasonsToShow
-  ? <Grid container direction='column' item>
-    {Object.entries(reasonsToShow)?.map(([key, value], index) => (
+{reasonsToShow === null ? (
+  <Typography fontSize='16px' fontWeight={500} width='100%'>
+    {t('No reasons found!')}
+  </Typography>
+) : !reasonsToShow ? (
+  <WaitForReserved rows={2} />
+) : (
+  <Grid container direction='column' item>
+    {Object.entries(reasonsToShow).map(([key, value], index) => (
       <Grid container item key={index} sx={{ fontSize: '16px' }}>
         <Grid item sx={{ fontWeight: 300 }} xs={4}>
           {toTitleCase(key)}
         </Grid>
         <Grid fontWeight={400} item>
           <ShowValue height={20} value={value?.toHuman()} />
         </Grid>
       </Grid>
     ))
     }
     {stillFetching && <WaitForReserved rows={1} />}
   </Grid>
-  : reasonsToShow === null
-    ? <Typography fontSize='16px' fontWeight={500} width='100%'>
-      {t('No reasons found!')}
-    </Typography>
-    : <WaitForReserved rows={2} />
)}

142-142: Simplify the notOnNativeAsset logic.

The current implementation can be simplified and made more readable by breaking down the conditions.

-const notOnNativeAsset = useMemo(() => (assetId !== undefined && Number(assetId) > 0) || assetToken?.toLowerCase() !== token?.toLowerCase(), [assetId, assetToken, token]);
+const notOnNativeAsset = useMemo(() => {
+  const isNonZeroAssetId = assetId !== undefined && Number(assetId) > 0;
+  const isNonNativeToken = assetToken?.toLowerCase() !== token?.toLowerCase();
+  return isNonZeroAssetId || isNonNativeToken;
+}, [assetId, assetToken, token]);
packages/extension-polkagate/src/hooks/useReservedDetails.ts (1)

456-457: Enhance TypeScript typings for myAssetsMetadata

The casting using as unknown as (AssetMetadata | undefined)[] suggests that TypeScript might not be inferring the types correctly. Consider updating the function signatures or adding proper generics to the API calls to eliminate the need for explicit type casting.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 6fc6c8f and 2eddc22.

📒 Files selected for processing (3)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/DisplayBalance.tsx (1 hunks)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (5 hunks)
  • packages/extension-polkagate/src/hooks/useReservedDetails.ts (4 hunks)
🧰 Additional context used
📓 Learnings (2)
packages/extension-polkagate/src/fullscreen/accountDetails/components/DisplayBalance.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-11-12T04:57:59.388Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)
Learnt from: AMIRKHANEF
PR: PolkaGate/extension#1394
File: packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx:0-0
Timestamp: 2024-11-12T04:57:59.388Z
Learning: When checking for NaN values, always use `Number.isNaN` instead of `isNaN` to avoid unexpected type coercions.
🪛 Biome (1.9.4)
packages/extension-polkagate/src/hooks/useReservedDetails.ts

[error] 9-9: Do not shadow the global "Proxy" property.

Consider renaming this variable. It's easy to confuse the origin of variables when they're named after a known global.

(lint/suspicious/noShadowRestrictedNames)

🔇 Additional comments (2)
packages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx (1)

176-176: Good use of React.memo for performance optimization.

The component is correctly memoized to prevent unnecessary re-renders.

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

43-53: The setValue function correctly manages state updates

The setValue function appropriately handles different states of value, ensuring that zero values are converted to null and others are converted to Balance types. This maintains consistency in the reserved state management.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
WIP Work In Progress
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants