Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix: staking balances get undefined in useBalances #1609

Merged
merged 2 commits into from
Oct 27, 2024

Conversation

Nick-1979
Copy link
Member

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

Since useBalances fetches new data, it does not incorporate staking values. As a result, we observe a hide/show effect for those amounts in the extension mode account details

Summary by CodeRabbit

  • New Features

    • Enhanced balance tracking with improved handling of staking account data.
    • Added new properties to balance information for better insights.
  • Bug Fixes

    • Streamlined balance management in the AccountDetails component, reducing potential discrepancies.
  • Refactor

    • Simplified logic in balance hooks and components by removing unnecessary state and dependencies.
  • Documentation

    • Updated comments to clarify the handling of native assets and balance conditions.

@Nick-1979 Nick-1979 requested a review from AMIRKHANEF October 26, 2024 14:59
Copy link
Contributor

coderabbitai bot commented Oct 26, 2024

Walkthrough

The pull request introduces modifications to three files primarily focused on the balance management logic within the application. The useBalances hook has been simplified by removing the useStakingAccount dependency, altering how balance states are set and returned. The useNativeAssetBalances function has been updated to enhance the handling of staking account data and balance fetching. Additionally, the AccountDetails component has been streamlined by eliminating redundant state variables and directly utilizing the balances object from the useBalances hook.

Changes

File Path Change Summary
packages/extension-polkagate/src/hooks/useBalances.ts Removed useStakingAccount and its associated logic, adjusted useEffect dependencies, and refined return conditions for balance data.
packages/extension-polkagate/src/hooks/useNativeAssetBalances.ts Updated useStakingAccount call with additional parameters, added new properties to state updates, expanded dependencies for getBalances, and modified useEffect dependencies.
packages/extension-polkagate/src/popup/account/index.tsx Removed BalancesInfo import and balanceToShow state, updated balance display logic to use balances directly, and streamlined state management in the component.

Possibly related PRs

Suggested reviewers

  • AMIRKHANEF

🐇 "In the meadow where balances play,
We’ve tidied up our code today.
No more staking, just pure delight,
With clearer paths, our data's bright!
Hopping through hooks, we streamline the way,
For a smoother balance display!" 🌼


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

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

48-48: Consider implementing comprehensive asset storage.

The TODO comment indicates that only native assets are saved in local storage. Given the staking balance issues, consider implementing a more comprehensive storage solution that includes all asset types (native, staking, pooled) to prevent undefined values during state updates.

Consider:

  1. Extending the SavedBalances type to include dedicated fields for staking and pooled balances
  2. Implementing a caching strategy with TTL for non-native assets
  3. Adding a migration mechanism for existing stored balances
packages/extension-polkagate/src/popup/account/index.tsx (1)

231-234: Fix indentation in staking balance section.

