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

bump up mods.irisnet.org/modules/farm to cosmos-sdk v0.50.10 #466

Open
wants to merge 7 commits into
base: main
Choose a base branch
from

Conversation

wangjiulian
Copy link
Collaborator

@wangjiulian wangjiulian commented Nov 26, 2024

Close: #459

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced farm pool functionality with support for multiple coin entries in reward calculations and fee structures.
    • Updated the proposal submission logic for community pool creation.
  • Improvements

    • Transitioned to using a new mathematical library for consistency in numerical operations.
    • Improved error handling in various methods, particularly around proposal processing and fee pool management.
  • Refactor

    • Updated method signatures across multiple components to use the new context management system.
    • Streamlined import statements and standardized mathematical operations throughout the codebase.
  • Bug Fixes

    • Adjusted balance comparison logic to improve accuracy in reward calculations.

Copy link

coderabbitai bot commented Nov 26, 2024

Walkthrough

The pull request introduces extensive modifications to the farm module, primarily updating data structures and method signatures to improve functionality and compatibility with the latest version of the cosmos-sdk (v0.50.10). Key changes include the addition of new fields in various structures, adjustments to existing methods to utilize new context types, and a shift from sdk types to math types for mathematical operations. The updates enhance error handling and streamline the module's integration with the updated SDK, ensuring better management of farm pool parameters and financial interactions.

Changes

File Path Change Summary
api/irismod/farm/farm.pulsar.go Added fields in CommunityPoolCreateFarmProposal, Params, FarmInfo, and EscrowInfo.
modules/farm/abci.go Updated EndBlocker method to accept context.Context.
modules/farm/depinject.go Changed store import path and made DistrKeeper optional.
modules/farm/go.mod Updated Go version and multiple dependencies to newer versions.
modules/farm/keeper/depinject_test.go Removed capability module imports and updated module initialization.
modules/farm/keeper/farm_info.go Replaced sdk.KVStorePrefixIterator with storetypes.KVStorePrefixIterator.
modules/farm/keeper/farmer.go Replaced sdk.ZeroInt() with math.ZeroInt() in several methods.
modules/farm/keeper/fees.go Changed sdk.NewDecFromInt to math.LegacyNewDecFromInt in DeductPoolCreationFee method.
modules/farm/keeper/grpc_query.go Updated imports and replaced sdk.ZeroInt() with math.ZeroInt().
modules/farm/keeper/invariants.go Updated balance comparison method in RewardInvariant.
modules/farm/keeper/keeper.go Updated import paths for logging and store types.
modules/farm/keeper/keeper_test.go Transitioned to using math types in test cases.
modules/farm/keeper/msg_server.go Added a new boolean parameter in CreatePoolWithCommunityPool.
modules/farm/keeper/params.go Changed return type of TaxRate method to math.LegacyDec.
modules/farm/keeper/pool.go Updated mathematical operations to use math package.
modules/farm/keeper/proposal.go Enhanced error handling in escrowFromFeePool and refundToFeePool methods.
modules/farm/keeper/proposal_hook.go Improved error handling in AfterProposalVotingPeriodEnded.
modules/farm/keeper/queue.go Replaced sdk.KVStorePrefixIterator with storetypes.KVStorePrefixIterator.
modules/farm/migrations/v2/migrate.go Updated DefaultTaxRate and TaxRate field types to use legacy decimal types.
modules/farm/module.go Updated method signatures in BeginBlock and EndBlock for error handling.
modules/farm/simulation/genesis.go Changed taxRate variable type to math.LegacyDec.
modules/farm/simulation/operations.go Added math imports and simplified function signatures.
modules/farm/types/expected_keeper.go Updated method signatures to use context.Context across multiple interfaces.
modules/farm/types/farm.go Adjusted CaclRewards method to use sdkmath.ZeroInt().
modules/farm/types/farm_test.go Updated test cases to use math types for RewardRule and FarmInfo.
modules/farm/types/params.go Changed parameter types in NewParams, DefaultParams, and validateTaxRate methods.
proto/irismod/farm/farm.proto Updated field types in RewardRule, FarmInfo, and Params messages to use new math types.

Assessment against linked issues

Objective Addressed Explanation
Bump up mods.irisnet.org/modules/farm to cosmos-sdk v0.50.10 (#459)

Possibly related issues

Suggested reviewers

  • mitch1024
  • dreamer-zq

Poem

🐇 In the fields where the farmers play,
New structures bloom, bright as the day.
With coins in hand, they dance and cheer,
For updates made, the future is clear!
So hop along, let’s celebrate,
A thriving farm, oh, isn’t it great? 🌾✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 787a577 and 8a7c6da.

📒 Files selected for processing (1)
  • modules/farm/depinject.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • modules/farm/depinject.go

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

@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: 8

🧹 Outside diff range and nitpick comments (26)
modules/farm/keeper/invariants.go (1)

Line range hint 1-47: Consider adding test coverage for invariant checks

While the invariant implementation looks correct, it would be beneficial to add test coverage specifically for the balance comparison changes to ensure the behavior remains consistent with the upgrade.

Would you like me to help create test cases for the invariant checks?

modules/farm/types/params.go (2)

23-25: Consider documenting the default parameter values

The type changes from sdk to math package are correct, but it would be helpful to add comments explaining the chosen default values:

  • Pool creation fee of 5000 default bond denom
  • Tax rate of 0.4 (40%)
 return NewParams(
+    // Default pool creation fee: 5000 stake
     sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(5000)),
     2,
+    // Default tax rate: 40%
     math.LegacyNewDecWithPrec(4, 1),
 )

53-60: LGTM with a minor suggestion for the error message

The type changes and validation logic are correct, but we could make the error message more precise.

-    return fmt.Errorf("tax rate must be positive and less than 1: %s", v.String())
+    return fmt.Errorf("tax rate must be strictly between 0 and 1, got: %s", v.String())
modules/farm/keeper/proposal_hook.go (1)

37-40: LGTM! Consider enhancing the error log with module context.

The improved error handling is well-implemented and aligns with Cosmos SDK v0.50.10 patterns. The structured logging provides good visibility into failures.

Consider adding the module name to the error log for better context in aggregated logs:

-		h.k.Logger(ctx).Error("failed to get proposal", "proposalID", proposalID, "err", err)
+		h.k.Logger(ctx).Error("failed to get proposal", "module", "farm", "proposalID", proposalID, "err", err)
modules/farm/keeper/queue.go (1)

64-64: Consider pagination for large datasets

While the iterator update is correct, consider implementing pagination for this method as iterating over all pools could become a performance bottleneck as the number of pools grows.

Consider adding a paginated version of this method:

func (k Keeper) IteratorAllPoolsPaginated(ctx sdk.Context, pageRequest *query.PageRequest, fun func(pool types.FarmPool)) (*query.PageResponse, error)
modules/farm/types/farm.go (3)

31-32: Fix typo in method name: "CaclRewards" should be "CalcRewards"

The method name contains a typo that should be corrected for better code maintainability and searchability.

-func (pool FarmPool) CaclRewards(farmInfo FarmInfo, deltaAmt sdkmath.Int) (rewards, rewardDebt sdk.Coins) {
+func (pool FarmPool) CalcRewards(farmInfo FarmInfo, deltaAmt sdkmath.Int) (rewards, rewardDebt sdk.Coins) {

Test coverage for reward calculations needs improvement

The existing test coverage for CaclRewards function has some limitations:

  • Only tests positive scenarios with non-zero locked amounts
  • Missing edge cases for zero amounts and zero reward per share
  • No tests for potential overflow scenarios with large numbers
  • Typo in the test function name (CaclRewards instead of CalcRewards)

Suggested improvements:

  • Add test cases for zero locked amounts
  • Add test cases for zero deltaAmt
  • Add test cases with very large numbers to verify no overflow
  • Fix the typo in the test function name
🔗 Analysis chain

Line range hint 32-41: LGTM! Math type migration looks correct

The change from sdk.ZeroInt() to sdkmath.ZeroInt() is consistent with the cosmos-sdk v0.50.x requirements.

Let's verify the test coverage for these financial calculations:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check test coverage for reward calculations

# Look for test files covering reward calculations
rg -l "TestCalcRewards|TestCaclRewards" --type go

# Check for existing test cases with different scenarios
rg -A 10 "func Test.*Rewards" --type go

Length of output: 669


Script:

#!/bin/bash
# Let's examine the actual test implementation to verify coverage of different scenarios

# Check the full test implementation
cat modules/farm/types/farm_test.go

Length of output: 3704


Method CaclRewards is used in multiple locations and needs to be renamed consistently

The method CaclRewards is currently used in:

  • modules/farm/types/farm.go: Method declaration
  • modules/farm/types/farm_test.go: Test implementation
  • modules/farm/keeper/grpc_query.go: Query implementation
  • modules/farm/keeper/farmer.go: Multiple usages in farmer operations

The method is misspelled as CaclRewards across the codebase and there are no existing usages of the correct spelling CalcRewards. All instances should be renamed to fix the typo.

🔗 Analysis chain

Line range hint 31-41: Verify impact of method rename across the codebase

Since we're suggesting renaming the method from CaclRewards to CalcRewards, we should verify all usage locations.


Let me try a different search strategy to verify the method usage.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for all usages of the CaclRewards method

# Search for current method usage
echo "Current usage of CaclRewards:"
ast-grep --pattern 'CaclRewards($$$)'

# Search for any existing correct spelling to avoid conflicts
echo "Checking for existing CalcRewards usage:"
ast-grep --pattern 'CalcRewards($$$)'

Length of output: 239


Script:

#!/bin/bash
# Search for method declarations and usages with ripgrep for better context
echo "Searching for CaclRewards:"
rg -i "caclrewards" -A 2 -B 2

echo -e "\nSearching for CalcRewards:"
rg -i "calcrewards" -A 2 -B 2

Length of output: 2684

modules/farm/migrations/v2/migrate.go (1)

Missing migration tests for farm module v2

The migration implementation is present and properly registered in the keeper, but there are no corresponding tests for the v2 migration in the farm module. This is concerning because:

  • Other modules (service, token, htlc, nft, coinswap) have proper migration tests
  • The migration includes critical changes like:
    • Setting new default values for PoolCreationFee and TaxRate
    • Granting burner permissions to the farm module account

Please add comprehensive tests for the v2 migration to ensure:

  • Parameter migration works correctly
  • Module account permissions are properly updated
  • Error cases are handled appropriately
🔗 Analysis chain

Line range hint 28-45: Verify migration testing and upgrade path.

The migration logic correctly uses the updated DefaultTaxRate and maintains the burner permission handling. However, we should ensure proper testing of the upgrade path.

Let's check for migration tests:


The initial results show migration files but we need to specifically verify the v2 farm migration tests and upgrade handler registration. Let's examine these aspects more closely.


Let's examine the v2 migration implementation and its tests more specifically, as the previous search patterns needed adjustment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Look for migration tests
rg -g "*test.go" "TestMigrate|TestUpgrade" 

# Check for any existing migrations to ensure proper sequencing
fd "migrate.go" -t f

Length of output: 989


Script:

#!/bin/bash
# Check for v2 migration tests in farm module
rg -g "farm/*test.go" "TestMigrate" -B 2 -A 10

# Check upgrade handler registration
rg "RegisterUpgradeHandler.*v2" -A 5

# Look for farm module v2 tests
fd "v2" --type f -p "*test.go" -d 2 modules/farm/migrations

Length of output: 387


Script:

#!/bin/bash
# Check for v2 migration tests in farm module with correct path
rg -g "*/farm/migrations/v2/*test.go" "TestMigrate" -B 2 -A 10

# Look for upgrade handler registration in app.go or similar files
rg "v2.Migrate" -A 3

# Check contents of the migrate.go file to understand the migration scope
cat modules/farm/migrations/v2/migrate.go

Length of output: 5607

modules/farm/depinject.go (1)

Line range hint 1-89: Consider updating module documentation

The changes look good overall, but it would be helpful to update the module's documentation to reflect:

  1. The SDK version compatibility requirements
  2. The optional nature of DistrKeeper and its implications

Would you like me to help draft the documentation updates?

proto/irismod/farm/farm.proto (2)

78-80: LGTM! Appropriate use of LegacyDec for rate calculation

The tax_rate field correctly uses math.LegacyDec which is appropriate for rate/percentage calculations requiring decimal precision.

For future updates, consider documenting the decimal precision requirements and valid ranges for tax_rate in the proto comments. This helps maintain consistency across different implementations and makes validation requirements clear.


Line range hint 1-120: Consider adding versioning information to the proto package

The module's proto definitions look solid. For better maintainability and version tracking:

  1. Consider adding a version suffix to the package name (e.g., irismod.farm.v1)
  2. Add comments documenting the cosmos-sdk version compatibility
  3. Consider adding Since: tags to fields using the new math types

Example:

// package irismod.farm.v1
// Requires cosmos-sdk v0.50.0+
modules/farm/types/farm_test.go (1)

Line range hint 73-157: Fix typo in test function name

The function name CaclRewards contains a typo and should be CalcRewards.

-func TestFarmPool_CaclRewards(t *testing.T) {
+func TestFarmPool_CalcRewards(t *testing.T) {
modules/farm/keeper/proposal.go (1)

69-74: Fix typo in variable name: 'feelPool' should be 'feePool'

While the error handling improvements are good, there's a typo in the variable name that should be fixed for consistency and clarity.

Apply this diff to fix the typo:

-	feelPool, err := k.dk.GetFeePool(ctx)
+	feePool, err := k.dk.GetFeePool(ctx)
	if err != nil {
		return err
	}
-	feelPool.CommunityPool = feelPool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(sdk.NewCoins(refundTotal...)...)...)
-	return k.dk.SetFeePool(ctx, feelPool)
+	feePool.CommunityPool = feePool.CommunityPool.Add(sdk.NewDecCoinsFromCoins(sdk.NewCoins(refundTotal...)...)...)
+	return k.dk.SetFeePool(ctx, feePool)
modules/farm/keeper/grpc_query.go (1)

139-147: Approve math package migration, but note method name typo

The migration from sdk.ZeroInt() to math.ZeroInt() is correct and aligns with the cosmos-sdk v0.50.10 update. However, there's a typo in the method name CaclRewards (should be CalcRewards).

-        rewards, _ := pool.CaclRewards(farmer, math.ZeroInt())
+        rewards, _ := pool.CalcRewards(farmer, math.ZeroInt())
modules/farm/keeper/farmer.go (2)

62-64: Consider consistent usage of math package

While the change to math.ZeroInt() is correct, consider updating RewardDebt initialization to use the math package as well for consistency with the cosmos-sdk v0.50.10 migration pattern.


Line range hint 1-246: Fix typo in method name throughout the file

There's a typo in the method name CaclRewards (should be CalcRewards) used throughout the file. While not directly related to the current changes, it would be good to fix this for better code maintainability.

modules/farm/keeper/msg_server.go (1)

Based on the verification results, I can now provide a final response:

Update required for cosmos-sdk v0.50.x compatibility

Several compatibility issues need to be addressed:

  • The file uses govv1.MsgExecLegacyContent which is deprecated in cosmos-sdk v0.50.x
  • Event emission uses the legacy pattern ctx.EventManager().EmitEvents(sdk.Events{sdk.NewEvent(...)})
  • Direct usage of sdkerrors.ErrUnauthorized should be replaced with errorsmod

The code needs to be updated to:

  1. Replace MsgExecLegacyContent with the new governance message types
  2. Use the new event emission pattern from v0.50.x
  3. Use errorsmod consistently instead of sdkerrors
🔗 Analysis chain

Line range hint 1-324: Verify cosmos-sdk v0.50.10 compatibility across the file

While the immediate change is minimal, let's ensure full compatibility with cosmos-sdk v0.50.10:

  1. Import statements use the latest paths
  2. No deprecated types or methods are in use
  3. Error handling follows the latest patterns
  4. Event emission follows the latest patterns

Let me analyze the results and generate additional verification scripts to check for specific compatibility concerns.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify compatibility with cosmos-sdk v0.50.10

# Check for deprecated import paths
rg -l 'github.com/cosmos/cosmos-sdk/types/errors'

# Check for deprecated method usage patterns
ast-grep --pattern 'sdk.NewEvent($$$)'

# Check error handling patterns
ast-grep --pattern 'errorsmod.Wrap($$$)'

# Check for any TODO or DEPRECATED markers
rg -i "todo|deprecated|fixme" 

Length of output: 39785


Script:

#!/bin/bash
# Check for specific deprecated patterns in cosmos-sdk v0.50.x

# Check for legacy event emission patterns
rg -A 2 'ctx.EventManager\(\).EmitEvents\(' modules/farm/keeper/msg_server.go

# Check for specific deprecated types/methods from cosmos-sdk
rg -l 'govv1.MsgExecLegacyContent'

# Check for any direct usage of deprecated cosmos-sdk error types
rg -A 1 'sdkerrors\.' modules/farm/keeper/msg_server.go

# Check for any legacy governance proposal handling
ast-grep --pattern 'SubmitProposal($$$)'

Length of output: 974

modules/farm/keeper/pool.go (2)

Line range hint 247-265: Consider performance implications of decimal operations

The changes to use math.ZeroInt() and math.LegacyNewDecFromInt are consistent with the SDK upgrade. However, decimal operations can be computationally expensive. Consider:

  1. Batching multiple decimal operations where possible
  2. Pre-calculating common values to reduce repeated conversions

Example optimization:

- newRewardPerShare := math.LegacyNewDecFromInt(rewardCollected).QuoInt(pool.TotalLptLocked.Amount)
+ // Pre-calculate for multiple rewards
+ totalLptLockedDec := math.LegacyNewDecFromInt(pool.TotalLptLocked.Amount)
+ newRewardPerShare := math.LegacyNewDecFromInt(rewardCollected).Quo(totalLptLockedDec)

Line range hint 1-300: Consider documenting the math package transition strategy

The file shows a systematic transition from sdk to math package types. To ensure a smooth long-term evolution:

  1. Document the transition strategy from legacy to non-legacy decimal types
  2. Consider adding unit tests specifically for decimal precision and rounding behavior
  3. Plan for future deprecation of legacy decimal types
modules/farm/keeper/keeper_test.go (2)

158-159: Consider extracting magic numbers into named constants

The test uses several magic numbers for coin amounts (e.g., 10_000_000). Consider extracting these into named constants to improve test readability and maintainability.

 var (
+    testAdjustmentAmount = math.NewInt(10_000_000)
     // ... existing variables ...
 )

-    sdk.NewCoin(sdk.DefaultBondDenom, math.NewInt(10_000_000)),
-    sdk.NewCoin("uiris", math.NewInt(10_000_000)),
+    sdk.NewCoin(sdk.DefaultBondDenom, testAdjustmentAmount),
+    sdk.NewCoin("uiris", testAdjustmentAmount),

Also applies to: 190-191, 202-202


447-447: Remove unnecessary blank line

Remove the extra blank line to comply with gofumpt formatting rules.

		err, broken := keeper.RewardInvariant(suite.keeper)(ctx)
		suite.Require().False(broken, err)
	}
-

}
🧰 Tools
🪛 golangci-lint (1.62.2)

447-447: File is not gofumpt-ed with -extra

(gofumpt)

modules/farm/simulation/operations.go (2)

Line range hint 169-176: Consider consolidating zero-value checks

The zero-value checks for rewardPerBlock and totalReward could be combined for better readability and maintainability.

Consider refactoring to:

-		if rewardPerBlock.Amount.LTE(math.ZeroInt()) {
-			return simtypes.NoOpMsg(
-				types.ModuleName,
-				types.TypeMsgCreatePool,
-				"rewardPerBlock less than zeroInt",
-			), nil, nil
-		}
-
-		if totalReward.Amount.LTE(rewardPerBlock.Amount) {
+		if rewardPerBlock.Amount.LTE(math.ZeroInt()) || totalReward.Amount.LTE(rewardPerBlock.Amount) {
			return simtypes.NoOpMsg(
				types.ModuleName,
				types.TypeMsgCreatePool,
-				"totalReward less than rewardPerBlock",
+				"invalid reward configuration",
			), nil, nil
		}

237-237: Standardize operation message returns

All simulation handlers have been correctly updated to use nil as the third argument in NewOperationMsg. However, consider standardizing the success message pattern across all handlers for better maintainability.

Consider adding a constant for the empty success message:

+const (
+    successMsg = ""
+)

-return simtypes.NewOperationMsg(msg, true, ""), nil, nil
+return simtypes.NewOperationMsg(msg, true, successMsg), nil, nil

Also applies to: 389-389, 496-496, 601-601, 680-680, 787-787

modules/farm/go.mod (2)

17-17: Consider upgrading to a stable release of github.com/cosmos/cosmos-proto

The dependency github.com/cosmos/cosmos-proto is currently set to version v1.0.0-beta.5, which is a beta release. Using beta versions may introduce instability into the codebase. It's recommended to use a stable release version to ensure reliability and avoid potential issues associated with pre-release software.


29-30: Replace pseudo-versions with tagged releases for mods.irisnet.org/api and mods.irisnet.org/simapp

The dependencies mods.irisnet.org/api and mods.irisnet.org/simapp are referenced using pseudo-versions (v0.0.0-...), which can make dependency management and version tracking more challenging. Consider tagging these modules with proper semantic version numbers and updating the go.mod file accordingly to improve clarity and maintainability.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bfbef28 and 33febf1.

⛔ Files ignored due to path filters (2)
  • modules/farm/go.sum is excluded by !**/*.sum
  • modules/farm/types/farm.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (27)
  • api/irismod/farm/farm.pulsar.go (1 hunks)
  • modules/farm/abci.go (1 hunks)
  • modules/farm/depinject.go (2 hunks)
  • modules/farm/go.mod (1 hunks)
  • modules/farm/keeper/depinject_test.go (2 hunks)
  • modules/farm/keeper/farm_info.go (3 hunks)
  • modules/farm/keeper/farmer.go (5 hunks)
  • modules/farm/keeper/fees.go (2 hunks)
  • modules/farm/keeper/grpc_query.go (2 hunks)
  • modules/farm/keeper/invariants.go (1 hunks)
  • modules/farm/keeper/keeper.go (3 hunks)
  • modules/farm/keeper/keeper_test.go (15 hunks)
  • modules/farm/keeper/msg_server.go (1 hunks)
  • modules/farm/keeper/params.go (2 hunks)
  • modules/farm/keeper/pool.go (6 hunks)
  • modules/farm/keeper/proposal.go (5 hunks)
  • modules/farm/keeper/proposal_hook.go (1 hunks)
  • modules/farm/keeper/queue.go (4 hunks)
  • modules/farm/migrations/v2/migrate.go (2 hunks)
  • modules/farm/module.go (2 hunks)
  • modules/farm/simulation/genesis.go (1 hunks)
  • modules/farm/simulation/operations.go (10 hunks)
  • modules/farm/types/expected_keeper.go (1 hunks)
  • modules/farm/types/farm.go (2 hunks)
  • modules/farm/types/farm_test.go (3 hunks)
  • modules/farm/types/params.go (3 hunks)
  • proto/irismod/farm/farm.proto (3 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
modules/farm/keeper/keeper_test.go

447-447: File is not gofumpt-ed with -extra

(gofumpt)

🔇 Additional comments (59)
modules/farm/abci.go (2)

Line range hint 16-33: LGTM: Robust error handling and logging maintained

The error handling and logging implementation remains comprehensive, properly tracking pool expiration and refund operations with detailed context for debugging.


4-5: LGTM: Context handling updates align with Cosmos SDK v0.50.10

The changes correctly implement the new context handling pattern required by Cosmos SDK v0.50.10, properly unwrapping the context while maintaining the existing functionality.

Let's verify this change is consistent with other ABCI interface implementations:

Also applies to: 13-14

✅ Verification successful

LGTM: Context handling updates are consistent across ABCI interfaces

The verification confirms that the context handling changes in modules/farm/abci.go align with the Cosmos SDK v0.50.10 pattern and are consistent with other ABCI implementations:

  • BeginBlocker implementations in other modules (htlc, random) correctly use context.Context with proper unwrapping
  • EndBlocker in farm module follows the same pattern as other ABCI interfaces
  • All ABCI interfaces consistently use sdk.UnwrapSDKContext(c) to maintain functionality
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify context handling in other ABCI interfaces
# Expected: All ABCI interfaces should use context.Context

# Check BeginBlocker and EndBlocker signatures
ast-grep --pattern 'func BeginBlocker(c context.Context, $$$)'
ast-grep --pattern 'func EndBlocker(c context.Context, $$$)'

# Check for any remaining sdk.Context parameters in ABCI interfaces
rg -l "func.*\(.*sdk\.Context.*\)"

Length of output: 10167

modules/farm/keeper/fees.go (2)

4-4: LGTM: Required import for SDK v0.50.10 compatibility

The addition of cosmossdk.io/math import aligns with the PR objective of upgrading to cosmos-sdk v0.50.10.


17-17: Consider using non-legacy decimal conversion

The use of math.LegacyNewDecFromInt might not be the most future-proof approach, as the "Legacy" prefix typically indicates deprecated or soon-to-be-deprecated functionality.

Let's verify if there's a recommended non-legacy alternative in cosmos-sdk v0.50.10:

Consider investigating if there's a recommended non-legacy alternative for decimal conversion in cosmos-sdk v0.50.10. This would ensure better long-term maintainability of the code.

modules/farm/keeper/params.go (2)

4-4: LGTM: Import addition aligns with Cosmos SDK v0.50.x changes

The addition of cosmossdk.io/math import is correct and necessary for the transition from sdk.Dec to math.LegacyDec types.


21-21: LGTM: Correct migration to math.LegacyDec

The change from sdk.Dec to math.LegacyDec aligns with Cosmos SDK v0.50.x type migrations.

Let's verify the consistency of this type change across the module:

✅ Verification successful

Type migration is consistent across the module

Based on the search results, I can confirm that:

  1. The TaxRate field in the farm module's Params struct is using cosmossdk_io_math.LegacyDec
  2. All usages of TaxRate across the module are consistent with the migration
  3. The migration includes both the keeper method and the underlying parameter type
  4. No remaining sdk.Dec usages were found for tax rate related code
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify consistent usage of math.LegacyDec for tax rate across the module
# Expected: All tax rate related code should use math.LegacyDec instead of sdk.Dec

# Check for any remaining sdk.Dec usage in tax rate related code
rg -A 2 -B 2 "TaxRate.*sdk\.Dec" modules/farm/

# Check if the parameter type in types.Params is updated
ast-grep --pattern 'type Params struct {
  $$$
  TaxRate math.LegacyDec
  $$$
}'

Length of output: 131


Script:

#!/bin/bash
# Let's try a broader search to find all TaxRate related code and type definitions

# Search for TaxRate in all Go files
rg -t go "TaxRate" modules/farm/

# Search for any remaining sdk.Dec usages
rg -t go "sdk\.Dec" modules/farm/

# Find the Params struct definition
fd -e go -x cat {} \; -x echo "---" \; | rg -A 10 -B 2 "type Params struct"

Length of output: 12292

modules/farm/keeper/invariants.go (1)

38-38: Verify SDK v0.50.10 compatibility for balance comparison

The change from IsEqual to Equal aligns with cosmos-sdk v0.50.10 updates. Let's verify this is the only instance requiring updates and that the behavior remains consistent.

✅ Verification successful

Let me gather more specific information about the types and methods being used in the farm keeper.


Based on the comprehensive analysis of the codebase, I can now provide the final response:

Change from IsEqual to Equal is correct and consistent

The change from IsEqual to Equal in the farm keeper's invariant check is correct for cosmos-sdk v0.50.10 compatibility. The evidence shows:

  • The changed line is the only instance of balance comparison in the farm keeper's invariants
  • Other balance comparisons in the module already use Equal
  • The remaining IsEqual instances in the codebase are in test files or in different contexts (htlc and token modules)
  • The sdk.Coins type from cosmos-sdk v0.50.10 uses Equal as the standard comparison method
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining instances of IsEqual and verify Equal usage in cosmos-sdk v0.50.10

# Check for any remaining IsEqual instances that might need updating
echo "Checking for remaining IsEqual instances..."
rg "IsEqual" --type go

# Verify the usage of Equal in cosmos-sdk v0.50.10 for reference
echo "Checking Equal usage in similar contexts..."
rg "Equal.*balance" --type go

Length of output: 3015


Script:

#!/bin/bash
# Check the type declarations and imports in the farm keeper
echo "Checking farm keeper invariants file..."
cat modules/farm/keeper/invariants.go

# Look for other Equal/IsEqual usage in farm module
echo -e "\nChecking Equal/IsEqual usage in farm module..."
rg -A 2 "(Equal|IsEqual)" modules/farm/

Length of output: 15193

modules/farm/simulation/genesis.go (3)

39-41: LGTM!

The MaxRewardCategoryN parameter generation is correctly implemented.


Line range hint 43-56: LGTM!

The genesis state creation and marshaling logic is well-implemented with proper error handling.


24-24: Verify consistent usage of math.LegacyDec across the farm module

The type change from sdk.Dec to math.LegacyDec is aligned with the cosmos-sdk v0.50.10 upgrade. However, we should ensure this change is consistently applied across the farm module.

✅ Verification successful

Type change from sdk.Dec to math.LegacyDec is consistently applied

The verification shows that the farm module has been consistently updated to use math.LegacyDec (or its alias sdkmath.LegacyDec) across all relevant files:

  • types/params.go: Uses math.LegacyDec for tax rate parameter
  • types/farm.pb.go: Uses cosmossdk_io_math.LegacyDec in protobuf definitions
  • simulation/genesis.go: Uses math.LegacyDec for tax rate
  • keeper/params.go: Uses math.LegacyDec for tax rate getter
  • migrations/v2/migrate.go: Uses sdkmath.LegacyDec for migration
  • keeper/keeper_test.go: Uses math.LegacyDec for reward calculations

No instances of sdk.Dec remain in the farm module, confirming the type change is complete and consistent.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining sdk.Dec usages in the farm module
rg --type go "sdk\.Dec" modules/farm/
# Search for math.LegacyDec usage to verify consistent adoption
rg --type go "math\.LegacyDec" modules/farm/

Length of output: 1394

modules/farm/types/params.go (2)

4-8: LGTM: Import changes align with the SDK upgrade

The addition of cosmossdk.io/math and adjustment of imports are appropriate for the migration to cosmos-sdk v0.50.10.


12-12: Verify the use of math.LegacyDec

While the change from sdk.Dec to math.LegacyDec is consistent with the SDK upgrade, we should verify if this is the recommended approach in cosmos-sdk v0.50.10 or if we should use a non-legacy type.

✅ Verification successful

Based on the search results, I can see that math.LegacyDec is widely used throughout the codebase, particularly in proto definitions and parameter types. The usage appears to be consistent with the SDK's migration pattern, where LegacyDec is used for decimal values in protocol buffer definitions and parameter types.

Let me verify if there are any newer decimal types being used in the codebase:


Let me try a different approach to check the imports and decimal type usage:


Based on the search results, I can now provide a definitive response about the use of math.LegacyDec:

Use of math.LegacyDec is appropriate in this context

The use of math.LegacyDec is the correct approach as evidenced by:

  1. Consistent usage throughout the codebase in similar parameter types and proto definitions
  2. Wide adoption in other core modules like token, service, coinswap, and farm modules
  3. Used specifically in proto definitions with (gogoproto.customtype) = "cosmossdk.io/math.LegacyDec"
  4. No usage of newer decimal types found in the codebase

The LegacyDec type is not just a transitional type but rather the standard decimal implementation in Cosmos SDK v0.50.x for protocol buffer compatibility and parameter types.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for patterns of math.LegacyDec usage in cosmos-sdk v0.50.10
# to confirm if this is the recommended approach

# Check for any migration guides or documentation
fd -t f README.md MIGRATION.md UPGRADING.md | xargs rg -l "LegacyDec"

# Check for usage patterns in the codebase
rg "math\.LegacyDec" -A 3 -B 3

Length of output: 37720


Script:

#!/bin/bash
# Check for usage of newer decimal types
rg "math\.Dec[^a]" -l

# Check go.mod for cosmos-sdk version
cat go.mod | rg "cosmos-sdk"

Length of output: 91


Script:

#!/bin/bash
# Check imports for math package usage
rg "\"cosmossdk.io/math\"" -A 3

# Check for any documentation about decimal types
fd README.md | xargs rg -i "decimal|math.Dec"

# Look for any migration guides
fd UPGRADING CHANGELOG -t f | xargs rg -i "decimal|math.Dec"

Length of output: 32411

modules/farm/keeper/farm_info.go (3)

4-4: LGTM: Import change aligns with cosmos-sdk v0.50.10

The addition of storetypes import from cosmossdk.io/store/types is correct and consistent with the SDK's modular architecture in v0.50.10.


35-35: LGTM: Iterator update is consistent

The change to storetypes.KVStorePrefixIterator is consistent with the previous update and maintains the same functionality.


24-24: LGTM: Iterator update is correct

The change from sdk.KVStorePrefixIterator to storetypes.KVStorePrefixIterator is appropriate and maintains the same functionality.

Let's verify that all KVStorePrefixIterator usages have been updated consistently:

✅ Verification successful

All iterator usages have been consistently updated

All instances of KVStorePrefixIterator in the codebase are using the new storetypes.KVStorePrefixIterator, and no occurrences of the old sdk.KVStorePrefixIterator were found. The migration has been completed consistently across all modules.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of sdk.KVStorePrefixIterator
rg "sdk\.KVStorePrefixIterator" 

# Search for the new usage to confirm the pattern
rg "storetypes\.KVStorePrefixIterator"

Length of output: 5414

modules/farm/keeper/queue.go (3)

4-4: LGTM: Import change aligns with cosmos-sdk v0.50.x standards

The update to use storetypes from cosmossdk.io/store/types is consistent with the migration to cosmos-sdk v0.50.10.


52-52: LGTM: Iterator update maintains proper resource handling

The iterator type update is consistent and maintains proper resource cleanup with defer iterator.Close().


40-40: Verify consistent iterator usage across the codebase

The change from sdk.KVStorePrefixIterator to storetypes.KVStorePrefixIterator looks correct. Let's ensure this pattern is consistently applied across the codebase.

✅ Verification successful

Iterator usage is consistently updated across the codebase

The verification shows that all instances of KVStorePrefixIterator in the codebase are using the new storetypes package. There are no remaining occurrences of sdk.KVStorePrefixIterator, confirming that the migration has been consistently applied across all modules.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining usage of sdk.KVStorePrefixIterator
# Expected: No occurrences of the old iterator type

# Search for any remaining instances of the old iterator
rg "sdk\.KVStorePrefixIterator"

# Search for the new iterator usage to confirm consistent adoption
rg "storetypes\.KVStorePrefixIterator"

Length of output: 5414

modules/farm/types/farm.go (1)

Line range hint 4-9: LGTM! Import changes align with cosmos-sdk v0.50.x requirements

The updates to use cosmossdk.io/math and cosmossdk.io/errors are consistent with the migration requirements for cosmos-sdk v0.50.x.

modules/farm/migrations/v2/migrate.go (2)

14-14: LGTM! Verify other decimal operations in the codebase.

The change to sdkmath.LegacyNewDecWithPrec is correct for cosmos-sdk v0.50.x compatibility.

Let's verify that all similar decimal operations have been updated consistently:

✅ Verification successful

Let me gather more specific information about decimal operations in the farm module to ensure all necessary updates have been made.


Let me try one more verification to check the imports specifically:


Based on the comprehensive verification results, I can now provide the final response:

The decimal type migration in the farm module is complete and consistent

The verification shows that:

  • All decimal operations in the farm module are using the new sdkmath.LegacyDec types
  • The DefaultTaxRate change is part of a consistent pattern across the module
  • Test files and core logic properly use the new decimal types from the math package
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining sdk.NewDecWithPrec usages that might need updating
rg "sdk\.NewDecWithPrec" --type go

# Search for other decimal operations that might need similar updates
rg "sdk\.Dec|sdk\.NewDec" --type go

Length of output: 2956


Script:

#!/bin/bash
# Search for decimal-related operations specifically in the farm module
rg "Dec|NewDec|DecWithPrec" --type go modules/farm/

# Check for any remaining sdk.Dec imports in the farm module
rg "sdk\s+\"github\.com\/cosmos\/cosmos-sdk\/types\"" --type go modules/farm/
rg "types\s+\"github\.com\/cosmos\/cosmos-sdk\/types\"" --type go modules/farm/

Length of output: 5161


Script:

#!/bin/bash
# Search for sdk/types imports in the farm module with properly escaped quotes
rg "\"github.com/cosmos/cosmos-sdk/types\"" modules/farm/

Length of output: 3309


23-25: Verify protobuf compatibility with the updated types.

The struct field updates look correct, particularly:

  • Updated customtype for TaxRate to use cosmossdk.io/math.LegacyDec
  • Preserved field ordering and tags

Let's verify the protobuf definitions are in sync:

✅ Verification successful

Protobuf definitions are correctly synchronized with the code changes

The proto file correctly defines the tax_rate field with the updated type cosmossdk.io/math.LegacyDec, which matches the Go struct's use of sdkmath.LegacyDec. The protobuf tags and customtype definitions are properly aligned between the Go code and proto definitions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if the proto files have been updated to match the new types
rg "tax_rate" --type proto

# Look for any remaining references to the old sdk.Dec type in proto files
rg "sdk\.Dec" --type proto

Length of output: 115


Script:

#!/bin/bash
# Search for proto files containing tax_rate
fd -e proto | xargs rg "tax_rate"

# Search for proto files containing sdk.Dec
fd -e proto | xargs rg "sdk\.Dec"

# List all proto files to ensure they exist
fd -e proto

Length of output: 2340


Script:

#!/bin/bash
# Check the specific proto definition for farm module's tax_rate field
cat proto/irismod/farm/farm.proto

# Check for any remaining references to sdk.Dec in farm.proto
rg "sdk\.Dec" proto/irismod/farm/farm.proto

Length of output: 3359

modules/farm/depinject.go (1)

46-46: LGTM: Store key type update

The Key field type update to *storestore.KVStoreKey correctly aligns with the new import path.

proto/irismod/farm/farm.proto (2)

58-60: LGTM! Consistent type update for amount field

The locked field correctly uses math.Int for amount storage, maintaining consistency with other amount fields in the module.


34-47: LGTM! Type updates align with Cosmos SDK v0.50.x standards

The changes correctly update the numeric types to use the new cosmossdk.io/math package:

  • Amount fields (total_reward, remaining_reward, reward_per_block) use math.Int
  • Rate field (reward_per_share) uses math.LegacyDec for decimal precision

Let's verify the consistency of these type changes across the codebase:

✅ Verification successful

Type updates are correctly implemented and consistent across modules

The verification confirms that:

  • No proto files contain old-style references to github.com/cosmos/cosmos-sdk/types.(Int|Dec)
  • The new cosmossdk.io/math.(Int|LegacyDec) types are consistently used across multiple modules including farm, coinswap, service, token, and htlc
  • The changes in the farm module align with the broader codebase migration to cosmossdk.io/math types
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for any remaining old-style Int/Dec type references
rg -l "github.com/cosmos/cosmos-sdk/types\.(Int|Dec)" --type proto

# Verify all math types are using the new package
rg -l "cosmossdk.io/math\.(Int|LegacyDec)" --type proto

Length of output: 186


Script:

#!/bin/bash
# Search for proto files first
fd '\.proto$' 

# Then check for any remaining old-style Int/Dec type references
fd '\.proto$' --exec rg -l "github.com/cosmos/cosmos-sdk/types\.(Int|Dec)" {}

# And verify all math types are using the new package
fd '\.proto$' --exec rg -l "cosmossdk.io/math\.(Int|LegacyDec)" {}

Length of output: 2335

modules/farm/types/farm_test.go (4)

29-30: LGTM: Appropriate type migration for SDK compatibility

The change from sdk.NewInt to math.NewInt is correct and aligns with the cosmos-sdk v0.50.10 update requirements.

Also applies to: 34-35


48-49: LGTM: Consistent type migration across test cases

The changes maintain consistency with the previous test case and properly implement the type migration.


99-102: LGTM: Consistent type migration in test values

The changes to use math.NewInt for all numerical values and coin creation are consistent and correct for the SDK update.

Also applies to: 105-106, 109-110, 128-134, 137-138, 141-142


89-89: Verify the use of LegacyNewDec

While the migration to math.LegacyNewDec is functionally correct, we should verify if this is the intended approach versus using newer alternatives in cosmos-sdk v0.50.10.

Also applies to: 93-93

✅ Verification successful

Use of LegacyNewDec is consistent with codebase migration patterns

The usage of math.LegacyNewDec in the farm test is consistent with the broader codebase migration pattern. The search results show extensive use of LegacyNewDec and related legacy decimal types across multiple modules (farm, token, service, coinswap) including in their core logic, migrations, and parameters. This indicates a deliberate choice to maintain compatibility with the legacy decimal implementation from cosmos-sdk.

Key evidence:

  • Used consistently in migration files (v2, v3, v4) across modules
  • Applied in critical financial calculations (fees, rates, rewards)
  • No usage of newer decimal alternatives found in the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other usages of LegacyNewDec to ensure consistency
rg "LegacyNewDec" --type go

# Search for any migration guides or documentation about LegacyNewDec usage
fd -e md -e txt | xargs rg "LegacyNewDec"

Length of output: 10530


Script:

#!/bin/bash
# Let's check for any newer Dec alternatives in the codebase
rg "NewDec|Dec\(" --type go -g '!*test.go' -g '!*legacy*' -A 2 -B 2

# Let's also check for any migration files that might indicate the intended approach
fd -e go | grep -i "migr" | xargs rg "Dec"

Length of output: 34237

modules/farm/keeper/keeper.go (3)

6-7: LGTM: Import paths correctly updated for Cosmos SDK v0.50.x

The import path changes align with the SDK's modular architecture reorganization.


95-95: LGTM: Iterator type correctly updated

The iterator type change to storetypes.KVStorePrefixIterator is consistent with the SDK's new module organization while maintaining the same functionality.


111-111: LGTM: Iterator type correctly updated

The iterator type change to storetypes.KVStorePrefixIterator is consistent with the SDK's new module organization while maintaining the same functionality.

modules/farm/keeper/proposal.go (4)

4-4: LGTM: Import addition aligns with SDK v0.50.x requirements

The addition of storetypes import is necessary for the updated iterator usage and follows the correct import path convention.


41-44: LGTM: Improved error handling for fee pool operations

The changes enhance error handling by:

  1. Properly checking GetFeePool errors before proceeding
  2. Directly returning SetFeePool errors instead of ignoring them

This makes the function more robust and reliable.

Also applies to: 60-60


121-121: LGTM: Updated iterator type for SDK v0.50.x compatibility

The change from sdk.KVStorePrefixIterator to storetypes.KVStorePrefixIterator correctly aligns with Cosmos SDK v0.50.x requirements while maintaining proper iterator usage patterns.


41-44: Verify consistent error handling patterns across the module

The improved error handling for fee pool operations has been added to this file. Let's verify that similar patterns are applied consistently across other keeper methods.

Also applies to: 69-72

✅ Verification successful

Error handling is consistently applied for distribution keeper operations

The verification shows that error handling is consistently implemented across all distribution keeper (k.dk) method calls in the module:

  • Both instances of GetFeePool properly check and handle errors
  • SetFeePool is used appropriately after error checks
  • No other distribution keeper methods are found that would require error handling
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for GetFeePool usage across the module to ensure consistent error handling
rg -A 3 "GetFeePool\(ctx\)" --type go

# Search for other distribution keeper method calls to verify error handling
rg -A 3 "k\.dk\." --type go

Length of output: 1369

modules/farm/keeper/grpc_query.go (1)

7-8: LGTM: Import updates align with cosmos-sdk v0.50.10

The import changes correctly reflect the new package structure in cosmos-sdk v0.50.10, where core components have been moved to dedicated cosmossdk.io packages.

modules/farm/keeper/farmer.go (4)

187-187: LGTM: Correct migration to math package

The change from sdk.ZeroInt() to math.ZeroInt() is appropriate and aligns with the cosmos-sdk v0.50.10 upgrade.


211-211: LGTM: Proper migration to math package

The update to use math.ZeroInt() in the updatePool call is correct and consistent with the cosmos-sdk v0.50.10 upgrade.


224-224: LGTM: Correct migration to math package

The change to math.ZeroInt() for RemainingReward is appropriate and aligns with the cosmos-sdk v0.50.10 upgrade.


Line range hint 1-246: Verify complete migration of numeric operations

Let's verify that all necessary numeric operations have been migrated from the sdk package to the math package.

✅ Verification successful

Based on the search results, I can now generate the final response:

All numeric operations in the farm keeper have been properly migrated

The code review shows that all numeric operations in the farm keeper module are already using the math package from Cosmos SDK v0.50.x:

  • Uses math.ZeroInt() for initializing zero values
  • Uses math.Int for amount fields and calculations
  • No remaining legacy sdk numeric types found in the farm keeper code
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for remaining sdk numeric operations that might need migration
rg -A 1 'sdk\.(Int|Dec|ZeroInt|OneDec|NewInt|NewDec)' --type go

# Search for math package usage to compare
rg -A 1 'math\.(Int|Dec|ZeroInt|OneDec|NewInt|NewDec)' --type go

Length of output: 109006

modules/farm/keeper/msg_server.go (1)

149-149: Verify the impact of non-expedited proposal setting

The addition of false parameter to SubmitProposal indicates this is setting the expedited flag for governance proposals. This change appears to be part of the cosmos-sdk v0.50.10 compatibility update, where proposals can now be marked as expedited or non-expedited.

Setting this to false means community pool farm proposals will follow the standard (non-expedited) governance process. Let's verify this behavior is intentional and consistent.

✅ Verification successful

Setting non-expedited proposal is consistent with codebase implementation

The verification shows that:

  • The expedited parameter is properly defined in the interface (modules/farm/types/expected_keeper.go)
  • The implementation in simapp/types.go correctly handles the expedited parameter
  • The farm module's proposal type is registered and handled through standard governance processes

Setting false for non-expedited proposals is the correct approach as it maintains the standard governance process for community pool farm proposals, which is appropriate for their scope and impact.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of expedited parameter in governance proposals
# across the codebase to ensure consistency

# Check for other SubmitProposal calls and their expedited parameter usage
ast-grep --pattern 'SubmitProposal($$$, $expedited)'

# Check for any governance-related configuration or constants that might
# affect proposal processing
rg -A 3 'ProposalType|VotingPeriod|expedited' 

Length of output: 2485

modules/farm/keeper/depinject_test.go (3)

28-30: LGTM: Import changes align with cosmos-sdk v0.50.10

The addition of evidence, feegrant, and upgrade type imports is consistent with the SDK upgrade requirements.


Line range hint 89-259: LGTM: Farm module configuration maintained

The farm module's configuration remains stable through the upgrade, with appropriate integration of new SDK modules in the BeginBlockers and EndBlockers lists. The module permissions and account restrictions are correctly preserved.


Line range hint 62-66: Verify module initialization dependencies

The module order looks correct, but please verify these critical dependencies:

  1. Farm module's position after its dependent modules
  2. Genesis module order maintains proper token initialization
✅ Verification successful

Let me analyze the output and generate additional verification scripts to check module dependencies more thoroughly.

The initial results show BeginBlocker/EndBlocker ordering and InitGenesis patterns, but we need to verify the specific dependencies of the farm module to ensure its position in the initialization sequence is correct. The additional scripts will help us understand the module's dependencies and validate its position in the module order.


Let me analyze the farm module's dependencies more specifically by checking its keeper initialization and bank dependencies.

The initial results show imports and module structure, but we need to verify the specific keeper dependencies to validate the module order. These additional scripts will help us understand the concrete dependencies of the farm module.


Based on the keeper dependencies revealed in the output, I can now verify the module initialization order. The farm module requires:

  1. Bank Keeper (for coin operations)
  2. Account Keeper (for module accounts)
  3. Distribution Keeper (for fee pool operations)
  4. Gov Keeper (for proposal handling)
  5. Coinswap Keeper (for LP token validation)

Let me verify if these dependent modules are properly ordered before the farm module in the initialization sequence.

This will help us confirm that all required modules are initialized before the farm module.


Based on the gathered evidence, I can now provide a final verification of the module order:

Module initialization order is correct

The farm module's position in the initialization sequence is properly ordered after all its dependencies:

  • auth and bank (for account and coin operations)
  • distribution (for fee pool)
  • gov (for proposal handling)
  • params (for parameter management)

The current order ensures that all required modules (auth, bank, distr, gov, params) are initialized before the farm module, maintaining the correct dependency chain for:

  1. Module account creation
  2. Token handling capabilities
  3. Governance features
  4. Parameter management
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any explicit module dependencies in the codebase

# Search for BeginBlocker/EndBlocker dependencies
rg -A 3 "BeginBlocker|EndBlocker" --type go

# Search for explicit initialization order requirements
rg -A 3 "InitGenesis" --type go

# Look for any dependency documentation
fd -t f "README.md|DEPENDENCIES.md"

Length of output: 27442


Script:

#!/bin/bash
# Check for module dependencies in farm module and its dependencies

# Search for imports and dependencies in farm module
rg -A 3 "import \(" modules/farm/
rg -A 3 "require \(" modules/farm/

# Check for any explicit dependency documentation in farm module
cat modules/farm/spec/README.md

# Search for any dependency initialization in farm keeper
rg -A 3 "NewKeeper" modules/farm/keeper/

Length of output: 10830


Script:

#!/bin/bash
# Check farm module's keeper dependencies and bank module interactions

# Check keeper initialization parameters and dependencies
rg -A 10 "NewKeeper" modules/farm/keeper/keeper.go

# Check bank keeper interface requirements
cat modules/farm/types/expected_keeper.go

# Check if farm module depends on any other modules in its operations
rg -A 3 "k\.[A-Z][a-zA-Z]+Keeper\." modules/farm/keeper/

Length of output: 2661


Script:

#!/bin/bash
# Verify the order of dependent modules in the initialization sequence

# Get the exact initialization order from the test file
rg -A 10 "InitGenesis: \[\]string{" modules/farm/keeper/depinject_test.go

# Check if there are any other dependencies in the farm module's initialization
rg "ModuleName," modules/farm/keeper/depinject_test.go

Length of output: 2704

modules/farm/keeper/pool.go (3)

114-114: LGTM: Correct transition to math.ZeroInt()

The change from sdk.ZeroInt() to math.ZeroInt() aligns with the cosmos-sdk v0.50.10 upgrade requirements.


141-141: LGTM: Proper usage of math.NewInt for reward calculation

The change to math.NewInt for remaining height calculation is consistent with the cosmos-sdk v0.50.10 upgrade.


Line range hint 192-202: Verify the usage of legacy decimal types

While the changes are correct, the use of math.LegacyZeroDec() suggests we're using legacy decimal types. Consider planning for a future migration to non-legacy decimal types to ensure long-term compatibility.

Let's check the usage of legacy decimal types across the codebase:

modules/farm/keeper/keeper_test.go (4)

18-23: LGTM: Type migration changes look good

The changes correctly migrate from sdk.NewInt to math.NewInt for numeric operations and update the context creation to use NewContextLegacy, which aligns with the cosmos-sdk v0.50.10 upgrade.

Also applies to: 59-59


Line range hint 247-298: LGTM: Test cases properly updated for new math types

The test cases for staking, unstaking, and harvesting have been correctly updated to use the new math types from cosmos-sdk v0.50.10, maintaining the test coverage and assertions.

Also applies to: 328-361, 380-444


456-458: LGTM: Helper methods properly updated

The helper methods have been correctly updated to use math.LegacyDec types and NewContextLegacy for context creation, maintaining consistency with the cosmos-sdk v0.50.10 upgrade.

Also applies to: 482-485, 526-528


Line range hint 1-544: Verify test coverage after type migration

The changes look good overall, but it's important to ensure that all test cases still pass after migrating to the new math types and context creation methods.

✅ Verification successful

Based on the output, I can now generate the final response:

Test coverage appears complete and properly maintained after type migration

The test suite shows:

  • Comprehensive test coverage with numerous assertions (>50 require/assert statements)
  • All test cases are active (no commented out or skipped tests)
  • Proper test setup and helper methods
  • Thorough validation of math operations after migration to math.LegacyDec()
  • Consistent assertions for both positive and negative test cases
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any skipped or pending tests
rg -B 2 -A 2 '(Skip|Pending)\(' modules/farm/keeper/
# Check for any commented out test cases
rg -B 2 -A 2 '^[\t ]*//.*func.*Test' modules/farm/keeper/

Length of output: 114


Script:

#!/bin/bash
# Check test coverage and patterns more broadly
# Look for test functions and their implementation
ast-grep --pattern 'func \($_\)TestKeeper\($_\)($$$) {
  $$$
}'

# Check for any potential test helper functions that might be commented out
rg -B 2 -A 2 '^\s*//.*Test' modules/farm/keeper/

# Look for test assertions to verify test coverage
rg 'suite\.(?:Require|Assert)' modules/farm/keeper/keeper_test.go

# Check for any potential test setup/teardown methods
ast-grep --pattern 'func \($_\) Setup\($_\)($$$) {
  $$$
}'

Length of output: 3227

modules/farm/module.go (2)

167-167: Update BeginBlock method signature to match Cosmos SDK v0.50.10

The BeginBlock method signature has been updated to accept context.Context and return an error, aligning with the new interface requirements in Cosmos SDK v0.50.10.


185-185: Update RegisterStoreDecoder parameter to simtypes.StoreDecoderRegistry

The parameter type for RegisterStoreDecoder has been updated to simtypes.StoreDecoderRegistry, reflecting changes in the Cosmos SDK v0.50.10. This change is appropriate and aligns with the updated interfaces.

modules/farm/go.mod (1)

27-27: Verify the google.golang.org/grpc dependency for updates and security advisories

The google.golang.org/grpc package is used at version v1.64.1. Ensure that this version is up-to-date and does not contain any known security vulnerabilities. Updating to the latest stable version may provide important bug fixes and security patches.

Run the following script to check for the latest version and any security advisories:

api/irismod/farm/farm.pulsar.go (1)

Line range hint 1-1: Notice: Modifications to Generated Code

The file farm.pulsar.go is generated by protoc-gen-go-pulsar and contains a header comment indicating "DO NOT EDIT". Direct modifications to this file will be overwritten when the code is regenerated. Instead, please make changes to the corresponding .proto files and regenerate the code using the appropriate tools.

modules/farm/types/expected_keeper.go (4)

36-36: Update ValidateLPToken Function Signature

The ValidateLPToken function now accepts context.Context instead of sdk.Context. Ensure that all implementations and calls to ValidateLPToken are updated to reflect this change to avoid inconsistencies and potential runtime issues.

Run the following script to find usages of ValidateLPToken still using sdk.Context:


54-57: Update GovKeeper Methods for Signature Changes

Several methods in the GovKeeper interface have updated signatures:

  • SubmitProposal now includes an additional expedited bool parameter.
  • GetGovernanceAccount now accepts context.Context instead of sdk.Context.

Please ensure that all implementations and calls to these methods are updated to match the new signatures. Failing to do so may result in compilation errors or unintended behavior.

Run the following script to find and update usages of GovKeeper methods:


40-43: Update AccountKeeper Methods to Use context.Context

The GetAccount and GetModuleAccount methods in the AccountKeeper interface now accept context.Context. Please update all implementations and method calls to use the new context type to ensure seamless integration and prevent compilation errors.

Run the following script to verify updates to AccountKeeper methods:


14-34: Update BankKeeper Methods to Use context.Context

The methods in the BankKeeper interface have been updated to accept context.Context instead of sdk.Context. Ensure that all implementations of this interface and all calls to these methods are updated accordingly to prevent compilation errors and maintain proper context management.

Run the following script to verify that all implementations and usages of BankKeeper methods have been updated:

modules/farm/simulation/genesis.go Outdated Show resolved Hide resolved
@@ -3,8 +3,8 @@ package farm
import (
"cosmossdk.io/core/appmodule"
"cosmossdk.io/depinject"
storestore "cosmossdk.io/store/types"
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Store types import needs updating in two remaining files

The verification revealed inconsistent store types imports across the codebase:

  • Files still using old import path:
    • e2e/sim_test.go
    • modules/nft/migrations/v2/store_test.go (commented out)

The rest of the codebase, including the farm module, correctly uses the new cosmossdk.io/store/types import path.

🔗 Analysis chain

Verify all store type usages across the module

The import path change from github.com/cosmos/cosmos-sdk/store/types to cosmossdk.io/store/types is correct for SDK v0.50.x compatibility.

Let's verify that all store type imports have been updated consistently:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining old store type imports that need updating
rg "github.com/cosmos/cosmos-sdk/store/types" --type go

# Search for the new store type import to ensure consistent usage
rg "cosmossdk.io/store/types" --type go

Length of output: 2787


AccountKeeper types.AccountKeeper
BankKeeper types.BankKeeper
DistrKeeper types.DistrKeeper
DistrKeeper types.DistrKeeper `optional:"true"`
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

DistrKeeper usage requires nil checks when optional

The DistrKeeper is used in the farm module's proposal handling to interact with the fee pool, but there are no nil checks present. Since it's being marked as optional, the following locations need attention:

  • modules/farm/keeper/proposal.go: Multiple usages of k.dk without nil checks:
    • GetFeePool and SetFeePool calls in fee pool management functions
    • refundToFeePool function that handles remaining funds

The code needs to be updated to handle cases where DistrKeeper is nil, either by:

  1. Adding nil checks before using DistrKeeper methods
  2. Documenting that certain proposal-related functionality will be unavailable when DistrKeeper is not provided
  3. Returning appropriate errors when DistrKeeper operations are attempted without the keeper being set
🔗 Analysis chain

Verify nil handling for optional DistrKeeper

Making DistrKeeper optional is a breaking change that requires careful consideration.

Let's verify proper nil handling in the keeper implementation:

Consider documenting:

  1. The implications of running without a DistrKeeper
  2. Which features become unavailable
  3. How the module behaves when DistrKeeper is nil

Let me gather more information about the usage of DistrKeeper in the farm module specifically.


Let me check how the DistrKeeper is used in the farm keeper's methods to understand if there are any potential nil pointer dereferences.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for DistrKeeper usage to ensure proper nil checks
ast-grep --pattern 'DistrKeeper.$$$' 

# Look for potential panic conditions
rg -A 5 "DistrKeeper\." --type go

Length of output: 2349


Script:

#!/bin/bash
# Search for DistrKeeper usage in farm module
rg -A 5 "DistrKeeper\." modules/farm/

# Look for nil checks on DistrKeeper
ast-grep --pattern 'if $_.DistrKeeper == nil { $$$ }'

# Search for farm keeper implementation to understand DistrKeeper usage
rg -A 10 "type Keeper struct" modules/farm/

Length of output: 994


Script:

#!/bin/bash
# Search for methods using DistrKeeper in farm module
rg -A 5 "k.dk\." modules/farm/

# Look for method implementations in keeper
ast-grep --pattern 'func ($_ *Keeper) $_($$$) {
  $$$
  $_.dk.$$$
  $$$
}'

Length of output: 1637

modules/farm/simulation/operations.go Outdated Show resolved Hide resolved
@@ -857,7 +858,7 @@
return sdk.NewCoin(pool.TotalLptLocked.Denom, amount), nil
}
}
return sdk.NewCoin(pool.TotalLptLocked.Denom, sdk.ZeroInt()), nil
return sdk.NewCoin(pool.TotalLptLocked.Denom, math.ZeroInt()), nil
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider explicit error handling in GenStake

The function returns a zero coin when no matching denomination is found, which might mask potential errors.

Consider returning an error instead of a zero coin to make the failure case more explicit:

-return sdk.NewCoin(pool.TotalLptLocked.Denom, math.ZeroInt()), nil
+return sdk.Coin{}, fmt.Errorf("no matching denomination found in spendable coins")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return sdk.NewCoin(pool.TotalLptLocked.Denom, math.ZeroInt()), nil
return sdk.Coin{}, fmt.Errorf("no matching denomination found in spendable coins")

modules/farm/simulation/operations.go Show resolved Hide resolved
Comment on lines +170 to +172
func (am AppModule) EndBlock(ctx context.Context) error {
EndBlocker(ctx, am.keeper)
return []abci.ValidatorUpdate{}
return nil
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure proper context conversion in EndBlock method

The EndBlock method now accepts context.Context, but the EndBlocker function likely expects an sdk.Context. To maintain compatibility, unwrap the context using sdk.UnwrapSDKContext(ctx) before passing it to EndBlocker.

Apply this diff to correct the context handling:

func (am AppModule) EndBlock(ctx context.Context) error {
+   sdkCtx := sdk.UnwrapSDKContext(ctx)
-   EndBlocker(ctx, am.keeper)
+   EndBlocker(sdkCtx, am.keeper)
    return nil
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (am AppModule) EndBlock(ctx context.Context) error {
EndBlocker(ctx, am.keeper)
return []abci.ValidatorUpdate{}
return nil
func (am AppModule) EndBlock(ctx context.Context) error {
sdkCtx := sdk.UnwrapSDKContext(ctx)
EndBlocker(sdkCtx, am.keeper)
return nil

modules/farm/types/expected_keeper.go Show resolved Hide resolved
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: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 33febf1 and 296fe7c.

📒 Files selected for processing (2)
  • modules/htlc/genesis_test.go (2 hunks)
  • modules/htlc/migrations/v2/migrate_test.go (2 hunks)
🔇 Additional comments (2)
modules/htlc/migrations/v2/migrate_test.go (1)

13-13: LGTM! Consistent with Cosmos SDK v0.50.x standards

The addition of the math package import aligns with the PR objective of updating to cosmos-sdk v0.50.10, where mathematical operations are moved from the sdk package to the dedicated math package.

modules/htlc/genesis_test.go (1)

13-13: LGTM: Import change aligns with cosmos-sdk v0.50.10 migration

The addition of cosmossdk.io/math import is consistent with the PR objective of upgrading to cosmos-sdk v0.50.10.

modules/htlc/migrations/v2/migrate_test.go Show resolved Hide resolved
modules/htlc/genesis_test.go Show resolved Hide resolved
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.

bump up mods.irisnet.org/modules/farm to cosmos-sdk v0.50.10
1 participant