-
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
Fix/use answer id in voting #1839
Conversation
WalkthroughThis pull request introduces significant changes to the Kleros SDK and related components, focusing on enhancing the structure and handling of answers in dispute resolution processes. The modifications span multiple files across the SDK, subgraph, and web interfaces, introducing a more robust and flexible approach to managing dispute answers. Key changes include the introduction of a new Changes
Possibly related PRs
Suggested Labels
Suggested Reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (15)
🪧 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-testnet-devtools 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-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: 4
🧹 Nitpick comments (2)
web/src/pages/Cases/CaseDetails/Appeal/Classic/StageExplainer.tsx (1)
69-70
: Fix text formatting and array rendering issues.
- Grammar: Remove the space before the colon
- The map function might render null values in the array, which could lead to unwanted commas
Consider this improvement:
- Following choices were funded in the stage 1 :{" "} - <small>{options?.map((option) => (option?.funded ? option.title : null))}</small> + Following choices were funded in stage 1:{" "} + <small> + {options + ?.filter((option) => option?.funded) + .map((option) => option.title) + .join(", ")} + </small>web/src/pages/Cases/CaseDetails/Appeal/Classic/index.tsx (1)
50-50
: Improve type safety for amount conversion.The current type assertion could be unsafe. Consider adding runtime validation:
- <Fund amount={amount as `${number}`} setAmount={setAmount} setIsOpen={setIsPopupOpen} /> + <Fund + amount={/^\d+$/.test(amount) ? (amount as `${number}`) : "0"} + setAmount={setAmount} + setIsOpen={setIsPopupOpen} + />
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (21)
kleros-sdk/src/dataMappings/utils/disputeDetailsSchema.ts
(1 hunks)kleros-sdk/src/dataMappings/utils/populateTemplate.ts
(2 hunks)kleros-sdk/src/utils/getDispute.ts
(0 hunks)subgraph/core/schema.graphql
(2 hunks)subgraph/core/src/DisputeKitClassic.ts
(2 hunks)subgraph/core/src/entities/ClassicRound.ts
(4 hunks)web/src/components/Verdict/DisputeTimeline.tsx
(2 hunks)web/src/hooks/queries/useClassicAppealQuery.ts
(1 hunks)web/src/hooks/useClassicAppealContext.tsx
(5 hunks)web/src/pages/Cases/CaseDetails/Appeal/AppealHistory.tsx
(2 hunks)web/src/pages/Cases/CaseDetails/Appeal/Classic/Fund.tsx
(1 hunks)web/src/pages/Cases/CaseDetails/Appeal/Classic/Options/StageOne.tsx
(2 hunks)web/src/pages/Cases/CaseDetails/Appeal/Classic/Options/StageTwo.tsx
(2 hunks)web/src/pages/Cases/CaseDetails/Appeal/Classic/StageExplainer.tsx
(2 hunks)web/src/pages/Cases/CaseDetails/Appeal/Classic/index.tsx
(3 hunks)web/src/pages/Cases/CaseDetails/Voting/Classic/Commit.tsx
(2 hunks)web/src/pages/Cases/CaseDetails/Voting/Classic/OptionsContainer.tsx
(4 hunks)web/src/pages/Cases/CaseDetails/Voting/Classic/Reveal.tsx
(5 hunks)web/src/pages/Cases/CaseDetails/Voting/VotesDetails/AccordionTitle.tsx
(1 hunks)web/src/pages/Cases/CaseDetails/Voting/VotesDetails/index.tsx
(1 hunks)web/src/utils/getVoteChoice.ts
(1 hunks)
💤 Files with no reviewable changes (1)
- kleros-sdk/src/utils/getDispute.ts
⏰ Context from checks skipped due to timeout of 90000ms (16)
- 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-devtools
- GitHub Check: Header rules - kleros-v2-testnet-devtools
- GitHub Check: Pages changed - kleros-v2-testnet-devtools
- 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: SonarCloud
- GitHub Check: Analyze (javascript)
- GitHub Check: contracts-testing
- GitHub Check: dependency-review
🔇 Additional comments (25)
web/src/pages/Cases/CaseDetails/Voting/VotesDetails/index.tsx (2)
Line range hint
141-196
: Enhance test coverage for voting scenarios.Given this component's critical role in displaying vote details and the PR's focus on answer IDs, ensure comprehensive test coverage for:
- Hidden votes handling
- Committed votes display
- Different voting periods
- Various answer ID formats
- Edge cases (undefined choices, missing justifications)
Let's check the existing test coverage:
Would you like me to help create additional test cases to cover these scenarios?
117-117
: Verify type safety and error handling for the choice parameter.The change from
parseInt(choice)
to passingchoice
directly aligns with using answer IDs. However, we should ensure proper type safety and error handling.Let's verify the implementation of
getVoteChoice
and its usage:Additionally, consider adding type guards or error handling:
{!isUndefined(choice) && typeof choice === 'string' && ( <VotedText dir="auto">{getVoteChoice(choice, answers)}</VotedText> )}web/src/utils/getVoteChoice.ts (1)
4-9
: Function correctly updated to handle vote IDs as strings using BigIntThe
getVoteChoice
function now accepts thevote
parameter as a string and usesBigInt
for comparison withanswer.id
. This ensures accurate matching when dealing with hexadecimal IDs. The implementation is correct, and the use of optional chaining and null checking is appropriate.subgraph/core/src/entities/ClassicRound.ts (3)
27-38
: Effective encapsulation withensureAnswer
functionThe introduction of the
ensureAnswer
function enhances code reuse and readability by encapsulating the creation and retrieval ofAnswer
entities. This approach simplifies answer management withinClassicRound
and promotes maintainability.
Line range hint
43-64
: Refactored logic improves clarity and consistencyBy utilizing the
ensureAnswer
function inupdateCountsAndGetCurrentRuling
, the code reduces duplication and ensures consistent handling ofAnswer
entities. This refactoring enhances the clarity of the count update logic.
80-83
: Consistent use ofensureAnswer
in funding updateThe update to
updateChoiceFundingFromContributionEvent
appropriately leverages theensureAnswer
function to manageAnswer
entities consistently. This change improves code consistency across different functions handling answers.web/src/pages/Cases/CaseDetails/Appeal/AppealHistory.tsx (1)
41-47
: Improved robustness by using option IDs instead of array indices.The changes enhance code reliability by:
- Using unique option IDs instead of array indices
- Safely handling undefined options with optional chaining
- Directly accessing option properties instead of relying on separate arrays
web/src/pages/Cases/CaseDetails/Appeal/Classic/Options/StageOne.tsx (2)
44-47
: Well-structured funding determination logic.The required funding calculation is clearly tied to the option's ID, making the code more maintainable and less prone to errors.
48-54
: Consistent use of option properties and ID-based comparisons.Good practices observed:
- Using unique IDs for React keys
- Direct property access for option data
- Clear boolean conditions for selection state
web/src/pages/Cases/CaseDetails/Appeal/Classic/Options/StageTwo.tsx (2)
38-38
: Good use of useMemo for derived state.Memoizing the choice calculation prevents unnecessary recalculations when unrelated state changes.
41-43
: Consider adding cleanup to useEffect.While the effect logic is clean, it's missing a cleanup function which might be needed if setSelectedOption or setAmount need to be cleaned up when the component unmounts.
Could you verify if these setter functions need cleanup in your component's lifecycle?
kleros-sdk/src/dataMappings/utils/disputeDetailsSchema.ts (2)
36-36
: Breaking Change:id
field is now required in AnswerSchemaThe removal of
.optional()
makes theid
field mandatory. This is a breaking change that might affect existing implementations.Run this script to check for potential impacts:
✅ Verification successful
The
id
field requirement aligns with existing implementationsAfter thorough verification of the codebase, all existing implementations already provide and rely on the
id
field, making this a non-breaking change that formalizes the existing usage pattern.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for Answer type usage without id field rg -A 5 "Answer.*{" --type typescriptLength of output: 121
Script:
#!/bin/bash # Search for Answer type/interface definitions and usages rg -l "type Answer|interface Answer|: Answer|: Answer\[\]" --type typescript # Search for AnswerSchema usage rg -l "AnswerSchema" --type typescript # Get content of files that use Answer or AnswerSchema echo "=== Files containing Answer or AnswerSchema ===" rg "(type Answer|interface Answer|: Answer|: Answer\[\]|AnswerSchema)" -A 3 --type typescriptLength of output: 423
Script:
#!/bin/bash # Search for Answer type/interface definitions and usages rg "(type Answer|interface Answer|: Answer|: Answer\[\])" -A 5 --glob "*.{ts,tsx}" # Search for AnswerSchema usage with context echo "=== AnswerSchema Usage ===" rg "AnswerSchema" -A 5 --glob "*.{ts,tsx}" # Search for imports of Answer type echo "=== Answer Imports ===" rg "import.*Answer.*from" --glob "*.{ts,tsx}"Length of output: 11356
42-47
: Verify the special case handling of RefuseToArbitrateAnswerThe introduction of
RefuseToArbitrateAnswer
withid: "0x0"
needs verification to ensure consistent handling across the codebase.Run this script to check the usage:
✅ Verification successful
Special case handling of RefuseToArbitrateAnswer is properly implemented and verified
The implementation in
populateTemplate.ts
ensures that:
- RefuseToArbitrateAnswer with id "0x0" is always the first option
- Any custom answers with id 0 are filtered out and replaced with the standard one
- Invalid dispute data cases are handled by directing users to this option
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for RefuseToArbitrateAnswer usage rg "RefuseToArbitrateAnswer" --type typescript # Search for "0x0" handling in voting logic rg '"0x0"' --type typescriptLength of output: 147
Script:
#!/bin/bash # Search for RefuseToArbitrateAnswer usage with context rg -l "\.ts$|\.js$" | xargs rg -l "RefuseToArbitrateAnswer" # Search for hex value usage with context rg -A 3 -B 3 '(0x0|0x00)' --glob '*.{ts,js}' # Search for files importing from disputeDetailsSchema rg -A 1 -B 1 "from.*disputeDetailsSchema" --glob '*.{ts,js}'Length of output: 59602
Script:
#!/bin/bash # Get content of populateTemplate.ts cat kleros-sdk/src/dataMappings/utils/populateTemplate.ts # Search for dispute resolution or voting logic rg -A 5 -B 5 "vote|ruling|resolution" --glob '*.ts' # Search for other special answer IDs rg -A 2 -B 2 'id: "(0x[0-9a-fA-F]+)"' --glob '*.ts'Length of output: 76799
web/src/pages/Cases/CaseDetails/Voting/VotesDetails/AccordionTitle.tsx (1)
76-76
: LGTM: Removed unnecessary parseInt for choice parameterThe removal of
parseInt
aligns with the transition to using hex IDs for answers. The change maintains type consistency with the updatedgetVoteChoice
function.web/src/pages/Cases/CaseDetails/Voting/Classic/Commit.tsx (2)
47-47
: Type safety improvement: Using bigint for choice parameterThe transition to
bigint
improves type safety and aligns with using hex IDs. The salt storage format has been updated accordingly.Also applies to: 59-59
64-67
: Improved error handling with publicClient checkThe additional check for
publicClient
enhances safety by ensuring both clients are available before proceeding with the contract write operation.web/src/pages/Cases/CaseDetails/Voting/Classic/OptionsContainer.tsx (2)
15-15
: Type safety improvement: Consistent use of bigint and SDK typesThe changes improve type safety by:
- Using the Answer type from SDK
- Converting to bigint for choice handling
- Using BigInt(-1) as default state
Also applies to: 45-45, 53-53
81-82
: Verify edge case handling for Refuse to ArbitrateThe "Refuse to Arbitrate" option uses
BigInt(0)
, which should be verified against theRefuseToArbitrateAnswer.id
("0x0") defined in the schema.Run this script to check consistency:
Also applies to: 95-96
✅ Verification successful
Edge case handling for "Refuse to Arbitrate" is correctly implemented
The usage of
BigInt(0)
in the UI correctly matches theRefuseToArbitrateAnswer.id
("0x0") defined in the schema. The conversion between hex string and BigInt is consistent with blockchain number handling practices.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Check for potential mismatches between BigInt(0) and "0x0" rg -A 5 'BigInt\(0\)' --type typescript # Check RefuseToArbitrateAnswer.id usage ast-grep --pattern 'RefuseToArbitrateAnswer.id'Length of output: 124
Script:
#!/bin/bash # Search for BigInt(0) usage in TypeScript files rg -g '*.{ts,tsx}' 'BigInt\(0\)' -B 2 -A 2 # Search for "0x0" usage rg -g '*.{ts,tsx}' '"0x0"' -B 2 -A 2 # Search for RefuseToArbitrateAnswer imports and usage rg -g '*.{ts,tsx}' 'RefuseToArbitrateAnswer' -B 2 -A 2 # Look for type definitions and constants ast-grep --pattern 'const RefuseToArbitrateAnswer = { $$$ }' ast-grep --pattern 'type RefuseToArbitrateAnswer = { $$$ }'Length of output: 9785
web/src/pages/Cases/CaseDetails/Appeal/Classic/Fund.tsx (1)
76-76
: LGTM: Safe access to answer IDThe change correctly uses optional chaining to access the ID property of the selected option, maintaining the same fallback value for safety.
web/src/pages/Cases/CaseDetails/Voting/Classic/Reveal.tsx (1)
23-23
: LGTM: Added Answer type importProper import of the Answer type from kleros-sdk improves type safety.
subgraph/core/src/DisputeKitClassic.ts (1)
105-114
:⚠️ Potential issueVerify the fee rewards calculation
The change from using
localRound.paidFees[choice.toI32()]
toanswer.paidFee
represents a significant architectural shift. While this improves the data model, please ensure:
- All existing fee calculations are migrated correctly
- No funds are lost in the transition
Run this script to verify the fee calculations:
web/src/components/Verdict/DisputeTimeline.tsx (1)
108-108
: LGTM: Improved timeline accuracyThe changes correctly:
- Use the winning choice directly for party display
- Update the appeal win condition to use the current ruling
- Display the correct party based on the dispute's current ruling
Also applies to: 127-130
subgraph/core/schema.graphql (1)
269-276
: Well-structured Answer entity with clear relationships.The new Answer entity provides a robust structure for tracking individual answers with their funding status and vote counts. The relationship with ClassicRound is properly established.
web/src/hooks/queries/useClassicAppealQuery.ts (1)
28-33
: Query structure properly aligned with schema changes.The query correctly retrieves all necessary fields from the new Answer entity structure, maintaining consistency with the schema changes.
web/src/hooks/useClassicAppealContext.tsx (1)
16-16
: Type definition properly extends Answer entity.The Option type correctly extends the Answer type with UI-specific fields.
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
🧹 Nitpick comments (4)
subgraph/core/src/entities/ClassicRound.ts (4)
27-38
: Add input validation for answerId.While the function implementation is clean and follows good patterns, consider adding validation for the
answerId
parameter to ensure it's not negative, as negative answer IDs might cause issues in the voting system.export function ensureAnswer(localRoundId: string, answerId: BigInt): Answer { + if (answerId.lt(ZERO)) { + throw new Error("Answer ID cannot be negative"); + } const id = `${localRoundId}-${answerId}`; let answer = Answer.load(id);
43-51
: Add overflow protection for vote counting.While the refactoring to use Answer entities is good, consider adding overflow protection when updating the vote count to prevent potential issues with large numbers.
- answer.count = answer.count.plus(delta); + const newCount = answer.count.plus(delta); + if (newCount.lt(answer.count)) { + throw new Error("Vote count overflow"); + } + answer.count = newCount;
80-83
: Add overflow protection for fee amounts and LGTM!The changes properly integrate with the new Answer entity system. Consider adding overflow protection for fee amounts similar to vote counts.
- answer.paidFee = answer.paidFee.plus(amount); + const newPaidFee = answer.paidFee.plus(amount); + if (newPaidFee.lt(answer.paidFee)) { + throw new Error("Fee amount overflow"); + } + answer.paidFee = newPaidFee;
Line range hint
1-85
: Great architectural improvement moving to entity-based storage!The transition from array-based to entity-based storage for answers is a solid architectural improvement that:
- Provides better data organization and querying capabilities
- Maintains proper data consistency with atomic updates
- Aligns well with GraphQL's entity-relationship model
- Supports the enhanced voting mechanism requirements
This change will make it easier to track and manage individual answers in the voting system.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
subgraph/core/src/entities/ClassicRound.ts
(4 hunks)web/src/components/Verdict/DisputeTimeline.tsx
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- web/src/components/Verdict/DisputeTimeline.tsx
⏰ Context from checks skipped due to timeout of 90000ms (16)
- 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: 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-testnet-devtools
- GitHub Check: Header rules - kleros-v2-testnet-devtools
- GitHub Check: Pages changed - kleros-v2-testnet-devtools
- GitHub Check: contracts-testing
- GitHub Check: SonarCloud
- GitHub Check: dependency-review
- GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
subgraph/core/src/entities/ClassicRound.ts (1)
3-3
: LGTM! Import changes align with the new entity-based approach.The addition of the
Answer
import and removal of array initializations increateClassicRound
properly support the transition to using answer entities instead of arrays.
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
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
🧹 Nitpick comments (1)
web/src/hooks/useClassicAppealContext.tsx (1)
135-136
: Add input validation for dispute data.Consider adding validation for the dispute parameter to ensure the data structure is valid before processing:
const getOptions = (dispute?: DisputeDetails, classicDispute?: ClassicAppealQuery["dispute"]) => { - if (!dispute) return []; + if (!dispute?.answers?.length) return []; + if (!Array.isArray(dispute.answers)) { + console.error("Invalid dispute data structure"); + return []; + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
web/src/hooks/useClassicAppealContext.tsx
(5 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
- GitHub Check: contracts-testing
- GitHub Check: dependency-review
- GitHub Check: SonarCloud
- GitHub Check: Analyze (javascript)
🔇 Additional comments (4)
web/src/hooks/useClassicAppealContext.tsx (4)
15-17
: LGTM! Well-structured type definitions.The Option type properly extends the Answer type with additional fields needed for appeal functionality.
26-30
: LGTM! Improved type safety in context definitions.The transition from primitive types (string[], number) to structured types (Option[], Option) enhances type safety and better represents the domain model.
64-67
: LGTM! Clean state management implementation.The state management for options and selectedOption is well-implemented, following React best practices.
135-150
: Add error handling for ID conversion.The BigInt conversion of answer.id could throw if the ID is invalid. Consider adding error handling:
const options = dispute.answers.map((answer) => { + try { const classicAnswer = classicAnswers?.find((classicAnswer) => BigInt(classicAnswer.answerId) == BigInt(answer.id)); // converting hexadecimal id to stringified bigint to match id from subgraph return { ...answer, id: BigInt(answer.id).toString(), paidFee: classicAnswer?.paidFee ?? "0", funded: classicAnswer?.funded ?? false, }; + } catch (error) { + console.error(`Failed to process answer: ${answer.id}`, error); + return null; + } -}); +}).filter((option): option is NonNullable<typeof option> => option !== null);
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.
looks good!
2db71ff
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: 2
🧹 Nitpick comments (1)
subgraph/core/src/entities/ClassicContribution.ts (1)
Line range hint
11-16
: Consider caching the contributor validation result.The contributor address is used twice:
- For user validation:
ensureUser(event.params._contributor.toHexString())
- For storing:
contributor = event.params._contributor.toHexString()
Consider caching the hexadecimal string to avoid duplicate conversion.
- ensureUser(event.params._contributor.toHexString()); - const contributor = event.params._contributor.toHexString(); + const contributor = event.params._contributor.toHexString(); + ensureUser(contributor);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
subgraph/core/src/entities/ClassicContribution.ts
(1 hunks)web/src/hooks/queries/useClassicAppealQuery.ts
(1 hunks)web/src/pages/Cases/CaseDetails/Appeal/Classic/StageExplainer.tsx
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- web/src/hooks/queries/useClassicAppealQuery.ts
⏰ Context from checks skipped due to timeout of 90000ms (15)
- 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: 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: contracts-testing
- GitHub Check: SonarCloud
- GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
subgraph/core/src/entities/ClassicContribution.ts (2)
4-4
: LGTM! Clean import addition.The import of
ensureUser
follows good separation of concerns by keeping user management logic separate from contribution handling.
11-11
: Verify the impact of additional user validation.The addition of user validation improves data integrity but adds an extra operation. Since this is a subgraph entity, we should verify:
- The performance impact of the additional database operation
- The behavior when the user doesn't exist
✅ Verification successful
User validation is lightweight and follows subgraph best practices
The
ensureUser
function implements a standard load-or-create pattern with minimal database operations. It safely handles non-existent users by creating them with default values, which is the expected behavior in subgraph entities.🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Analyze the implementation of ensureUser to understand its impact # Check the User entity implementation echo "Checking User entity implementation:" ast-grep --pattern 'export function ensureUser($_) { $$$ }' # Check for error handling in existing usage echo "\nChecking existing error handling patterns:" rg -A 5 "ensureUser\("Length of output: 6188
Script:
#!/bin/bash # Get the complete implementation of ensureUser and related User entity operations echo "Complete ensureUser implementation:" ast-grep --pattern 'export function ensureUser($_) { $$$ }' echo "\nUser entity definition:" ast-grep --pattern 'export class User extends Entity { $$$ }' echo "\nChecking for save operations:" rg "user\.save\(\)" -A 2 -B 2Length of output: 1235
Script:
#!/bin/bash # Get the complete User entity related code echo "Searching for complete ensureUser implementation:" rg -A 15 "^export function ensureUser" subgraph/core/src/entities/User.ts echo "\nChecking User entity initialization:" rg "new User" -A 5 -B 5Length of output: 1281
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
ed1b8ad
to
b734465
Compare
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
🧹 Nitpick comments (2)
web/src/hooks/useClassicAppealContext.tsx (2)
29-30
: Add type validation for selected option.Consider adding runtime validation to ensure the selected option has valid values for
id
,paidFee
, etc.const SelectedOptionContext = createContext<ISelectedOptionContext>({ selectedOption: undefined, - setSelectedOption: () => {}, + setSelectedOption: (option: Option) => { + if (option && ( + !option.id || + BigInt(option.paidFee ?? "0") < 0n + )) { + console.warn("Invalid option selected:", option); + return; + } + }, });
135-150
: Optimize BigInt conversions.Multiple BigInt conversions could be optimized by converting IDs once and reusing the values.
const getOptions = (dispute?: DisputeDetails, classicDispute?: ClassicAppealQuery["dispute"]) => { if (!dispute) return []; const currentLocalRound = getCurrentLocalRound(classicDispute); const classicAnswers = currentLocalRound?.answers; + // Pre-convert classic answer IDs to BigInt for better performance + const classicAnswerMap = new Map( + classicAnswers?.map(answer => [ + BigInt(answer.answerId).toString(), + answer + ]) ?? [] + ); + const options = dispute.answers.map((answer) => { - const classicAnswer = classicAnswers?.find((classicAnswer) => BigInt(classicAnswer.answerId) == BigInt(answer.id)); + const answerId = BigInt(answer.id).toString(); + const classicAnswer = classicAnswerMap.get(answerId); return { ...answer, - id: BigInt(answer.id).toString(), + id: answerId, paidFee: classicAnswer?.paidFee ?? "0", funded: classicAnswer?.funded ?? false, }; }); return options; };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
subgraph/core/schema.graphql
(2 hunks)subgraph/package.json
(1 hunks)web/src/hooks/useClassicAppealContext.tsx
(5 hunks)web/src/pages/Cases/CaseDetails/Appeal/Classic/Fund.tsx
(1 hunks)web/src/pages/Cases/CaseDetails/Voting/VotesDetails/AccordionTitle.tsx
(1 hunks)
✅ Files skipped from review due to trivial changes (1)
- subgraph/package.json
🚧 Files skipped from review as they are similar to previous changes (2)
- web/src/pages/Cases/CaseDetails/Appeal/Classic/Fund.tsx
- web/src/pages/Cases/CaseDetails/Voting/VotesDetails/AccordionTitle.tsx
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: Analyze (javascript)
- GitHub Check: SonarCloud
- GitHub Check: contracts-testing
🔇 Additional comments (3)
web/src/hooks/useClassicAppealContext.tsx (1)
17-17
: LGTM! Well-structured type definition.The
Option
type properly extends theAnswer
type with optional fields for paid fees and funding status.subgraph/core/schema.graphql (2)
271-278
: Add field validation for Answer entity.Consider adding field validation to ensure data integrity:
answerId
should be non-negativecount
should be non-negativepaidFee
should be non-negative
284-284
: Ensure data migration for removed fields.The removal of
counts
andpaidFees
fields is a breaking change. Ensure that:
- Data is migrated to the new
answers
structure- All queries are updated to use the new structure
Code Climate has analyzed commit af70b25 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.
lgtm
requires subgraph redeploy, currently using my personal studio endpoint https://api.studio.thegraph.com/query/71663/core-dev/version/latest
requires kleros-sdk redeploy
Please pay close attention to
PR-Codex overview
This PR updates the
kleros-v2-subgraph
package and enhances the handling of voting and appeal functionalities. It introduces new structures for answers, modifies existing functions to accommodate these changes, and improves the overall data flow and state management.Detailed summary
version
inpackage.json
from0.10.3
to0.11.0
.answers
structure in queries and components.getVoteChoice
to acceptstring
and return titles based onanswer.id
.paidFees
from some contexts and components.RefuseToArbitrateAnswer
indisputeDetailsSchema
.ClassicRound
to includeanswers
and updated related logic.ensureAnswer
andupdateCountsAndGetCurrentRuling
functions.Summary by CodeRabbit
Release Notes
New Features
Answer
entity with enhanced tracking of dispute resolution choices.Improvements
Bug Fixes
Technical Updates