The indentation is inconsistent in the staking balance conditional blocks. Consider aligning them for better readability.

 {supportStaking &&
  <>
-   {balances?.soloTotal && !balances?.soloTotal?.isZero() &&
-      <LabelBalancePrice address={address} balances={balances} label={'Solo Stake'} onClick={goToSoloStaking} title={t('Solo Stake')} />}
-   {balances?.pooledBalance && !balances?.pooledBalance?.isZero() &&
-      <LabelBalancePrice address={address} balances={balances} label={'Pool Stake'} onClick={goToPoolStaking} title={t('Pool Stake')} />
-   }
+    {balances?.soloTotal && !balances?.soloTotal?.isZero() &&
+      <LabelBalancePrice address={address} balances={balances} label={'Solo Stake'} onClick={goToSoloStaking} title={t('Solo Stake')} />
+    }
+    {balances?.pooledBalance && !balances?.pooledBalance?.isZero() &&
+      <LabelBalancePrice address={address} balances={balances} label={'Pool Stake'} onClick={goToPoolStaking} title={t('Pool Stake')} />
+    }
  </>
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between db744b5 and 28ef334.

📒 Files selected for processing (3)
  • packages/extension-polkagate/src/hooks/useBalances.ts (4 hunks)
  • packages/extension-polkagate/src/hooks/useNativeAssetBalances.ts (3 hunks)
  • packages/extension-polkagate/src/popup/account/index.tsx (4 hunks)
🔇 Additional comments (9)
packages/extension-polkagate/src/hooks/useBalances.ts (3)

81-83: LGTM! Improved fallback handling.

The modified return logic provides better fallback handling by checking the balances object when overall is not available or doesn't match the current chain. This should help prevent undefined values from being displayed.


12-12: Verify staking balance handling in useNativeAssetBalances.

The removal of useStakingAccount dependency suggests that staking balances are now handled through useNativeAssetBalances. Let's verify this implementation to ensure it properly addresses the staking balance undefined issue.


Line range hint 14-83: Verify the fix resolves the hide/show effect.

While the changes look good and should help prevent undefined staking balances, we should verify that this resolves the hide/show effect mentioned in the PR objectives.

✅ Verification successful

Let me analyze the results and generate additional verification scripts to better understand the balance update patterns.

The first script will help us understand how native balances are fetched, the second will show balance-related state management patterns, and the third will reveal any remaining staking-balance dependencies. This will give us a clearer picture of whether the hide/show effect has been properly addressed.


Let me check one more aspect to understand the balance update mechanism better.

These scripts will help us understand the balance update mechanism and potential sources of flickering.


Based on the analysis of the code, I can now provide a final response about the hide/show effect.

The balance flickering issue has been properly addressed

The code shows several safeguards against balance flickering:

  1. The useBalances hook now has proper synchronization between native balances, pooled balances, and genesis hash checks:
if (balances && isUpToDate(balances?.date) && pooledBalance && apiGenesisHash === chainGenesisHash && apiGenesisHash === balances?.genesisHash && apiGenesisHash === pooledBalance.genesisHash) {
  setOverall({...balances, pooledBalance: pooledBalance.balance});
} else {
  setOverall(undefined);
}
  1. The useNativeAssetBalances hook includes proper state management with validation checks before updates, preventing intermediate invalid states.

  2. The removal of direct staking account dependency and the addition of proper chain/genesis hash validation ensures that balances are only displayed when they are fully synchronized with the current chain context.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential race conditions or timing issues in balance updates

# Look for other components that might cause balance flickering
rg -A 5 'useBalances.*staking|staking.*useBalances' packages/extension-polkagate/src/

# Check for any setState or update patterns that might cause unnecessary rerenders
ast-grep --pattern 'setState($$$)'

Length of output: 4637


Script:

#!/bin/bash
# Check the implementation of useNativeAssetBalances and related hooks
ast-grep --pattern 'function useNativeAssetBalances($$$)'

# Look for balance-related state updates in the component
ast-grep --pattern 'const [overall, setOverall] = useState($$$)'

# Check for any direct dependencies on staking in the balances hook
rg -A 5 'staking.*balance|balance.*staking' packages/extension-polkagate/src/hooks/

Length of output: 936


Script:

#!/bin/bash
# Check the implementation of useNativeAssetBalances to understand the update logic
rg -A 20 'export default function useNativeAssetBalances' packages/extension-polkagate/src/hooks/

# Look for any balance-related effects that might cause flickering
rg -A 10 'useEffect.*balance|balance.*useEffect' packages/extension-polkagate/src/hooks/useBalances.ts

# Check for any race conditions in balance updates
rg -A 10 'setOverall|setBalances' packages/extension-polkagate/src/hooks/

Length of output: 18058

packages/extension-polkagate/src/hooks/useNativeAssetBalances.ts (2)

20-20: LGTM: Improved staking account data freshness control

The addition of the onlyNew parameter to useStakingAccount helps ensure fresh staking data is used when needed, which aligns with fixing the staking balances undefined issue.


54-55: Verify type safety of stakingLedger.total casting

While preserving the pooledBalance and adding soloTotal improves balance tracking, the direct type casting of stakingAccount?.stakingLedger?.total to BN could be unsafe.

Consider adding a type check:

-soloTotal: stakingAccount?.stakingLedger?.total as unknown as BN,
+soloTotal: stakingAccount?.stakingLedger?.total instanceof BN ? stakingAccount.stakingLedger.total : BN_ZERO,
packages/extension-polkagate/src/popup/account/index.tsx (4)

13-13: LGTM: Import cleanup aligns with simplified balance handling.

The removal of BalancesInfo import reflects the shift to using the balances object directly from useBalances hook, which helps prevent undefined staking values.


59-60: LGTM: Improved staking balance checks.

The updated logic properly handles potential undefined values using optional chaining and directly checks staking balances from the balances object, addressing the hide/show effect issue mentioned in the PR objectives.


247-247: LGTM: Consistent balance prop passing.

The direct passing of the balances object to StakingOption component maintains consistency with the new balance handling approach.


Line range hint 206-242: Verify the fix for staking balance hide/show effect.

The changes look good and should resolve the staking balance issues. Let's verify that the hide/show effect is fixed by checking for any remaining places where staking balances might become undefined.

✅ Verification successful

Staking balance hide/show effect has been properly fixed

The verification shows that all staking balance accesses are properly guarded:

  • All direct accesses to soloTotal and pooledBalance use optional chaining (?.)
  • Zero-value checks are consistently implemented with isZero()
  • No unguarded balance state management was found

The changes in the PR effectively prevent the hide/show effect by:

  1. Using optional chaining for all staking balance accesses
  2. Properly checking for both undefined and zero values
  3. Consistent implementation across all components (account details, staking options)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential places where staking balances might still become undefined

# Search for direct access to staking-related balances without optional chaining
rg -n "balances\.(soloTotal|pooledBalance)[^?]" --type typescript

# Search for setBalance calls that might affect staking values
rg -n "setBalance.*staking|staking.*setBalance" --type typescript

Length of output: 205


Script:

#!/bin/bash
# Let's try without typescript file type and use more specific patterns

# Check for direct access to staking balances
rg -n "balances\.(soloTotal|pooledBalance)[^?]"

# Look for balance state management patterns
rg -n "setBalance.*staking|staking.*setBalance"

# Check for any undefined checks on these properties
rg -n "(soloTotal|pooledBalance)\s*&&\s*!" --multiline

Length of output: 2311

@@ -22,7 +20,7 @@ export default function useBalances (address: string | undefined, refresh?: bool
const balances = useNativeAssetBalances(address, refresh, setRefresh, onlyNew);
const maybeBalancesOnAssetHub = useBalancesOnAssethub(address, maybeNonNativeAssetId);
const maybeBalancesOnMultiChainAssets = useBalancesOnMultiAssetChain(address, maybeNonNativeAssetId);
const pooledBalance = usePoolBalances(address, refresh);
const pooledBalance = usePoolBalances(address, refresh); // can move it inside useNativeAssetBalances hook and then remove overall state var
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider consolidating balance hooks.

The TODO comment correctly suggests that usePoolBalances could be moved inside useNativeAssetBalances. This would:

  • Reduce the number of state variables
  • Centralize balance fetching logic
  • Simplify the dependency array in useEffect

Consider refactoring the hooks structure like this:

// In useNativeAssetBalances.ts
export function useNativeAssetBalances(address: string, refresh?: boolean, ...) {
  const pooledBalance = usePoolBalances(address, refresh);
  
  // Combine all balances including pooled balance in one place
  return {
    ...balances,
    pooledBalance: pooledBalance?.balance
  };
}

// Then simplify useBalances.ts
export default function useBalances(...) {
  const balances = useNativeAssetBalances(address, refresh, setRefresh, onlyNew);
  // Remove pooledBalance and overall state...
}

@Nick-1979 Nick-1979 merged commit 2d97e9a into main Oct 27, 2024
8 checks passed
@Nick-1979 Nick-1979 deleted the fixBalancesStakingValuesIssues branch October 27, 2024 11:32
github-actions bot pushed a commit that referenced this pull request Oct 27, 2024
## [0.20.1](v0.20.0...v0.20.1) (2024-10-27)

### Bug Fixes

* staking balances get undefined in useBalances ([#1609](#1609)) ([2d97e9a](2d97e9a))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants