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

Add some Asset hubs reserved amount #1394

Draft
wants to merge 16 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 ReservedDetails component to filter and display reasons dynamically.
    • Introduced new state logic to conditionally render UI elements based on asset parameters.
    • Added support for displaying various reserved asset types, including NFTs and unique NFT classes.
  • Improvements

    • Updated the useReservedDetails hook to manage state and handle API queries for multiple entities.
    • Enhanced AccountDetails to include new asset-related properties for more detailed information display.

Copy link
Contributor

coderabbitai bot commented Jun 26, 2024

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The updates enhance the ReservedDisplayBalance component to show filtered reasons based on paramAssetId, updating its state and rendering logic. The useReservedDetails hook has been redesigned for better state management and additional API queries. Corresponding props for assetId and assetToken are added to the AccountDetails component.

Changes

File Path Change Summary
.../ReservedDisplayBalance.tsx Added useParams hook, introduced new state variable notOnNativeAsset, modified logic to filter and display reasons; added new props assetId and assetToken.
.../useReservedDetails.ts Enhanced state management and API query handling for multiple entities; added decimal, amountToHuman, amountToMachine imports; modified function and callbacks.
.../accountDetails/index.tsx Added new props assetId and assetToken to the ReservedDisplayBalance component.

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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
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';

Comment on lines +43 to +53
const setValue = useCallback((item: string, value: BN | null | undefined) => {
setReserved((prev) => {
const newState = { ...prev };

newState[item] = value
? value.isZero() ? null : toBalance(value)
: value;

return newState;
});
}, [toBalance]);
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor the setValue function to improve clarity and efficiency.

The function can be simplified to enhance readability and reduce redundancy.

- setReserved((prev) => {
-   const newState = { ...prev };
-   newState[item] = value ? (value.isZero() ? null : toBalance(value)) : value;
-   return newState;
- });
+ setReserved((prev) => ({ ...prev, [item]: value ? (value.isZero() ? null : toBalance(value)) : value }));
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.

Suggested change
const setValue = useCallback((item: string, value: BN | null | undefined) => {
setReserved((prev) => {
const newState = { ...prev };
newState[item] = value
? value.isZero() ? null : toBalance(value)
: value;
return newState;
});
}, [toBalance]);
const setValue = useCallback((item: string, value: BN | null | undefined) => {
setReserved((prev) => ({ ...prev, [item]: value ? (value.isZero() ? null : toBalance(value)) : value }));
}, [toBalance]);

Comment on lines 87 to 98
setValue('identity', undefined);

api.query.proxy.proxies(formatted).then((p) => {
const mayBeDeposit = p?.[1] as BN;

if (!mayBeDeposit?.isZero()) {
setReserved((prev) => {
prev.proxy = toBalance(mayBeDeposit);

return prev;
});
}
}).catch(console.error);
setValue('proxy', mayBeDeposit);
}).catch((error) => {
console.error(error);
setValue('proxy', null);
});
} else {
setValue('proxy', null);
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve error handling for proxy fetch.

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

- console.error(error);
+ console.error('Error fetching proxy:', error);
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.

Suggested change
setValue('identity', undefined);
api.query.proxy.proxies(formatted).then((p) => {
const mayBeDeposit = p?.[1] as BN;
if (!mayBeDeposit?.isZero()) {
setReserved((prev) => {
prev.proxy = toBalance(mayBeDeposit);
return prev;
});
}
}).catch(console.error);
setValue('proxy', mayBeDeposit);
}).catch((error) => {
console.error(error);
setValue('proxy', null);
});
} else {
setValue('proxy', null);
setValue('identity', undefined);
api.query.proxy.proxies(formatted).then((p) => {
const mayBeDeposit = p?.[1] as BN;
setValue('proxy', mayBeDeposit);
}).catch((error) => {
console.error('Error fetching proxy:', error);
setValue('proxy', null);
});
} else {
setValue('proxy', null);

Comment on lines +102 to +117
if (api.query?.recovery) {
setValue('recovery', undefined);

api.query.recovery.recoverable(formatted).then((r) => {
const recoveryInfo = r.isSome ? r.unwrap() as unknown as PalletRecoveryRecoveryConfig : null;

recoveryInfo?.deposit && setReserved((prev) => {
prev.recovery = toBalance((recoveryInfo.deposit as unknown as BN).add(activeLost?.deposit as unknown as BN || BN_ZERO));
const recoveryDeposit = (recoveryInfo?.deposit as unknown as BN || BN_ZERO).add(activeLost?.deposit as unknown as BN || BN_ZERO);

return prev;
setValue('recovery', recoveryDeposit);
}).catch((error) => {
console.error(error);
setValue('recovery', null);
});
}).catch(console.error);
} else {
setValue('recovery', null);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve error handling for recovery fetch.

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

- console.error(error);
+ console.error('Error fetching recovery:', error);
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.

Suggested change
if (api.query?.recovery) {
setValue('recovery', undefined);
api.query.recovery.recoverable(formatted).then((r) => {
const recoveryInfo = r.isSome ? r.unwrap() as unknown as PalletRecoveryRecoveryConfig : null;
recoveryInfo?.deposit && setReserved((prev) => {
prev.recovery = toBalance((recoveryInfo.deposit as unknown as BN).add(activeLost?.deposit as unknown as BN || BN_ZERO));
const recoveryDeposit = (recoveryInfo?.deposit as unknown as BN || BN_ZERO).add(activeLost?.deposit as unknown as BN || BN_ZERO);
return prev;
setValue('recovery', recoveryDeposit);
}).catch((error) => {
console.error(error);
setValue('recovery', null);
});
}).catch(console.error);
} else {
setValue('recovery', null);
}
if (api.query?.recovery) {
setValue('recovery', undefined);
api.query.recovery.recoverable(formatted).then((r) => {
const recoveryInfo = r.isSome ? r.unwrap() as unknown as PalletRecoveryRecoveryConfig : null;
const recoveryDeposit = (recoveryInfo?.deposit as unknown as BN || BN_ZERO).add(activeLost?.deposit as unknown as BN || BN_ZERO);
setValue('recovery', recoveryDeposit);
}).catch((error) => {
console.error('Error fetching recovery:', error);
setValue('recovery', null);
});
} else {
setValue('recovery', null);
}

Comment on lines 63 to 83
if (api.query?.identity?.identityOf) {
setValue('identity', undefined);

const subs = await api.query.identity.subsOf(formatted);
api.query.identity.identityOf(formatted).then(async (id) => {
const basicDeposit = api.consts.identity.basicDeposit as unknown as BN;
const subAccountDeposit = api.consts.identity.subAccountDeposit as unknown as BN;

const subAccountsDeposit = (subs ? subs[0] : BN_ZERO) as unknown as BN;
const subs = await api.query.identity.subsOf(formatted);

const sum = (basicDeposit.add(subAccountsDeposit)) as unknown as BN;
const subAccountsDeposit = (subs ? subs[0] : BN_ZERO) as unknown as BN;

!id.isEmpty && setReserved((prev) => {
prev.identity = toBalance(sum);
const sum = (basicDeposit.add(subAccountsDeposit)) as unknown as BN;

return prev;
setValue('identity', sum);
}).catch((error) => {
console.error(error);
setValue('identity', null);
});
}).catch(console.error);
} else {
setValue('identity', null);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve error handling for identity fetch.

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

- console.error(error);
+ console.error('Error fetching identity:', error);
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.

Suggested change
if (api.query?.identity?.identityOf) {
setValue('identity', undefined);
const subs = await api.query.identity.subsOf(formatted);
api.query.identity.identityOf(formatted).then(async (id) => {
const basicDeposit = api.consts.identity.basicDeposit as unknown as BN;
const subAccountDeposit = api.consts.identity.subAccountDeposit as unknown as BN;
const subAccountsDeposit = (subs ? subs[0] : BN_ZERO) as unknown as BN;
const subs = await api.query.identity.subsOf(formatted);
const sum = (basicDeposit.add(subAccountsDeposit)) as unknown as BN;
const subAccountsDeposit = (subs ? subs[0] : BN_ZERO) as unknown as BN;
!id.isEmpty && setReserved((prev) => {
prev.identity = toBalance(sum);
const sum = (basicDeposit.add(subAccountsDeposit)) as unknown as BN;
return prev;
setValue('identity', sum);
}).catch((error) => {
console.error(error);
setValue('identity', null);
});
}).catch(console.error);
} else {
setValue('identity', null);
}
if (api.query?.identity?.identityOf) {
setValue('identity', undefined);
api.query.identity.identityOf(formatted).then(async (id) => {
const basicDeposit = api.consts.identity.basicDeposit as unknown as BN;
const subAccountDeposit = api.consts.identity.subAccountDeposit as unknown as BN;
const subs = await api.query.identity.subsOf(formatted);
const subAccountsDeposit = (subs ? subs[0] : BN_ZERO) as unknown as BN;
const sum = (basicDeposit.add(subAccountsDeposit)) as unknown as BN;
setValue('identity', sum);
}).catch((error) => {
console.error('Error fetching identity:', error);
setValue('identity', null);
});
} else {
setValue('identity', null);
}

Comment on lines +371 to +389
if (api.query?.uniques) {
setValue('uniques_NFT', null);

api.query.uniques.class.entries().then((classes) => {
const myClasses = classes.filter(([uniquesId, uniquesInfo]) => String(uniquesInfo.toPrimitive().owner) === formatted).map(([uniquesId, uniquesInfo]) => uniquesInfo.toPrimitive());

const totalClassesDeposit = myClasses.reduce((acc, myClass) => {
const depositAsBn = amountToMachine(String(myClass.totalDeposit / (10 ** decimal)), decimal);

return acc.add(depositAsBn);
}, BN_ZERO);

setValue('uniques_NFT', totalClassesDeposit);
}).catch((error) => {
console.error(error);
setValue('uniques_NFT', null);
});
} else {
setValue('uniques_NFT', null);
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix error handling and improve performance for unique NFT fetch.

The code for fetching unique NFTs has redundant error handling and can be optimized for performance.

- setValue('uniques_NFT', null);
+ setValue('uniques_NFT', undefined);

- api.query.uniques.class.entries().then((classes) => {
+ try {
+   const classEntries = await api.query.uniques.class.entries();
+   const myClasses = classEntries.filter(([uniquesId, uniquesInfo]) => String(uniquesInfo.toPrimitive().owner) === formatted).map(([uniquesId, uniquesInfo]) => uniquesInfo.toPrimitive());
+   const totalClassesDeposit = myClasses.reduce((acc, myClass) => acc.add(amountToMachine(String(myClass.totalDeposit / (10 ** decimal)), decimal)), BN_ZERO);
+   setValue('uniques_NFT', totalClassesDeposit);
+ } catch (error) {
+   console.error('Error fetching unique NFTs:', error);
+   setValue('uniques_NFT', null);
+ }
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.

Suggested change
if (api.query?.uniques) {
setValue('uniques_NFT', null);
api.query.uniques.class.entries().then((classes) => {
const myClasses = classes.filter(([uniquesId, uniquesInfo]) => String(uniquesInfo.toPrimitive().owner) === formatted).map(([uniquesId, uniquesInfo]) => uniquesInfo.toPrimitive());
const totalClassesDeposit = myClasses.reduce((acc, myClass) => {
const depositAsBn = amountToMachine(String(myClass.totalDeposit / (10 ** decimal)), decimal);
return acc.add(depositAsBn);
}, BN_ZERO);
setValue('uniques_NFT', totalClassesDeposit);
}).catch((error) => {
console.error(error);
setValue('uniques_NFT', null);
});
} else {
setValue('uniques_NFT', null);
if (api.query?.uniques) {
setValue('uniques_NFT', undefined);
try {
const classEntries = await api.query.uniques.class.entries();
const myClasses = classEntries.filter(([uniquesId, uniquesInfo]) => String(uniquesInfo.toPrimitive().owner) === formatted).map(([uniquesId, uniquesInfo]) => uniquesInfo.toPrimitive());
const totalClassesDeposit = myClasses.reduce((acc, myClass) => acc.add(amountToMachine(String(myClass.totalDeposit / (10 ** decimal)), decimal)), BN_ZERO);
setValue('uniques_NFT', totalClassesDeposit);
} catch (error) {
console.error('Error fetching unique NFTs:', error);
setValue('uniques_NFT', null);
}
} else {
setValue('uniques_NFT', null);

Comment on lines +337 to +368
if (api.query?.nfts) {
setValue('NFT', null);

api.query.nfts.item.entries().then(async (nft) => {

const myNFTs = nft.filter(([ntfId, nftInfo]) => String(nftInfo.toPrimitive().deposit.account) === formatted).map(([ntfId, nftInfo]) => [ntfId.toHuman(), nftInfo.toPrimitive()]);
const nftDepositRequests = myNFTs.map(([nftId, nftInfo]) => api.query.nfts.itemMetadataOf(...nftId));
const nftDepositAmount = (await Promise.all(nftDepositRequests)).map((deposit) => deposit.toPrimitive().deposit.amount);

const totalNftDeposits = nftDepositAmount.reduce((acc, deposit) => {
const depositAsBn = amountToMachine(String(deposit / (10 ** decimal)), decimal);

return acc.add(depositAsBn);
}, BN_ZERO);

const myNFTDeposits = myNFTs.map(([ntfId, nftInfo]) => nftInfo.deposit.amount as number);
const totalNFTDeposit = myNFTDeposits.reduce((acc, deposit) => {
const depositAsBn = amountToMachine(String(deposit / (10 ** decimal)), decimal);

return acc.add(depositAsBn);
}, BN_ZERO);

const finalNFTDeposit = totalNFTDeposit.add(totalNftDeposits);

setValue('NFT', finalNFTDeposit);
}).catch((error) => {
console.error(error);
setValue('NFT', null);
});
} else {
setValue('NFT', null);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix error handling and improve performance for NFT fetch.

The code for fetching NFTs has redundant error handling and can be optimized for performance.

- setValue('NFT', null);
+ setValue('NFT', undefined);

- api.query.nfts.item.entries().then(async (nft) => {
+ try {
+   const nftEntries = await api.query.nfts.item.entries();
+   const myNFTs = nftEntries.filter(([ntfId, nftInfo]) => String(nftInfo.toPrimitive().deposit.account) === formatted).map(([ntfId, nftInfo]) => [ntfId.toHuman(), nftInfo.toPrimitive()]);
+   const nftDepositRequests = myNFTs.map(([nftId, nftInfo]) => api.query.nfts.itemMetadataOf(...nftId));
+   const nftDepositAmount = (await Promise.all(nftDepositRequests)).map((deposit) => deposit.toPrimitive().deposit.amount);
+   const totalNftDeposits = nftDepositAmount.reduce((acc, deposit) => acc.add(amountToMachine(String(deposit / (10 ** decimal)), decimal)), BN_ZERO);
+   const myNFTDeposits = myNFTs.map(([ntfId, nftInfo]) => nftInfo.deposit.amount as number);
+   const totalNFTDeposit = myNFTDeposits.reduce((acc, deposit) => acc.add(amountToMachine(String(deposit / (10 ** decimal)), decimal)), BN_ZERO);
+   const finalNFTDeposit = totalNFTDeposit.add(totalNftDeposits);
+   setValue('NFT', finalNFTDeposit);
+ } catch (error) {
+   console.error('Error fetching NFTs:', error);
+   setValue('NFT', null);
+ }
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.

Suggested change
if (api.query?.nfts) {
setValue('NFT', null);
api.query.nfts.item.entries().then(async (nft) => {
const myNFTs = nft.filter(([ntfId, nftInfo]) => String(nftInfo.toPrimitive().deposit.account) === formatted).map(([ntfId, nftInfo]) => [ntfId.toHuman(), nftInfo.toPrimitive()]);
const nftDepositRequests = myNFTs.map(([nftId, nftInfo]) => api.query.nfts.itemMetadataOf(...nftId));
const nftDepositAmount = (await Promise.all(nftDepositRequests)).map((deposit) => deposit.toPrimitive().deposit.amount);
const totalNftDeposits = nftDepositAmount.reduce((acc, deposit) => {
const depositAsBn = amountToMachine(String(deposit / (10 ** decimal)), decimal);
return acc.add(depositAsBn);
}, BN_ZERO);
const myNFTDeposits = myNFTs.map(([ntfId, nftInfo]) => nftInfo.deposit.amount as number);
const totalNFTDeposit = myNFTDeposits.reduce((acc, deposit) => {
const depositAsBn = amountToMachine(String(deposit / (10 ** decimal)), decimal);
return acc.add(depositAsBn);
}, BN_ZERO);
const finalNFTDeposit = totalNFTDeposit.add(totalNftDeposits);
setValue('NFT', finalNFTDeposit);
}).catch((error) => {
console.error(error);
setValue('NFT', null);
});
} else {
setValue('NFT', null);
}
if (api.query?.nfts) {
setValue('NFT', undefined);
try {
const nftEntries = await api.query.nfts.item.entries();
const myNFTs = nftEntries.filter(([ntfId, nftInfo]) => String(nftInfo.toPrimitive().deposit.account) === formatted).map(([ntfId, nftInfo]) => [ntfId.toHuman(), nftInfo.toPrimitive()]);
const nftDepositRequests = myNFTs.map(([nftId, nftInfo]) => api.query.nfts.itemMetadataOf(...nftId));
const nftDepositAmount = (await Promise.all(nftDepositRequests)).map((deposit) => deposit.toPrimitive().deposit.amount);
const totalNftDeposits = nftDepositAmount.reduce((acc, deposit) => acc.add(amountToMachine(String(deposit / (10 ** decimal)), decimal)), BN_ZERO);
const myNFTDeposits = myNFTs.map(([ntfId, nftInfo]) => nftInfo.deposit.amount as number);
const totalNFTDeposit = myNFTDeposits.reduce((acc, deposit) => acc.add(amountToMachine(String(deposit / (10 ** decimal)), decimal)), BN_ZERO);
const finalNFTDeposit = totalNFTDeposit.add(totalNftDeposits);
setValue('NFT', finalNFTDeposit);
} catch (error) {
console.error('Error fetching NFTs:', error);
setValue('NFT', null);
}
} else {
setValue('NFT', null);
}

Comment on lines +312 to +332
api.query.assets.asset.entries().then(async (assets) => {
const myAssets = assets.filter((asset) => asset[1].toHuman()['owner'] === formatted);
const myAssetsId = myAssets.map(([assetId, assetInfo]) => String(assetId.toHuman()[0]).replaceAll(',', ''));
const assetDeposit = api.consts.assets.assetDeposit as BN;

const myAssetsMetadata = await Promise.all(myAssetsId.map((assetId) => api.query.assets.metadata(assetId)));

const totalAssetDeposit = myAssetsMetadata.reduce((acc, metadata) => {
const metaDeposit = metadata.deposit as BN;

return acc.add(metaDeposit);
}, BN_ZERO);

const finalDeposit = totalAssetDeposit.add(assetDeposit.muln(myAssetsId.length));

setValue('assets', finalDeposit);
}).catch((error) => {
console.error(error);
setValue('assets', null);
});
} else {
Copy link
Contributor

Choose a reason for hiding this comment

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

Optimize asset handling logic in the assets section.

The logic for handling asset details can be streamlined to reduce complexity and improve performance.

- const myAssetsMetadata = await Promise.all(myAssetsId.map((assetId) => api.query.assets.metadata(assetId)));
- const totalAssetDeposit = myAssetsMetadata.reduce((acc, metadata) => {
-   const metaDeposit = metadata.deposit as BN;
-   return acc.add(metaDeposit);
- }, BN_ZERO);
- const finalDeposit = totalAssetDeposit.add(assetDeposit.muln(myAssetsId.length));
+ const totalAssetDeposit = await myAssetsId.reduce(async (accPromise, assetId) => {
+   const acc = await accPromise;
+   const metadata = await api.query.assets.metadata(assetId);
+   return acc.add(metadata.deposit as BN);
+ }, Promise.resolve(BN_ZERO));
+ const finalDeposit = totalAssetDeposit.add(assetDeposit.muln(myAssetsId.length));
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.

Suggested change
api.query.assets.asset.entries().then(async (assets) => {
const myAssets = assets.filter((asset) => asset[1].toHuman()['owner'] === formatted);
const myAssetsId = myAssets.map(([assetId, assetInfo]) => String(assetId.toHuman()[0]).replaceAll(',', ''));
const assetDeposit = api.consts.assets.assetDeposit as BN;
const myAssetsMetadata = await Promise.all(myAssetsId.map((assetId) => api.query.assets.metadata(assetId)));
const totalAssetDeposit = myAssetsMetadata.reduce((acc, metadata) => {
const metaDeposit = metadata.deposit as BN;
return acc.add(metaDeposit);
}, BN_ZERO);
const finalDeposit = totalAssetDeposit.add(assetDeposit.muln(myAssetsId.length));
setValue('assets', finalDeposit);
}).catch((error) => {
console.error(error);
setValue('assets', null);
});
} else {
api.query.assets.asset.entries().then(async (assets) => {
const myAssets = assets.filter((asset) => asset[1].toHuman()['owner'] === formatted);
const myAssetsId = myAssets.map(([assetId, assetInfo]) => String(assetId.toHuman()[0]).replaceAll(',', ''));
const assetDeposit = api.consts.assets.assetDeposit as BN;
const totalAssetDeposit = await myAssetsId.reduce(async (accPromise, assetId) => {
const acc = await accPromise;
const metadata = await api.query.assets.metadata(assetId);
return acc.add(metadata.deposit as BN);
}, Promise.resolve(BN_ZERO));
const finalDeposit = totalAssetDeposit.add(assetDeposit.muln(myAssetsId.length));
setValue('assets', finalDeposit);
}).catch((error) => {
console.error(error);
setValue('assets', null);
});
} else {

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

Comment on lines 124 to 135
export default function ReservedDisplayBalance({ address, amount, assetToken, assetId, disabled, price }: Props): React.ReactElement {
const { t } = useTranslation();
const reservedDetails = useReservedDetails(address);
const { decimal, genesisHash, token } = useInfo(address);

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

const [showReservedDetails, setShowReservedDetails] = useState<boolean>(false);

useEffect(() => {
setShowReservedDetails(false); // to reset collapsed area on chain change
}, [genesisHash]);
}, [address, genesisHash, assetId]);
Copy link
Contributor

Choose a reason for hiding this comment

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

Ensure proper handling of undefined addresses.

The useReservedDetails hook is called with address cast to a string without checking if address is defined. This could lead to runtime errors if address is undefined.

-  const reservedDetails = useReservedDetails(address);
+  const reservedDetails = useReservedDetails(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.

Suggested change
export default function ReservedDisplayBalance({ address, amount, assetToken, assetId, disabled, price }: Props): React.ReactElement {
const { t } = useTranslation();
const reservedDetails = useReservedDetails(address);
const { decimal, genesisHash, token } = useInfo(address);
const notOnNativeAsset = useMemo(() => (assetId !== undefined && assetId > 0) || assetToken?.toLowerCase() !== token?.toLowerCase() , [assetId, assetToken, token]);
const [showReservedDetails, setShowReservedDetails] = useState<boolean>(false);
useEffect(() => {
setShowReservedDetails(false); // to reset collapsed area on chain change
}, [genesisHash]);
}, [address, genesisHash, assetId]);
export default function ReservedDisplayBalance({ address, amount, assetToken, assetId, disabled, price }: Props): React.ReactElement {
const { t } = useTranslation();
const reservedDetails = useReservedDetails(address ?? '');
const { decimal, genesisHash, token } = useInfo(address);
const notOnNativeAsset = useMemo(() => (assetId !== undefined && assetId > 0) || assetToken?.toLowerCase() !== token?.toLowerCase() , [assetId, assetToken, token]);
const [showReservedDetails, setShowReservedDetails] = useState<boolean>(false);
useEffect(() => {
setShowReservedDetails(false); // to reset collapsed area on chain change
}, [address, genesisHash, assetId]);

Comment on lines 70 to 90
const reasonsToShow = useMemo(() => {
const details = Object.values(reservedDetails);

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
}, [reservedDetails]);
Copy link
Contributor

Choose a reason for hiding this comment

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

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;
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.

Suggested change
const reasonsToShow = useMemo(() => {
const details = Object.values(reservedDetails);
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
}, [reservedDetails]);
const reasonsToShow = useMemo(() => {
const details = Object.values(reservedDetails);
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;
}, [reservedDetails]);

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