-
Notifications
You must be signed in to change notification settings - Fork 47
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
Conversation
WalkthroughThe pull request introduces a new custom React hook Changes
Sequence DiagramsequenceDiagram
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
Possibly related PRs
Suggested reviewers
Poem
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for kleros-v2-testnet ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
✅ Deploy Preview for kleros-v2-neo ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
✅ Deploy Preview for kleros-v2-testnet-devtools ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this 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
📒 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.
✅ Deploy Preview for kleros-v2-university ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this 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 callThe 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 processingWhile 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 logicWhile 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
📒 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
|
Code Climate has analyzed commit de7fdd2 and detected 4 issues on this pull request. Here's the issue category breakdown:
View more on Code Climate. |
|
There was a problem hiding this 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 issueUpdate environment variable prefix for Vite.
When using Vite, environment variables should be prefixed with
VITE_
. The current usage ofREACT_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
📒 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 suggestionEnhance query configuration for better caching and error handling.
The query implementation needs improvements in several areas:
- Query key should include variables for proper caching
- Missing error handling for network failures
- 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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lgtm
PR-Codex overview
This PR introduces a new custom hook,
useSpamEvidence
, to fetch spam evidence data and integrates it into theEvidence
component. It replaces the previous spam evidence logic with this new hook, improving code organization and functionality.Detailed summary
useSpamEvidence
hook inweb/src/hooks/useSpamEvidence.ts
.useSpamEvidence
into theEvidence
component inweb/src/pages/Cases/CaseDetails/Evidence/index.tsx
.Summary by CodeRabbit
New Features
Refactor