8000 feat: delegations status filter by beer-1 · Pull Request #386 · initia-labs/initia · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: delegations status filter #386

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

Merged
merged 5 commits into from
Apr 17, 2025
Merged

Conversation

beer-1
Copy link
Member
@beer-1 beer-1 commented Apr 7, 2025

Description

introduce status filter on delegator delegations and total delegation balance query


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

@beer-1 beer-1 self-assigned this Apr 7, 2025
@beer-1 beer-1 requested a review from a team as a code owner April 7, 2025 07:26
Copy link
coderabbitai bot 8000 commented Apr 7, 2025

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

💤 Files selected but had no reviewable changes (1)
  • client/docs/statik/statik.go
⛔ Files ignored due to path filters (1)
  • client/docs/swagger-ui/swagger.yaml is excluded by !**/*.yaml

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough

Walkthrough

This pull request introduces a new optional field, status, to two proto messages used for querying delegator data. The changes allow queries to filter delegations based on the validator's bonding state (Bonded, Unbonded, or Unbonding). Additionally, helper functions are added in the keeper package to centralize status validation and delegation balance computations, including caching validators to optimize lookups. The query methods are refactored to use these helpers. Corresponding test cases are enhanced to verify behavior with both valid and invalid validator statuses, ensuring proper filtering and error handling.

Changes

File(s) Summary
proto/…/mstaking/v1/query.proto Added the status field to both QueryDelegatorDelegationsRequest (field 3) and QueryDelegatorTotalDelegationBalanceRequest (field 2) for status filtering.
x/mstaking/keeper/grpc_query.go Added contextKeyValidators constant and helper functions: isValidStatus, lookupValidator, delegationStatusFilterFunc, totalDelegationBalance, and delegationBalance. Refactored query methods to validate status, cache validators, and filter delegations accordingly.
x/mstaking/keeper/grpc_query_test.go Added test cases checking query behavior with invalid and valid validator statuses, confirming error handling and correct filtering results. Updated balance assertion comment.

Sequence Diagram(s)

sequenceDiagram
    participant D as Delegator
    participant Q as Query Handler
    participant V as Status Validator (isValidStatus)
    participant C as Validator Cache (context)
    participant F as Filter Function (delegationStatusFilterFunc)
    participant T as Balance Calculator (totalDelegationBalance)

    D->>Q: Send query with status parameter
    Q->>V: Validate status
    alt Valid status
        V-->>Q: Status OK
        Q->>C: Initialize validator cache in context
        Q->>F: Filter delegations by status using cache
        alt Request Total Balance
            Q->>T: Calculate balance based on filtered delegations
            T-->>Q: Return computed balance
        end
        Q-->>D: Return filtered delegations or balance
    else Invalid status
        V-->>Q: Return error
        Q-->>D: Return error response
    end
Loading

Poem

Oh, what a joy, hop and skip,
New status fields on our proto trip!
With helper functions smart and bright,
Valid or not, they set things right.
I'm a rabbit, coding in delight 🐰💻!


🪧 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 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
github-actions bot commented Apr 7, 2025

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

Scanned Files

None

Copy link
codecov bot commented Apr 7, 2025

Codecov Report

Attention: Patch coverage is 79.10448% with 14 lines in your changes missing coverage. Please review.

Project coverage is 40.14%. Comparing base (92df11e) to head (714791a).
Report is 5 commits behind head on main.

Files with missing lines Patch % Lines
x/mstaking/keeper/grpc_query.go 79.10% 8 Missing and 6 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #386      +/-   ##
==========================================
+ Coverage   40.07%   40.14%   +0.07%     
==========================================
  Files         294      294              
  Lines       27511    27562      +51     
==========================================
+ Hits        11025    11066      +41     
- Misses      14785    14791       +6     
- Partials     1701     1705       +4     
Files with missing lines Coverage Δ
x/mstaking/keeper/grpc_query.go 48.67% <79.10%> (+3.67%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
x/mstaking/keeper/grpc_query.go (1)

19-21: Consider using a typed context key for safety.

Currently, the code uses iota for the context key. For clarity and to avoid potential collisions with other packages, you can define a private type and constant, for example:

-const (
-	contextKeyValidators = iota
-)
+type contextKey int
+const contextKeyValidators contextKey = iota
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d84fc24 and 7ebf9cd.

📒 Files selected for processing (1)
  • x/mstaking/keeper/grpc_query.go (8 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
x/mstaking/keeper/grpc_query.go (2)
x/ibc/perm/keeper/keeper.go (1)
  • Keeper (21-29)
x/mstaking/types/validator.go (1)
  • Validators (77-80)
🔇 Additional comments (13)
x/mstaking/keeper/grpc_query.go (13)

37-39: Looks good!

The additional status validation check aligns well with the new isValidStatus function.


239-243: Validation approach is consistent.

Enforcing valid statuses here helps ensure error messages are surfaced early.


253-256: Validator caching initialization is clear.

Storing a local map of validators in the context is a good approach to reduce redundant store lookups.


257-259: Delegation filtering integration looks correct.

This call to delegationStatusFilterFunc properly plugs into the pagination filter to handle status logic.


406-409: Repeated validation check is consistent.

Continuing the same pattern of ensuring req.Status is acceptable keeps the behavior uniform.


425-427: Helper function usage is clean.

Extracting the delegation balance calculation into totalDelegationBalance improves readability.


431-431: Return statement is straightforward.

Returning the computed balance in a typed response aligns with the design.


544-567: Caching validators in lookupValidator is efficient.

This function neatly checks the context cache before falling back to the store, avoiding duplicate lookups.


569-570: Refined usage of lookupValidator.

Switching from direct store calls to lookupValidator keeps caching consistent and reduces repeated logic.


608-615: Redelegation logic uses cache effectively.

Calling lookupValidator for the destination validator, then generating a truncated balance, is in line with the rest of the module’s design.


637-650: Filtering closure is well-organized.

Providing a closure for CollectionFilteredPaginate offers a flexible, pluggable approach to status-based filtering.


652-663: Aggregating balances in totalDelegationBalance.

Iterating delegations and summing upon success is straightforward. This helps keep the calling method concise.


665-677: Delegation balance function is concise.

Skipping shares when the validator status doesn't match requested criteria is an efficient way to avoid extra computation.

@beer-1 beer-1 requested review from sh-cha and ALPAC-4 April 7, 2025 08:33
Copy link
Contributor
@sh-cha sh-cha left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
@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)
x/mstaking/keeper/grpc_query.go (1)

684-689: 🛠️ Refactor suggestion

Ensure case handling consistency within isValidStatus.

Currently, isValidStatus checks for an exact string match, but other parts of the code (e.g., delegationStatusFilterFunc) use strings.EqualFold for status comparison.

To unify behavior, consider allowing case-insensitive checks:

func isValidStatus(s string) bool {
-	if s != "" && !(s == types.Bonded.String() || s == types.Unbonded.String() || s == types.Unbonding.String()) {
-		return false
-	}
-	return true
+	if s == "" {
+		return true
+	}
+	s = strings.ToLower(s)
+	return s == strings.ToLower(types.Bonded.String()) ||
+		s == strings.ToLower(types.Unbonded.String()) ||
+		s == strings.ToLower(types.Unbonding.String())
}
🧹 Nitpick comments (1)
x/mstaking/keeper/grpc_query.go (1)

549-572: Consider optimizing validator cache lookup.

The validator cache lookup implementation is sound, but there's a small optimization opportunity.

The function accesses the context twice to get the same validators map - once for lookup and once for update. Consider retrieving the map only once:

func lookupValidator(ctx context.Context, k *Keeper, valAddrStr string) (types.Validator, error) {
-  if validators, ok := sdk.UnwrapSDKContext(ctx).Value(contextKeyValidators).(map[string]types.Validator); ok {
+  sdkCtx := sdk.UnwrapSDKContext(ctx)
+  if validators, ok := sdkCtx.Value(contextKeyValidators).(map[string]types.Validator); ok {
    if val, ok := validators[valAddrStr]; ok {
      return val, nil
    }
+    
+    // Continue using validators for store lookup case
+    valAddr, err := k.validatorAddressCodec.StringToBytes(valAddrStr)
+    if err != nil {
+      return types.Validator{}, err
+    }
+
+    val, err := k.Validators.Get(ctx, valAddr)
+    if err != nil {
+      return types.Validator{}, err
+    }
+
+    validators[valAddrStr] = val
+    return val, nil
  }

  valAddr, err := k.validatorAddressCodec.StringToBytes(valAddrStr)
  if err != nil {
    return types.Validator{}, err
  }

  val, err := k.Validators.Get(ctx, valAddr)
  if err != nil {
    return types.Validator{}, err
  }

-  if validators, ok := sdk.UnwrapSDKContext(ctx).Value(contextKeyValidators).(map[string]types.Validator); ok {
-    validators[valAddrStr] = val
-  }

  return val, nil
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 30b7e1d and 9b87840.

⛔ Files ignored due to path filters (2)
  • x/mstaking/types/query.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
  • x/mstaking/types/query.pb.gw.go is excluded by !**/*.pb.gw.go, !**/*.pb.gw.go
📒 Files selected for processing (3)
  • proto/initia/mstaking/v1/query.proto (2 hunks)
  • x/mstaking/keeper/grpc_query.go (8 hunks)
  • x/mstaking/keeper/grpc_query_test.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • x/mstaking/keeper/grpc_query_test.go
  • proto/initia/mstaking/v1/query.proto
🔇 Additional comments (11)
x/mstaking/keeper/grpc_query.go (11)

19-21: LGTM: Context key for validator cache.

The constant contextKeyValidators is appropriately defined using iota as a unique key for storing validator cache in the context.


239-242: LGTM: Status validation in DelegatorDelegations.

Good addition of status validation before processing delegations. This ensures that invalid status values are rejected with a proper error message.


253-255: LGTM: Validator caching implementation.

Creating a validator cache and storing it in the context is a good optimization that will reduce repeated validator lookups when processing multiple delegations.


257-263: LGTM: Using filtered pagination with status filter.

The approach of using CollectionFilteredPaginate with a dedicated filter function is clean and maintainable.


411-414: LGTM: Status validation in DelegatorTotalDelegationBalance.

Consistent validation of status parameters across query methods ensures a uniform API experience.


430-434: LGTM: Using helper for total delegation balance calculation.

The new approach using a dedicated helper function improves code organization and reusability.


574-592: LGTM: Using cached validator in delegation response.

The function appropriately uses the new lookupValidator helper to efficiently retrieve validators for delegation responses.


609-640: LGTM: Using cached validator in redelegation responses.

Consistent use of the validator cache mechanism across all response generation functions improves overall performance.


642-655: LGTM: Status filtering implementation.

The filter function correctly handles empty status (return all delegations) and performs case-insensitive matching with strings.EqualFold.


657-668: LGTM: Total delegation balance calculation.

The function correctly handles all edge cases, including nil balances from filtered delegations that don't match the status criteria.


670-682: LGTM: Single delegation balance calculation with status filtering.

The function correctly returns nil for delegations that don't match the status filter, which is then properly handled by the calling function.

@beer-1 beer-1 merged commit 10c26ca into main Apr 17, 2025
6 checks passed
@beer-1 beer-1 deleted the feat/delegations-status-filter branch April 17, 2025 05:05
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.

2 participants
0