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

fix(x/protocolpool): withdraw rewards before export genesis #23467

Merged
merged 5 commits into from
Jan 21, 2025

Conversation

julienrbrt
Copy link
Member

@julienrbrt julienrbrt commented Jan 20, 2025

Description

Closes: #XXXX


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 (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • 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.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

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

Summary by CodeRabbit

  • New Features

    • Enhanced genesis state management for protocol pool module
    • Added funds distribution update before genesis export
  • Improvements

    • Refined module initialization and export processes
    • Implemented automatic reward withdrawal during genesis export
  • Changes

    • Removed bankv2 module from initial genesis configuration
    • Reordered module export priorities
    • Updated test to focus on export functionality and adjusted expected outcomes

@julienrbrt julienrbrt requested review from alpe and a team as code owners January 20, 2025 17:03
Copy link
Contributor

coderabbitai bot commented Jan 20, 2025

Warning

Rate limit exceeded

@julienrbrt has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 12 minutes and 10 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 89e4fd2 and 58e4644.

📒 Files selected for processing (1)
  • x/protocolpool/keeper/genesis_test.go (2 hunks)
📝 Walkthrough

Walkthrough

The pull request introduces changes to the genesis state management in the simapp and protocol pool module. The modifications primarily focus on adjusting the module initialization and export processes. In the simapp/v2/app_config.go, the ModuleConfig has been updated to remove bankv2types.ModuleName from InitGenesis and add pooltypes.ModuleName to ExportGenesis. In the x/protocolpool/keeper/genesis.go, the ExportGenesis method now includes additional steps to update funds distribution and withdraw rewards before exporting the genesis state.

Changes

File Change Summary
simapp/v2/app_config.go - Removed bankv2types.ModuleName from InitGenesis
- Added pooltypes.ModuleName to ExportGenesis
x/protocolpool/keeper/genesis.go - Added k.IterateAndUpdateFundsDistribution(ctx) before export
- Implemented reward withdrawal process during genesis export
x/protocolpool/keeper/genesis_test.go - Renamed TestInitGenesis to TestInitExportGenesis
- Updated test expectations for balance checks

Sequence Diagram

sequenceDiagram
    participant Keeper
    participant Context
    participant FundsDistribution
    participant RecipientFunds

    Keeper->>Context: ExportGenesis
    Keeper->>FundsDistribution: IterateAndUpdateFundsDistribution
    FundsDistribution-->>Keeper: Update Funds
    Keeper->>RecipientFunds: Walk and Withdraw Funds
    RecipientFunds-->>Keeper: Withdraw Rewards
    Keeper->>Keeper: Export Genesis State
Loading

Possibly related PRs

  • fix(runtime/v2): return genesis val updates #22729: This PR modifies the InitGenesis method to return additional validator updates, which is relevant to the changes in the ExportGenesis field of the ModuleConfig in the main PR, as both involve genesis state management.
  • fix(x/gov,x/distribution): Balance assertions on genesis import shouldn't be exact #22832: This PR addresses balance assertions during genesis import in the governance and distribution modules, which relates to the changes in the ExportGenesis field in the main PR, as both involve the handling of genesis state and module exports.
  • chore: Review feedback #23465: This PR includes changes to the ExportGenesis method in the x/staking/keeper/genesis.go file, which is directly related to the modifications made to the ExportGenesis field in the main PR, as both involve the export functionality during genesis state management.

Suggested reviewers

  • kocubinski
  • facundomedica
  • testinginprod
  • sontrinh16

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

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.

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Jan 20, 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: 1

🧹 Nitpick comments (1)
x/protocolpool/keeper/genesis.go (1)

81-83: Consider wrapping errors for better context.

The error handling could be improved by wrapping the errors with additional context about the operation being performed.

 	if err := k.IterateAndUpdateFundsDistribution(ctx); err != nil {
-		return nil, err
+		return nil, fmt.Errorf("failed to update funds distribution: %w", err)
 	}
...
 		if _, err := k.withdrawRecipientFunds(ctx, key.Bytes()); err != nil {
-			return true, err
+			return true, fmt.Errorf("failed to withdraw funds for recipient %x: %w", key.Bytes(), err)
 		}

Also applies to: 87-89

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 66a766b and d7d128b.

📒 Files selected for processing (2)
  • simapp/v2/app_config.go (1 hunks)
  • x/protocolpool/keeper/genesis.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
simapp/v2/app_config.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/protocolpool/keeper/genesis.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

📓 Learnings (1)
📓 Common learnings
Learnt from: likhita-809
PR: cosmos/cosmos-sdk#18471
File: x/protocolpool/keeper/genesis.go:12-51
Timestamp: 2024-11-10T03:53:32.474Z
Learning: - The user `likhita-809` has confirmed the changes suggested in the previous interaction.
- The file in question is `x/protocolpool/keeper/genesis.go` from a Cosmos SDK module.
- The changes involve optimizing the `InitGenesis` function by removing redundant code and ensuring proper handling of start times for budget proposals.
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (1)
simapp/v2/app_config.go (1)

176-197: Correct ordering of protocol pool export before bank.

The placement of pooltypes.ModuleName before banktypes.ModuleName in ExportGenesis is crucial as it ensures that all protocol pool rewards are withdrawn and reflected in account balances before the bank module exports its state.

Comment on lines +80 to +93
// refresh all funds
if err := k.IterateAndUpdateFundsDistribution(ctx); err != nil {
return nil, err
}

// withdraw all rewards before exporting genesis
if err := k.RecipientFundDistribution.Walk(ctx, nil, func(key sdk.AccAddress, value types.DistributionAmount) (stop bool, err error) {
if _, err := k.withdrawRecipientFunds(ctx, key.Bytes()); err != nil {
return true, err
}
return false, nil
}); err != nil {
return nil, err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

New functionality requires additional test coverage

While ExportGenesis has basic test coverage in genesis_test.go, the new operations need specific test cases:

  • Verify funds refresh via IterateAndUpdateFundsDistribution
  • Verify rewards withdrawal through RecipientFundDistribution.Walk
🔗 Analysis chain

Implementation looks good, but needs test coverage.

The added functionality to refresh funds and withdraw rewards before export is well-structured with proper error handling. However, as noted in a previous review, we still need test coverage for the ExportGenesis function.

Let's verify the test coverage:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for ExportGenesis test coverage
rg -l "TestExportGenesis" "x/protocolpool/keeper"

Length of output: 47


Script:

#!/bin/bash
# Find all test files in keeper directory
fd ".*_test.go" "x/protocolpool/keeper"

# Search for any genesis-related test content
rg -l "genesis" "x/protocolpool/keeper" --type go | grep "_test"

# Search for specific genesis-related function calls in test files
rg "Export.*Genesis|Import.*Genesis" "x/protocolpool/keeper" --type go -A 5

Length of output: 1284

Copy link
Contributor

@julienrbrt your pull request is missing a changelog!

@julienrbrt julienrbrt marked this pull request as draft January 21, 2025 10:56
@julienrbrt julienrbrt marked this pull request as ready for review January 21, 2025 11:02
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)
x/protocolpool/keeper/genesis_test.go (3)

8-8: Reorder imports according to project guidelines.

The imports should follow the standard order: standard library, third-party packages, and then project-specific packages.

Apply this ordering:

import (
	"time"

	"cosmossdk.io/math"
	"cosmossdk.io/x/protocolpool/types"
-	"go.uber.org/mock/gomock"
	
	sdk "github.com/cosmos/cosmos-sdk/types"
+	"go.uber.org/mock/gomock"
)
🧰 Tools
🪛 golangci-lint (1.62.2)

8-8: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)


13-15: Consider adding specific test cases for fund transfers.

The mock expectations are correctly set up, but they accept any arguments which might be too permissive. Consider adding specific test cases to verify the exact amounts and accounts involved in the transfers.

Example approach:

suite.bankKeeper.EXPECT().
    SendCoinsFromModuleToModule(
        suite.ctx,
        types.ProtocolPoolDistrAccount,
        types.StreamAccount,
        sdk.NewCoins(sdk.NewCoin("stake", math.NewInt(100))),
    ).
    Return(nil)

56-56: LGTM! Consider adding more balance assertions.

The zero balance check correctly verifies that all funds are withdrawn during export. Consider adding assertions for:

  • Other potential denominations
  • The destination of the withdrawn funds
// Example additional assertions:
suite.Require().True(exportedGenState.LastBalance.Amount.IsZero(), "all balances should be zero")
// Verify funds in destination account
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d7d128b and 89e4fd2.

📒 Files selected for processing (1)
  • x/protocolpool/keeper/genesis_test.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
x/protocolpool/keeper/genesis_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

📓 Learnings (1)
📓 Common learnings
Learnt from: likhita-809
PR: cosmos/cosmos-sdk#18471
File: x/protocolpool/keeper/genesis.go:12-51
Timestamp: 2024-11-10T03:53:32.474Z
Learning: - The user `likhita-809` has confirmed the changes suggested in the previous interaction.
- The file in question is `x/protocolpool/keeper/genesis.go` from a Cosmos SDK module.
- The changes involve optimizing the `InitGenesis` function by removing redundant code and ensuring proper handling of start times for budget proposals.
🪛 golangci-lint (1.62.2)
x/protocolpool/keeper/genesis_test.go

8-8: File is not gci-ed with --skip-generated -s standard -s default -s prefix(cosmossdk.io) -s prefix(github.com/cosmos/cosmos-sdk) --custom-order

(gci)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary

Copy link
Member

@facundomedica facundomedica left a comment

Choose a reason for hiding this comment

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

LGTM 👌

@aljo242 aljo242 added this pull request to the merge queue Jan 21, 2025
Merged via the queue into main with commit f40f820 Jan 21, 2025
72 of 73 checks passed
@aljo242 aljo242 deleted the julien/fix-protocolpool branch January 21, 2025 13:34
mergify bot pushed a commit that referenced this pull request Jan 21, 2025
(cherry picked from commit f40f820)

# Conflicts:
#	simapp/app_config.go
julienrbrt added a commit that referenced this pull request Jan 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:x/protocolpool
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants