Skip to content

feat(kleros-sdk): Initial SDK documentation and README improvements #2006

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

Draft
wants to merge 1 commit into
base: dev
Choose a base branch
from

Conversation

jaybuidl
Copy link
Member

@jaybuidl jaybuidl commented May 21, 2025

This commit introduces the first phase of enhancing the kleros-sdk package for better usability and maintainability.

Key changes include:

  1. Enhanced README.md:

    • Overhauled the README with a comprehensive introduction, installation instructions, a "Quick Start" guide, SDK configuration details, core concept explanations (Public Client, Data Mappings, Requests), and contribution guidelines.
  2. API Documentation (TSDoc):

    • Added TSDoc comments to functions and types in the following core modules:
      • src/sdk.ts: Documented configureSDK and getPublicClient.
      • src/types/index.ts: Documented SdkConfig and GetDisputeParameters.
      • src/utils/getDispute.ts: Refined existing TSDoc for the main getDispute utility function, detailing its parameters, return value, and potential errors.
      • src/requests/gqlClient.ts: Documented the internal GraphQL client helper.
      • src/requests/fetchDisputeDetails.ts: Documented the internal function for fetching dispute details from a subgraph.
      • src/requests/fetchDisputeTemplateFromId.ts: Documented the internal function for fetching dispute templates from a DTR subgraph.

So far, my focus has been on establishing a solid foundation for the SDK's documentation, starting with the README and core utility/request functions. Next, I plan to dive deeper into the dataMappings module, which appears to contain a significant portion of the SDK's logic, and continue to add TSDoc comments throughout. I also plan to review error handling and build processes.

I was about to start exploring the dataMappings module by examining its index.ts and executeActions.ts files to understand its public interface and internal workings, with the goal of adding comprehensive TSDoc comments.


PR-Codex overview

This PR enhances the kleros-sdk by improving the documentation, error handling, and type safety across various modules. It introduces detailed comments for functions and types, ensuring better clarity and usability for developers.

Detailed summary

  • Added comprehensive JSDoc comments for functions and types in gqlClient.ts, index.ts, sdk.ts, fetchDisputeDetails.ts, and fetchDisputeTemplateFromId.ts.
  • Enhanced error handling by wrapping errors in KlerosSDKError and RequestError.
  • Improved type safety for publicClient in sdk.ts.
  • Updated getClient function to ensure correct typing for exchanges.
  • Modified fetchDisputeDetails and fetchDisputeTemplateFromId to streamline error handling and response processing.
  • Refined the getDispute function to ensure proper SDK configuration and enhanced error messages.
  • Improved README with clearer installation instructions, usage examples, and features of the SDK.

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

Summary by CodeRabbit

  • Documentation

    • Significantly expanded and restructured the SDK's README with detailed usage instructions, feature overview, installation steps, configuration examples, and contribution guidelines.
    • Added comprehensive JSDoc comments throughout the SDK, enhancing clarity on function parameters, return types, possible errors, and usage examples.
  • Refactor

    • Improved type safety and error handling across several functions for more robust developer experience.
    • Updated function signatures and type definitions for stricter typing and clearer API contracts.
    • Enhanced error messages and validation, especially for SDK configuration and data mapping execution.

This commit introduces the first phase of enhancing the `kleros-sdk` package for better usability and maintainability.

Key changes include:

1.  **Enhanced README.md**:
    *   Overhauled the README with a comprehensive introduction, installation instructions, a "Quick Start" guide, SDK configuration details, core concept explanations (Public Client, Data Mappings, Requests), and contribution guidelines.

2.  **API Documentation (TSDoc)**:
    *   Added TSDoc comments to functions and types in the following core modules:
        *   `src/sdk.ts`: Documented `configureSDK` and `getPublicClient`.
        *   `src/types/index.ts`: Documented `SdkConfig` and `GetDisputeParameters`.
        *   `src/utils/getDispute.ts`: Refined existing TSDoc for the main `getDispute` utility function, detailing its parameters, return value, and potential errors.
        *   `src/requests/gqlClient.ts`: Documented the internal GraphQL client helper.
        *   `src/requests/fetchDisputeDetails.ts`: Documented the internal function for fetching dispute details from a subgraph.
        *   `src/requests/fetchDisputeTemplateFromId.ts`: Documented the internal function for fetching dispute templates from a DTR subgraph.

So far, my focus has been on establishing a solid foundation for the SDK's documentation, starting with the README and core utility/request functions. Next, I plan to dive deeper into the `dataMappings` module, which appears to contain a significant portion of the SDK's logic, and continue to add TSDoc comments throughout. I also plan to review error handling and build processes.

I was about to start exploring the `dataMappings` module by examining its `index.ts` and `executeActions.ts` files to understand its public interface and internal workings, with the goal of adding comprehensive TSDoc comments.
Copy link

netlify bot commented May 21, 2025

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit dfe3858
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-testnet/deploys/682e20164b057d0008cc6a2b
😎 Deploy Preview https://deploy-preview-2006--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 May 21, 2025

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

Name Link
🔨 Latest commit dfe3858
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-university/deploys/682e20164dc9be000836bffa

Copy link

netlify bot commented May 21, 2025

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit dfe3858
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-neo/deploys/682e201679771f00089d9d93
😎 Deploy Preview https://deploy-preview-2006--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
Contributor

coderabbitai bot commented May 21, 2025

Walkthrough

This update introduces extensive improvements to the Kleros SDK documentation and refines several TypeScript modules for enhanced type safety, error handling, and developer guidance. The README is restructured with detailed usage instructions, while exported types, function signatures, and JSDoc comments are clarified across core modules. No core logic is altered.

Changes

File(s) Change Summary
kleros-sdk/README.md Replaced minimal content with a comprehensive guide: introduction, features, installation, configuration, core concepts, API documentation, examples, contribution guidelines, testing, and license. Added code snippets and structured navigation.
kleros-sdk/src/requests/fetchDisputeDetails.ts
kleros-sdk/src/requests/fetchDisputeTemplateFromId.ts
Refactored both functions for explicit TypeScript typing, improved error handling (distinguishing error types and wrapping with context), and added extensive JSDoc documentation. Function signatures now clarify possible undefined returns, and GraphQL queries are strongly typed.
kleros-sdk/src/requests/gqlClient.ts Added detailed JSDoc to getClient, explicitly typed its return value, and ensured correct typing of the exchanges array.
kleros-sdk/src/sdk.ts Updated publicClient typing, changed configureSDK and getPublicClient signatures for stricter type safety, and added thorough JSDoc documentation. getPublicClient now throws if not configured, never returns undefined.
kleros-sdk/src/types/index.ts Changed SdkConfig.client type from PublicClientConfig to PublicClient. Added GetDisputeParametersOptions type and enhanced all types with detailed JSDoc comments.
kleros-sdk/src/utils/getDispute.ts Expanded JSDoc documentation, improved error handling, added local SDK config override, refined template checks, and made data mapping execution more robust. Function signature unchanged.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SDK
    participant ViemClient
    participant GraphQL
    participant IPFS

    User->>SDK: configureSDK({ client: ViemClient })
    User->>SDK: getDispute({ disputeId, coreSubgraph, dtrSubgraph, options })
    SDK->>GraphQL: fetchDisputeDetails(disputeId)
    SDK->>GraphQL: fetchDisputeTemplateFromId(templateId)
    SDK->>IPFS: Fetch template data (if needed)
    SDK->>ViemClient: Interact with blockchain (if needed)
    SDK-->>User: DisputeDetails or error
Loading

Possibly related PRs

Suggested labels

Type: Feature🗿, Package: SDK

Suggested reviewers

  • alcercu

Poem

In the warren where code bunnies dwell,
We’ve polished our docs and typed things well.
With errors now clearer and guidance in tow,
The SDK’s ready—just npm install and go!
From queries to mappings, it’s all in your paw,
Hop in, dear dev, and code without flaw.
🐇✨

Note

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 30th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

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

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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

codeclimate bot commented May 21, 2025

Code Climate has analyzed commit dfe3858 and detected 10 issues on this pull request.

Here's the issue category breakdown:

Category Count
Style 10

View more on Code Climate.

Copy link

Copy link

netlify bot commented May 21, 2025

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

Name Link
🔨 Latest commit dfe3858
🔍 Latest deploy log https://app.netlify.com/projects/kleros-v2-testnet-devtools/deploys/682e20162b834a0008fd1398

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 (8)
kleros-sdk/src/requests/gqlClient.ts (2)

24-31: Remove the superfluous filter(Boolean) + type-cast to avoid masking issues

[cacheExchange, fetchExchange] is already a fully-typed Exchange[].
Running it through filter(Boolean) coerces the array to (Exchange | undefined)[], forcing a manual cast back to Exchange[], and—more importantly—silently swallows future falsy exchanges that might indicate a configuration bug.

-      exchanges: [cacheExchange, fetchExchange].filter(Boolean) as Exchange[], // Ensure exchanges are correctly typed
+      exchanges: [cacheExchange, fetchExchange], // Already Exchange[]

Besides eliminating an unnecessary operation, dropping the cast restores the compiler’s ability to warn if you ever pass a non-Exchange value.


3-4: Consider bounding the in-memory client cache

clients is a module-level Map that grows for every distinct endpoint ever encountered.
For long-running processes or multi-tenant environments this can lead to unbounded memory use.

Options:

  1. Add a simple LRU eviction (e.g., quick-lru) with a sane max size.
  2. Expose a clearClientCache() helper for consumers who spin up many ephemeral endpoints.

Not urgent but worth planning before the SDK is widely adopted.

kleros-sdk/src/utils/getDispute.ts (2)

72-77: Guard against accidental global re-configuration

When sdkConfig is provided, configureSDK mutates the global singleton, potentially overwriting a client already in use elsewhere.

Two safer alternatives:

  1. Accept a PublicClient in options and thread it down to request helpers without touching global state.
  2. Detect mismatched clients and warn rather than overwrite:
if (options?.sdkConfig) {
  if (publicClient && publicClient !== options.sdkConfig.client) {
    throw new KlerosSDKError("getDispute attempted to overwrite existing PublicClient");
  }
  configureSDK(options.sdkConfig);
}

This prevents subtle cross-request bugs in multi-network apps.


108-114: Harden JSON parsing of templateDataMappings

JSON.parse on arbitrary on-chain or subgraph strings can throw and currently bubbles up as a generic SyntaxError wrapped in KlerosSDKError.
For better DX and security consider:

let parsedMappings: unknown;
try {
  parsedMappings = typeof templateDataMappings === "string"
    ? JSON.parse(templateDataMappings)
    : templateDataMappings;
  // Validate structure here (e.g., using zod / io-ts)
} catch (e) {
  throw new KlerosSDKError(
    `Invalid templateDataMappings JSON for template ${disputeDetails.dispute.templateId}`,
    { cause: e }
  );
}

Adding schema validation will surface malformed mappings early and protect executeActions from unexpected shapes.

kleros-sdk/README.md (4)

23-31: Inconsistent list style in Features section.

The Features section uses asterisks (*) for bullet points while the rest of the document uses dashes (-). This inconsistency affects readability and professional appearance.

Change the list style to use dashes for consistency:

-*   **Viem Integration**: Leverages the power and efficiency of [Viem](httpsa://viem.sh/) for Ethereum blockchain interactions.
-*   **Type-Safe**: Fully written in TypeScript for robust type checking and improved developer experience.
-*   **Dispute Resolution**: Tools to fetch dispute details, and interact with the Kleros arbitration process.
-*   **Data Handling**: Utilities for working with Kleros-specific data structures and evidence.
-*   **Subgraph Interaction**: Functionality to query Kleros subgraphs for indexed data.
-*   **IPFS Support**: Helpers for fetching data stored on IPFS.
+- **Viem Integration**: Leverages the power and efficiency of [Viem](httpsa://viem.sh/) for Ethereum blockchain interactions.
+- **Type-Safe**: Fully written in TypeScript for robust type checking and improved developer experience.
+- **Dispute Resolution**: Tools to fetch dispute details, and interact with the Kleros arbitration process.
+- **Data Handling**: Utilities for working with Kleros-specific data structures and evidence.
+- **Subgraph Interaction**: Functionality to query Kleros subgraphs for indexed data.
+- **IPFS Support**: Helpers for fetching data stored on IPFS.
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

25-25: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


26-26: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


27-27: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


28-28: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


29-29: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


30-30: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


25-25: Fix typo in Viem URL.

There's a typo in the URL for Viem documentation.

-*   **Viem Integration**: Leverages the power and efficiency of [Viem](httpsa://viem.sh/) for Ethereum blockchain interactions.
+*   **Viem Integration**: Leverages the power and efficiency of [Viem](https://viem.sh/) for Ethereum blockchain interactions.
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

25-25: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


69-110: Helpful quick start example with transparency about WIP status.

The example clearly communicates that it's illustrative while the API is being finalized, which helps set correct expectations for developers. The note about the example being illustrative uses inconsistent emphasis style with asterisks instead of underscores.

-*Note: The Quick Start example is illustrative. The exact API usage, especially for fetching dispute details, will be refined as the SDK's public API is further clarified in subsequent steps.*
+_Note: The Quick Start example is illustrative. The exact API usage, especially for fetching dispute details, will be refined as the SDK's public API is further clarified in subsequent steps._
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

110-110: Emphasis style
Expected: underscore; Actual: asterisk

(MD049, emphasis-style)


110-110: Emphasis style
Expected: underscore; Actual: asterisk

(MD049, emphasis-style)


112-125: Informative core concepts with inconsistent list style.

The Data Mappings section effectively explains the module's purpose and capabilities, but uses asterisks for list items instead of dashes, which is inconsistent with other lists in the document.

-*   Calling smart contract functions
-*   Fetching JSON data from IPFS
-*   Querying Kleros subgraphs
+- Calling smart contract functions
+- Fetching JSON data from IPFS
+- Querying Kleros subgraphs
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)

121-121: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


122-122: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


123-123: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1ca9066 and dfe3858.

📒 Files selected for processing (7)
  • kleros-sdk/README.md (1 hunks)
  • kleros-sdk/src/requests/fetchDisputeDetails.ts (2 hunks)
  • kleros-sdk/src/requests/fetchDisputeTemplateFromId.ts (2 hunks)
  • kleros-sdk/src/requests/gqlClient.ts (1 hunks)
  • kleros-sdk/src/sdk.ts (1 hunks)
  • kleros-sdk/src/types/index.ts (1 hunks)
  • kleros-sdk/src/utils/getDispute.ts (3 hunks)
🧰 Additional context used
🧠 Learnings (2)
kleros-sdk/src/requests/gqlClient.ts (1)
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1703
File: kleros-sdk/src/requests/gqlClient.ts:5-16
Timestamp: 2024-10-24T08:18:13.218Z
Learning: In the `getClient` function in `kleros-sdk/src/requests/gqlClient.ts`, the consumer is responsible for validating the endpoint, and the `Client` handles invalid endpoints by throwing appropriate errors.
kleros-sdk/src/sdk.ts (2)
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1703
File: kleros-sdk/src/sdk.ts:1-3
Timestamp: 2024-10-22T10:23:15.789Z
Learning: In `kleros-sdk/src/sdk.ts`, the `PublicClient` type is used and should not be flagged as unused.
Learnt from: Harman-singh-waraich
PR: kleros/kleros-v2#1703
File: kleros-sdk/src/sdk.ts:13-17
Timestamp: 2024-10-22T10:07:21.327Z
Learning: In the SDK, `getPublicClient()` handles the scenario where `publicClient` is undefined by throwing `SdkNotConfiguredError`, so additional error handling in functions that call `getPublicClient()` is not necessary.
🧬 Code Graph Analysis (3)
kleros-sdk/src/sdk.ts (1)
kleros-sdk/src/types/index.ts (1)
  • SdkConfig (6-23)
kleros-sdk/src/utils/getDispute.ts (4)
kleros-sdk/src/types/index.ts (1)
  • GetDisputeParameters (45-65)
kleros-sdk/src/sdk.ts (2)
  • configureSDK (30-35)
  • getPublicClient (59-64)
kleros-sdk/src/errors/index.ts (1)
  • NotFoundError (24-31)
kleros-sdk/src/dataMappings/executeActions.ts (1)
  • executeActions (49-66)
kleros-sdk/src/requests/fetchDisputeTemplateFromId.ts (1)
kleros-sdk/src/errors/index.ts (1)
  • RequestError (32-39)
🪛 markdownlint-cli2 (0.17.2)
kleros-sdk/README.md

25-25: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


26-26: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


27-27: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


28-28: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


29-29: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


30-30: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


110-110: Emphasis style
Expected: underscore; Actual: asterisk

(MD049, emphasis-style)


110-110: Emphasis style
Expected: underscore; Actual: asterisk

(MD049, emphasis-style)


121-121: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


122-122: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)


123-123: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)

⏰ Context from checks skipped due to timeout of 90000ms (15)
  • GitHub Check: Redirect rules - kleros-v2-university
  • GitHub Check: Redirect rules - kleros-v2-neo
  • GitHub Check: Header rules - kleros-v2-university
  • GitHub Check: Header rules - kleros-v2-neo
  • GitHub Check: SonarCloud
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-neo
  • GitHub Check: contracts-testing
  • GitHub Check: Pages changed - kleros-v2-university
  • GitHub Check: Analyze (javascript)
  • 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
🔇 Additional comments (22)
kleros-sdk/src/requests/fetchDisputeDetails.ts (6)

1-2: Well-structured imports for error handling.

The imports correctly bring in both the specific RequestError and the base KlerosSDKError classes, and the typed GraphQL utilities from @urql/core.


5-22: Good type definition with clear documentation.

The DisputeDetailsQueryResponse type is well-documented with JSDoc comments that clearly explain the purpose of each field. The null union type properly handles cases where a dispute might not be found.


24-39: Excellent typed GraphQL query definition.

Using TypedDocumentNode provides strong type safety between the query structure and expected response type. This helps catch potential schema mismatches at compile time rather than runtime.


41-71: Comprehensive function documentation.

The JSDoc comments provide excellent documentation covering:

  • Function purpose and context
  • Parameter types and descriptions
  • Return type with possible values
  • Detailed error handling expectations
  • A practical usage example

This level of documentation significantly improves developer experience.


72-85: Improved async handling and error management.

The function now uses modern async/await syntax instead of promise chaining, making the code more readable. The explicit error checking for result.error provides clearer error propagation.


86-96: Robust layered error handling.

The error handling implementation follows best practices by:

  1. Differentiating between GraphQL errors, standard errors, and unknown errors
  2. Preserving the original error as a cause for debugging
  3. Adding contextual information to error messages (dispute ID, endpoint)
  4. Using specific error types for better error classification
kleros-sdk/src/types/index.ts (3)

3-23: Well-documented SDK configuration type.

The SdkConfig type is thoroughly documented with clear explanations of:

  • Purpose of the configuration object
  • Requirements for the Viem PublicClient
  • Link to Viem documentation for further reference
  • A complete usage example

This helps developers understand exactly how to configure the SDK properly.


25-40: Clear options type with well-explained fields.

The GetDisputeParametersOptions type clearly documents:

  • The purpose of the optional SDK configuration override
  • How additional context can be used for specific dispute resolution flows

This gives developers flexibility while providing clear guidance on when to use these options.


42-65: Comprehensive parameter documentation.

The GetDisputeParameters type documentation clearly explains:

  • The format and type of the dispute ID
  • The purpose of each GraphQL endpoint
  • How the optional parameters can be used

This level of detail helps prevent misuse and guides developers to correct implementation.

kleros-sdk/README.md (7)

3-22: Well-structured README with comprehensive ToC.

The introduction clearly positions the SDK as Archon's successor, and the Table of Contents provides an excellent overview of all sections, making navigation easy for developers.


32-44: Clear installation instructions.

The installation section provides straightforward commands for both npm and yarn, and correctly notes the peer dependency requirement for Viem.


46-67: Excellent configuration example.

The configuration section provides a complete and clear example of how to set up the SDK with a Viem Public Client, which is essential for first-time users.


126-129: Clear explanation of the Requests module.

The Requests section succinctly explains the purpose of the module and provides a relevant example of fetchDisputeDetails.ts.


130-139: Transparent API documentation status.

The section clearly communicates the current state and future plans for documentation, setting appropriate expectations for developers.


140-160: Well-structured contribution guidelines.

The Contributing section provides clear instructions for submitting issues and pull requests, along with information about coding standards and running tests.


162-164: Clear license information.

The License section clearly states the MIT License and provides a link to the license file.

kleros-sdk/src/requests/fetchDisputeTemplateFromId.ts (6)

1-3: Appropriate imports for GraphQL client and error handling.

The imports correctly bring in the necessary components for typed GraphQL queries and structured error handling.


5-21: Well-documented type definition.

The DisputeTemplateQueryResponse type includes clear JSDoc comments explaining each field's purpose and format. The null union type correctly handles cases where templates might not be found.


23-34: Type-safe GraphQL query definition.

Using TypedDocumentNode provides compile-time type checking between the query structure and expected response, improving type safety throughout the codebase.


36-66: Comprehensive function documentation.

The JSDoc comments provide excellent documentation covering:

  • Function purpose and internal usage context
  • Parameter descriptions
  • Return type with possible values
  • Detailed error handling expectations
  • A practical usage example

This level of detail significantly improves code maintainability and developer onboarding.


67-81: Improved async/await implementation with clear error handling.

The function signature now correctly specifies the return type and uses modern async/await syntax. The explicit error checking for result.error provides better error propagation.


82-92: Robust error handling with proper context.

The error handling approach follows best practices by:

  1. Differentiating between GraphQL errors, standard errors, and unknown errors
  2. Including contextual information in error messages (template ID, endpoint)
  3. Preserving original errors as causes for debugging
  4. Using specific error types for better classification

Comment on lines 30 to 35
export const configureSDK = (config: SdkConfig) => {
if (config.client) {
publicClient = createPublicClient(config.client);
// Type assertion to satisfy the more specific type of publicClient
publicClient = config.client as PublicClient<Transport, Chain>;
}
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Tighten configureSDK: redundant check & risky type-assertion

SdkConfig.client is non-optional, so the if (config.client) guard is redundant.
More importantly, the cast to PublicClient<Transport, Chain> may hide a client created for an incompatible chain/transport combination.

Recommended:

-export const configureSDK = (config: SdkConfig) => {
-  if (config.client) {
-    // Type assertion to satisfy the more specific type of publicClient
-    publicClient = config.client as PublicClient<Transport, Chain>;
-  }
-};
+export const configureSDK = (config: SdkConfig): void => {
+  // Prefer a generic parameter on SdkConfig so the cast is unnecessary.
+  publicClient = config.client;
+}

If you need the extra generics, extend SdkConfig:

export type SdkConfig<T extends Transport = Transport, C extends Chain = Chain> = {
  client: PublicClient<T, C>;
};

This preserves safety while avoiding assertions.

🤖 Prompt for AI Agents
In kleros-sdk/src/sdk.ts around lines 30 to 35, remove the redundant if-check
for config.client since it is non-optional, and eliminate the unsafe type
assertion to PublicClient<Transport, Chain>. Instead, update the SdkConfig type
to be generic with parameters extending Transport and Chain, and type the client
property as PublicClient<T, C>. Then update configureSDK to accept this generic
SdkConfig and assign config.client directly to publicClient without casting,
preserving type safety.

throw error;
} else if (error instanceof Error) {
throw new RequestError(`Error querying Dispute Template: ${error.message}`, endpoint);
// Wrap other errors in RequestError for consistent SDK error types
throw new RequestError(`Error querying Dispute Template for ID ${id}: ${error.message}`, endpoint, { cause: error });
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Inconsistency with RequestError constructor.

The RequestError constructor is being called with three arguments, but the RequestError class shown in the relevant snippets only accepts two parameters (message and endpoint). The third argument ({ cause: error }) might not be correctly handled.


🏁 Script executed:

#!/bin/bash
# Verify the RequestError constructor implementation
rg -A 10 "export class RequestError"

Length of output: 683


🏁 Script executed:

#!/bin/bash
# Inspect the CustomError class to see if it handles 'cause'
rg -A 10 "export class CustomError" kleros-sdk/src/errors/index.ts

Length of output: 302


Fix RequestError constructor or remove unsupported cause argument

The throw at kleros-sdk/src/requests/fetchDisputeTemplateFromId.ts:88 passes three arguments to RequestError, but its signature is only:

constructor(message: string, endpoint?: string)

The third { cause: error } is discarded at runtime. You should either:

  • Extend the RequestError (and possibly CustomError) constructor to accept an optional options?: { cause?: Error } parameter and assign this.cause = options.cause.
  • Or remove the unsupported { cause: error } argument from the throw and rely on chaining the original error manually if needed.

Locations to update:

  • kleros-sdk/src/requests/fetchDisputeTemplateFromId.ts (line 88)
  • kleros-sdk/src/errors/index.ts (update RequestError and/or CustomError constructors)
🤖 Prompt for AI Agents
In kleros-sdk/src/requests/fetchDisputeTemplateFromId.ts at line 88, the throw
statement passes three arguments to the RequestError constructor, but the
constructor only accepts two parameters (message and endpoint). To fix this,
either update the RequestError (and possibly CustomError) constructor in
kleros-sdk/src/errors/index.ts to accept an optional options parameter that
includes cause and assign this.cause accordingly, or remove the unsupported
third argument { cause: error } from the throw statement and handle error
chaining manually if needed.

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.

1 participant