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

feat(subgraph): add StakeSet entity and handler tweak #1901

Merged
merged 7 commits into from
Mar 14, 2025

Conversation

kemuru
Copy link
Contributor

@kemuru kemuru commented Feb 21, 2025

this is needed for the Staking Rewards script (for pnk-merkle-drop) in V2


PR-Codex overview

This PR focuses on updating the subgraph's schema and functionality to accommodate a new StakeSet entity, reflecting changes in staking events and enhancing data management for jurors.

Detailed summary

  • Updated version in subgraph/package.json to 0.12.0.
  • Added StakeSet entity in multiple subgraph.yaml files.
  • Defined StakeSet type in subgraph/core/schema.graphql.
  • Modified handleStakeSet function to create and save StakeSetEntity.
  • Updated imports to include StakeSetEntity in relevant TypeScript files.

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

Summary by CodeRabbit

  • New Features

    • Introduced a new entity, StakeSet, to enhance staking tracking with detailed information (e.g., stake amounts, updated totals, timestamps) for stake events, offering more granular insights for data monitoring.
  • Refactor

    • Improved event handling logic for stake updates to streamline processing and ensure reliable performance without affecting existing functionality.
  • Chores

    • Updated package version from "0.11.0" to "0.12.0".

@kemuru kemuru requested a review from a team as a code owner February 21, 2025 17:23
Copy link
Contributor

coderabbitai bot commented Feb 21, 2025

Walkthrough

This pull request introduces the new StakeSet entity across multiple subgraph configuration files and the GraphQL schema. It expands the SortitionModule capabilities by adding logic to handle the StakeSet event. In the TypeScript modules, the event is renamed to StakeSetEvent, and additional logic is implemented to create and persist a corresponding entity. The changes ensure that the subgraph now processes and tracks new staking-related data without altering any existing entities or configurations.

Changes

File(s) Change Summary
subgraph/core-neo/subgraph.yaml, subgraph/core-university/subgraph.yaml, subgraph/core/subgraph.yaml Added a new StakeSet entity to the SortitionModule data source.
subgraph/core/schema.graphql Introduced a new GraphQL entity StakeSet with fields: id, juror, courtID, stake, newTotalStake, blocknumber, timestamp, and logIndex.
subgraph/core/src/SortitionModule.ts, subgraph/core-university/src/SortitionModule.ts Renamed event import to StakeSetEvent and updated the handleStakeSet function to create and persist a StakeSetEntity based on event data.

Possibly related PRs

Suggested labels

Type: Feature🗿, Package: Web

Suggested reviewers

  • Harman-singh-waraich
  • alcercu

Poem

In the digital field, I hop with glee,
New StakeSet sprouts for all to see.
Events now dance in a code parade,
With names refined and logic made.
A bunny cheers in ASCII delight 🐇
Celebrating change in the starlit byte.


🪧 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 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.

@kemuru kemuru changed the title feat(subgraph): add StakeSet entity and handler feat(subgraph): add StakeSet entity and handler tweak Feb 21, 2025
Copy link

netlify bot commented Feb 21, 2025

Deploy Preview for kleros-v2-testnet ready!

Name Link
🔨 Latest commit 809b085
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet/deploys/67d41adfd5163c000810ffb5
😎 Deploy Preview https://deploy-preview-1901--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 Feb 21, 2025

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

Name Link
🔨 Latest commit 809b085
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-testnet-devtools/deploys/67d41adfaff3b40008bbb9ea
😎 Deploy Preview https://deploy-preview-1901--kleros-v2-testnet-devtools.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

netlify bot commented Feb 21, 2025

Deploy Preview for kleros-v2-neo ready!

Name Link
🔨 Latest commit 809b085
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-neo/deploys/67d41adf9f6471000872f197
😎 Deploy Preview https://deploy-preview-1901--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 Feb 21, 2025

Deploy Preview for kleros-v2-university ready!

Name Link
🔨 Latest commit 809b085
🔍 Latest deploy log https://app.netlify.com/sites/kleros-v2-university/deploys/67d41adf0e4dc10008e03558
😎 Deploy Preview https://deploy-preview-1901--kleros-v2-university.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
subgraph/core/src/SortitionModule.ts (2)

36-37: Add error logging for missing general court.

The early return if the general court is not found could lead to silent failures. Consider adding error logging to help with debugging.

-  if (!generalCourt) return;
+  if (!generalCourt) {
+    log.error("General court not found when processing StakeSet event. TX: {}", [event.transaction.hash.toHex()]);
+    return;
+  }

39-46: Add parameter validation before entity creation.

Consider validating event parameters before creating the entity to ensure data integrity.

+  if (event.params._amount.isZero() && event.params._courtID.isZero()) {
+    log.warning("StakeSet event with zero amount and courtID. TX: {}", [event.transaction.hash.toHex()]);
+  }
+
   const stakeSet = new StakeSetEntity(event.transaction.hash.toHex() + "-" + event.logIndex.toString());
   stakeSet.address = event.params._address;
   stakeSet.courtID = event.params._courtID;
   stakeSet.stake = event.params._amount;
   stakeSet.newTotalStake = generalCourt.effectiveStake;
   stakeSet.blocknumber = event.block.number;
   stakeSet.timestamp = event.block.timestamp;
   stakeSet.logIndex = event.logIndex;
   stakeSet.save();
subgraph/core/schema.graphql (1)

357-366: Review of the New StakeSet Entity

  • Entity Structure: The new StakeSet entity is defined with all the required fields. The fields for address, courtID, stake, newTotalStake, timestamp, and logIndex all match the expected data types.
  • ID Field Comment: The comment on the id field indicates it is constructed from the transaction hash and log index. For improved clarity, consider explicitly using a delimiter like '-' (e.g., event.transaction.hash.toHex() + '-' + event.logIndex.toString()) rather than + - +.
  • Naming Consistency: The field blocknumber is defined in all lowercase. To maintain consistency with the camelCase naming found throughout the schema (e.g., transactionHash, createdAt, blockNumber in other parts), it is recommended to rename this field to blockNumber.

Suggested Diff Change for Consistency:

-  blocknumber: BigInt!
+  blockNumber: BigInt!
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3d09b18 and 2277793.

📒 Files selected for processing (5)
  • subgraph/core-neo/subgraph.yaml (1 hunks)
  • subgraph/core-university/subgraph.yaml (1 hunks)
  • subgraph/core/schema.graphql (1 hunks)
  • subgraph/core/src/SortitionModule.ts (2 hunks)
  • subgraph/core/subgraph.yaml (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • 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
🔇 Additional comments (5)
subgraph/core/src/SortitionModule.ts (2)

7-7: LGTM! Clear type distinction between event and entity.

The renaming of StakeSet to StakeSetEvent and separate import of StakeSetEntity improves code clarity by clearly distinguishing between event and entity types.

Also applies to: 9-9


27-47: LGTM! Well-structured event handling.

The function correctly:

  1. Updates juror stake information
  2. Creates and persists the StakeSet entity with all relevant data
  3. Uses a unique, deterministic ID based on transaction hash and log index
subgraph/core/subgraph.yaml (1)

152-152: LGTM! Consistent entity configuration across subgraphs.

The addition of the StakeSet entity to the SortitionModule's entities list is consistent across all subgraph configurations and properly aligns with the handler implementation in SortitionModule.ts.

subgraph/core-university/subgraph.yaml (1)

151-153: Addition of StakeSet Entity: The new StakeSet entity is correctly added to the entities list under the SortitionModule data source. Please confirm that the corresponding GraphQL type definitions and event handler implementations (handleStakeSet) are updated consistently to reflect the intended staking data model.

subgraph/core-neo/subgraph.yaml (1)

151-153: StakeSet Entity Integration Validated: The addition of the StakeSet entity under the SortitionModule is implemented in line with the subgraph enhancements. Ensure that the new entity aligns with the GraphQL schema and that the event handler (handleStakeSet) properly processes the StakeSet event as expected.

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

🧹 Nitpick comments (1)
subgraph/core-university/src/SortitionModule.ts (1)

17-27: Consider adding error logging and validation.

The implementation correctly creates and persists the StakeSetEntity with all required fields. However, consider these improvements:

  1. Add error logging when user is not found to help with debugging:
-  if (!juror) return;
+  if (!juror) {
+    log.warning('User not found for address {}', [jurorAddress]);
+    return;
+  }
  1. Consider adding validation for the stake amount:
+  if (event.params._amount.lt(ZERO)) {
+    log.warning('Invalid stake amount {} for address {}', [event.params._amount.toString(), jurorAddress]);
+    return;
+  }
   const stakeSet = new StakeSetEntity(event.transaction.hash.toHex() + "-" + event.logIndex.toString());
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2277793 and f16a0e2.

📒 Files selected for processing (3)
  • subgraph/core-university/src/SortitionModule.ts (1 hunks)
  • subgraph/core/schema.graphql (1 hunks)
  • subgraph/core/src/SortitionModule.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • subgraph/core/schema.graphql
  • subgraph/core/src/SortitionModule.ts
⏰ Context from checks skipped due to timeout of 90000ms (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)
subgraph/core-university/src/SortitionModule.ts (2)

1-2: LGTM! Clear type distinction between event and entity.

The renaming of StakeSet to StakeSetEvent improves code clarity by distinguishing between the event and entity types. The new imports are necessary for the added functionality.


8-8: LGTM! Function signature updated correctly.

The function signature change aligns with the import renaming and is consistent with the PR objectives.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 22, 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

🧹 Nitpick comments (2)
subgraph/core/schema.graphql (1)

357-366: The StakeSet entity looks good, but consider improving naming consistency.

The implementation properly marks the entity as immutable and correctly links to the User entity as suggested in previous comments. However, the field naming is inconsistent: blocknumber uses lowercase while courtID uses camelCase.

Consider renaming blocknumber to blockNumber for consistency with the other camelCase field names:

-  blocknumber: BigInt!
+  blockNumber: BigInt!
subgraph/core/src/SortitionModule.ts (1)

36-38: Consider adding error handling.

While ensureUser and ensureJurorTokensPerCourt likely handle errors internally, it might be worth adding error logging for monitoring purposes, especially for production environments.

 const stakeSet = new StakeSetEntity(event.transaction.hash.toHex() + "-" + event.logIndex.toString());
 const jurorTokensPerCourt = ensureJurorTokensPerCourt(jurorAddress, "1");
+ // Log the event for monitoring
+ log.debug("StakeSet event processed for juror {} with court {} and amount {}", [
+   jurorAddress,
+   courtID,
+   event.params._amount.toString()
+ ]);
 stakeSet.juror = juror.id;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between f16a0e2 and 250ac14.

📒 Files selected for processing (4)
  • subgraph/core-university/src/SortitionModule.ts (1 hunks)
  • subgraph/core/schema.graphql (1 hunks)
  • subgraph/core/src/SortitionModule.ts (2 hunks)
  • subgraph/package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • subgraph/package.json
⏰ Context from checks skipped due to timeout of 90000ms (15)
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Redirect rules - kleros-v2-neo
  • GitHub Check: Redirect rules - kleros-v2-university
  • GitHub Check: Header rules - kleros-v2-neo
  • GitHub Check: Header rules - kleros-v2-university
  • GitHub Check: Pages changed - kleros-v2-neo
  • GitHub Check: Pages changed - kleros-v2-university
  • GitHub Check: contracts-testing
  • GitHub Check: Analyze (javascript)
  • GitHub Check: SonarCloud
🔇 Additional comments (6)
subgraph/core-university/src/SortitionModule.ts (4)

1-2: Good import renaming for clarity.

Renaming the import from StakeSet to StakeSetEvent helps distinguish between the event and the entity, reducing potential confusion.


8-11: Good use of ensureUser.

Storing the result of ensureUser in a variable for later use is a good practice. This helps avoid duplicate calls and makes the code more readable.


17-27: Well-structured entity creation.

The StakeSet entity creation is well implemented. It correctly follows the ID format specified in the schema and captures all necessary data from the event and related entities.


18-18:

❓ Verification inconclusive

Verify court ID used in ensureJurorTokensPerCourt.

The function uses a hardcoded court ID "1", but the courtID from the event is stored in the entity. Consider if this is intentional or if the courtID from the event should be used instead.


🏁 Script executed:

#!/bin/bash
# Check for other instances of ensureJurorTokensPerCourt to understand usage patterns

rg -A 3 "ensureJurorTokensPerCourt\(" --type ts

Length of output: 2764


Revisit the court ID value passed into ensureJurorTokensPerCourt

It appears that in subgraph/core-university/src/SortitionModule.ts the call to:

const jurorTokensPerCourt = ensureJurorTokensPerCourt(jurorAddress, "1");

uses the hardcoded string "1", even though the event carries a _courtID (which is later set in stakeSet.courtID). In contrast, other parts of the codebase (e.g. in subgraph/core/src/entities/JurorTokensPerCourt.ts) pass a variable value (like court.id or courtID).

Please verify if this hardcoded court ID is intentional. If the court ID from the event should actually be used consistently, consider updating the call to:

const jurorTokensPerCourt = ensureJurorTokensPerCourt(jurorAddress, event.params._courtID);

Otherwise, please add a comment explaining why a default value of "1" is appropriate in this instance.

subgraph/core/src/SortitionModule.ts (2)

1-9: Good import organization.

The import renaming from StakeSet to StakeSetEvent is consistent with the changes in the university version and helps distinguish between the event and entity.


27-46: Well-implemented entity creation.

The implementation correctly creates and populates a new StakeSetEntity with all required information. The approach is consistent with the university version of the handler.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 13, 2025
Copy link

codeclimate bot commented Mar 14, 2025

Code Climate has analyzed commit 809b085 and detected 2 issues on this pull request.

Here's the issue category breakdown:

Category Count
Duplication 2

View more on Code Climate.

Copy link

Quality Gate Failed Quality Gate failed

Failed conditions
70.6% Duplication on New Code (required ≤ 10%)

See analysis details on SonarQube Cloud

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro (Legacy)

📥 Commits

Reviewing files that changed from the base of the PR and between 90c8b71 and 809b085.

📒 Files selected for processing (2)
  • subgraph/core-university/src/SortitionModule.ts (1 hunks)
  • subgraph/core/src/SortitionModule.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • subgraph/core/src/SortitionModule.ts
⏰ Context from checks skipped due to timeout of 90000ms (15)
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Redirect rules - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Header rules - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Pages changed - kleros-v2-testnet
  • GitHub Check: Redirect rules - kleros-v2-neo
  • GitHub Check: Header rules - kleros-v2-neo
  • GitHub Check: Pages changed - kleros-v2-neo
  • 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: SonarCloud
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
subgraph/core-university/src/SortitionModule.ts (3)

1-2: Good import refactoring for clarity.

Renaming the imported event to StakeSetEvent is a good practice to avoid naming conflicts with the new entity type. This makes the code more maintainable and readable.


8-8: Appropriate function signature update.

The function signature has been correctly updated to use the renamed StakeSetEvent type, maintaining type consistency with the imports.


17-17: Good implementation of user handling.

Using ensureUser here and storing the result in a variable follows good practices for code reusability and clarity. This matches the previous review suggestion to add ensureUser in this context.

Copy link
Contributor

@alcercu alcercu left a comment

Choose a reason for hiding this comment

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

lgtm

@alcercu alcercu merged commit 3f7de4f into dev Mar 14, 2025
23 of 26 checks passed
@alcercu alcercu deleted the feat/add-stake-set-event-and-type branch March 14, 2025 15:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants