Skip to content

Conversation

jaybuidl
Copy link
Member

@jaybuidl jaybuidl commented Jul 22, 2025

PR-Codex overview

This PR focuses on enhancing token validation for gated dispute kits in the application. It introduces new hooks for validating ERC20, ERC721, and ERC1155 tokens, along with updates to the user interface for displaying validation states.

Detailed summary

  • Added isTokenGateValid property to the NewDisputeContext.
  • Updated extraDataToTokenInfo to return undefined for invalid gated dispute kits.
  • Implemented token validation hooks: useERC20ERC721Validation and useERC1155Validation.
  • Enhanced NextButton to include gated token validation.
  • Updated Court component to manage token validation states and UI feedback.
  • Introduced styled components for displaying validation results.

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

Summary by CodeRabbit

  • New Features

    • Real-time validation for Ethereum token contract addresses (ERC‑20, ERC‑721, ERC‑1155) when configuring gated dispute kits.
    • Visual feedback for token address validation with loading, valid, and invalid states.
    • "Next" button disables when gated token validation fails.
    • Added a tri-state validation field on gated dispute data (not validated / valid / invalid).
  • Bug Fixes

    • Validation state resets when token address or token type changes.
  • Chores

    • Token info extraction may now return undefined when data is insufficient.

@jaybuidl jaybuidl requested a review from a team as a code owner July 22, 2025 23:56
Copy link
Contributor

coderabbitai bot commented Jul 22, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

Adds token-gate address validation for gated dispute kits: new validation hooks for ERC-20/ERC-721 and ERC-1155, UI feedback and styling on the Court page, synchronization of validation state into dispute context via isTokenGateValid, Next button gating update, and a small API change to extraDataToTokenInfo return type.

Changes

Cohort / File(s) Change Summary
Token validation hooks
web/src/hooks/useTokenAddressValidation.ts
New hook module implementing debounced contract validation for ERC-20/ERC-721 and ERC-1155 (calls balanceOf), with react-query caching, retries, error handling, and exports useERC20ERC721Validation and useERC1155Validation.
Gated dispute data interface
web/src/context/NewDisputeContext.tsx
Added optional `isTokenGateValid?: boolean
Court page (validation + UI)
web/src/pages/Resolver/Parameters/Court.tsx
Integrates validation hooks, adds validation UI components and styled input, runs ERC-1155 vs ERC-20/ERC-721 checks, updates disputeData.isTokenGateValid, resets validation on address/type changes, and manages tokenId input for ERC-1155.
Navigation gating
web/src/pages/Resolver/NavigationButtons/NextButton.tsx
Consumes isTokenGateValid from dispute data and adjusts disable logic for the /resolver/court route based on gating validity and disputeKitId.
Extra data parsing API
web/src/utils/extradataToTokenInfo.ts
Changed return type to `GatedTokenInfo

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CourtPage
    participant ValidationHook
    participant EthereumClient
    participant DisputeContext
    participant NextButton

    User->>CourtPage: Enter token address or change token type
    CourtPage->>ValidationHook: Debounced request to validate(address, tokenType)
    ValidationHook->>EthereumClient: Call contract.balanceOf(...)
    EthereumClient-->>ValidationHook: Success / Revert / Error
    ValidationHook-->>CourtPage: { isValid, isValidating, error }
    CourtPage->>DisputeContext: set disputeData.isTokenGateValid (null/true/false)
    CourtPage-->>User: Update input border, spinner/icon, and message
    NextButton->>DisputeContext: Read isTokenGateValid + disputeKitId
    NextButton-->>User: Enable or disable navigation
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • alcercu
  • kemuru

Poem

"I hopped to sniff a contract gate,
I checked the address — is it straight?
A spin, a ping, a tiny light,
Green for go or red for 'try night',
🐇🔎✨"

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 635aa6d and 3b59568.

📒 Files selected for processing (1)
  • web/src/hooks/useTokenAddressValidation.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/gated-dk-address-validation

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@jaybuidl jaybuidl requested review from tractorss and kemuru and removed request for a team July 22, 2025 23:56
@jaybuidl jaybuidl force-pushed the feat/gated-dk-address-validation branch from 8a3862f to f1fe7c9 Compare July 23, 2025 13:58
Base automatically changed from web/dk-support-improvement to dev July 28, 2025 15:54
Copy link

netlify bot commented Aug 5, 2025

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

Name Link
🔨 Latest commit 3b59568
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-university/deploys/68a7c79d5e2ae5000877bf81

Copy link

netlify bot commented Aug 5, 2025

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit 3b59568
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-testnet/deploys/68a7c79d6b9ca00008e534a5
😎 Deploy Preview https://deploy-preview-2052--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 project configuration.

Copy link

netlify bot commented Aug 5, 2025

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit 3b59568
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-neo/deploys/68a7c79ddcbbbc000829cf7e
😎 Deploy Preview https://deploy-preview-2052--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 project configuration.

Copy link

netlify bot commented Aug 5, 2025

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

Name Link
🔨 Latest commit 3b59568
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-testnet-devtools/deploys/68a7c79da1ef8100081235d5
😎 Deploy Preview https://deploy-preview-2052--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 project 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: 2

🧹 Nitpick comments (3)
web/src/pages/Resolver/NavigationButtons/NextButton.tsx (1)

24-25: Consider using optional chaining for cleaner code.

-    const gatedData = disputeData.disputeKitData as IGatedDisputeData;
-    if (!gatedData?.tokenGate?.trim()) return true; // No token address provided, so valid
+    const gatedData = disputeData.disputeKitData as IGatedDisputeData;
+    if (!gatedData.tokenGate?.trim()) return true; // No token address provided, so valid
web/src/hooks/useTokenAddressValidation.ts (2)

169-171: Consider preserving error details for debugging.

The catch block discards the original error which might contain useful information for debugging contract-specific issues.

-      } catch {
-        throw new Error(`Address does not implement ${tokenType} interface`);
+      } catch (error) {
+        console.debug(`Token validation failed for ${debouncedAddress}:`, error);
+        throw new Error(`Address does not implement ${tokenType} interface`);
       }

202-210: Error message handling could be more robust.

The error message parsing relies on string matching which might be fragile if error messages change.

Consider using error codes or more structured error handling if the contract interaction library supports it.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e3ed3c9 and 92852da.

📒 Files selected for processing (4)
  • web/src/context/NewDisputeContext.tsx (1 hunks)
  • web/src/hooks/useTokenAddressValidation.ts (1 hunks)
  • web/src/pages/Resolver/NavigationButtons/NextButton.tsx (3 hunks)
  • web/src/pages/Resolver/Parameters/Court.tsx (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (14)
  • GitHub Check: Redirect rules - kleros-v2-neo
  • GitHub Check: Header rules - kleros-v2-neo
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-neo
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Redirect rules - kleros-v2-university
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-university
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-university
  • GitHub Check: Analyze (javascript)
  • GitHub Check: contracts-testing
🔇 Additional comments (7)
web/src/context/NewDisputeContext.tsx (1)

64-64: LGTM! Well-designed validation state property.

The tri-state boolean (null = not validated, false = invalid, true = valid) is an appropriate design choice for tracking asynchronous validation status.

web/src/pages/Resolver/NavigationButtons/NextButton.tsx (1)

20-29: LGTM! Validation logic is well-structured.

The memoized validation check correctly handles all cases: non-gated kits, empty token addresses, and validated addresses.

web/src/pages/Resolver/Parameters/Court.tsx (3)

1-1: Import statement updated correctly.

Added useEffect import which is used for validation state synchronization.


90-168: Excellent UI feedback components for validation.

The styled components provide clear visual feedback with loading spinner, success checkmark, and error cross. The color scheme follows standard UX patterns (green for success, red for error).


327-336: Well-implemented validation feedback UI.

The conditional rendering of validation status with appropriate messages for each state (validating, error, success) provides excellent user experience.

web/src/hooks/useTokenAddressValidation.ts (2)

122-129: Good implementation of debouncing.

The 500ms debounce delay is appropriate for reducing unnecessary network calls while maintaining responsive UX.


150-152: Appropriate caching and retry configuration.

The 5-minute cache time and single retry with 1-second delay provide a good balance between performance and user experience.

Copy link
Contributor

@tractorss tractorss 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, pushed some small refactors

jaybuidl and others added 2 commits August 6, 2025 00:47
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 6, 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: 0

🔭 Outside diff range comments (1)
web/src/utils/extradataToTokenInfo.ts (1)

24-29: Avoid Buffer in the browser; use viem’s bytesToHex

Using Buffer can break in web builds if polyfills aren’t present. viem exposes bytesToHex which is portable and simpler.

Apply these changes:

-import { Address, hexToBytes } from "viem";
+import { Address, hexToBytes, bytesToHex } from "viem";
@@
-  const packed = BigInt("0x" + Buffer.from(packedBytes).toString("hex"));
+  const packed = BigInt(bytesToHex(packedBytes));
@@
-  const tokenId = BigInt("0x" + Buffer.from(tokenIdBytes).toString("hex"));
+  const tokenId = BigInt(bytesToHex(tokenIdBytes));
♻️ Duplicate comments (1)
web/src/pages/Resolver/NavigationButtons/NextButton.tsx (1)

44-45: Court step gating is correct and enforces mandatory token address for gated kits

Disabling Next when the token gate is missing/invalid, courtId is unset, or disputeKitId is missing aligns with the requirement that token address is mandatory for token-gated dispute kits.

🧹 Nitpick comments (3)
web/src/utils/extradataToTokenInfo.ts (1)

19-20: Be explicit: return undefined instead of bare return

Returning undefined explicitly improves readability and satisfies stricter linters (e.g., consistent-return).

-  if (extraDataBytes.length < 160) {
-    return;
-  }
+  if (extraDataBytes.length < 160) {
+    return undefined;
+  }
web/src/pages/Resolver/NavigationButtons/NextButton.tsx (2)

20-30: Simplify and de-stale: compute gating validity without useMemo and remove unnecessary type assertion

The computation is trivial and better evaluated directly each render. This avoids potential staleness if the context mutates the object in place and removes an unnecessary cast (type is already narrowed by the "type" discriminator).

-  // Check gated dispute kit validation status
-  const isGatedTokenValid = React.useMemo(() => {
-    if (!disputeData.disputeKitData || disputeData.disputeKitData.type !== "gated") return true;
-
-    const gatedData = disputeData.disputeKitData as IGatedDisputeData;
-    if (!gatedData?.tokenGate?.trim()) return false; // No token address provided, so invalid
-
-    // If token address is provided, it must be validated as valid ERC20
-    return gatedData.isTokenGateValid === true;
-  }, [disputeData.disputeKitData]);
+  // Check gated dispute kit validation status
+  const isGatedTokenValid =
+    disputeData.disputeKitData?.type !== "gated"
+      ? true
+      : Boolean(disputeData.disputeKitData.tokenGate?.trim()) &&
+        disputeData.disputeKitData.isTokenGateValid === true;

Optional (if ERC-1155 requires a tokenId to proceed): additionally gate on tokenId presence for ERC-1155:

-      : Boolean(disputeData.disputeKitData.tokenGate?.trim()) &&
-        disputeData.disputeKitData.isTokenGateValid === true;
+      : Boolean(disputeData.disputeKitData.tokenGate?.trim()) &&
+        disputeData.disputeKitData.isTokenGateValid === true &&
+        (!disputeData.disputeKitData.isERC1155 ||
+          String(disputeData.disputeKitData.tokenId ?? "").trim() !== "");

24-26: Remove the type assertion; discriminated union already narrows

After checking type !== "gated", TS can narrow disputeKitData to IGatedDisputeData when type === "gated", making the cast redundant.

No separate diff needed if you apply the simplification in the previous comment; otherwise:

-    const gatedData = disputeData.disputeKitData as IGatedDisputeData;
+    const gatedData = disputeData.disputeKitData;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d78e212 and a374113.

📒 Files selected for processing (2)
  • web/src/pages/Resolver/NavigationButtons/NextButton.tsx (3 hunks)
  • web/src/utils/extradataToTokenInfo.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-05-15T06:50:40.859Z
Learnt from: tractorss
PR: kleros/kleros-v2#1982
File: web/src/pages/Resolver/Landing/index.tsx:62-62
Timestamp: 2025-05-15T06:50:40.859Z
Learning: In the Landing component, it's safe to pass `dispute?.dispute?.arbitrated.id as 0x${string}` to `usePopulatedDisputeData` without additional null checks because the hook internally handles undefined parameters through its `isEnabled` flag and won't execute the query unless all required data is available.

Applied to files:

  • web/src/pages/Resolver/NavigationButtons/NextButton.tsx
📚 Learning: 2024-10-14T13:58:25.708Z
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1703
File: web/src/hooks/queries/usePopulatedDisputeData.ts:58-61
Timestamp: 2024-10-14T13:58:25.708Z
Learning: In `web/src/hooks/queries/usePopulatedDisputeData.ts`, the query and subsequent logic only execute when `disputeData.dispute?.arbitrableChainId` and `disputeData.dispute?.externalDisputeId` are defined, so `initialContext` properties based on these values are safe to use without additional null checks.

Applied to files:

  • web/src/pages/Resolver/NavigationButtons/NextButton.tsx
📚 Learning: 2024-10-29T10:13:04.524Z
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1729
File: web/src/layout/Header/navbar/Menu/Settings/Notifications/FormContactDetails/index.tsx:69-69
Timestamp: 2024-10-29T10:13:04.524Z
Learning: In `web/src/layout/Header/navbar/Menu/Settings/Notifications/FormContactDetails/index.tsx`, when the button is disabled, the associated logic won't be reached, and certain code paths may exist for TypeScript purposes.

Applied to files:

  • web/src/pages/Resolver/NavigationButtons/NextButton.tsx
🧬 Code Graph Analysis (1)
web/src/pages/Resolver/NavigationButtons/NextButton.tsx (1)
web/src/context/NewDisputeContext.tsx (1)
  • IGatedDisputeData (59-65)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
🔇 Additional comments (2)
web/src/utils/extradataToTokenInfo.ts (1)

13-16: ```diff

  • Public API now returns undefined — verify all call sites handle it
  • Verify callers of extraDataToTokenInfo handle undefined result

Findings: Only one usage in web/src/pages/Resolver/Landing/index.tsx – inside a useMemo:

const gatedTokenInfo = useMemo(() => {
  if (isUndefined(extradata)) return
  return extraDataToTokenInfo(extradata)
}, [roundData])
  • The code guards only against a missing extradata input, not against the function returning undefined when the data isn’t a gated disputeKit.
  • In practice, both “no input” and “non-gated data” yield undefined here, so downstream code sees the same value.
  • Confirm that wherever gatedTokenInfo gets used, the component tolerates it being undefined (e.g. via conditional rendering or optional chaining).

Action items:
• In web/src/pages/Resolver/Landing/index.tsx, audit any usage of gatedTokenInfo to ensure you check for undefined before accessing its properties.
• If additional call sites of extraDataToTokenInfo exist elsewhere in the codebase, repeat this check.

web/src/pages/Resolver/NavigationButtons/NextButton.tsx (1)

7-8: LGTM on importing IGatedDisputeData for accurate narrowing

Importing the discriminated union member improves type safety across components relying on disputeKitData.

coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 13, 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: 0

♻️ Duplicate comments (1)
web/src/pages/Resolver/Parameters/Court.tsx (1)

223-235: Nice: narrowed effect dependencies per earlier guidance.

Thanks for switching the dependency from the whole disputeData object to disputeData.disputeKitData; this avoids effect churn on unrelated context updates.

🧹 Nitpick comments (9)
web/src/pages/Resolver/Parameters/Court.tsx (9)

93-93: Fix invalid flex alignment value.

align-items does not accept "left". Use "center" (or "flex-start") depending on desired vertical alignment. Currently the rule is ignored.

-  align-items: left;
+  align-items: center;

112-125: Respect reduced-motion preferences for the spinner.

Add a prefers-reduced-motion guard to avoid continuous rotation for users who opt out of animations.

       return css`
         border: 2px solid ${({ theme }) => theme.stroke};
         border-top-color: ${({ theme }) => theme.primaryBlue};
         animation: spin 1s linear infinite;

         @keyframes spin {
           to {
             transform: rotate(360deg);
           }
         }
+        @media (prefers-reduced-motion: reduce) {
+          animation: none;
+        }
       `;

153-159: Color-only status messaging; add accessible semantics.

Validation relies on color and an icon. Provide assistive text semantics so SR users are informed.

Follow-up change proposed in the rendering block (Lines 319-326) to add aria attributes and an explicit "Invalid" message when no error string is present.


195-206: Pre-validate address shape to reduce needless RPC calls.

Gate validation by a cheap EVM address regex before invoking the hooks. This cuts contract reads while users are typing.

-const tokenGateAddress = (disputeData.disputeKitData as IGatedDisputeData)?.tokenGate ?? "";
-const isERC1155 = (disputeData.disputeKitData as IGatedDisputeData)?.isERC1155 ?? false;
-const validationEnabled = isGatedDisputeKit && !!tokenGateAddress.trim();
+const tokenGateAddress = (disputeData.disputeKitData as IGatedDisputeData)?.tokenGate ?? "";
+const isERC1155 = (disputeData.disputeKitData as IGatedDisputeData)?.isERC1155 ?? false;
+const trimmedAddress = tokenGateAddress.trim();
+const isPotentialAddress = /^0x[a-fA-F0-9]{40}$/.test(trimmedAddress);
+const validationEnabled = isGatedDisputeKit && isPotentialAddress;
-  } = useERC20ERC721Validation({
-    address: tokenGateAddress,
+  } = useERC20ERC721Validation({
+    address: trimmedAddress,
-  } = useERC1155Validation({
-    address: tokenGateAddress,
+  } = useERC1155Validation({
+    address: trimmedAddress,

228-231: Prefer functional setState to avoid stale merges.

Spreading a closed-over disputeData risks clobbering concurrent updates. Use the functional updater and return prev when no change is needed.

-    if (isGatedDisputeKit && disputeData.disputeKitData) {
-      const currentData = disputeData.disputeKitData as IGatedDisputeData;
-      if (currentData.isTokenGateValid !== isValidToken) {
-        setDisputeData({
-          ...disputeData,
-          disputeKitData: { ...currentData, isTokenGateValid: isValidToken },
-        });
-      }
-    }
-  }, [isValidToken, isGatedDisputeKit, disputeData.disputeKitData, setDisputeData]);
+    if (!isGatedDisputeKit) return;
+    setDisputeData((prev) => {
+      if (!prev.disputeKitData) return prev;
+      const currentData = prev.disputeKitData as IGatedDisputeData;
+      if (currentData.isTokenGateValid === isValidToken) return prev;
+      return { ...prev, disputeKitData: { ...currentData, isTokenGateValid: isValidToken } };
+    });
+  }, [isValidToken, isGatedDisputeKit, setDisputeData]);

256-266: Trim input and use functional updater on token address change.

Trimming avoids spurious “invalid” states caused by trailing spaces and functional updates prevent stomping concurrent context changes.

-const handleTokenAddressChange = (event: React.ChangeEvent<HTMLInputElement>) => {
-  const currentData = disputeData.disputeKitData as IGatedDisputeData;
-  setDisputeData({
-    ...disputeData,
-    disputeKitData: {
-      ...currentData,
-      tokenGate: event.target.value,
-      isTokenGateValid: null, // Reset validation state when address changes
-    },
-  });
-};
+const handleTokenAddressChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+  const value = event.target.value.trim();
+  setDisputeData((prev) => {
+    const currentData = prev.disputeKitData as IGatedDisputeData;
+    return {
+      ...prev,
+      disputeKitData: {
+        ...currentData,
+        tokenGate: value,
+        isTokenGateValid: null, // Reset validation state when address changes
+      },
+    };
+  });
+};

268-278: Functional updater for ERC-1155 toggle.

Same stale-merge concern; switch to functional setState.

-const handleERC1155TokenChange = (event: React.ChangeEvent<HTMLInputElement>) => {
-  const currentData = disputeData.disputeKitData as IGatedDisputeData;
-  setDisputeData({
-    ...disputeData,
-    disputeKitData: {
-      ...currentData,
-      isERC1155: event.target.checked,
-      isTokenGateValid: null, // Reset validation state when token type changes
-    },
-  });
-};
+const handleERC1155TokenChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+  const checked = event.target.checked;
+  setDisputeData((prev) => {
+    const currentData = prev.disputeKitData as IGatedDisputeData;
+    return {
+      ...prev,
+      disputeKitData: {
+        ...currentData,
+        isERC1155: checked,
+        isTokenGateValid: null, // Reset validation state when token type changes
+      },
+    };
+  });
+};

311-327: Improve validation status UX and a11y; add explicit “Invalid” message.

Currently, an invalid result without an error string shows only a red icon. Add aria semantics and a fallback message.

-          {tokenGateAddress.trim() !== "" && (
-            <ValidationContainer>
-              <ValidationIcon $isValidating={isValidating} $isValid={isValidToken} />
-              <ValidationMessage $isError={Boolean(validationError)}>
-                {isValidating && `Validating ${isERC1155 ? "ERC-1155" : "ERC-20 or ERC-721"} token...`}
-                {validationError && validationError}
-                {isValidToken === true && `Valid ${isERC1155 ? "ERC-1155" : "ERC-20 or ERC-721"} token`}
-              </ValidationMessage>
-            </ValidationContainer>
-          )}
+          {tokenGateAddress.trim() !== "" && (
+            <ValidationContainer>
+              <ValidationIcon aria-hidden $isValidating={isValidating} $isValid={isValidToken} />
+              <ValidationMessage
+                aria-live="polite"
+                aria-atomic="true"
+                role={validationError ? "alert" : "status"}
+                $isError={Boolean(validationError)}
+              >
+                {isValidating && `Validating ${isERC1155 ? "ERC-1155" : "ERC-20 or ERC-721"} token...`}
+                {!isValidating && validationError && validationError}
+                {!isValidating && isValidToken === true && `Valid ${isERC1155 ? "ERC-1155" : "ERC-20 or ERC-721"} token`}
+                {!isValidating && isValidToken === false && !validationError &&
+                  `Invalid ${isERC1155 ? "ERC-1155" : "ERC-20 or ERC-721"} token`}
+              </ValidationMessage>
+            </ValidationContainer>
+          )}

160-168: Theme tokens sanity check.

StyledFieldWithValidation uses theme.success and theme.error. Ensure those exist across all themes, or set fallbacks to avoid runtime styling issues in unsupported themes.

Optionally, guard with defaults:

-    border-color: ${({ $isValid, theme }) => {
+    border-color: ${({ $isValid, theme }) => {
       if ($isValid === true) return theme.success;
       if ($isValid === false) return theme.error;
       return "inherit";
     }};

If success/error aren’t guaranteed, map to existing palette keys or provide CSS custom properties with fallbacks.

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a374113 and 635aa6d.

📒 Files selected for processing (1)
  • web/src/pages/Resolver/Parameters/Court.tsx (6 hunks)
🧰 Additional context used
🧠 Learnings (8)
📚 Learning: 2024-10-09T10:22:41.474Z
Learnt from: jaybuidl
PR: kleros/kleros-v2#1582
File: web-devtools/src/app/(main)/ruler/SelectArbitrable.tsx:88-90
Timestamp: 2024-10-09T10:22:41.474Z
Learning: Next.js recommends using the `useEffect` hook to set `isClient` and using `suppressHydrationWarning` as a workaround for handling hydration inconsistencies, especially when dealing with data like `knownArbitrables` that may differ between server-side and client-side rendering. This approach is acceptable in TypeScript/React applications, such as in `web-devtools/src/app/(main)/ruler/SelectArbitrable.tsx`.

Applied to files:

  • web/src/pages/Resolver/Parameters/Court.tsx
📚 Learning: 2025-05-09T13:39:15.086Z
Learnt from: tractorss
PR: kleros/kleros-v2#1982
File: web/src/pages/Resolver/Parameters/NotablePersons/PersonFields.tsx:64-0
Timestamp: 2025-05-09T13:39:15.086Z
Learning: In PersonFields.tsx, the useEffect hook for address validation intentionally uses an empty dependency array to run only once on component mount. This is specifically designed for the dispute duplication flow when aliasesArray is already populated with addresses that need initial validation.

Applied to files:

  • web/src/pages/Resolver/Parameters/Court.tsx
📚 Learning: 2025-05-15T06:50:40.859Z
Learnt from: tractorss
PR: kleros/kleros-v2#1982
File: web/src/pages/Resolver/Landing/index.tsx:62-62
Timestamp: 2025-05-15T06:50:40.859Z
Learning: In the Landing component, it's safe to pass `dispute?.dispute?.arbitrated.id as 0x${string}` to `usePopulatedDisputeData` without additional null checks because the hook internally handles undefined parameters through its `isEnabled` flag and won't execute the query unless all required data is available.

Applied to files:

  • web/src/pages/Resolver/Parameters/Court.tsx
📚 Learning: 2024-06-27T10:11:54.861Z
Learnt from: nikhilverma360
PR: kleros/kleros-v2#1632
File: web/src/components/DisputeView/DisputeInfo/DisputeInfoList.tsx:37-42
Timestamp: 2024-06-27T10:11:54.861Z
Learning: `useMemo` is used in `DisputeInfoList` to optimize the rendering of `FieldItems` based on changes in `fieldItems`, ensuring that the mapping and truncation operation are only performed when necessary.

Applied to files:

  • web/src/pages/Resolver/Parameters/Court.tsx
📚 Learning: 2024-10-28T05:55:12.728Z
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1716
File: web-devtools/src/app/(main)/dispute-template/CustomContextInputs.tsx:29-42
Timestamp: 2024-10-28T05:55:12.728Z
Learning: In the `CustomContextInputs` component located at `web-devtools/src/app/(main)/dispute-template/CustomContextInputs.tsx`, the `DisputeRequestParams` array is used to exclude certain variables from the custom input since they are already provided in a preceding component. Therefore, converting it to a type is unnecessary.

Applied to files:

  • web/src/pages/Resolver/Parameters/Court.tsx
📚 Learning: 2024-10-14T13:58:25.708Z
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1703
File: web/src/hooks/queries/usePopulatedDisputeData.ts:58-61
Timestamp: 2024-10-14T13:58:25.708Z
Learning: In `web/src/hooks/queries/usePopulatedDisputeData.ts`, the query and subsequent logic only execute when `disputeData.dispute?.arbitrableChainId` and `disputeData.dispute?.externalDisputeId` are defined, so `initialContext` properties based on these values are safe to use without additional null checks.

Applied to files:

  • web/src/pages/Resolver/Parameters/Court.tsx
📚 Learning: 2025-05-15T06:50:45.650Z
Learnt from: tractorss
PR: kleros/kleros-v2#1982
File: web/src/pages/Resolver/Landing/index.tsx:0-0
Timestamp: 2025-05-15T06:50:45.650Z
Learning: In the Kleros V2 codebase, it's acceptable to use ESLint disable comments for dependency arrays in useEffect hooks when including certain dependencies (like state that is being updated within the effect) would cause infinite loops.

Applied to files:

  • web/src/pages/Resolver/Parameters/Court.tsx
📚 Learning: 2024-12-06T13:04:50.495Z
Learnt from: kemuru
PR: kleros/kleros-v2#1774
File: web/src/components/CasesDisplay/index.tsx:61-61
Timestamp: 2024-12-06T13:04:50.495Z
Learning: In `web/src/components/CasesDisplay/index.tsx`, the variables `numberDisputes` and `numberClosedDisputes` can sometimes be `NaN`, and should default to `0` using logical OR (`||`) to prevent display issues in the `StatsAndFilters` component.

Applied to files:

  • web/src/pages/Resolver/Parameters/Court.tsx
🧬 Code graph analysis (1)
web/src/pages/Resolver/Parameters/Court.tsx (4)
web-devtools/src/styles/responsiveSize.ts (1)
  • responsiveSize (9-12)
web-devtools/src/styles/Theme.tsx (1)
  • theme (3-10)
web/src/context/NewDisputeContext.tsx (1)
  • IGatedDisputeData (59-65)
web/src/hooks/useTokenAddressValidation.ts (2)
  • useERC20ERC721Validation (75-86)
  • useERC1155Validation (94-102)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (11)
  • 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: contracts-testing
  • GitHub Check: Mend Security Check
🔇 Additional comments (2)
web/src/pages/Resolver/Parameters/Court.tsx (2)

191-194: LGTM: gated kit detection is concise and stable.

Using a memoized lookup keyed by disputeKitId is clear and efficient.


305-306: Confirm controlled vs. uncontrolled select usage.

Using defaultValue makes the DropdownSelect uncontrolled; UI won’t reflect later disputeKitId changes. If the component supports a controlled value prop, switch to value.

-          defaultValue={disputeData.disputeKitId}
+          value={disputeData.disputeKitId}

If DropdownSelect is intentionally uncontrolled, confirm that disputeKitId never updates programmatically after mount; otherwise the selection can desync.

coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 21, 2025
kemuru
kemuru previously approved these changes Aug 21, 2025
alcercu
alcercu previously approved these changes Aug 21, 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

@jaybuidl jaybuidl dismissed stale reviews from alcercu, kemuru, and coderabbitai[bot] via 8f4993d August 22, 2025 01:27
@jaybuidl jaybuidl merged commit f02d718 into dev Aug 22, 2025
5 checks passed
@jaybuidl jaybuidl deleted the feat/gated-dk-address-validation branch August 22, 2025 01:28
Copy link

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.

4 participants