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

DisputeKit with token gating #1804

Merged
merged 2 commits into from
Jan 22, 2025
Merged

DisputeKit with token gating #1804

merged 2 commits into from
Jan 22, 2025

Conversation

jaybuidl
Copy link
Member

@jaybuidl jaybuidl commented Dec 18, 2024

A juror must have a non-zero balance of tokenGate to be drawn.
It is enforced by _postDrawCheck() here.


PR-Codex overview

This PR introduces the DisputeKitGated contract, an implementation of a dispute kit that leverages token gating for participation. It incorporates structures for managing disputes, rounds, and votes while offering governance and funding mechanisms.

Detailed summary

  • Added DisputeKitGated contract implementing IDisputeKit.
  • Defined Dispute, Round, and Vote structs for dispute management.
  • Implemented governance functions for upgrading and managing the contract.
  • Created mechanisms for funding appeals and managing contributions.
  • Added events for dispute creation, vote casting, contributions, and withdrawals.
  • Included functions for drawing jurors, casting votes, and checking vote statuses.
  • Established modifiers for access control and state management.

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

Summary by CodeRabbit

  • New Features

    • Introduced a gated dispute resolution system with enhanced governance and juror participation.
    • Added functionality for creating disputes, drawing jurors, casting votes, funding appeals, and managing contributions.
    • Enhanced transparency with public view functions to retrieve dispute and voting information.
  • Bug Fixes

    • Implemented error handling to ensure valid operations within the dispute process.

Copy link
Contributor

coderabbitai bot commented Dec 18, 2024

Walkthrough

The pull request introduces a new smart contract DisputeKitGated.sol in the arbitration dispute kits, implementing a gated dispute resolution system. This contract extends the existing dispute resolution functionality with enhanced governance, juror participation, and funding mechanisms. It provides a structured approach to managing disputes, including creating disputes, drawing jurors, casting votes, funding appeals, and managing contributions, with built-in access controls and state management.

Changes

File Change Summary
contracts/src/arbitration/dispute-kits/DisputeKitGated.sol New contract implementing a gated dispute resolution system with comprehensive dispute management features, including juror selection, voting mechanisms, appeal funding, and reward withdrawal. Interfaces for token standards added, along with multiple functions for dispute operations and state retrieval.

Poem

🐰 In the realm of disputes, a new gate stands tall,
Where justice and tokens together enthrall.
Jurors vote with precision and might,
Kleros' wisdom shines ever so bright!
A gated system, fair and clear,
Dispute resolution without a fear! 🏛️


📜 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 7308fd8 and c0f2f89.

📒 Files selected for processing (1)
  • contracts/src/arbitration/dispute-kits/DisputeKitGated.sol (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Redirect rules - kleros-v2-neo
  • GitHub Check: Redirect rules - kleros-v2-testnet-devtools
  • GitHub Check: Header rules - kleros-v2-neo
  • GitHub Check: Pages changed - kleros-v2-neo
  • 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: contracts-testing
  • GitHub Check: Analyze (javascript)
  • GitHub Check: SonarCloud
  • GitHub Check: dependency-review
🔇 Additional comments (6)
contracts/src/arbitration/dispute-kits/DisputeKitGated.sol (6)

175-187: Add validation checks to prevent misconfiguration

The initialize function does not validate critical parameters such as _governor, _core, and _tokenGate. This could lead to misconfiguration or security vulnerabilities if these addresses are incorrect or set to the zero address.

Apply this diff to add validation checks:

 function initialize(
     address _governor,
     KlerosCore _core,
     address _tokenGate,
     uint256 _tokenId,
     bool _isERC1155
 ) external reinitializer(1) {
+    require(_governor != address(0), "Governor address cannot be zero.");
+    require(address(_core) != address(0), "Core address cannot be zero.");
+    require(_tokenGate != address(0), "TokenGate address cannot be zero.");

     governor = _governor;
     core = _core;
     tokenGate = _tokenGate;
     tokenId = _tokenId;
     isERC1155 = _isERC1155;
 }

214-217: Add validation for the new governor address

The changeGovernor function does not validate the new governor address. Setting the governor to the zero address could lock critical governance functions.

Apply this diff to add a validation check:

 function changeGovernor(address payable _governor) external onlyByGovernor {
+    require(_governor != address(0), "Governor address cannot be zero.");

     governor = _governor;
 }

220-222: Validate the new core address in changeCore

The changeCore function allows updating the core address without validation. Assigning the zero address or an incorrect contract could disrupt critical functionalities.

Apply this diff to add a validation check:

 function changeCore(address _core) external onlyByGovernor {
+    require(_core != address(0), "Core address cannot be zero.");

     core = KlerosCore(_core);
 }

226-229: Validate the new token gate address for ERC20/ERC721

The changeTokenGateERC20OrERC721 function lacks validation for the _tokenGate parameter. Assigning the zero address could prevent juror eligibility checks.

Apply this diff to add a validation check:

 function changeTokenGateERC20OrERC721(address _tokenGate) external onlyByGovernor {
+    require(_tokenGate != address(0), "TokenGate address cannot be zero.");

     tokenGate = _tokenGate;
     isERC1155 = false;
 }

234-238: Validate the new token gate address for ERC1155

The changeTokenGateERC1155 function should validate the _tokenGate address to prevent misconfiguration.

Apply this diff to add a validation check:

 function changeTokenGateERC1155(address _tokenGate, uint256 _tokenId) external onlyByGovernor {
+    require(_tokenGate != address(0), "TokenGate address cannot be zero.");

     tokenGate = _tokenGate;
     tokenId = _tokenId;
     isERC1155 = true;
 }

272-295: Improve clarity in draw() regarding zero address returns

The draw function sets drawnAddress to address(0) if _postDrawCheck fails. Consider emitting an event or updating the documentation to indicate that a zero address can be a valid outcome for an unsuccessful draw. This can help with debugging and improve clarity.


🪧 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 18, 2024

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit c0f2f89
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet/deploys/67903d4d1610ef0008f1dc5f
😎 Deploy Preview https://deploy-preview-1804--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 18, 2024

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit c0f2f89
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-neo/deploys/67903d4d36d07d0008b792b3
😎 Deploy Preview https://deploy-preview-1804--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 18, 2024

Deploy Preview for kleros-v2-testnet-devtools failed. Why did it fail? →

Name Link
🔨 Latest commit c0f2f89
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet-devtools/deploys/67903d4d3aaae10008bd30c5

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

🧹 Nitpick comments (4)
contracts/src/arbitration/dispute-kits/DisputeKitGated.sol (4)

18-23: Ensure IToken interface is clearly documented and tested.
The IToken interface usage is straightforward, but ensure that you have corresponding tests to verify that calls to balanceOf() do not revert and handle edge cases (such as token contracts that implement custom logic).


70-73: Evaluate constants for potential configurability.
The multipliers (WINNER_STAKE_MULTIPLIER, LOSER_STAKE_MULTIPLIER, etc.) are hardcoded. Depending on governance requirements, you might want to allow these values to be adjusted in the future or make them configurable by the governor.


136-149: Modifiers appear consistent but consider dedicated revert messages for each.
While the existing revert strings are descriptive, they could be refined to clarify which contract, function, or condition has failed. This can speed up debugging.


628-638: Token gating logic in _postDrawCheck is correct but check edge cases.
You are verifying that the juror’s tokenGate balance is > 0. Ensure that corner cases (e.g., tokens with deflationary mechanisms, transfer fees, or off-chain bridging) don’t cause unintended gating failures. Thorough testing is recommended.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f9cb5a6 and 9303c62.

📒 Files selected for processing (1)
  • contracts/src/arbitration/dispute-kits/DisputeKitGated.sol (1 hunks)
🔇 Additional comments (2)
contracts/src/arbitration/dispute-kits/DisputeKitGated.sol (2)

160-168: Initialize function covers the essential references.
The initialize function correctly sets governor, core, and tokenGate. Ensure tests verify that these values are not overwritten multiple times except via governance calls.


421-466: Ensure safe usage of .send() during refunds.
Using .send() is a deliberate choice to avoid revert loops. Verify that you handle the scenario where .send() fails (returns false) due to a custom fallback or insufficient gas. Consider emitting an event or adopting the “withdraw” pattern.

Copy link

netlify bot commented Dec 18, 2024

Deploy Preview for kleros-v2-university ready!

Name Link
🔨 Latest commit c0f2f89
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-university/deploys/67903d4d4cff5d0009e64119
😎 Deploy Preview https://deploy-preview-1804--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.

@jaybuidl jaybuidl self-assigned this Dec 18, 2024
@jaybuidl jaybuidl marked this pull request as ready for review December 18, 2024 19:31
coderabbitai[bot]
coderabbitai bot previously approved these changes Jan 21, 2025
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: 5

🧹 Nitpick comments (3)
contracts/src/arbitration/dispute-kits/DisputeKitGated.sol (3)

449-493: Ensure safe usage of send in withdrawFeesAndRewards

The function uses _beneficiary.send(amount); to transfer ETH. While the use of send mitigates reentrancy by forwarding limited gas, it could fail silently if the recipient reverts or if the gas stipend is insufficient.

Consider using call with a checks-effects-interactions pattern and handle potential failures appropriately:

     round.contributions[_beneficiary][_choice] = 0;

     if (amount != 0) {
-        _beneficiary.send(amount); // Deliberate use of send to prevent reverting fallback. It's the user's responsibility to accept ETH.
+        (bool success, ) = _beneficiary.call{value: amount}("");
+        require(success, "Transfer failed.");
         emit Withdrawal(_coreDisputeID, _coreRoundID, _choice, _beneficiary, amount);
     }

Note: Ensure reentrancy is prevented by updating the state before external calls and consider the implications of reverting on failed transfers.


383-448: Reentrancy considerations in fundAppeal

Although previous discussions mention that core is a trusted contract, it's good practice to protect against potential reentrancy, especially when external calls are involved.

Consider adding the nonReentrant modifier from OpenZeppelin's ReentrancyGuard to critical functions like fundAppeal to enhance security.

+import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
+
 contract DisputeKitGated is IDisputeKit, Initializable, UUPSProxiable, ReentrancyGuard {
     // ...

-    function fundAppeal(uint256 _coreDisputeID, uint256 _choice) external payable notJumped(_coreDisputeID) {
+    function fundAppeal(uint256 _coreDisputeID, uint256 _choice) external payable notJumped(_coreDisputeID) nonReentrant {
         // Function body
     }
 }

351-354: Enhance commit scheme security in castVote

In the commit-reveal scheme, including the voter's address in the commitment can prevent certain attacks like vote replays.

Consider modifying the commit to include the voter's address:

 require(
     !hiddenVotes || round.votes[_voteIDs[i]].commit == keccak256(abi.encodePacked(_choice, _salt)),
     "The commit must match the choice in courts with hidden votes."
 );

Change to:

 require(
     !hiddenVotes || round.votes[_voteIDs[i]].commit == keccak256(abi.encodePacked(_choice, _salt, msg.sender)),
     "The commit must match the choice in courts with hidden votes."
 );

Note: This change would require voters to include their address when creating their commit during the castCommit phase.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9303c62 and 7308fd8.

📒 Files selected for processing (1)
  • contracts/src/arbitration/dispute-kits/DisputeKitGated.sol (1 hunks)
🔇 Additional comments (2)
contracts/src/arbitration/dispute-kits/DisputeKitGated.sol (2)

647-654: Consider potential issues with IERC20OrERC721 balanceOf usage

The IERC20OrERC721 interface uses the balanceOf function for both ERC20 and ERC721 tokens. While ERC20's balanceOf returns the token amount, ERC721's balanceOf returns the number of NFTs owned. Ensure that using balanceOf without differentiation does not introduce logical errors, especially if the juror must own a specific NFT.

Please confirm that this implementation correctly enforces the token gating mechanism for both ERC20 and ERC721 tokens.


656-668: Check for potential race conditions during contract references update

Previous reviews highlighted potential race conditions when updating core and tokenGate references.

Ensure that transitional states are handled safely when changing critical contract addresses to prevent inconsistent behavior.

Copy link

codeclimate bot commented Jan 22, 2025

Code Climate has analyzed commit c0f2f89 and detected 0 issues on this pull request.

View more on Code Climate.

@jaybuidl jaybuidl merged commit c0f2f89 into dev Jan 22, 2025
20 of 27 checks passed
@jaybuidl jaybuidl deleted the feat/gated-dk branch January 22, 2025 00:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant