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

Disable Actions when data is not synced #4845

Merged
merged 14 commits into from
Oct 22, 2024

Conversation

MohammadPCh
Copy link
Collaborator

@MohammadPCh MohammadPCh commented Oct 21, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced custom hooks useSubgraphInfo, useFetchSubgraphDataForAllChains, and useInteractedBlockNumber for streamlined data fetching.
    • Added a synchronization check for subgraph data in relevant components.
    • Enhanced interactivity with new buttons for updating query data.
  • Bug Fixes

    • Improved error handling and state management across various components.
  • Refactor

    • Replaced multiple useQueries with a single hook approach to simplify data fetching logic.
    • Updated components for better readability and maintainability by consolidating state management.
    • Enhanced the data fetching mechanism by integrating new hooks across components.
  • Documentation

    • Updated internal documentation to reflect new hooks and data fetching strategies.

Copy link

vercel bot commented Oct 21, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
giveth-dapps-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Oct 21, 2024 10:54am

Copy link
Contributor

coderabbitai bot commented Oct 21, 2024

Walkthrough

The changes in this pull request involve significant refactoring of various components and hooks to streamline data fetching from subgraphs. The updates replace multiple queries with custom hooks like useFetchSubgraphDataForAllChains and useSubgraphInfo, enhancing code clarity and maintainability. Additionally, state management has been updated to utilize the chainId instead of address, simplifying the logic across components. New hooks have been introduced, and existing hooks have been modified to improve data handling and interactivity within the application.

Changes

File Path Change Summary
pages/test2.tsx Updated imports to use useQuery and useFetchSubgraphDataForAllChains, modified state management to include chain, and added a button for updating query data.
src/components/GIVeconomyPages/GIVbacks.tsx Replaced useQuery with useSubgraphInfo, updated state management to use chainId, and modified logic for network checks.
src/components/GIVeconomyPages/GIVpower.tsx Changed import from fetchSubgraphData to useFetchSubgraphDataForAllChains, simplifying data retrieval.
src/components/GIVeconomyPages/GIVstream.tsx Replaced useQuery with useSubgraphInfo, updated destructuring from useAccount to only retrieve chain.
src/components/cards/StakingCards/BaseStakingCard/StakingPoolInfoAndActions.tsx Added useSubgraphSyncInfo for synchronization checks in button enabling conditions.
src/components/cards/StakingCards/GIVpowerCard/GIVpowerCardIntro.tsx Replaced useQuery and useAccount with useSubgraphInfo, simplifying data fetching.
src/components/controller/subgraph.ctrl.tsx Removed useQueries, added useFetchSubgraphDataForAllChains and useInteractedBlockNumber, updated state management.
src/components/givfarm/RegenStreamCard.tsx Replaced useQuery with useSubgraphInfo, updated destructuring from useAccount.
src/components/menu/RewardButtonWithMenu.tsx Replaced useAccount and useQuery with useSubgraphInfo, simplifying data retrieval.
src/components/menu/RewardItems.tsx Updated to use useSubgraphInfo, modified destructuring from useAccount.
src/components/modals/Boost/BoostModal.tsx Replaced useQueries with useFetchSubgraphDataForAllChains, simplifying data fetching.
src/components/modals/GIVdropHarvestModal.tsx Replaced useQuery with useSubgraphInfo, updated destructuring from useAccount.
src/components/modals/HarvestAll.tsx Added blockNumber to transaction handling and dispatched a new chainEvent.
src/components/modals/StakeLock/LockSlider.tsx Replaced useAccount and useQuery with useSubgraphInfo, simplifying data fetching.
src/components/modals/StakeLock/LockingBrief.tsx Replaced useAccount and useQuery with useSubgraphInfo, simplifying data fetching.
src/components/modals/StakeLock/TotalGIVpowerBox.tsx Replaced useQueries with useFetchSubgraphDataForAllChains, simplifying data retrieval.
src/components/views/claim/cards/Govern.tsx Updated to use useSubgraphInfo, simplifying data fetching.
src/components/views/claim/cards/Stake.tsx Replaced useAccount and useQuery with useSubgraphInfo, consolidating data fetching.
src/components/views/userProfile/ProfileOverviewTab.tsx Replaced useQueries with useFetchSubgraphDataForAllChains, simplifying data retrieval.
src/components/views/userProfile/boostedTab/EmptyPowerBoosting.tsx Replaced useQueries with useFetchSubgraphDataForAllChains, simplifying data retrieval.
src/components/views/userProfile/boostedTab/ProfileBoostedTab.tsx Replaced useQueries with useFetchSubgraphDataForAllChains, simplifying data retrieval.
src/hooks/useFetchSubgraphDataForAllChains.ts Introduced a new hook to fetch data from multiple subgraphs based on chain configuration.
src/hooks/useGIVTokenDistroHelper.ts Replaced useQuery and useAccount with useSubgraphInfo, simplifying data fetching.
src/hooks/useInteractedBlockNumber.ts Introduced a new hook to manage interacted block number fetching.
src/hooks/useStakingPool.ts Replaced useQuery with useSubgraphInfo, simplifying data fetching.
src/hooks/useSubgraphInfo.ts Introduced a new hook for fetching subgraph data based on chain ID.
src/hooks/useSubgraphSyncInfo.ts Introduced a new hook for managing subgraph synchronization status.
src/hooks/useTokenDistroHelper.ts Replaced useAccount and fetchSubgraphData with useSubgraphInfo, simplifying data fetching.
src/lib/subgraph/subgraphDataTransform.ts Introduced a new function for transforming indexed block information.
src/lib/subgraph/subgraphQueryBuilder.ts Added a new method to construct queries for indexed block retrieval.
src/components/RewardCard.tsx Integrated useSubgraphSyncInfo to control button enabling based on synchronization status.

Possibly related PRs

  • Reduce subgraph requests #4458: This PR focuses on reducing subgraph requests, which is related to the changes in the main PR that streamline data fetching processes and enhance interactivity within components by optimizing how subgraph data is retrieved.

Suggested reviewers

  • kkatusic
  • Meriem-BM

🐇 In the fields we hop and play,
New hooks and queries lead the way.
With data fetching now so bright,
Our code is clean, our future's light!
So let us cheer, with joy and glee,
For streamlined paths, as smooth as can be! 🌼


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

🧹 Outside diff range and nitpick comments (29)
src/hooks/useSubgraphInfo.ts (1)

6-15: LGTM: Well-implemented custom hook with good practices.

The useSubgraphInfo hook is well-structured and follows React hooks best practices. It properly handles the optional chainId parameter and uses useAccount to get user information. The useQuery configuration is appropriate, with a well-constructed query key and proper use of the enabled option.

Consider adding TypeScript type annotations for improved type safety:

export const useSubgraphInfo = (chainId?: number) => {
  const { address, chainId: accountChainId } = useAccount();
  const _chainId: number | undefined = chainId || accountChainId;
  return useQuery<ReturnType<typeof fetchSubgraphData>, Error>({
    // ... rest of the implementation
  });
};
src/hooks/useFetchSubgraphDataForAllChains.ts (1)

9-21: LGTM: Query configuration is well-structured. Consider adding error handling.

The query configuration is excellent, following react-query best practices with unique keys, efficient polling, and conditional enabling. To further improve robustness, consider adding error handling and retry logic.

You could enhance the configuration by adding error handling and retry options:

 return useQueries({
   queries: config.CHAINS_WITH_SUBGRAPH.map(chain => ({
     queryKey: ['subgraph', chain.id, address] as [
       string,
       number,
       Address,
     ],
     queryFn: async () => await fetchSubgraphData(chain.id, address),
     staleTime: config.SUBGRAPH_POLLING_INTERVAL,
     enabled: !!address,
+    retry: (failureCount, error) => failureCount < 3 && error.status !== 404,
+    onError: (error) => console.error(`Error fetching subgraph data for chain ${chain.id}:`, error),
   })),
 });

This addition will retry failed queries up to 3 times (except for 404 errors) and log errors to the console.

src/hooks/useSubgraphSyncInfo.ts (2)

6-10: Consider improving type safety for chainId.

The hook's structure and logic look good. However, to enhance type safety, consider explicitly typing the chainId parameter:

export const useSubgraphSyncInfo = (chainId?: number) => {

This change will ensure that only numbers can be passed as the chainId parameter, preventing potential runtime errors.


12-24: Consider adding error logging in the catch block.

The isSynced calculation logic is well-implemented and optimized using useMemo. The error handling is good, but it could be improved by logging the error:

} catch (error) {
  console.error('Error calculating isSynced:', error);
  return false;
}

This addition would help with debugging if issues arise in production.

src/hooks/useTokenDistroHelper.ts (1)

Line range hint 19-43: LGTM: Core functionality preserved with room for improvement.

The retention of the existing useEffect logic, including the TokenDistroHelper instantiation and periodic updates, maintains the hook's core functionality. This is good for consistency and reliability.

However, consider the following enhancement:

To improve performance and reduce unnecessary re-renders, consider memoizing the updateHelper function using useCallback. This would ensure that the function reference remains stable across re-renders, potentially optimizing the useEffect dependency array. Here's a suggested implementation:

const updateHelper = useCallback(() => {
  if (regenStreamConfig) {
    setTokenDistroHelper(
      new TokenDistroHelper(
        sdh.getTokenDistro(
          regenStreamConfig?.tokenDistroAddress as string,
        ),
      ),
    );
  } else {
    setTokenDistroHelper(
      new TokenDistroHelper(sdh.getGIVTokenDistro()),
    );
  }
}, [regenStreamConfig, sdh]);

useEffect(() => {
  updateHelper(); // Initial update
  const interval = setInterval(updateHelper, 5000);
  return () => clearInterval(interval);
}, [updateHelper]);

This change would help ensure that the effect is only re-run when updateHelper actually changes, which would be when regenStreamConfig or sdh change.

src/components/modals/StakeLock/LockingBrief.tsx (2)

7-7: Approved: Improved data fetching approach

The switch to useSubgraphInfo custom hook streamlines the data fetching process and removes the dependency on useQuery and useAccount. This change aligns with the broader refactoring effort across the application to simplify subgraph data retrieval.

Consider documenting the useSubgraphInfo hook's functionality and any potential limitations to assist other developers who might use it in the future.


Line range hint 1-53: Approved: Maintained component functionality with improved data fetching

The refactoring has successfully maintained the core functionality of the LockingBrief component while improving the data fetching approach. The component's structure and rendering logic remain intact, which is a positive outcome of this refactoring effort.

Consider the following suggestions to ensure the changes are fully integrated:

  1. Update any existing unit tests for this component to reflect the new data fetching method.
  2. Review and update the component's documentation or comments if they reference the old data fetching approach.
  3. Ensure that any parent components passing props to LockingBrief are aware of the changes in data flow, particularly if they were previously responsible for fetching or passing account-related data.
src/hooks/useGIVTokenDistroHelper.ts (1)

Line range hint 23-38: LGTM: Streamlined data fetching implementation.

The changes effectively simplify the data fetching process by utilizing the useSubgraphInfo hook. This aligns well with the PR objectives of streamlining subgraph data retrieval. The periodic update mechanism and cleanup are properly maintained.

Consider adding a comment explaining the purpose of the 5-second update interval for better code documentation:

// Update the helper every 5 seconds to reflect the latest subgraph data
const interval = setInterval(updateHelper, 5000);
src/components/modals/Boost/BoostModal.tsx (2)

32-32: LGTM: Simplified data fetching with new hook

The use of useFetchSubgraphDataForAllChains simplifies the data fetching logic, maintaining functionality while reducing code complexity. This is a positive change that aligns with the broader refactoring effort.

Consider adding a brief comment explaining what subgraphValues represents, to enhance code readability:

// Fetch subgraph data for all chains to calculate GIV power
const subgraphValues = useFetchSubgraphDataForAllChains();

14-14: Overall impact: Improved maintainability without functional changes

The changes to this component, particularly the introduction of useFetchSubgraphDataForAllChains, successfully refactor the data fetching logic without altering the core functionality of the BoostModal. This refactoring aligns well with the PR objectives and contributes to improved code maintainability and consistency across the application.

As this refactoring pattern is being applied across multiple components, consider creating a comprehensive guide or documentation for the team on how to use these new hooks effectively. This will ensure consistent implementation and make it easier for other developers to understand and maintain the codebase.

Also applies to: 32-32

src/components/menu/RewardButtonWithMenu.tsx (1)

Line range hint 100-110: Consider adding error handling and loading state.

While the transition to useSubgraphInfo is an improvement, there's no visible error handling or loading state management in this component. Consider adding these to improve the user experience and robustness of the component.

Here's a suggested implementation:

const HeaderRewardButton = () => {
  const { data, isLoading, error } = useSubgraphInfo();
  
  if (isLoading) return <LoadingSpinner />; // Implement or import a loading component
  if (error) return <ErrorMessage message="Failed to load balance" />; // Implement or import an error component
  
  const sdh = new SubgraphDataHelper(data);
  const givBalance = sdh.getGIVTokenBalance();
  
  return (
    <HBContainer>
      <IconGIV size={24} />
      <HBContent size='Big'>
        {formatWeiHelper(givBalance.balance)}
      </HBContent>
    </HBContainer>
  );
};
src/components/modals/StakeLock/LockSlider.tsx (4)

18-18: Approve changes in imports and data fetching

The refactoring to use useSubgraphInfo simplifies the component's data fetching logic, which is a good improvement. This change aligns with the broader refactoring effort across the application.

Consider grouping related imports together for better organization. For example, you could move the new import statement next to other custom hook imports:

import { smallFormatDate } from '@/lib/helpers';
import { getUnlockDate } from '@/helpers/givpower';
import { useSubgraphInfo } from '@/hooks/useSubgraphInfo';
import config from '@/configuration';
import type { IGIVpower } from '@/types/subgraph';

Also applies to: 30-32


Line range hint 46-57: Extract slider configuration for better maintainability

Consider extracting the slider configuration into a separate constant object. This would improve readability and make it easier to modify the slider's appearance in the future.

Here's an example of how you could refactor this:

const sliderConfig = {
  min: 0,
  max: maxRound,
  railStyle: { backgroundColor: brandColors.giv[800] },
  trackStyle: { backgroundColor: brandColors.giv[200] },
  handleStyle: {
    backgroundColor: brandColors.giv[500],
    border: '3px solid #F6F3FF',
  },
};

// In the JSX
<StyledSlider
  {...sliderConfig}
  onChange={value => {
    const _value = Array.isArray(value) ? value[0] : value;
    setRound(_value);
    setIsChanged(true);
  }}
  value={round}
/>

Line range hint 138-140: Use a more descriptive name for the Flex1 styled component

The name Flex1 is not very descriptive. Consider using a more meaningful name that describes its purpose or role in the layout.

For example, you could rename it to something like:

const FlexSpacer = styled.div`
  flex: 1;
`;

This makes it clearer that this component is used to create space between other elements in a flex container.


Line range hint 46-57: Improve accessibility of the slider component

The current implementation of the slider might not be fully accessible. Consider adding ARIA attributes to improve its accessibility for users with assistive technologies.

Here's an example of how you could enhance the accessibility:

<StyledSlider
  // ... other props
  aria-label={formatMessage({ id: 'label.rounds_to_lock' })}
  aria-valuemin={0}
  aria-valuemax={maxRound}
  aria-valuenow={round}
  aria-valuetext={`${round} ${formatMessage({ id: 'label.rounds' })}`}
/>

Also, consider adding keyboard support for adjusting the slider value, if not already provided by the rc-slider component.

src/components/views/userProfile/boostedTab/ProfileBoostedTab.tsx (1)

Line range hint 1-238: Summary: Improved data fetching with custom hook

The changes in this file successfully refactor the subgraph data fetching logic by introducing the useFetchSubgraphDataForAllChains custom hook. This aligns with the PR objectives of streamlining data fetching from subgraphs and should improve code maintainability.

Key points:

  1. Replaced useQueries with a custom hook, simplifying the component.
  2. The overall functionality of the component remains intact.
  3. This change is part of a larger refactoring effort across multiple components.

To ensure the refactoring's success:

  1. Verify that the new hook provides the same data structure as the previous implementation.
  2. Check for consistent usage of the new hook across the codebase.
  3. Run thorough tests to catch any potential regressions in functionality.

Consider documenting the new data fetching pattern in the project's documentation to ensure consistent usage across the team.

src/lib/subgraph/subgraphDataTransform.ts (2)

201-203: LGTM! Consider adding type safety.

The new transformIndexedBlockInfo function is well-implemented. It safely handles potential undefined values and uses optional chaining, which is good practice.

For improved type safety, consider defining an interface for the expected shape of the info object:

interface IndexedBlockInfo {
  block?: {
    number?: number;
  };
}

const transformIndexedBlockInfo = (info: IndexedBlockInfo = {}): number => {
  return info.block?.number ?? 0;
};

This change would make the function's input more explicit and catch potential type-related issues earlier.


236-238: LGTM! Consider consistent naming.

The new case for handling the _meta key is well-integrated into the existing transformSubgraphData function. It correctly utilizes the new transformIndexedBlockInfo function to process the block number information.

For consistency with other transformed properties, consider renaming the result key from indexedBlockNumber to _meta:

case key === '_meta':
  result['_meta'] = { indexedBlockNumber: transformIndexedBlockInfo(value) };
  break;

This change would maintain the structure of the original data in the transformed result, making it easier to track the source of each piece of information.

src/components/views/userProfile/ProfileOverviewTab.tsx (1)

39-39: Approve: Improved data fetching with custom hook

The replacement of useQueries with useFetchSubgraphDataForAllChains is a good refactoring step. It simplifies the component's code and aligns with the PR's objective of streamlining subgraph data fetching.

Consider adding a comment above line 116 to briefly explain what subgraphValues contains, enhancing code readability:

// Fetch subgraph data for all chains (includes GIVpower, etc.)
const subgraphValues = useFetchSubgraphDataForAllChains();

Also applies to: 116-116

src/components/GIVeconomyPages/GIVbacks.tsx (2)

55-60: LGTM: Improved state management and data fetching.

The changes to use chainId from useAccount and the introduction of useSubgraphInfo align well with the refactoring strategy. This simplifies network checks and streamlines data fetching.

Consider extracting the network number constants to improve readability:

const OPTIMISM_NETWORK = config.OPTIMISM_NETWORK_NUMBER;
const GNOSIS_NETWORK = config.GNOSIS_NETWORK_NUMBER;

const dataChainId = chainId === OPTIMISM_NETWORK ? OPTIMISM_NETWORK : GNOSIS_NETWORK;

Line range hint 165-305: Consider refactoring TabGIVbacksBottom in the future.

While this component wasn't changed in this PR, it still uses the old data fetching method with Apollo client. To maintain consistency across the application, consider refactoring this component in the future to use the new useSubgraphInfo hook or a similar custom hook for data fetching.

This would align the component with the new data handling strategy and potentially simplify its implementation.

src/components/GIVeconomyPages/GIVstream.tsx (2)

66-66: LGTM! Consider removing unused imports.

The changes improve data fetching by using the new useSubgraphInfo hook. This aligns well with the broader refactoring across the application.

Consider removing any unused imports that may have been left after this refactoring, such as the useQuery import if it's no longer used in this file.

Also applies to: 74-75


381-381: LGTM! Consider removing unused variables.

The change to use useSubgraphInfo for fetching current values is consistent with the refactoring in other components.

The 'address' variable is still being destructured from useAccount (line 380) but doesn't appear to be used in this component. Consider removing it if it's no longer needed.

src/components/cards/StakingCards/BaseStakingCard/StakingPoolInfoAndActions.tsx (3)

359-364: LGTM: Enhanced ClaimButton disabled state

The addition of !subgraphSyncedInfo.isSynced to the disabled conditions improves the reliability of the ClaimButton by preventing actions when the data might be out of sync.

Consider extracting the disabled logic into a separate variable for improved readability:

+const isClaimDisabled = exploited || earned === 0n || !started || !subgraphSyncedInfo.isSynced;

 <ClaimButton
-  disabled={
-    exploited ||
-    earned === 0n ||
-    !started ||
-    !subgraphSyncedInfo.isSynced
-  }
+  disabled={isClaimDisabled}
   onClick={() => setShowHarvestModal(true)}
   label={formatMessage({
     id: 'label.harvest_rewards',
   })}
   buttonType={isGIVpower ? 'secondary' : 'primary'}
 />

399-400: LGTM: Improved StakeButton disabled state

The addition of !subgraphSyncedInfo.isSynced to the disabled conditions enhances the StakeButton's reliability, consistent with the ClaimButton changes.

For consistency with the previous suggestion, consider extracting the disabled logic:

+const isStakeDisabled = isDiscontinued || exploited || userNotStakedAmount === 0n || !subgraphSyncedInfo.isSynced;

 <StakeButton
   label={formatMessage({
     id: 'label.stake',
   })}
   size='small'
-  disabled={
-    isDiscontinued ||
-    exploited ||
-    userNotStakedAmount === 0n ||
-    !subgraphSyncedInfo.isSynced
-  }
+  disabled={isStakeDisabled}
   onClick={() => setShowStakeModal(true)}
 />

418-421: LGTM: Enhanced UnstakeButton disabled state

The addition of !subgraphSyncedInfo.isSynced to the disabled conditions improves the UnstakeButton's reliability, consistent with the other button changes.

For consistency with the previous suggestions, consider extracting the disabled logic:

+const isUnstakeDisabled = availableStakedToken === 0n || !subgraphSyncedInfo.isSynced;

 <StakeButton
   label={formatMessage({
     id: 'label.unstake',
   })}
   size='small'
-  disabled={
-    availableStakedToken === 0n ||
-    !subgraphSyncedInfo.isSynced
-  }
+  disabled={isUnstakeDisabled}
   onClick={() => setShowUnStakeModal(true)}
 />
src/components/modals/HarvestAll.tsx (1)

259-267: Approve new event dispatching and suggest consistent application

The addition of the 'chainEvent' CustomEvent is a good way to notify other parts of the application about successful transactions. This can be useful for updating related components or triggering additional actions.

Consider applying this event dispatching logic consistently to both branches of the conditional (poolStakingConfig and non-poolStakingConfig) to ensure uniform behavior across different types of transactions.

 // In the poolStakingConfig branch
 if (status) {
+  const event = new CustomEvent('chainEvent', {
+    detail: {
+      type: 'success',
+      chainId: chainId,
+      blockNumber: blockNumber, // Make sure to extract blockNumber as suggested in the previous comment
+      address: address,
+    },
+  });
+  window.dispatchEvent(event);
   setState(HarvestStates.CONFIRMED);
 } else {
   setState(HarvestStates.ERROR);
 }
pages/test2.tsx (2)

26-29: Replace placeholder in 'queryFn' with actual data fetching

Currently, the queryFn in useQuery returns a constant 0. If this is a placeholder, consider implementing the actual data fetching logic to retrieve the interactedBlockNumber. This ensures that data reflects real values and improves the usefulness of the query.


32-32: Consider removing console.log statements

If console.log('data', data); is used for debugging, consider removing it or using a proper logging mechanism before deploying to production.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 783616a and 8f5288f.

📒 Files selected for processing (30)
  • pages/test2.tsx (3 hunks)
  • src/components/GIVeconomyPages/GIVbacks.tsx (2 hunks)
  • src/components/GIVeconomyPages/GIVpower.tsx (1 hunks)
  • src/components/GIVeconomyPages/GIVstream.tsx (4 hunks)
  • src/components/cards/StakingCards/BaseStakingCard/StakingPoolInfoAndActions.tsx (6 hunks)
  • src/components/cards/StakingCards/GIVpowerCard/GIVpowerCardIntro.tsx (2 hunks)
  • src/components/controller/subgraph.ctrl.tsx (2 hunks)
  • src/components/givfarm/RegenStreamCard.tsx (2 hunks)
  • src/components/menu/RewardButtonWithMenu.tsx (2 hunks)
  • src/components/menu/RewardItems.tsx (2 hunks)
  • src/components/modals/Boost/BoostModal.tsx (2 hunks)
  • src/components/modals/GIVdropHarvestModal.tsx (2 hunks)
  • src/components/modals/HarvestAll.tsx (1 hunks)
  • src/components/modals/StakeLock/LockSlider.tsx (2 hunks)
  • src/components/modals/StakeLock/LockingBrief.tsx (2 hunks)
  • src/components/modals/StakeLock/TotalGIVpowerBox.tsx (1 hunks)
  • src/components/views/claim/cards/Govern.tsx (2 hunks)
  • src/components/views/claim/cards/Stake.tsx (2 hunks)
  • src/components/views/userProfile/ProfileOverviewTab.tsx (2 hunks)
  • src/components/views/userProfile/boostedTab/EmptyPowerBoosting.tsx (1 hunks)
  • src/components/views/userProfile/boostedTab/ProfileBoostedTab.tsx (2 hunks)
  • src/hooks/useFetchSubgraphDataForAllChains.ts (1 hunks)
  • src/hooks/useGIVTokenDistroHelper.ts (2 hunks)
  • src/hooks/useInteractedBlockNumber.ts (1 hunks)
  • src/hooks/useStakingPool.ts (2 hunks)
  • src/hooks/useSubgraphInfo.ts (1 hunks)
  • src/hooks/useSubgraphSyncInfo.ts (1 hunks)
  • src/hooks/useTokenDistroHelper.ts (2 hunks)
  • src/lib/subgraph/subgraphDataTransform.ts (2 hunks)
  • src/lib/subgraph/subgraphQueryBuilder.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (73)
src/hooks/useInteractedBlockNumber.ts (2)

1-2: LGTM: Imports are correctly defined and necessary.

The import statements are concise and include only the required dependencies for the hook's functionality.


1-11: Overall assessment: Well-structured hook with potential implementation concerns

The useInteractedBlockNumber hook is well-structured and follows React conventions. However, there are concerns about its current implementation:

  1. The query function always returns 0, which may not reflect real-world usage.
  2. The Infinity stale time might not be suitable for all use cases.

These issues should be addressed to ensure the hook functions as intended within the larger system.

To better understand the context and usage of this hook, let's examine the SubgraphController component mentioned in the AI summary:

#!/bin/bash
# Search for the SubgraphController component
rg -A 20 "SubgraphController.*=.*" src/components/controller/subgraph.ctrl.tsx
src/hooks/useSubgraphInfo.ts (2)

1-4: LGTM: Imports look good and are properly utilized.

The imports are correctly bringing in the necessary dependencies for the hook's functionality.


1-15: Overall, excellent implementation of the useSubgraphInfo hook.

This new custom hook centralizes subgraph data fetching, which should improve code maintainability and consistency across the application. The implementation follows React and TypeScript best practices, with good use of React Query and Wagmi hooks.

A few minor suggestions have been made for further improvement, but the overall structure and functionality of the hook are solid. Great job on this addition!

src/hooks/useFetchSubgraphDataForAllChains.ts (3)

1-5: LGTM: Import statements are well-organized and follow best practices.

The import statements are concise, use named imports where appropriate, and follow the project's conventions for import paths.


7-9: LGTM: Hook implementation is clear and follows best practices.

The useFetchSubgraphDataForAllChains hook is well-named and efficiently combines useAccount with useQueries to fetch subgraph data for all chains.


1-21: Great implementation that aligns well with PR objectives.

This new useFetchSubgraphDataForAllChains hook effectively streamlines data fetching from subgraphs across multiple chains. It's well-implemented, following React and react-query best practices, and will significantly simplify data management across the application. This aligns perfectly with the PR's goal of enhancing code clarity and maintainability.

The only suggestion for improvement is to add error handling and retry logic, as mentioned in the previous comment. Otherwise, this is a solid addition to the codebase.

src/hooks/useSubgraphSyncInfo.ts (3)

1-4: LGTM: Imports are well-organized and necessary.

The imports are correctly structured, with external libraries first followed by local imports. All imported items are used in the hook, maintaining a clean and efficient import structure.


26-30: LGTM: Return statement is concise and provides all necessary data.

The hook returns an object with all the relevant information: isSynced, interactedBlockNumber, and indexedBlockNumber. This structure allows consumers of the hook to access all the necessary data easily.


1-31: Overall, excellent implementation of the useSubgraphSyncInfo hook.

This new hook effectively combines data from multiple sources to determine if the subgraph is synced, which is crucial for the PR's objective of disabling actions when data is not synced. The implementation is well-structured, uses React hooks effectively, and follows best practices.

The hook's return value, particularly the isSynced boolean, will be valuable for components that need to make decisions based on the subgraph's sync status, such as the StakingPoolInfoAndActions component mentioned in the summary.

Minor suggestions for improvement:

  1. Add explicit typing for the chainId parameter.
  2. Implement error logging in the isSynced calculation.

These changes will further enhance the robustness and maintainability of the code.

src/hooks/useTokenDistroHelper.ts (3)

5-5: LGTM: Import changes align with new data fetching approach.

The addition of useSubgraphInfo and removal of useAccount are consistent with the refactoring to streamline data fetching from subgraphs.


14-14: LGTM: Simplified data fetching with useSubgraphInfo.

The replacement of useQuery with useSubgraphInfo streamlines the data fetching process and aligns with the broader refactoring effort. This change should improve code maintainability and consistency across the application.


Line range hint 1-43: Overall: Successful refactoring with minor improvement suggestion.

The changes to useTokenDistroHelper successfully implement the broader refactoring strategy of streamlining data fetching from subgraphs. The core functionality is preserved while simplifying the hook's implementation. The use of useSubgraphInfo aligns with the project's direction and should improve maintainability.

To further enhance the hook, consider the useCallback optimization suggested earlier. This would be a minor but valuable improvement to the already solid implementation.

src/components/modals/StakeLock/LockingBrief.tsx (1)

21-22: Approved: Simplified data fetching logic

The use of useSubgraphInfo with a fixed network number simplifies the data fetching process. However, this change might affect the component's reactivity to user account changes.

Please verify that the component still updates correctly when the user switches accounts. You can use the following script to check for any remaining references to account-based queries in this file:

src/hooks/useGIVTokenDistroHelper.ts (2)

5-5: LGTM: Import changes align with new implementation.

The addition of useSubgraphInfo import and removal of unused imports improve code cleanliness and reflect the updated hook implementation.


20-20: LGTM: Improved type safety for function parameter.

The explicit type declaration for the hold parameter enhances type safety and code readability while maintaining the existing default value.

src/hooks/useStakingPool.ts (2)

11-11: LGTM: Import of new custom hook.

The addition of useSubgraphInfo import aligns with the broader refactoring effort to streamline data fetching from subgraphs.


Line range hint 1-76: Overall: Good refactoring, verify impact on dependent components.

The changes to useStakingPool are part of a larger refactoring effort to streamline data fetching from subgraphs. The replacement of useQuery with useSubgraphInfo simplifies the code and should improve maintainability. However, it's crucial to ensure that this change doesn't inadvertently affect the behavior of components relying on this hook.

To ensure the refactoring hasn't introduced any regressions:

  1. Review and update unit tests for this hook if they exist.
  2. Manually test components that use useStakingPool to verify they still function as expected.
  3. Consider adding integration tests if they don't already exist to catch any potential issues in the data flow.
#!/bin/bash
# Description: Find components using useStakingPool for manual testing

echo "Components using useStakingPool:"
rg -n "useStakingPool\(" --type tsx
src/components/modals/StakeLock/TotalGIVpowerBox.tsx (4)

16-16: Approve import changes: Shift to custom hook for subgraph data fetching

The introduction of useFetchSubgraphDataForAllChains and removal of useQueries reflects a positive shift towards using a custom hook for subgraph data fetching. This change aligns with the broader refactoring effort mentioned in the PR summary, potentially improving code maintainability and consistency across the application.


22-22: Approve use of custom hook: Simplified subgraph data fetching

The replacement of useQueries with useFetchSubgraphDataForAllChains streamlines the data fetching process. This change enhances code readability and maintainability by encapsulating the complexity of fetching subgraph data for multiple chains within a custom hook.


Line range hint 1-108: Summary: Successful refactoring with a minor performance consideration

The changes in this file successfully implement the refactoring strategy outlined in the PR objectives. The shift to using useFetchSubgraphDataForAllChains aligns with the broader effort to streamline data fetching across the application. The core functionality of the TotalGIVpowerBox component remains intact, which is positive.

Key points:

  1. The custom hook improves code maintainability and consistency.
  2. The component's logic and error handling remain robust.
  3. There's a potential performance optimization opportunity regarding re-renders.

Overall, these changes represent a positive step in improving the application's architecture. The only action item is to address the potential re-render issue highlighted in the TODO comment.


Line range hint 50-50: Address TODO comment: Potential unnecessary re-renders

The TODO comment raises a valid concern about potential unnecessary re-renders. To address this:

  1. Evaluate if all dependencies in the useEffect hook's dependency array are necessary.
  2. Consider memoizing the subgraphValues if they're complex objects to prevent unnecessary re-renders.
  3. Use the React DevTools Profiler to measure the impact of these dependencies on component re-renders.

To help investigate this issue, you can run the following command to check for other usages of useFetchSubgraphDataForAllChains and how they handle potential re-renders:

src/components/modals/Boost/BoostModal.tsx (1)

14-14: LGTM: Import change aligns with refactoring strategy

The introduction of useFetchSubgraphDataForAllChains hook and removal of fetchSubgraphData import aligns well with the overall refactoring strategy to streamline data fetching from subgraphs. This change enhances code modularity and maintainability.

src/components/cards/StakingCards/GIVpowerCard/GIVpowerCardIntro.tsx (3)

43-44: Approve logic change and verify component behavior.

The switch to useSubgraphInfo simplifies the data fetching logic and removes the direct dependency on user account information. This change is consistent with the broader refactoring effort and should improve code maintainability.

To ensure the component behavior remains correct after this change, please verify the following:

  1. The SubgraphDataHelper is still instantiated correctly with the data from useSubgraphInfo.
  2. The getUserGIVLockedBalance() method is called and returns the expected result.
  3. The component renders correctly with the fetched data.

You may want to add unit tests or update existing ones to cover these scenarios.


Line range hint 1-138: Summary: Approved changes align with refactoring objectives.

The modifications to GIVpowerCardIntro.tsx are consistent with the broader refactoring effort mentioned in the PR objectives and AI summary. The changes improve code consistency and maintainability by streamlining the data fetching process. No apparent issues or inconsistencies were found.

Key points:

  1. Replaced useQuery with a custom useSubgraphInfo hook.
  2. Removed direct dependency on user account information.
  3. Maintained existing functionality while simplifying the implementation.

These changes should contribute to a more maintainable and efficient codebase.


25-25: Approve import change and verify new hook implementation.

The shift from useQuery and useAccount to useSubgraphInfo aligns with the broader refactoring effort to streamline subgraph data fetching. This change should improve code maintainability and consistency across components.

To ensure the new hook is implemented correctly, please run the following script:

src/components/menu/RewardButtonWithMenu.tsx (3)

23-23: Import changes align with refactoring goals.

The addition of useSubgraphInfo and removal of useAccount and useQuery imports align well with the broader refactoring effort to streamline data fetching from subgraphs. This change centralizes the subgraph data retrieval logic, potentially improving maintainability.


100-100: Simplified data fetching with useSubgraphInfo.

The transition to useSubgraphInfo successfully simplifies the data fetching process, aligning with the broader refactoring goals. This change enhances code clarity and maintainability by centralizing the subgraph data retrieval logic.


Line range hint 1-110: Summary: Successful refactoring with room for enhancement

The changes in this file successfully contribute to the larger refactoring effort to streamline data fetching from subgraphs. The transition to useSubgraphInfo simplifies the code and improves maintainability while preserving the core functionality of the RewardButtonWithMenu component.

To further enhance this refactoring:

  1. Consider adding error handling and loading state management to improve user experience.
  2. Ensure that the useSubgraphInfo hook is thoroughly tested, as it now plays a central role in data fetching across multiple components.
  3. Update the component's documentation to reflect these changes, if applicable.

Overall, these changes represent a positive step towards a more maintainable and efficient codebase.

src/components/views/userProfile/boostedTab/ProfileBoostedTab.tsx (2)

40-40: LGTM! Verify data structure and usage consistency.

The simplification of subgraph data fetching using useFetchSubgraphDataForAllChains improves code maintainability. However, we should ensure that the new implementation provides the same data structure and functionality as the previous one.

Let's verify the consistency of the data structure and its usage:

#!/bin/bash
# Description: Verify the consistency of subgraph data structure and usage

# Test 1: Check the return type of useFetchSubgraphDataForAllChains
echo "Checking return type of useFetchSubgraphDataForAllChains:"
rg -p 'export function useFetchSubgraphDataForAllChains' -A 10 src/hooks/useFetchSubgraphDataForAllChains.ts

# Test 2: Verify usage of subgraphValues in this file
echo "\nChecking usage of subgraphValues in ProfileBoostedTab.tsx:"
rg 'subgraphValues' src/components/views/userProfile/boostedTab/ProfileBoostedTab.tsx

# Test 3: Check for any potential type errors or unused variables
echo "\nChecking for type errors or unused variables:"
rg '(subgraphValues|useFetchSubgraphDataForAllChains).*: any' src
rg 'eslint-disable-next-line @typescript-eslint/no-unused-vars' src/components/views/userProfile/boostedTab/ProfileBoostedTab.tsx

31-31: LGTM! Verify the implementation of the new custom hook.

The change from useQueries to useFetchSubgraphDataForAllChains aligns with the refactoring effort mentioned in the PR summary. This abstraction should simplify subgraph data fetching across the application.

To ensure consistency, let's verify the implementation and usage of this new hook:

src/lib/subgraph/subgraphQueryBuilder.ts (3)

16-23: LGTM: New method getIndexedBlockQuery looks good.

The new static method getIndexedBlockQuery is well-implemented. It follows the existing coding style and correctly constructs a GraphQL query to retrieve the block number from the _meta field.


245-245: LGTM: Integration of getIndexedBlockQuery in getChainQuery.

The new getIndexedBlockQuery is correctly integrated into the getChainQuery method. Its placement at the beginning of the query string is appropriate, and it doesn't interfere with the existing functionality.


16-23: Request for clarification: Purpose of the new indexed block query.

The addition of the getIndexedBlockQuery and its integration into getChainQuery is well-implemented. However, it would be helpful to understand the purpose of this new query:

  1. Why is the indexed block information needed?
  2. How will this information be used in the application?

Consider adding a comment to explain the purpose of this query, which would improve the code's maintainability and help future developers understand its importance.

To better understand the context, let's check for any related changes or usage of this new query:

Also applies to: 245-245

src/lib/subgraph/subgraphDataTransform.ts (1)

Line range hint 201-238: Overall, the changes look good and enhance subgraph data handling.

The addition of transformIndexedBlockInfo and the modification to transformSubgraphData improve the handling of indexed block information, aligning well with the PR's objective of streamlining subgraph data fetching.

To ensure these changes are properly integrated, let's verify the usage of indexedBlockNumber in other parts of the codebase:

This script will help identify where the new indexedBlockNumber is being used and if there are any instances of _meta that might need to be updated to use the new transformation.

✅ Verification successful

Verification Successful: indexedBlockNumber is correctly integrated and _meta has been removed.

  • indexedBlockNumber is used in:
    • src/hooks/useSubgraphSyncInfo.ts
    • src/lib/subgraph/subgraphDataTransform.ts
  • No remaining usages of _meta found in the codebase.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usage of indexedBlockNumber in the codebase

echo "Searching for indexedBlockNumber usage:"
rg "indexedBlockNumber" --type ts --type tsx

echo "\nChecking for potential missed usages of _meta:"
rg "_meta\s*[:=]" --type ts --type tsx

Length of output: 337


Script:

#!/bin/bash
# Description: Check for usage of indexedBlockNumber in the codebase

echo "Searching for indexedBlockNumber usage:"
rg "indexedBlockNumber" -g "*.ts" -g "*.tsx"

echo "\nChecking for potential missed usages of _meta:"
rg "_meta\s*[:=]" -g "*.ts" -g "*.tsx"

Length of output: 919

src/components/views/userProfile/ProfileOverviewTab.tsx (1)

Line range hint 1-285: LGTM: Focused refactoring with minimal impact

The changes are focused on improving data fetching while maintaining the component's existing functionality. The rest of the component remains unchanged, which is good for maintaining stability.

To ensure the refactoring didn't introduce any regressions, please verify that:

  1. The ProfileOverviewTab component renders correctly with the new data fetching method.
  2. The GIVpower values are displayed accurately.
  3. The component's behavior remains the same as before the changes.

You can use the following script to check for any unexpected changes in the component's rendering or behavior:

✅ Verification successful

LGTM: Refactoring Verified Successfully

The verification scripts did not find any errors or unexpected changes in the ProfileOverviewTab component. All data fetching and sub-component renderings are functioning as expected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for unexpected changes in ProfileOverviewTab component

# Test: Look for any error logs or unexpected console outputs related to ProfileOverviewTab
rg -i 'error|warning|unexpected' -g '!*.md' -g '!*.json' | rg 'ProfileOverviewTab'

# Test: Check if the GIVpower calculation is still being used correctly
rg 'getTotalGIVpower' -A 5 -B 5

# Test: Verify that the component is still rendering all necessary sub-components
rg '<(DonateContributeCard|ProjectsContributeCard|ContributeCard|PublicGIVpowerContributeCard|QFDonorEligibilityCard)' src/components/views/userProfile/ProfileOverviewTab.tsx

Length of output: 16142

src/components/views/claim/cards/Govern.tsx (4)

37-37: LGTM: New hook import for subgraph data fetching.

The import of useSubgraphInfo aligns with the refactoring effort to streamline data fetching from subgraphs.


113-113: LGTM: Replaced query with custom hook for subgraph data.

The use of useSubgraphInfo simplifies the data fetching process. However, please ensure that the gnosisValues object returned by this hook provides all the necessary data that was previously fetched using useQuery.

#!/bin/bash
# Verify the usage of 'gnosisValues' in the component
rg '\bgnosisValues\b' src/components/views/claim/cards/Govern.tsx

Line range hint 37-113: Overall: Good refactoring, suggest thorough testing.

The changes in this file align well with the broader refactoring effort to streamline data fetching and improve code maintainability. The introduction of the useSubgraphInfo hook and the simplification of account data usage are positive improvements.

To ensure the refactoring hasn't introduced any regressions:

  1. Verify that all functionality previously dependent on the chain variable still works correctly.
  2. Confirm that the gnosisValues object provides all necessary data previously fetched via useQuery.
  3. Conduct thorough testing of the GovernCard component to ensure it behaves as expected with these changes.
#!/bin/bash
# List all files that import or use GovernCard to identify potential areas for integration testing
rg -l 'GovernCard' src/

111-111: LGTM: Simplified account hook usage.

The change to directly extract chainId aligns with the refactoring effort. However, please verify that the removal of the chain variable doesn't impact any other part of the component.

src/components/views/claim/cards/Stake.tsx (4)

35-35: LGTM: Import statements updated to use custom hook.

The changes in the import statements reflect the shift from using useQuery and useAccount to a custom useSubgraphInfo hook. This aligns with the overall refactoring strategy mentioned in the PR summary, which aims to streamline data fetching from subgraphs.


97-98: LGTM: Data fetching logic simplified using custom hook.

The implementation now uses useSubgraphInfo for both Gnosis and Mainnet networks, replacing the previous separate queries. This change simplifies the data fetching logic and aligns with the PR's objective of streamlining subgraph data access.


Line range hint 133-133: LGTM: APR calculation logic updated to use new data sources.

The APR calculation logic has been updated to use the new data sources (gnosisValues and mainnetValues) from the useSubgraphInfo hook. The additional check ensures that APR is calculated only when data from both networks is available, improving the robustness of the calculation.


Line range hint 1-270: Overall assessment: Changes improve code maintainability and align with PR objectives.

The modifications in this file successfully refactor the data fetching mechanism to use the custom useSubgraphInfo hook. This change:

  1. Simplifies the component's data fetching logic.
  2. Improves code maintainability by centralizing subgraph data access.
  3. Aligns with the PR's objective of streamlining data fetching from subgraphs.

The core functionality of the InvestCard component remains intact, with the APR calculation logic updated to work with the new data sources. These changes contribute to a more efficient and maintainable codebase.

src/components/GIVeconomyPages/GIVbacks.tsx (3)

47-47: LGTM: New hook import aligns with refactoring strategy.

The addition of the useSubgraphInfo hook import is consistent with the overall refactoring strategy to improve data fetching from subgraphs.


104-104: LGTM: Consistent use of chainId.

The update to use chainId in the network prop of GIVbackRewardCard maintains consistency with the earlier changes and ensures the component receives the correct network information.


Line range hint 1-305: Summary: Successful refactoring with room for future improvements.

The changes in this file successfully implement the refactoring strategy to improve data fetching and state management. The introduction of the useSubgraphInfo hook and the consistent use of chainId enhance code clarity and maintainability.

Key improvements:

  1. Simplified network configuration checks
  2. Streamlined data fetching with useSubgraphInfo
  3. Consistent use of chainId across the component

While the TabGIVbacksTop component has been successfully refactored, the TabGIVbacksBottom component still uses the old data fetching method. Consider refactoring this component in a future PR to fully align the file with the new data handling strategy.

Overall, these changes contribute positively to the codebase's quality and consistency.

src/components/givfarm/RegenStreamCard.tsx (4)

39-39: LGTM: Import of custom hook for subgraph data.

The addition of the useSubgraphInfo hook import aligns with the PR objective of streamlining data fetching from subgraphs. This change should improve code organization and reusability.


Line range hint 1-467: Summary of changes in RegenStreamCard.tsx

The changes in this file align well with the PR objectives:

  1. Introduction of useSubgraphInfo hook simplifies data fetching.
  2. Removal of address from useAccount destructuring potentially simplifies the component's logic.
  3. Replacement of useQuery with useSubgraphInfo streamlines subgraph data handling.

These changes should improve code maintainability and organization. However, please ensure to run the provided verification scripts to confirm that no functionality has been inadvertently broken and that all necessary data is still being fetched and used correctly.


67-67: Verify data completeness with new useSubgraphInfo hook.

The replacement of useQuery with useSubgraphInfo simplifies the data fetching logic and aligns with the PR objective. This change should improve code maintainability. However, please ensure that all necessary data is still being fetched and used correctly throughout the component.

To verify this change, please run the following script:

✅ Verification successful

Data completeness verified with new useSubgraphInfo hook.

The replacement of useQuery with useSubgraphInfo has been successfully verified. All necessary data is being fetched and utilized correctly within the component.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the implementation of useSubgraphInfo and its usage in RegenStreamCard

# Test 1: Check the implementation of useSubgraphInfo
echo "Checking useSubgraphInfo implementation:"
rg -A 20 'export const useSubgraphInfo' src/hooks/useSubgraphInfo.ts

# Test 2: Compare the returned data structure from useSubgraphInfo with the previous useQuery
echo "Comparing data structure:"
rg 'const currentValues = useSubgraphInfo' src/components/givfarm/RegenStreamCard.tsx -C 10

# Test 3: Check for any uses of currentValues to ensure all necessary data is accessed
echo "Checking uses of currentValues:"
rg 'currentValues\.' src/components/givfarm/RegenStreamCard.tsx

Length of output: 1620


Script:

#!/bin/bash
# Description: Compare data structures of useQuery and useSubgraphInfo in RegenStreamCard

# Test 1: Retrieve previous useQuery data structure
echo "Retrieving previous useQuery data structure:"
rg -A 15 'const currentValues = useQuery' src/components/givfarm/RegenStreamCard.tsx

# Test 2: Retrieve useSubgraphInfo data structure
echo "Retrieving useSubgraphInfo data structure:"
rg -A 15 'const currentValues = useSubgraphInfo' src/components/givfarm/RegenStreamCard.tsx

# Test 3: Compare data fields accessed from currentValues
echo "Listing data fields accessed from currentValues with useSubgraphInfo:"
rg 'currentValues\.' src/components/givfarm/RegenStreamCard.tsx

Length of output: 1093


65-65: Verify removal of address from useAccount destructuring.

The change to only destructure chain from useAccount aligns with simplifying the component's logic. However, please ensure that removing address doesn't inadvertently break any functionality within this component or its children.

To verify this change, please run the following script:

src/components/modals/GIVdropHarvestModal.tsx (4)

44-44: LGTM: New hook import for improved data fetching.

The addition of the useSubgraphInfo hook aligns with the PR's objective of streamlining data fetching from subgraphs. This change enhances code maintainability and consistency across components.


82-82: LGTM: Consistent use of chainId from useAccount hook.

The change from chain to chainId in the destructured output of useAccount improves consistency across components. This update aligns with the broader refactoring effort mentioned in the PR summary.


83-83: LGTM: Simplified data fetching with useSubgraphInfo.

The replacement of the query with useSubgraphInfo hook simplifies the data fetching logic. This change is in line with the PR's objective of streamlining subgraph data retrieval, potentially improving performance and reducing code complexity.


Line range hint 44-83: Verify component functionality after data fetching changes.

The updates to data fetching and chainId usage improve code consistency and maintainability. However, it's crucial to ensure these changes haven't inadvertently affected the component's functionality.

Please run the following script to check for any regressions in the GIVdropHarvestModal component:

src/components/GIVeconomyPages/GIVstream.tsx (2)

175-175: LGTM! Consistent use of useSubgraphInfo.

The change to use useSubgraphInfo for fetching current values is consistent with the refactoring in other components.


Line range hint 1-489: Overall, the changes improve code consistency and simplify data fetching.

The refactoring to use useSubgraphInfo across all components in this file aligns well with the broader modifications mentioned in the PR summary. These changes should enhance maintainability and readability of the codebase.

To ensure that all instances of useQuery have been replaced and there are no leftover imports, run the following script:

src/components/cards/StakingCards/BaseStakingCard/StakingPoolInfoAndActions.tsx (2)

57-57: LGTM: Subgraph sync status integration

The addition of useSubgraphSyncInfo hook enhances the component's ability to manage data synchronization state. This change aligns well with the overall effort to improve data handling across the application.

Also applies to: 91-91


Line range hint 1-545: Overall: Consistent integration of subgraph sync status

The changes in this file effectively integrate the subgraph synchronization status across multiple interactive elements. This enhancement improves the reliability of user interactions and aligns well with the broader refactoring efforts to streamline data handling in the application.

Consider implementing the suggested readability improvements for consistency across the component.

src/components/modals/HarvestAll.tsx (1)

Line range hint 1-724: Overall assessment: Positive changes with room for consistency improvements

The changes to the HarvestAllModal component, particularly in the onHarvest function, are generally positive. They provide more detailed transaction information and introduce event dispatching for better inter-component communication. To further improve the code:

  1. Apply the blockNumber extraction consistently across all transaction types.
  2. Implement the 'chainEvent' dispatching for all successful transactions, regardless of the transaction type.

These consistency improvements will enhance the overall reliability and maintainability of the component.

src/components/views/userProfile/boostedTab/EmptyPowerBoosting.tsx (1)

14-14: Importing the custom hook correctly

The useFetchSubgraphDataForAllChains hook is correctly imported from the appropriate path.

src/components/controller/subgraph.ctrl.tsx (3)

3-7: Imports are appropriately added

The new imports for useQueryClient, fetchLatestIndexedBlock, useFetchSubgraphDataForAllChains, and useInteractedBlockNumber are correctly introduced and align with their usage in the component.


10-10: Destructure 'chain' alongside 'address' from useAccount

Including both address and chain from the useAccount() hook allows for better management of account and chain-specific data, which is necessary for subsequent operations.


39-42: Consistently update the query cache with setQueryData

Using queryClient.setQueryData to update the 'interactedBlockNumber' cache with the new blockNumber is appropriate. Ensure that the query key ['interactedBlockNumber', eventChainId] is used consistently throughout the application to prevent cache inconsistencies.

You can verify the consistency of the query key across the codebase with the following script:

✅ Verification successful

Consistent Query Key Usage Confirmed

All instances of queryClient.setQueryData use the 'interactedBlockNumber' query key with appropriate chain ID variables, ensuring cache consistency across the application.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of the 'interactedBlockNumber' query key.

# Test: Search for all instances of 'interactedBlockNumber' in query keys.
# Expectation: All instances should use ['interactedBlockNumber', chainId].

rg -o "['\"]interactedBlockNumber['\"],\s*[\w\.]+" --glob "**/*.ts*" .

Length of output: 335


Script:

#!/bin/bash
# Description: Locate definitions of chain ID variables used with 'interactedBlockNumber'.

# Variables to investigate:
# - _chainId
# - eventChainId
# - chain
# - chain.id

# Search for declarations or assignments of the variables
rg -n -e "const\s+_chainId\s*=" -e "let\s+_chainId\s*=" \
     -e "const\s+eventChainId\s*=" -e "let\s+eventChainId\s*=" \
     -e "const\s+chain\s*=" -e "let\s+chain\s*=" .

# Additionally, search for usages of 'chain.id' to understand its context
rg -n "chain\.id" .

Length of output: 2630

pages/test2.tsx (6)

2-2: Importing 'useQuery' and 'useQueryClient'

The import statement correctly adds useQuery and useQueryClient from @tanstack/react-query.


17-17: Importing custom hook 'useFetchSubgraphDataForAllChains'

Properly importing the custom hook for subgraph data fetching.


22-22: Initializing 'queryClient'

Correctly initializing queryClient using useQueryClient().


23-23: Verify destructuring of 'chain' from 'useAccount'

While useAccount() provides address, ensure that chain is indeed part of its return value. In some versions of wagmi, chain is retrieved using useNetwork(). Confirm that chain is correctly obtained here.


24-24: Using 'useFetchSubgraphDataForAllChains' hook

Appropriately utilizing the custom hook to fetch subgraph data.


129-144: New UI elements for displaying and updating query data

The added UI effectively displays the data from the query and allows updating the query data using queryClient.setQueryData. This enhances interactivity and aligns with the desired user experience.

src/components/menu/RewardItems.tsx (2)

39-39: Import of useSubgraphInfo is correct

The addition of useSubgraphInfo from the custom hook is appropriate.


58-58: Usage of useSubgraphInfo hook is appropriate

The use of useSubgraphInfo() without parameters is correct if the hook internally handles the required context.

src/components/GIVeconomyPages/GIVpower.tsx (1)

63-63: Import statement updated appropriately

The import of useFetchSubgraphDataForAllChains from '@/hooks/useFetchSubgraphDataForAllChains' is correct and aligns with the updated data fetching approach.

src/hooks/useInteractedBlockNumber.ts Show resolved Hide resolved
src/hooks/useSubgraphInfo.ts Show resolved Hide resolved
src/hooks/useStakingPool.ts Show resolved Hide resolved
src/components/modals/HarvestAll.tsx Show resolved Hide resolved
src/components/controller/subgraph.ctrl.tsx Outdated Show resolved Hide resolved
src/components/menu/RewardItems.tsx Show resolved Hide resolved
src/components/GIVeconomyPages/GIVpower.tsx Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (4)
src/components/controller/subgraph.ctrl.tsx (4)

14-15: LGTM: New hooks introduced for improved data management

The introduction of useFetchSubgraphDataForAllChains and useInteractedBlockNumber aligns with the refactoring strategy, consolidating data fetching and management logic.

Consider adding a brief comment explaining the purpose of each hook for improved code readability:

// Fetch subgraph data for all chains
useFetchSubgraphDataForAllChains();

// Manage the interacted block number
useInteractedBlockNumber();

39-42: LGTM: Interacted block number update added

The addition of queryClient.setQueryData for updating the interacted block number is consistent with the new data management approach.

Consider adding a type check for blockNumber to ensure it's a valid number:

if (typeof blockNumber === 'number') {
  queryClient.setQueryData(
    ['interactedBlockNumber', eventChainId],
    blockNumber
  );
} else {
  console.warn(`Invalid block number received: ${blockNumber}`);
}

This will help prevent potential issues if an invalid block number is received.


Line range hint 17-95: LGTM: Event handling and polling mechanism updated

The changes to the handleEvent function and the useEffect hook successfully adapt the existing functionality to the new data fetching approach. The use of refetchedChainsRef is a good optimization to prevent unnecessary refetches.

Consider extracting the pollLatestBlock function outside of the useEffect hook to improve readability:

const pollLatestBlock = async (eventChainId: number, blockNumber: number, eventAddress: Address) => {
  const latestBlockNumber = await fetchLatestIndexedBlock(eventChainId);
  console.log('event latestBlockNumber', latestBlockNumber);

  if (latestBlockNumber >= blockNumber && !refetchedChainsRef.current.has(eventChainId)) {
    refetchedChainsRef.current.add(eventChainId);
    console.log('event Refetching queries for chain', latestBlockNumber, blockNumber);

    queryClient.refetchQueries({
      queryKey: ['subgraph', eventChainId, eventAddress],
    });
  } else {
    // Schedule next check if condition is not met
    pollingTimeoutsRef.current[eventChainId] = setTimeout(
      () => pollLatestBlock(eventChainId, blockNumber, eventAddress),
      2000
    );
  }
};

// Then in the useEffect:
if (type === 'success' && eventChainId) {
  // ... existing code ...
  pollingTimeoutsRef.current[eventChainId] = setTimeout(
    () => pollLatestBlock(eventChainId, blockNumber, eventAddress),
    3000
  );
}

This change would make the code more modular and easier to maintain.


Line range hint 1-101: Overall LGTM: Successful refactoring to new data management approach

The changes in this file successfully implement the new data fetching and management strategy using custom hooks. The event handling and polling mechanism have been updated to work seamlessly with this new approach.

To improve documentation and make the purpose of this component clearer, consider adding a brief comment at the top of the file explaining its role in managing subgraph data and handling chain events:

/**
 * SubgraphController
 * 
 * This component manages subgraph data fetching and synchronization across multiple chains.
 * It listens for chain events, updates the interacted block number, and triggers data refetching
 * when necessary to ensure the application has the most up-to-date subgraph data.
 */

This addition would help other developers quickly understand the purpose and importance of this component within the application.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 8f5288f and f8c556e.

📒 Files selected for processing (1)
  • src/components/controller/subgraph.ctrl.tsx (2 hunks)
🧰 Additional context used
🔇 Additional comments (1)
src/components/controller/subgraph.ctrl.tsx (1)

3-7: LGTM: Import statements updated to reflect new data fetching approach

The new imports align with the refactoring described in the PR summary, introducing custom hooks for more efficient data management across chains.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (2)
src/components/RewardCard.tsx (2)

67-67: LGTM: Hook usage is correct. Consider adding error handling.

The useSubgraphSyncInfo hook is correctly used with the network prop. The naming is clear and descriptive.

Consider adding error handling or a fallback value in case the hook fails or returns unexpected data:

const subgraphSyncedInfo = useSubgraphSyncInfo(network) || { isSynced: false };

137-140: LGTM: Button disabled state logic improved. Consider extracting the condition.

The addition of !subgraphSyncedInfo.isSynced to the disabled prop is a good improvement to prevent actions on outdated data.

For improved readability, consider extracting the condition into a separate variable:

const isButtonDisabled = liquidAmount === 0n || !subgraphSyncedInfo.isSynced;

<ActionButton
    label={actionLabel}
    onClick={actionCb}
    buttonType='primary'
    disabled={isButtonDisabled}
/>

This would make the component more readable and the condition reusable if needed elsewhere.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f8c556e and ab4262f.

📒 Files selected for processing (2)
  • src/components/GIVeconomyPages/GIVstream.tsx (4 hunks)
  • src/components/RewardCard.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/components/GIVeconomyPages/GIVstream.tsx
🧰 Additional context used
🔇 Additional comments (2)
src/components/RewardCard.tsx (2)

28-28: LGTM: New hook import looks good.

The import statement for useSubgraphSyncInfo is correctly formatted and follows React's hook naming conventions.


Line range hint 1-240: Overall, the changes improve the RewardCard component.

The addition of the useSubgraphSyncInfo hook and its integration into the ActionButton's disabled state logic enhances the component's functionality. It now prevents actions when the subgraph data is not synced, which is a good practice for data integrity.

A few minor suggestions have been made for improved error handling and code readability, but these are not critical issues. The changes are well-implemented and align with React best practices.

Copy link
Collaborator

@kkatusic kkatusic left a comment

Choose a reason for hiding this comment

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

LGTM ;), thx @MohammadPCh

Copy link
Collaborator

@Meriem-BM Meriem-BM left a comment

Choose a reason for hiding this comment

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

LGTM!

@MohammadPCh MohammadPCh merged commit 50f71a8 into develop Oct 22, 2024
3 checks passed
@MohammadPCh MohammadPCh deleted the disable-harvest-when-data-is-not-updated branch October 22, 2024 14:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: QA
Development

Successfully merging this pull request may close these issues.

3 participants