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

refactor: add useLockedInReferenda #1608

Merged
merged 3 commits into from
Oct 27, 2024
Merged

refactor: add useLockedInReferenda #1608

merged 3 commits into from
Oct 27, 2024

Conversation

Nick-1979
Copy link
Member

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

plus using two lock shapes

Summary by CodeRabbit

  • New Features

    • Introduced a new hook, useLockedInReferenda, to manage and provide information about locked referenda.
    • Updated the LockedInReferenda component to utilize the new hook, streamlining state management and enhancing visual feedback with conditional icons.
  • Bug Fixes

    • Improved error handling in the useCurrentBlockNumber and useHasDelegated hooks to prevent unhandled promise rejections.
  • Documentation

    • Updated component logic and rendering to reflect the new state structure and data flow.

plus using two lock shapes
@Nick-1979 Nick-1979 requested a review from AMIRKHANEF October 26, 2024 12:44
Copy link
Contributor

coderabbitai bot commented Oct 26, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces significant changes to the LockedInReferendaFS component and related hooks. It replaces multiple individual hooks with a new consolidated hook, useLockedInReferenda, which manages account lock states more efficiently. The LockedInReferenda component also adopts this new hook, streamlining its logic. Additionally, updates to type definitions enhance type safety in the useAccountLocks hook. Overall, these changes aim to improve the clarity and manageability of the components involved in handling locked referenda.

Changes

File Change Summary
packages/extension-polkagate/src/fullscreen/accountDetails/components/LockedInReferendaFS.tsx Refactored logic for account locks, replaced multiple hooks with useLockedInReferenda, simplified state management, and updated icon rendering.
packages/extension-polkagate/src/hooks/index.ts Added export statement for the new useLockedInReferenda hook.
packages/extension-polkagate/src/hooks/useAccountLocks.ts Updated type imports and enhanced the type definition for maybeVotes. No logic changes.
packages/extension-polkagate/src/hooks/useLockedInReferenda.ts Introduced useLockedInReferenda hook to manage locked referenda states with defined interfaces.
packages/extension-polkagate/src/popup/account/unlock/LockedInReferenda.tsx Replaced useAccountLocks with useLockedInReferenda, simplifying logic and updating rendering.
packages/extension-polkagate/src/hooks/useCurrentBlockNumber.ts Added error handling to API calls and minor formatting changes.
packages/extension-polkagate/src/hooks/useHasDelegated.ts Introduced new state tracking for fetched addresses and improved data fetching logic with error handling.
packages/extension-polkagate/src/hooks/useTimeToUnlock.tsx Updated function signature to include delegatedBalance, enhanced state management on address changes.

Possibly related PRs

  • feat: add vote type to governance comment section #1544: This PR introduces a custom React hook useLockedInReferenda, which is directly related to the changes made in the main PR that refactors the LockedInReferendaFS component to use this new hook for managing account locks and related data.
  • refactor: remove duplicate codes AFAP #1540: The introduction of the useTransactionHistory hook in this PR may relate to the overall management of state and data in the application, which could indirectly connect to the changes in the main PR regarding state management in the LockedInReferendaFS component.
  • fix: referenda tracks Max #1591: This PR addresses issues related to referenda tracks, which may connect to the overall governance functionality that the LockedInReferendaFS component is part of, especially in terms of managing locked referenda.
  • fix: asset requested issue while currency is something other than USD #1594: The changes in this PR regarding the handling of currency signs in the governance context may relate to the financial aspects of the LockedInReferendaFS component, which deals with locked amounts and their representation.
  • feat: auto loading referenda list #1599: The auto-loading feature for referenda lists may connect to the user experience improvements that are also a focus in the main PR, enhancing how users interact with locked referenda data.
  • style: adjust divider colors #1606: Adjustments to divider colors in the UI may relate to the visual presentation of the LockedInReferendaFS component, ensuring consistency in styling across the application.
  • refactor: handle account icon's tooltip translations #1607: The refactor to handle tooltip translations in account icons may connect to the overall user interface improvements that include the LockedInReferendaFS component, enhancing user interactions with account-related information.
  • fix: staking balances get undefined in useBalances #1609: This PR addresses issues with undefined staking balances, which could relate to the financial data management in the LockedInReferendaFS component, ensuring that all relevant balances are accurately represented.

Suggested labels

new feature

Suggested reviewers

  • AMIRKHANEF

Poem

🐰 In the land of code where rabbits play,
New hooks are hopping in a brighter way.
Locked referenda, now sleek and neat,
With clearer paths, our logic's a treat!
So let’s unlock the joy, let’s cheer and sway,
For every change brings a brighter day! 🌟


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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

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

12-18: Consider documenting the 'N/A' special case in refId.

The refId property allows 'N/A' as a special case. Adding JSDoc comments would help explain when and why this special case occurs.

 interface Lock {
   classId: BN;
   endBlock: BN;
   locked: string;
+  /** Reference ID of the lock. 'N/A' indicates [document the special case here] */
   refId: BN | 'N/A';
   total: BN;
 }
packages/extension-polkagate/src/fullscreen/accountDetails/components/LockedInReferendaFS.tsx (1)

Line range hint 82-89: Simplify nested ternary expressions for better readability.

The status text logic using nested ternaries could be made more maintainable.

-          <Typography fontSize='12px' fontWeight={500} textAlign='right'>
-            {api && unlockableAmount && !unlockableAmount.isZero()
-              ? `${api.createType('Balance', unlockableAmount).toHuman()} can be unlocked`
-              : delegatedBalance && !delegatedBalance.isZero()
-                ? t('Locked as delegated')
-                : timeToUnlock === null ? '' : timeToUnlock
-            }
-          </Typography>
+          <Typography fontSize='12px' fontWeight={500} textAlign='right'>
+            {getStatusText()}
+          </Typography>

// Add this function above the component or in a separate utils file
+const getStatusText = () => {
+  if (api && unlockableAmount && !unlockableAmount.isZero()) {
+    return `${api.createType('Balance', unlockableAmount).toHuman()} can be unlocked`;
+  }
+  
+  if (delegatedBalance && !delegatedBalance.isZero()) {
+    return t('Locked as delegated');
+  }
+  
+  return timeToUnlock === null ? '' : timeToUnlock;
+};
packages/extension-polkagate/src/hooks/useAccountLocks.ts (3)

Line range hint 156-157: Remove eslint-disable comment for floating promise.

The code disables eslint warning for floating promises. This could lead to unhandled promise rejections.

Apply this fix to properly handle the promise:

- // eslint-disable-next-line @typescript-eslint/no-floating-promises
- getLockClass();
+ void getLockClass().catch((error) => {
+   console.error('Failed to get lock class:', error);
+   setInfo(undefined);
+ });

Line range hint 89-155: Consider optimizing state updates in getLockClass function.

The function performs multiple async operations and state updates. Consider:

  1. Implementing batch queries where possible
  2. Memoizing expensive computations
  3. Adding loading states for better UX

Consider implementing the following optimizations:

  1. Use combineLatest or similar RxJS operators for handling multiple observables
  2. Implement request caching for frequently accessed data
  3. Add loading states to handle async operations more gracefully

Line range hint 165-186: Optimize memory usage in useMemo dependency array.

The current dependency array includes the entire API object, which could cause unnecessary re-renders.

Consider extracting only the required API methods:

- }, [api, chain?.genesisHash, info, currentBlock, palletVote, notExpired]);
+ }, [
+   api?.genesisHash.toString(),
+   chain?.genesisHash,
+   info,
+   currentBlock,
+   palletVote,
+   notExpired
+ ]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

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

📒 Files selected for processing (5)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/LockedInReferendaFS.tsx (3 hunks)
  • packages/extension-polkagate/src/hooks/index.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useAccountLocks.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useLockedInReferenda.ts (1 hunks)
  • packages/extension-polkagate/src/popup/account/unlock/LockedInReferenda.tsx (4 hunks)
🔇 Additional comments (11)
packages/extension-polkagate/src/hooks/useLockedInReferenda.ts (3)

1-10: LGTM! Imports and headers are properly structured.

The file includes appropriate copyright notice, license information, and well-organized imports.


41-43: ⚠️ Potential issue

Add unlockableAmount to useMemo dependencies.

The hasDescription computation depends on unlockableAmount but it's missing from the dependency array.

  const hasDescription = useMemo(() =>
    (unlockableAmount && !unlockableAmount.isZero()) || (delegatedBalance && !delegatedBalance.isZero()) || timeToUnlock
-  , [delegatedBalance, timeToUnlock, unlockableAmount]);
+  , [delegatedBalance, timeToUnlock, unlockableAmount]);

Likely invalid or redundant comment.


32-37: Add error handling for hook failures.

The hook calls multiple external hooks but doesn't handle potential failures. Consider wrapping the calls in try-catch blocks and providing fallback values.

Let's check if these hooks have error handling:

Consider implementing a custom error handling hook that can be reused across all blockchain-related hooks.

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

8-14: LGTM! Clean import consolidation.

The consolidation of multiple hooks into useLockedInReferenda reduces complexity while maintaining functionality. The addition of lock icons enhances the UI feedback.


100-103: LGTM! Clear and intuitive icon feedback.

The conditional icon rendering provides clear visual feedback about the lock state, enhancing the user experience.

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

10-10: LGTM: Type import addition improves type safety.

The addition of ITuple type import enhances type safety for tuple structures used in vote casting operations.


Line range hint 28-82: Consider enhancing error handling in getLocks function.

The function uses console.error for unhandled cases, which might not be sufficient for production error handling. Consider implementing proper error reporting or recovery mechanisms.

Let's check for other similar error handling patterns:

Consider implementing a more robust error handling strategy:

- console.error(`Unable to handle ${accountVote.type}`);
+ const error = new Error(`Unhandled vote type: ${accountVote.type}`);
+ // Either throw the error or handle it through a proper error reporting mechanism
+ throw error;
packages/extension-polkagate/src/hooks/index.ts (1)

64-64: LGTM! The export follows the established patterns.

The new export for useLockedInReferenda is correctly placed alphabetically and follows the same export pattern as other hooks in the file.

Let's verify that the hook implementation exists:

✅ Verification successful

Verified: The hook implementation exists and follows React hook conventions

The useLockedInReferenda hook is properly implemented as a React hook function that takes address and refreshNeeded parameters, and uses other hooks like useHasDelegated and useAccountLocks internally.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the useLockedInReferenda hook implementation exists
# Test: Check if the hook file exists and exports a default function
fd -t f "useLockedInReferenda.ts" packages/extension-polkagate/src/hooks/ --exec rg -l "export default"

Length of output: 166


Script:

#!/bin/bash
# Let's verify the hook implementation to ensure it's a proper React hook
ast-grep --pattern 'export default function useLockedInReferenda' -l typescript

Length of output: 426


Script:

#!/bin/bash
# Let's try a simpler pattern to verify the hook implementation
rg "function useLockedInReferenda" -A 2 packages/extension-polkagate/src/hooks/useLockedInReferenda.ts

Length of output: 403

packages/extension-polkagate/src/popup/account/unlock/LockedInReferenda.tsx (3)

11-11: Importing FontAwesome icons

The faLock and faUnlockAlt icons are correctly imported from @fortawesome/free-solid-svg-icons.


19-19: Importing useLockedInReferenda hook

The useLockedInReferenda hook is properly imported from the hooks directory.


39-39: Destructuring values from useLockedInReferenda hook

The hook is invoked with address and refresh, and the returned values are correctly destructured.

Copy link
Member

@AMIRKHANEF AMIRKHANEF left a comment

Choose a reason for hiding this comment

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

please before merge have a look at the PR #1610

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

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

32-32: Well-structured hook consolidation!

The consolidation of multiple hooks into useLockedInReferenda improves code organization and maintainability. This is a good example of the custom hooks pattern in React.

Consider documenting the hook's interface in a separate types file to make it more maintainable and reusable across the application.


92-92: Consider extracting the icon selection logic.

While the conditional icon rendering works well, consider extracting it to a constant for improved readability:

+ const lockIcon = unlockableAmount && !unlockableAmount.isZero() ? faUnlockAlt : faLock;
  <FontAwesomeIcon
    color={isDisable ? theme.palette.action.disabledBackground : theme.palette.secondary.light}
-   icon={ unlockableAmount && !unlockableAmount.isZero() ? faUnlockAlt : faLock}
+   icon={lockIcon}
    shake={shake}
    style={{ height: '25px' }}
  />
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a77d854 and 6d6a8ce.

📒 Files selected for processing (6)
  • packages/extension-polkagate/src/fullscreen/accountDetails/components/LockedInReferendaFS.tsx (3 hunks)
  • packages/extension-polkagate/src/hooks/useAccountLocks.ts (3 hunks)
  • packages/extension-polkagate/src/hooks/useCurrentBlockNumber.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useHasDelegated.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useLockedInReferenda.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useTimeToUnlock.tsx (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/extension-polkagate/src/hooks/useAccountLocks.ts
  • packages/extension-polkagate/src/hooks/useLockedInReferenda.ts
🔇 Additional comments (7)
packages/extension-polkagate/src/hooks/useHasDelegated.ts (3)

17-24: Well-structured state management.

The addition of fetchedFor state effectively prevents redundant API calls when the address hasn't changed, improving performance.


26-31: Clean refresh handling implementation.

The refresh logic properly resets all relevant state variables, ensuring a fresh fetch cycle.


66-69: Clean implementation following React hooks best practices.

The effect cleanup and return value handling are well-implemented, following React hooks patterns.

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

8-14: LGTM! Import changes align with the refactoring.

The imports have been properly updated to support the new consolidated hook pattern and animation functionality.


33-33: Great improvement in animation handling!

The use of useAnimateOnce hook addresses the previous review comment about animation logic extraction. This is a cleaner and more reusable approach.

packages/extension-polkagate/src/hooks/useTimeToUnlock.tsx (2)

14-14: LGTM: Hook signature updated correctly.

The addition of delegatedBalance parameter is well-typed and maintains backward compatibility with nullable/undefined values.

Also applies to: 16-16


54-55: LGTM: Consistent state initialization.

The initialization of unlockableAmount and totalLocked to BN_ZERO when referendaLocks is null, and to undefined when referendaLocks is undefined, maintains proper state consistency.

Also applies to: 63-64

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