Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: show validators APY #1633

Merged
merged 10 commits into from
Nov 10, 2024
Merged

feat: show validators APY #1633

merged 10 commits into from
Nov 10, 2024

Conversation

Nick-1979
Copy link
Member

@Nick-1979 Nick-1979 commented Nov 7, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new hook useValidatorApy to calculate the annual percentage yield (APY) for validators.
    • Enhanced ShowValidator component to display APY based on validator status.
    • Added optional px property to the DraggableModal for customizable horizontal padding.
  • Improvements

    • Improved type safety in ShowValue and useCurrentEraIndex components by removing // @ts-nocheck directive.
    • Enhanced error handling in useValidators hook to ensure API calls are made only when currentEraIndex is defined.
    • Added optional apy property to the ValidatorInfo interface for better data representation.
  • Bug Fixes

    • Refined logic in ShowValidator for determining validator election status.
  • Style

    • Minor formatting adjustments across various components for improved readability.
    • Adjusted margins in ValidatorInfoPage for better layout.

@Nick-1979 Nick-1979 requested a review from AMIRKHANEF November 7, 2024 13:39
Copy link
Contributor

coderabbitai bot commented Nov 7, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces several changes across multiple components and hooks in the codebase. Key modifications include reordering parameters in the ShortAddress component, enhancing type safety by removing // @ts-nocheck directives in ShowValue and useCurrentEraIndex, and adding a new hook useValidatorApy for calculating annual percentage yield. The ShowValidator component has been updated to include new logic for displaying APY and improved error handling in the useValidators hook. Overall, these changes focus on code organization, type safety, and enhanced functionality.

Changes

File Change Summary
packages/extension-polkagate/src/components/ShortAddress.tsx - Moved AccountId import statement to the top.
- Reordered parameters in ShortAddress function signature.
packages/extension-polkagate/src/components/ShowValue.tsx - Removed // @ts-nocheck directive.
- Minor formatting change in function signature.
packages/extension-polkagate/src/fullscreen/stake/solo/partials/ShowValidator.tsx - Added import for ShowValue and useValidatorApy.
- Updated logic for validator election status and APY calculation.
- Introduced new UI elements for displaying APY.
packages/extension-polkagate/src/hooks/index.ts - Added export for new hook useValidatorApy.
packages/extension-polkagate/src/hooks/useCurrentEraIndex.ts - Added optional chaining in API call.
- Removed // @ts-nocheck directive.
- Minor formatting change in function signature.
packages/extension-polkagate/src/hooks/useValidatorApy.ts - Implemented new hook for calculating validator APY.
packages/extension-polkagate/src/hooks/useValidators.ts - Enhanced error handling for API checks.
- Refactored validator processing logic for clarity.
packages/extension-polkagate/src/util/ObserveResize.tsx - Minor formatting change in function signature.
packages/extension-polkagate/src/util/types.ts - Added optional apy property to ValidatorInfo interface.
packages/extension-polkagate/src/fullscreen/governance/components/DraggableModal.tsx - Added optional px property for horizontal padding in modal.
packages/extension-polkagate/src/popup/staking/partial/ValidatorInfo.tsx - Adjusted margin property in Grid component.
- Updated DraggableModal to include new px attribute.

Possibly related PRs

Suggested reviewers

  • AMIRKHANEF

🐰 In the code where bunnies hop,
Changes made, we’ll never stop!
ShortAddress shines with a new face,
Validators dance in a happier space.
With hooks and types, we leap and play,
Code improvements brighten the 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: 13

🧹 Outside diff range and nitpick comments (9)
packages/extension-polkagate/src/components/ShowValue.tsx (1)

4-7: Enhance component documentation

While the JSDoc comment provides basic information, consider expanding it to:

  • Document all supported props (value, height, unit, width)
  • Provide usage examples
  • List all pages where this component is used, not just contributeToCrowdloan
 /**
- * @description  this component is used to show an account balance in some pages like contributeToCrowdloan
+ * @description A reusable component for displaying values with optional units and loading states
+ * @param {number|string|BN|null|undefined} value - The value to display
+ * @param {number} [height=20] - Height of the skeleton loader
+ * @param {string} [unit] - Optional unit to display after the value
+ * @param {string} [width='90px'] - Width of the skeleton loader
+ * @example
+ * <ShowValue value={balance} unit="DOT" />
+ * <ShowValue value={undefined} height={30} width="120px" />
  */
packages/extension-polkagate/src/hooks/useCurrentEraIndex.ts (1)

16-18: Consider using dot notation for better type safety.

While the optional chaining improves null safety, using bracket notation (['staking']) instead of dot notation (staking) bypasses TypeScript's property checking. This could make typos harder to catch during development.

Consider this alternative:

-    api?.query['staking']?.['currentEra']().then((i) => {
+    api?.query.staking?.currentEra().then((i) => {
      setIndex(Number(i?.toString() || '0'));
    }).catch(console.error);
packages/extension-polkagate/src/components/ShortAddress.tsx (1)

Line range hint 26-57: Consider performance optimizations.

The component could benefit from some performance improvements:

  1. Memoize the decreaseCharactersCount callback with all its dependencies
  2. Consider using ResizeObserver directly instead of a custom ObserveResize utility for better performance

Here's how to optimize the callback:

-  const decreaseCharactersCount = useCallback(() => clipped && setCharactersCount(charactersCount - 1), [charactersCount, clipped]);
+  const decreaseCharactersCount = useCallback(() => {
+    if (clipped) {
+      setCharactersCount((prev) => prev - 1);
+    }
+  }, [clipped]);
packages/extension-polkagate/src/fullscreen/stake/solo/partials/ShowValidator.tsx (1)

40-44: Consider enhancing the Div component for better reusability

While the implementation is clean, consider making this component more reusable:

  1. Move it to a shared components folder if it's used elsewhere
  2. Add props for customizing height, margin, and color
-const Div = () => (
+interface DivProps {
+  height?: string;
+  margin?: string;
+  color?: string;
+}
+
+const Div = ({ color = 'divider', height = '15px', margin = '3px 10px' }: DivProps) => (
   <Grid alignItems='center' item justifyContent='center'>
-    <Divider orientation='vertical' sx={{ bgcolor: 'divider', height: '15px', m: '3px 10px', width: '1px' }} />
+    <Divider orientation='vertical' sx={{ bgcolor: color, height, m: margin, width: '1px' }} />
   </Grid>
 );
packages/extension-polkagate/src/util/types.ts (1)

76-76: LGTM! Consider adding JSDoc comments.

The optional apy property with string | null type is well-designed for handling various states (loading, not applicable, and actual values). The change is non-breaking and follows TypeScript best practices.

Consider adding JSDoc comments to document:

  • The purpose of this property
  • The format of the APY string (e.g., percentage with decimal places)
  • The meaning of null vs undefined
 export interface ValidatorInfo extends DeriveStakingQuery {
   exposure: {
     own: BN,
     total: BN,
     others: Other[]
   };
   accountInfo?: DeriveAccountInfo;
+  /** Annual Percentage Yield (APY) of the validator
+   * @remarks
+   * - undefined: APY is still loading
+   * - null: APY is not applicable
+   * - string: APY value as a percentage with decimal places
+   */
   apy?: string | null;
packages/extension-polkagate/src/hooks/useValidatorApy.ts (4)

94-96: Add dependency to calculateValidatorAPY in useEffect

The useEffect hook uses calculateValidatorAPY, but it's not included in the dependency array. This might lead to stale closures if calculateValidatorAPY changes.

Apply this diff to add the missing dependency:

 useEffect(() => {
   if (!api || !isElected) {
     return;
   }

   calculateValidatorAPY(validatorAddress).catch(console.error);
-}, [api, isElected, validatorAddress]);
+}, [api, calculateValidatorAPY, isElected, validatorAddress]);

6-6: Remove unnecessary @ts-ignore comment

The @ts-ignore comment suppresses TypeScript errors, which might hide potential issues. If the import is correct and no errors are present, this comment can be removed.

Apply this diff to remove the comment:

-//@ts-ignore

14-14: Initialize state with a defined type

The state apy is initialized without a default value, which can be undefined. For better type safety, consider initializing it explicitly.

Apply this diff to initialize apy with null:

-const [apy, setApy] = useState<string | null>();
+const [apy, setApy] = useState<string | null>(null);

16-91: Optimize API calls by batching requests

Inside the loop, multiple asynchronous API calls are made sequentially, which can be slow. Consider batching these calls to improve performance.

As a follow-up, you might:

  • Use Promise.all to fetch eraReward, eraPoints, and validatorExposure in parallel.
  • Collect all required eras and make bulk requests if the API supports it.

This can significantly reduce the total execution time of the APY calculation.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2206c12 and 4226ab1.

📒 Files selected for processing (10)
  • packages/extension-polkagate/src/components/ShortAddress.tsx (2 hunks)
  • packages/extension-polkagate/src/components/ShowValue.tsx (2 hunks)
  • packages/extension-polkagate/src/fullscreen/stake/solo/partials/ShowValidator.tsx (4 hunks)
  • packages/extension-polkagate/src/hooks/getValidatorApy.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/index.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useCurrentEraIndex.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useValidatorApy.ts (1 hunks)
  • packages/extension-polkagate/src/hooks/useValidators.ts (4 hunks)
  • packages/extension-polkagate/src/util/ObserveResize.tsx (1 hunks)
  • packages/extension-polkagate/src/util/types.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/extension-polkagate/src/util/ObserveResize.tsx
🔇 Additional comments (10)
packages/extension-polkagate/src/components/ShowValue.tsx (1)

19-19: LGTM!

The function signature formatting change follows common React/TypeScript conventions.

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

Line range hint 11-21: Verify error handling and state updates.

The hook's implementation looks good overall, but there are a few considerations:

  1. The fallback to '0' when i is undefined might not be the best default for all cases
  2. The error is logged but the state isn't updated on error
  3. The hook doesn't clean up subscriptions on unmount

Let's verify the error handling pattern in other similar hooks:

packages/extension-polkagate/src/components/ShortAddress.tsx (2)

26-26: Verify updates to component usage after parameter reordering.

The ShortAddress component's parameter order has changed. Ensure all component usages are updated accordingly.

Let's check for any instances that might need updates:

#!/bin/bash
# Description: Find all usages of ShortAddress component
# to verify they're updated with the new parameter order

rg -l 'ShortAddress.*clipped.*charsCount' 

3-5: ⚠️ Potential issue

Avoid disabling TypeScript checks.

Adding @ts-nocheck removes valuable type safety checks. Consider fixing the underlying type issues instead of disabling TypeScript verification completely.

Let's check if there are any TypeScript errors that need to be addressed:

packages/extension-polkagate/src/fullscreen/stake/solo/partials/ShowValidator.tsx (1)

17-18: LGTM: Import statements are well-structured

The new imports for ShowValue and useValidatorApy are properly organized and align with the new APY functionality.

packages/extension-polkagate/src/hooks/useValidators.ts (4)

108-108: LGTM: Improved error handling

Good addition of the null check for currentEraIndex. This prevents potential runtime errors and makes the code more robust.


Line range hint 155-185: LGTM: Improved validator processing logic

The refactored loop using for...of improves readability and maintainability. The separation of current and waiting validators is now clearer.


157-162: ⚠️ Potential issue

Complete APY calculation implementation

The commented-out APY calculation code suggests an incomplete feature implementation. This seems to be part of the PR's objective to show validator APY.

-          // const apy = await getValidatorApy(api, v, currentEraValidatorsOverview[v].total, validatorPrefs[v].commission, currentEraIndex);
+          const apy = await getValidatorApy(api, v, currentEraValidatorsOverview[v].total, validatorPrefs[v].commission, currentEraIndex);

           current.push(
             {
               accountId: v as unknown as AccountId,
-              // apy,
+              apy,
#!/bin/bash
# Check if getValidatorApy function is implemented
rg -A 5 "function getValidatorApy|const getValidatorApy"

# Check if APY is used in the UI
rg -A 5 "apy.*validator"

6-7: Verify if @ts-ignore can be avoided

The use of @ts-ignore suppresses TypeScript type checking. Consider investigating if this can be resolved by:

  1. Updating @polkadot/types package
  2. Using proper type imports
  3. Adding necessary type declarations
packages/extension-polkagate/src/hooks/index.ts (1)

119-119: LGTM! The export follows established patterns.

The new useValidatorApy hook export is properly placed alphabetically among other validator-related hooks and follows the established naming conventions.

Let's verify the hook implementation exists:

✅ Verification successful

✓ Hook implementation verified and properly structured

The useValidatorApy hook exists and follows React hooks conventions:

  • Exports a default function with the correct name
  • Uses React's useState and useCallback hooks
  • Takes appropriate parameters (api, validatorAddress, isElected)
  • Returns expected APY value type
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the useValidatorApy hook implementation exists
# Expected: The hook file should exist and export a default function

# Check if the hook file exists
fd -t f "useValidatorApy.ts" packages/extension-polkagate/src/hooks/

# Verify the hook implementation
ast-grep --pattern 'export default function useValidatorApy' packages/extension-polkagate/src/hooks/useValidatorApy.ts

Length of output: 247


Script:

#!/bin/bash
# Let's verify the actual implementation of the hook
rg -A 5 "export default function useValidatorApy" packages/extension-polkagate/src/hooks/useValidatorApy.ts

Length of output: 419

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 (1)
packages/extension-polkagate/src/hooks/useValidatorApy.ts (1)

115-125: Improve error handling and add cleanup.

The current implementation only logs errors to console. Consider:

  1. Adding proper error handling
  2. Adding a cleanup function to cancel pending operations

Apply this diff:

 useEffect(() => {
+  let mounted = true;
+
   if (!api || isElected === undefined) {
     return;
   }

   if (isElected === false) {
     return setApy(null);
   }

-  calculateValidatorAPY(validatorAddress).catch(console.error);
+  calculateValidatorAPY(validatorAddress)
+    .then((result) => {
+      if (mounted) {
+        // Handle successful calculation
+      }
+    })
+    .catch((error) => {
+      console.error('Failed to calculate validator APY:', error);
+      if (mounted) {
+        setApy(null);
+      }
+    });
+
+  return () => {
+    mounted = false;
+  };
 }, [api, calculateValidatorAPY, isElected, validatorAddress]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 5520349 and 9bce9d8.

📒 Files selected for processing (1)
  • packages/extension-polkagate/src/hooks/useValidatorApy.ts (1 hunks)
🧰 Additional context used
🪛 Biome
packages/extension-polkagate/src/hooks/useValidatorApy.ts

[error] 108-108: isFinite is unsafe. It attempts a type coercion. Use Number.isFinite instead.

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

(lint/suspicious/noGlobalIsFinite)


[error] 108-108: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

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

(lint/suspicious/noGlobalIsNan)

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9bce9d8 and d1cadad.

📒 Files selected for processing (1)
  • packages/extension-polkagate/src/hooks/useValidatorApy.ts (1 hunks)
🧰 Additional context used
🪛 Biome
packages/extension-polkagate/src/hooks/useValidatorApy.ts

[error] 110-110: isFinite is unsafe. It attempts a type coercion. Use Number.isFinite instead.

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

(lint/suspicious/noGlobalIsFinite)


[error] 110-110: isNaN is unsafe. It attempts a type coercion. Use Number.isNaN instead.

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

(lint/suspicious/noGlobalIsNan)

🔇 Additional comments (2)
packages/extension-polkagate/src/hooks/useValidatorApy.ts (2)

6-7: ⚠️ Potential issue

Remove @ts-ignore directive and properly import types.

The @ts-ignore directive suppresses TypeScript errors and should be avoided. Instead, properly import the required types.

Apply this diff:

-//@ts-ignore
-import type { PalletStakingActiveEraInfo, PalletStakingEraRewardPoints, PalletStakingValidatorPrefs, SpStakingPagedExposureMetadata } from '@polkadot/types/lookup';
+import type { 
+  PalletStakingActiveEraInfo,
+  PalletStakingEraRewardPoints,
+  PalletStakingValidatorPrefs,
+  SpStakingPagedExposureMetadata 
+} from '@polkadot/types/lookup';

Likely invalid or redundant comment.


106-108: ⚠️ Potential issue

Prevent precision loss in APY calculation.

Converting BN instances to numbers using toNumber() can lead to precision loss with large values. Perform calculations using BN methods instead.

Apply this diff:

-const dailyReturn = dailyReward.toNumber() / totalStaked.toNumber();
-
-const APY = (dailyReturn * 365 * 100).toFixed(2);
+if (!totalStaked.isZero()) {
+  const dailyReturn = dailyReward.mul(BN_HUNDRED).muln(365).div(totalStaked);
+  const APY = dailyReturn.toString();
+  setApy(APY);
+} else {
+  setApy('0');
+}

Likely invalid or redundant comment.

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.

there are some misplacements
image

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