-
Notifications
You must be signed in to change notification settings - Fork 5
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
base: main
Are you sure you want to change the base?
Conversation
WalkthroughThe updates enhance the Changes
Possibly related PRs
Suggested labels
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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
, anduseParams
aligns with the new functionality related to handling dynamic UI states and parameters.
15-15
: Use ofuseParams
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 ongenesisHash
andnotOnNativeAsset
.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 FileThe 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.
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Outdated
Show resolved
Hide resolved
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Outdated
Show resolved
Hide resolved
@AMIRKHANEF |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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)
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Outdated
Show resolved
Hide resolved
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Outdated
Show resolved
Hide resolved
Eliminate // @ts-nocheck Apply code rabit suggestions
4c3d72a
to
230133e
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Outside diff range and nitpick comments (3)
packages/extension-polkagate/src/components/Assets.tsx (3)
Line range hint
23-23
: Fix the type ofsetAssetId
prop.The
setAssetId
prop should be typed asReact.Dispatch<React.SetStateAction<number | undefined>>
instead ofReact.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 whereaddress
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
: InitializeisLoading
state properly.The
isLoading
state is declared but not initialized. Initialize it tofalse
.- const [isLoading, setLoading] = useState<boolean>(); + const [isLoading, setLoading] = useState<boolean>(false);
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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
andTheme
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 unnecessaryuseCallback
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 unnecessaryuseCallback
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 unnecessaryBN
import.The
BN
class is imported but not used in the file.- import { BN } from '@polkadot/util';
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 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
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 handleundefined
andnull
to avoid rendering issues or errors in edge cases.
57-77
: Revisit the conditional logic inuseMemo
.The logic inside
useMemo
has been a point of contention. The conditionsdetails.length === 0
anddetails.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 ofNumber.isNaN
for NaN checking.This is a good practice and aligns with previous learnings to avoid type coercion issues.
69-89
: Simplify conditional logic inuseMemo
.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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 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
, anduseAssetHubAssets
hooks are called withaddress
cast to a string without checking ifaddress
is defined. This could lead to runtime errors ifaddress
isnull
orundefined
.- 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
anduseTokenPrice
hooks are called withaddress
cast to a string without checking ifaddress
is defined. This could lead to runtime errors ifaddress
isundefined
.- 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 inuseMemo
.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
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 withtrue
if bothassetHubOptions
andmultiChainAssetsOptions
areundefined
, andfalse
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 inuseMemo
.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 redundantelse
clause innotOnNativeAsset
.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 redundantelse
clause innotOnNativeAsset
.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.
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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 theassetId
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 inuseMemo
.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 theassetId
parameter, are correct and well-integrated.
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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 inuseMemo
.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.
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Outdated
Show resolved
Hide resolved
address #1360 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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 ofuseMemo
is appropriate.The
useMemo
hook is necessary for memoizing values that depend on dependencies.
13-13
: LGTM! The import ofisOnRelayChain
is appropriate.The
isOnRelayChain
function is necessary for checking if the current chain is a relay chain.
22-22
: LGTM! The addition of theassetId
property to theProps
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 ofuseMemo
fornotOnNativeAsset
is appropriate.This change memoizes the calculation of
notOnNativeAsset
based on theassetId
.
134-134
: LGTM! The addition ofaddress
andgenesisHash
as dependencies for theuseEffect
hook is appropriate.This change ensures that the effect runs whenever
address
orgenesisHash
changes.
140-148
: LGTM! The conditional rendering logic forReservedDisplayBalance
is appropriate.This change ensures that the component renders correctly based on
genesisHash
andnotOnNativeAsset
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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.
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 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
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 removingPROXY_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 removingamountToHuman
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';
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
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 functionisOnRelayChain
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.tsxLength of output: 314
129-129
: Simplify theuseMemo
logic fornotOnNativeAsset
.The
useMemo
logic fornotOnNativeAsset
can be simplified by removing the redundanttypeof
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
anduseCallback
are indeed used in the code to avoid unnecessary imports.Verification successful
Imports are necessary and used in the code.
Both
useMemo
anduseCallback
are utilized inReservedDisplayBalance.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.tsxLength of output: 470
22-25
: Ensure the new propertiesassetId
andassetToken
are used appropriately.Verify that
assetId
andassetToken
are used correctly in the code to ensure they serve their intended purpose.Verification successful
The properties
assetId
andassetToken
are used appropriately in theReservedDisplayBalance
component.
assetId
andassetToken
are included in the function signature ofReservedDisplayBalance
.- They are used in a
useMemo
hook to determine the value ofnotOnNativeAsset
.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.tsxLength of output: 539
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Outdated
Show resolved
Hide resolved
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Outdated
Show resolved
Hide resolved
579ba40
to
f734a4a
Compare
…EF/polkagate-extension into AssetHubsReservedAmount
b7cc69d
to
a845d45
Compare
…EF/polkagate-extension into AssetHubsReservedAmount
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Outside diff range and nitpick comments (3)
packages/extension-polkagate/src/fullscreen/accountDetails/index.tsx (3)
Line range hint
89-106
: Consider simplifying the balance selection logicThe 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 logicThe 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:
- Encapsulates asset selection logic in a reusable hook
- Makes the logic easier to test and maintain
- Reduces the risk of race conditions
Line range hint
43-435
: Consider breaking down AccountDetails into smaller componentsThe 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:
- Create separate components for:
- AssetManagement (handling asset selection and balance display)
- StakingSection (handling staking-related functionality)
- AccountOperations (handling account-related operations)
- 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
📒 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 asstring | number | undefined
assetToken
is typed asstring | 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
.
...ages/extension-polkagate/src/fullscreen/accountDetails/components/ReservedDisplayBalance.tsx
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
🧹 Outside diff range and nitpick comments (7)
packages/extension-polkagate/src/fullscreen/accountDetails/components/DisplayBalance.tsx (1)
Line range hint
67-71
: Fix incorrect logical condition affecting icon rotationThe current condition
openCollapse !== undefined || disabled
could cause unintended icon rotations when the component is disabled butopenCollapse
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 theassetId
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, preferablynumber
, 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 bothuseEffect
anduseMemo
. Consider extracting it into a separateuseMemo
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:
- More descriptive comments explaining the business logic
- Type annotations for intermediate variables
- 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:
- Remove unnecessary optional chaining
- 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 thenotOnNativeAsset
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 formyAssetsMetadata
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
📒 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.
Works Done
Summary by CodeRabbit
New Features
ReservedDisplayBalance
component to requireassetId
andassetToken
for improved functionality.ReservedDetails
to track data fetching and conditionally render messages based on asset parameters.Improvements
AccountDetails
component to better manage and display reserved balances with specific asset context.useReservedDetails
hook, enhancing type safety and robustness.