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

Fix/use answer id in voting #1839

Merged
merged 12 commits into from
Jan 30, 2025
Merged

Fix/use answer id in voting #1839

merged 12 commits into from
Jan 30, 2025

Conversation

Harman-singh-waraich
Copy link
Contributor

@Harman-singh-waraich Harman-singh-waraich commented Jan 17, 2025

⚠️ ⚠️

⚠️
Please pay close attention to

  • voting
    • commiting,
    • revealing with brute force,
    • revealing normall
  • appealing
    • appealing one side to go to stage two
    • appealing two options
    • not appealing any option

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

  • Updated version in package.json from 0.10.3 to 0.11.0.
  • Added answers structure in queries and components.
  • Modified getVoteChoice to accept string and return titles based on answer.id.
  • Removed paidFees from some contexts and components.
  • Introduced RefuseToArbitrateAnswer in disputeDetailsSchema.
  • Adjusted ClassicRound to include answers and updated related logic.
  • Enhanced ensureAnswer and updateCountsAndGetCurrentRuling functions.
  • Updated components to utilize new answer structures and handle state more effectively.

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced a new Answer entity with enhanced tracking of dispute resolution choices.
    • Added a "Refuse to Arbitrate" option for dispute scenarios.
    • Improved handling of answer funding and selection across multiple components.
  • Improvements

    • Refined type safety for dispute-related data structures.
    • Updated GraphQL schema to support more detailed answer tracking.
    • Enhanced context management for appeal and voting processes.
  • Bug Fixes

    • Resolved issues with option selection and funding logic.
    • Improved error handling for undefined dispute details.
  • Technical Updates

    • Updated subgraph package version to 0.11.0.
    • Migrated from numeric to BigInt-based choice handling.

Copy link
Contributor

coderabbitai bot commented Jan 17, 2025

Walkthrough

This 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 RefuseToArbitrateAnswer, modifications to answer schemas, and updates to how answers are tracked and processed throughout the application.

Changes

File Change Summary
kleros-sdk/src/dataMappings/utils/disputeDetailsSchema.ts - Made id field required in AnswerSchema
- Added RefuseToArbitrateAnswer constant
kleros-sdk/src/dataMappings/utils/populateTemplate.ts - Imported RefuseToArbitrateAnswer
- Modified answers processing logic
subgraph/core/schema.graphql - Added new Answer entity
- Updated ClassicRound entity structure
subgraph/core/src/DisputeKitClassic.ts - Added ensureAnswer function for answer management
subgraph/core/src/entities/ClassicRound.ts - Updated to manage answers with new ensureAnswer function
web/src/components/Verdict/DisputeTimeline.tsx - Updated logic for determining voting outcomes
web/src/hooks/queries/useClassicAppealQuery.ts - Removed paidFees field and added answers field in query
web/src/hooks/useClassicAppealContext.tsx - Enhanced type definitions and context management
Multiple web components - Updated type handling for answers
- Removed paidFees context
- Enhanced option selection logic

Possibly related PRs

Suggested Labels

Type: Enhancement :sparkles:, Package: SDK

Suggested Reviewers

  • kemuru
  • alcercu

Poem

🐰 In the realm of disputes so grand,
Where answers dance at our command,
A schema refined, with choices clear,
RefuseToArbitrate now draws near!
Code hops forward, with wisdom bright,
Resolving conflicts with rabbit might! 🏛️


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b734465 and af70b25.

📒 Files selected for processing (1)
  • web/src/pages/Profile/JurorInfo/JurorRewards.tsx (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • web/src/pages/Profile/JurorInfo/JurorRewards.tsx
⏰ Context from checks skipped due to timeout of 90000ms (15)
  • 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
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Redirect rules - kleros-v2-neo
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-neo
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-neo
  • GitHub Check: contracts-testing
  • GitHub Check: SonarCloud
  • GitHub Check: Analyze (javascript)

🪧 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 Jan 17, 2025

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit af70b25
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet/deploys/679b761ed548040008a97759
😎 Deploy Preview https://deploy-preview-1839--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 Jan 17, 2025

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

Name Link
🔨 Latest commit af70b25
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet-devtools/deploys/679b761eb860bf000811d2af
😎 Deploy Preview https://deploy-preview-1839--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

netlify bot commented Jan 17, 2025

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit af70b25
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-neo/deploys/679b761edc060900082a1f04
😎 Deploy Preview https://deploy-preview-1839--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 Jan 17, 2025

Deploy Preview for kleros-v2-university ready!

Name Link
🔨 Latest commit af70b25
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-university/deploys/679b761e6236a800081abe84
😎 Deploy Preview https://deploy-preview-1839--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: 4

🧹 Nitpick comments (2)
web/src/pages/Cases/CaseDetails/Appeal/Classic/StageExplainer.tsx (1)

69-70: Fix text formatting and array rendering issues.

  1. Grammar: Remove the space before the colon
  2. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3110e46 and f765960.

📒 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 passing choice 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 BigInt

The getVoteChoice function now accepts the vote parameter as a string and uses BigInt for comparison with answer.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 with ensureAnswer function

The introduction of the ensureAnswer function enhances code reuse and readability by encapsulating the creation and retrieval of Answer entities. This approach simplifies answer management within ClassicRound and promotes maintainability.


Line range hint 43-64: Refactored logic improves clarity and consistency

By utilizing the ensureAnswer function in updateCountsAndGetCurrentRuling, the code reduces duplication and ensures consistent handling of Answer entities. This refactoring enhances the clarity of the count update logic.


80-83: Consistent use of ensureAnswer in funding update

The update to updateChoiceFundingFromContributionEvent appropriately leverages the ensureAnswer function to manage Answer 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 AnswerSchema

The removal of .optional() makes the id 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 implementations

After 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 typescript

Length 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 typescript

Length 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 RefuseToArbitrateAnswer

The introduction of RefuseToArbitrateAnswer with id: "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 typescript

Length 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 parameter

The removal of parseInt aligns with the transition to using hex IDs for answers. The change maintains type consistency with the updated getVoteChoice function.

web/src/pages/Cases/CaseDetails/Voting/Classic/Commit.tsx (2)

47-47: Type safety improvement: Using bigint for choice parameter

The 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 check

The 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 types

The 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 Arbitrate

The "Refuse to Arbitrate" option uses BigInt(0), which should be verified against the RefuseToArbitrateAnswer.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 the RefuseToArbitrateAnswer.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 ID

The 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 import

Proper import of the Answer type from kleros-sdk improves type safety.

subgraph/core/src/DisputeKitClassic.ts (1)

105-114: ⚠️ Potential issue

Verify the fee rewards calculation

The change from using localRound.paidFees[choice.toI32()] to answer.paidFee represents a significant architectural shift. While this improves the data model, please ensure:

  1. All existing fee calculations are migrated correctly
  2. 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 accuracy

The changes correctly:

  1. Use the winning choice directly for party display
  2. Update the appeal win condition to use the current ruling
  3. 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.

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

🧹 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

📥 Commits

Reviewing files that changed from the base of the PR and between 86b02a7 and 3b6f17e.

📒 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 in createClassicRound properly support the transition to using answer entities instead of arrays.

alcercu
alcercu previously approved these changes Jan 24, 2025
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

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

🧹 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3b6f17e and 2682977.

📒 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);

kemuru
kemuru previously approved these changes Jan 28, 2025
Copy link
Contributor

@kemuru kemuru left a comment

Choose a reason for hiding this comment

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

looks good!

@Harman-singh-waraich Harman-singh-waraich dismissed stale reviews from kemuru and alcercu via 2db71ff January 28, 2025 13:38
@Harman-singh-waraich Harman-singh-waraich requested a review from a team as a code owner January 28, 2025 13:38
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

  1. For user validation: ensureUser(event.params._contributor.toHexString())
  2. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2682977 and 2db71ff.

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

  1. The performance impact of the additional database operation
  2. 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 2

Length 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 5

Length of output: 1281

alcercu
alcercu previously approved these changes Jan 28, 2025
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

@Harman-singh-waraich Harman-singh-waraich force-pushed the fix/use-answer-id-in-voting branch from ed1b8ad to b734465 Compare January 30, 2025 12:02
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

🧹 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

📥 Commits

Reviewing files that changed from the base of the PR and between ed1b8ad and b734465.

📒 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 the Answer 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-negative
  • count should be non-negative
  • paidFee should be non-negative

284-284: Ensure data migration for removed fields.

The removal of counts and paidFees fields is a breaking change. Ensure that:

  1. Data is migrated to the new answers structure
  2. All queries are updated to use the new structure

coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 30, 2025
Copy link

codeclimate bot commented Jan 30, 2025

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

Here's the issue category breakdown:

Category Count
Style 4

View more on Code Climate.

@alcercu alcercu self-requested a review January 30, 2025 12:58
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 merged commit 4954a10 into dev Jan 30, 2025
24 of 26 checks passed
@alcercu alcercu deleted the fix/use-answer-id-in-voting branch January 30, 2025 12:59
@coderabbitai coderabbitai bot mentioned this pull request Feb 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants