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(web): use-atlas-spam-api #1789

Merged
merged 5 commits into from
Jan 23, 2025
Merged

feat(web): use-atlas-spam-api #1789

merged 5 commits into from
Jan 23, 2025

Conversation

Harman-singh-waraich
Copy link
Contributor

@Harman-singh-waraich Harman-singh-waraich commented Dec 13, 2024

PR-Codex overview

This PR introduces a new custom hook, useSpamEvidence, to fetch spam evidence data and integrates it into the Evidence component. It replaces the previous spam evidence logic with this new hook, improving code organization and functionality.

Detailed summary

  • Added useSpamEvidence hook in web/src/hooks/useSpamEvidence.ts.
  • Implemented GraphQL query to fetch spam evidence based on deployment and evidence group ID.
  • Integrated useSpamEvidence into the Evidence component in web/src/pages/Cases/CaseDetails/Evidence/index.tsx.
  • Replaced the previous spam evidence identification logic with the new hook's data.
  • Updated rendering logic to conditionally display spam evidence.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features

    • Introduced a dynamic hook to fetch spam evidence data for cases
    • Enhanced evidence rendering with spam evidence detection
    • Improved user feedback for evidence submission status
  • Refactor

    • Updated evidence component to use dynamic spam evidence retrieval
    • Optimized spam evidence checking mechanism with memoized callback

Copy link
Contributor

coderabbitai bot commented Dec 13, 2024

Walkthrough

The pull request introduces a new custom React hook useSpamEvidence in the web/src/hooks directory to dynamically fetch spam evidence data from a GraphQL API. The hook is integrated into the Evidence component, replacing a static import with a dynamic data fetching mechanism. The implementation allows for context-sensitive spam evidence retrieval based on the current dispute ID, with built-in caching and query management using React Query.

Changes

File Change Summary
web/src/hooks/useSpamEvidence.ts Added new custom hook to fetch spam evidence using GraphQL query with dynamic deployment type detection
web/src/pages/Cases/CaseDetails/Evidence/index.tsx Updated evidence rendering logic to use dynamic useSpamEvidence hook, memoized spam check, and improved rendering of evidences

Sequence Diagram

sequenceDiagram
    participant Component as Evidence Component
    participant Hook as useSpamEvidence
    participant GraphQL as GraphQL API
    
    Component->>Hook: Call with disputeId
    Hook->>GraphQL: Fetch spam evidences
    GraphQL-->>Hook: Return spam evidence data
    Hook-->>Component: Provide spam evidences
    Component->>Component: Render evidences with spam filtering
Loading

Possibly related PRs

Suggested reviewers

  • alcercu

Poem

🐰 A rabbit's tale of spam detection,
Hooks that dance with query perfection,
Evidences sorted, clean and bright,
Dynamic data takes its flight,
GraphQL magic, no more rejection! 🕵️‍♀️

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

🪧 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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 or @coderabbitai title 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

netlify bot commented Dec 13, 2024

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit de7fdd2
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet/deploys/67922080af698f0008f0da5b
😎 Deploy Preview https://deploy-preview-1789--kleros-v2-testnet.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

netlify bot commented Dec 13, 2024

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit de7fdd2
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-neo/deploys/67922080716e670008356e55
😎 Deploy Preview https://deploy-preview-1789--kleros-v2-neo.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

netlify bot commented Dec 13, 2024

Deploy Preview for kleros-v2-testnet-devtools ready!

Name Link
🔨 Latest commit de7fdd2
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet-devtools/deploys/679220820928d60008e76499
😎 Deploy Preview https://deploy-preview-1789--kleros-v2-testnet-devtools.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6abacc8 and 15430c7.

📒 Files selected for processing (3)
  • web/src/hooks/useSpamEvidence.ts (1 hunks)
  • web/src/pages/Cases/CaseDetails/Evidence/index.tsx (3 hunks)
  • web/tsconfig.json (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
web/src/pages/Cases/CaseDetails/Evidence/index.tsx

[error] 102-102: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

🔇 Additional comments (1)
web/tsconfig.json (1)

71-71: LGTM

Adding "dom" to the lib array is appropriate to include DOM-related types.

Copy link

netlify bot commented Dec 13, 2024

Deploy Preview for kleros-v2-university ready!

Name Link
🔨 Latest commit de7fdd2
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-university/deploys/6792208029800400084ba730
😎 Deploy Preview https://deploy-preview-1789--kleros-v2-university.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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 (3)
web/src/pages/Cases/CaseDetails/Evidence/index.tsx (3)

83-83: Consider adding error handling for the spam evidence API call

The hook usage should handle potential API failures to ensure graceful degradation.

-  const { data: spamEvidences } = useSpamEvidence();
+  const { data: spamEvidences, error: spamError } = useSpamEvidence();
+  if (spamError) {
+    console.error('Failed to fetch spam evidence:', spamError);
+    // Fallback to treating all evidence as non-spam
+  }

98-108: Consider simplifying the spam evidence processing

While the current implementation avoids the O(n²) spread operator issue, it could be further simplified for better readability.

   const flattenedSpamEvidences = useMemo(
     () =>
-      spamEvidences?.courtv2EvidenceSpamsByDeployment.reduce<string[]>((acc, current) => {
-        if (current.dispute === id) {
-          acc.push(current.disputeEvidenceIndex);
-          return acc;
-        }
-        return acc;
-      }, []),
+      spamEvidences?.courtv2EvidenceSpamsByDeployment
+        .filter(current => current.dispute === id)
+        .map(current => current.disputeEvidenceIndex),
     [id, spamEvidences]
   );

117-122: Consider optimizing the evidence filtering logic

While the current implementation is correct, it could be optimized to avoid unnecessary array iterations.

   const evidences = useMemo(() => {
     if (!data?.evidences) return;
+    // Single pass through the array instead of two filter operations
+    const { spam, real } = data.evidences.reduce(
+      (acc, evidence) => {
+        if (isSpam(evidence.id)) {
+          acc.spam.push(evidence);
+        } else {
+          acc.real.push(evidence);
+        }
+        return acc;
+      },
+      { spam: [], real: [] }
+    );
-    const spamEvidences = data.evidences.filter((evidence) => isSpam(evidence.id));
-    const realEvidences = data.evidences.filter((evidence) => !isSpam(evidence.id));
-    return { realEvidences, spamEvidences };
+    return { realEvidences: real, spamEvidences: spam };
   }, [data, isSpam]);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 15430c7 and 01be41e.

📒 Files selected for processing (1)
  • web/src/pages/Cases/CaseDetails/Evidence/index.tsx (3 hunks)
🔇 Additional comments (3)
web/src/pages/Cases/CaseDetails/Evidence/index.tsx (3)

11-12: LGTM: Imports are properly organized

The new imports for useSpamEvidence hook and Divider component are correctly placed and used within the component.

Also applies to: 18-18


110-115: LGTM: Efficient implementation of isSpam check

The isSpam callback is properly memoized and implements an efficient check using array includes.


11-11: Verify the implementation of useSpamEvidence hook

Let's ensure the hook is properly implemented and the GraphQL query is correctly structured.

✅ Verification successful

Based on the results, I can generate the final response as we have sufficient information about the implementation of the useSpamEvidence hook and its usage.

The useSpamEvidence hook is properly implemented and integrated

The hook is well-structured with:

  • Proper GraphQL query definition with courtv2EvidenceSpamsByDeployment field
  • Correct type definitions for the response data
  • Deployment-aware configuration
  • Integration with React Query for data fetching
  • Proper usage in the Evidence component for spam detection
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check the implementation of useSpamEvidence hook
ast-grep --pattern 'export const useSpamEvidence = () => {
  $$$
}'

# Check for the GraphQL query definition
rg -A 10 'courtv2EvidenceSpamsByDeployment'

Length of output: 2813

coderabbitai[bot]
coderabbitai bot previously approved these changes Dec 13, 2024
Copy link

Copy link

codeclimate bot commented Jan 23, 2025

Code Climate has analyzed commit de7fdd2 and detected 4 issues on this pull request.

Here's the issue category breakdown:

Category Count
Duplication 2
Style 2

View more on Code Climate.

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

♻️ Duplicate comments (1)
web/src/hooks/useSpamEvidence.ts (1)

30-30: ⚠️ Potential issue

Update environment variable prefix for Vite.

When using Vite, environment variables should be prefixed with VITE_. The current usage of REACT_APP_ATLAS_URI needs to be updated.

-const atlasUri = import.meta.env.REACT_APP_ATLAS_URI;
+const atlasUri = import.meta.env.VITE_ATLAS_URI;
🧹 Nitpick comments (3)
web/src/hooks/useSpamEvidence.ts (1)

19-29: Consider using an enum for deployment types.

The deployment logic could benefit from using TypeScript enums or as const objects to ensure type safety and maintainability.

+type AtlasDeployment = "university" | "beta" | "testnet" | "devnet";
+
+const ATLAS_DEPLOYMENTS: Record<string, AtlasDeployment> = {
+  UNIVERSITY: "university",
+  BETA: "beta",
+  TESTNET: "testnet",
+  DEVNET: "devnet",
+} as const;
+
 const getAtlasDeployment = () => {
   if (isKlerosUniversity()) {
-    return "university";
+    return ATLAS_DEPLOYMENTS.UNIVERSITY;
   } else if (isKlerosNeo()) {
-    return "beta";
+    return ATLAS_DEPLOYMENTS.BETA;
   } else if (isTestnetDeployment()) {
-    return "testnet";
+    return ATLAS_DEPLOYMENTS.TESTNET;
   } else {
-    return "devnet";
+    return ATLAS_DEPLOYMENTS.DEVNET;
   }
 };
web/src/pages/Cases/CaseDetails/Evidence/index.tsx (2)

133-154: Consider extracting spam evidence section into a separate component.

The spam evidence section contains complex conditional rendering logic that could be simplified by extracting it into a dedicated component.

+const SpamEvidenceSection = ({ spamEvidences, showSpam, setShowSpam }) => {
+  if (!spamEvidences || spamEvidences.length === 0) return null;
+  
+  return (
+    <>
+      <Divider />
+      {showSpam ? (
+        <>
+          <SpamLabel onClick={() => setShowSpam(false)}>Hide spam</SpamLabel>
+          {spamEvidences.map(({ evidence, sender, timestamp, transactionHash, name, description, fileURI, evidenceIndex }) => (
+            <EvidenceCard
+              key={timestamp}
+              index={parseInt(evidenceIndex)}
+              sender={sender?.id}
+              {...{ evidence, timestamp, transactionHash, name, description, fileURI }}
+            />
+          ))}
+        </>
+      ) : (
+        <SpamLabel onClick={() => setShowSpam(true)}>Show likely spam</SpamLabel>
+      )}
+    </>
+  );
+};

Then use it in the main component:

-          {spamEvidences && evidences?.spamEvidences.length !== 0 ? (
-            <>
-              <Divider />
-              {showSpam ? (
-                <>
-                  <SpamLabel onClick={() => setShowSpam(false)}>Hide spam</SpamLabel>
-                  {evidences?.spamEvidences.map(
-                    ({ evidence, sender, timestamp, transactionHash, name, description, fileURI, evidenceIndex }) => (
-                      <EvidenceCard
-                        key={timestamp}
-                        index={parseInt(evidenceIndex)}
-                        sender={sender?.id}
-                        {...{ evidence, timestamp, transactionHash, name, description, fileURI }}
-                      />
-                    )
-                  )}
-                </>
-              ) : (
-                <SpamLabel onClick={() => setShowSpam(true)}>Show likely spam</SpamLabel>
-              )}
-            </>
-          ) : null}
+          <SpamEvidenceSection
+            spamEvidences={evidences?.spamEvidences}
+            showSpam={showSpam}
+            setShowSpam={setShowSpam}
+          />

157-157: Add loading state for spam evidence.

The skeleton loader should account for both evidence and spam evidence loading states.

-        <SkeletonEvidenceCard />
+        <>
+          <SkeletonEvidenceCard />
+          {/* Show additional skeleton for spam evidence section if needed */}
+          {showSpam && <SkeletonEvidenceCard />}
+        </>
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 01be41e and de7fdd2.

📒 Files selected for processing (2)
  • web/src/hooks/useSpamEvidence.ts (1 hunks)
  • web/src/pages/Cases/CaseDetails/Evidence/index.tsx (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (17)
  • GitHub Check: Redirect rules - kleros-v2-university
  • GitHub Check: Header rules - kleros-v2-university
  • GitHub Check: Pages changed - kleros-v2-university
  • GitHub Check: Redirect rules - kleros-v2-neo
  • GitHub Check: Header rules - kleros-v2-neo
  • GitHub Check: Pages changed - kleros-v2-neo
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Mend Security Check
  • GitHub Check: SonarCloud
  • GitHub Check: Analyze (javascript)
  • GitHub Check: dependency-review
  • GitHub Check: contracts-testing
🔇 Additional comments (3)
web/src/hooks/useSpamEvidence.ts (2)

7-13: LGTM! Well-structured GraphQL query.

The query is well-defined with proper typing and clear field selection.


32-42: 🛠️ Refactor suggestion

Enhance query configuration for better caching and error handling.

The query implementation needs improvements in several areas:

  1. Query key should include variables for proper caching
  2. Missing error handling for network failures
  3. Missing retry configuration for failed requests
 export const useSpamEvidence = (evidenceGroupId: string) => {
   const isEnabled = !isUndefined(atlasUri) && !isUndefined(evidenceGroupId);
 
   const variables = { deployment: getAtlasDeployment(), evidenceGroupId };
   return useQuery<SpamEvidences>({
-    queryKey: [`evidenceSpamQuery`],
+    queryKey: [`evidenceSpamQuery`, variables],
     enabled: isEnabled,
     staleTime: 60000,
+    retry: 3,
+    retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
     queryFn: async () => await request(`${atlasUri}/graphql`, spamEvidenceQuery, variables),
+    onError: (error) => {
+      console.error('Failed to fetch spam evidence:', error);
+    },
   });
 };

Likely invalid or redundant comment.

web/src/pages/Cases/CaseDetails/Evidence/index.tsx (1)

103-108: LGTM! Well-implemented memoized spam detection.

The spam detection callback is properly memoized with the correct dependency array.

@Harman-singh-waraich Harman-singh-waraich marked this pull request as ready for review January 23, 2025 11:00
Copy link
Contributor

@alcercu alcercu left a comment

Choose a reason for hiding this comment

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

lgtm

@alcercu alcercu added this pull request to the merge queue Jan 23, 2025
Merged via the queue into dev with commit 07327fa Jan 23, 2025
26 of 27 checks passed
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.

3 participants