Skip to content

Conversation

JayT106
Copy link
Contributor

@JayT106 JayT106 commented Jul 24, 2025

Description

backport #19896

Summary by CodeRabbit

  • New Features

    • Introduced a new "MaxSupply" parameter to the mint module, allowing a configurable cap on the total token supply.
    • The minting logic now enforces the maximum supply cap, preventing minting beyond the specified limit.
  • Documentation

    • Updated documentation to describe the new "MaxSupply" parameter and its effect on minting.
    • Added changelog entry for the new parameter.
  • Bug Fixes

    • Corrected a minor spelling error in a comment.
  • Tests

    • Enhanced and added tests to cover the new "MaxSupply" parameter and its migration.
  • Chores

    • Added a migration to support upgrading to the new "MaxSupply" parameter.
    • Updated consensus version and module migrations accordingly.

Copy link
Contributor

coderabbitai bot commented Jul 24, 2025

📝 Walkthrough

Walkthrough

A new max_supply parameter was introduced to the mint module, affecting its Protobuf definition, parameter struct, and minting logic. The minting process now enforces a maximum supply cap, and related tests, documentation, migration logic, and interface definitions were updated accordingly. Migration and consensus versioning were incremented.

Changes

Files/Paths Change Summary
proto/cosmos/mint/v1beta1/mint.proto Added max_supply field to Params message.
x/mint/types/params.go Updated Params struct and constructor for MaxSupply; added validation logic.
x/mint/types/expected_keepers.go Added GetSupply method to BankKeeper interface.
x/mint/keeper/mint.go Modified minting logic to enforce MaxSupply cap.
x/mint/keeper/genesis_test.go
x/mint/keeper/mint_test.go
x/mint/keeper/msg_server_test.go
x/mint/simulation/genesis.go
tests/e2e/mint/grpc.go
Updated tests and simulations to include/use new MaxSupply parameter and related expectations.
x/mint/README.md Documented new MaxSupply parameter and updated examples.
x/mint/keeper/migrator.go Added Migrate2to3 migration method for state upgrade.
x/mint/migrations/v3/migrate.go Introduced migration logic for version 2→3, initializing MaxSupply.
x/mint/migrations/v3/migrator_test.go Added tests for v3 migration logic.
x/mint/module.go Increased consensus version to 3; registered v2→v3 migration.
tools/benchmark/CHANGELOG.md Updated changelog to document addition of max supply parameter.
x/gov/types/config.go Corrected a comment typo ("initialising" → "initializing").

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MintModule
    participant BankKeeper

    User->>MintModule: BeginBlock (minting event)
    MintModule->>BankKeeper: GetSupply(denom)
    BankKeeper-->>MintModule: currentSupply
    MintModule->>MintModule: Calculate mintAmount
    alt maxSupply == 0 or currentSupply + mintAmount <= maxSupply
        MintModule->>BankKeeper: MintCoins(mintAmount)
    else maxSupply > 0 and currentSupply + mintAmount > maxSupply
        MintModule->>BankKeeper: MintCoins(maxSupply - currentSupply)
    end
    MintModule->>MintModule: Update minter state, emit events
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Note

⚡️ Unit Test Generation - Beta

CodeRabbit's unit test generation is now available in Beta! Automatically generate comprehensive unit tests for your code changes, ensuring better test coverage and catching edge cases you might miss. Our AI analyzes your code structure and creates tests that follow best practices and your project's testing patterns. Learn more here, or just try it under ✨ Finishing Touches.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai 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
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 (2)
tools/benchmark/CHANGELOG.md (1)

31-31: Fix the formatting inconsistency in the changelog entry.

The PR reference is missing the # symbol before the number, which is inconsistent with the format used in line 30.

-* [19896](https://github.com/cosmos/cosmos-sdk/pull/19896) Added a new max supply genesis param to existing params.
+* [#19896](https://github.com/cosmos/cosmos-sdk/pull/19896) Added a new max supply genesis param to existing params.
x/mint/migrations/v3/migrator_test.go (1)

28-50: Consider explicitly verifying MaxSupply initialization.

While the test verifies that parameters are preserved during migration, it would be more robust to explicitly check that the MaxSupply field is properly initialized to zero.

Add explicit verification:

 	require.NoError(t, err)
 	require.NoError(t, cdc.Unmarshal(bz, &res))
 	require.Equal(t, dp.ps, res)
+	// Explicitly verify MaxSupply is initialized to zero
+	require.True(t, res.MaxSupply.IsZero(), "MaxSupply should be zero after migration")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Knowledge Base: Disabled due to Reviews > Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between d6c085d and a5f405b.

⛔ Files ignored due to path filters (6)
  • api/cosmos/mint/v1beta1/mint.pulsar.go is excluded by !**/*.pulsar.go
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
  • tests/go.mod is excluded by !**/*.mod
  • x/mint/testutil/expected_keepers_mocks.go is excluded by !**/*_mocks.go
  • x/mint/types/mint.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
📒 Files selected for processing (16)
  • proto/cosmos/mint/v1beta1/mint.proto (1 hunks)
  • tests/e2e/mint/grpc.go (1 hunks)
  • tools/benchmark/CHANGELOG.md (1 hunks)
  • x/gov/types/config.go (1 hunks)
  • x/mint/README.md (5 hunks)
  • x/mint/keeper/genesis_test.go (1 hunks)
  • x/mint/keeper/migrator.go (2 hunks)
  • x/mint/keeper/mint.go (1 hunks)
  • x/mint/keeper/mint_test.go (1 hunks)
  • x/mint/keeper/msg_server_test.go (1 hunks)
  • x/mint/migrations/v3/migrate.go (1 hunks)
  • x/mint/migrations/v3/migrator_test.go (1 hunks)
  • x/mint/module.go (2 hunks)
  • x/mint/simulation/genesis.go (1 hunks)
  • x/mint/types/expected_keepers.go (1 hunks)
  • x/mint/types/params.go (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (9)
tests/e2e/mint/grpc.go (2)
math/legacy_dec.go (2)
  • LegacyNewDec (101-103)
  • LegacyNewDecWithPrec (107-112)
math/int.go (1)
  • ZeroInt (192-192)
x/mint/keeper/msg_server_test.go (1)
math/int.go (1)
  • ZeroInt (192-192)
x/mint/simulation/genesis.go (2)
x/mint/types/params.go (1)
  • NewParams (14-24)
math/int.go (1)
  • ZeroInt (192-192)
x/mint/keeper/mint.go (1)
types/coin.go (2)
  • NewCoins (194-201)
  • NewCoin (19-30)
x/mint/keeper/mint_test.go (2)
math/int.go (1)
  • NewInt (119-121)
types/coin.go (1)
  • NewCoin (19-30)
x/mint/migrations/v3/migrate.go (1)
math/int.go (1)
  • NewInt (119-121)
x/mint/types/params.go (1)
math/int.go (1)
  • ZeroInt (192-192)
x/mint/keeper/genesis_test.go (1)
math/int.go (1)
  • ZeroInt (192-192)
x/mint/keeper/migrator.go (1)
x/mint/migrations/v3/migrate.go (1)
  • Migrate (21-39)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Summary
🔇 Additional comments (17)
x/gov/types/config.go (1)

3-3: Good catch on spelling correction

Documentation now consistently uses American English across the module.

x/mint/keeper/genesis_test.go (1)

72-72: LGTM! Correct addition of MaxSupply parameter to genesis test.

The addition of math.ZeroInt() as the MaxSupply parameter aligns with the updated NewParams constructor signature and correctly represents infinite supply for the test scenario.

x/mint/types/expected_keepers.go (1)

32-32: LGTM! Well-designed interface extension for supply querying.

The new GetSupply method provides a clean interface for the mint module to query current token supply, which is essential for enforcing the maximum supply constraint. The method signature follows Go conventions and returns appropriate types.

x/mint/keeper/msg_server_test.go (1)

56-56: LGTM! Clear test update with helpful documentation.

The addition of MaxSupply: sdkmath.ZeroInt() correctly extends the valid parameters test case. The inline comment clarifying that zero represents infinite supply is particularly helpful for code readability.

proto/cosmos/mint/v1beta1/mint.proto (1)

62-67: LGTM! Well-defined protobuf field for maximum supply parameter.

The new max_supply field is properly defined with:

  • Sequential field number (7)
  • Appropriate string type with cosmos.Int scalar annotation
  • Correct Go custom type mapping to cosmossdk.io/math.Int
  • Non-nullable constraint
  • Clear documentation

The definition follows established patterns in the codebase and integrates well with the existing parameter structure.

tests/e2e/mint/grpc.go (1)

32-32: LGTM! Test correctly updated for new MaxSupply parameter.

The addition of math.ZeroInt() as the seventh parameter properly reflects the new MaxSupply field in the mint module parameters, with zero indicating unlimited supply.

x/mint/keeper/mint_test.go (1)

90-92: LGTM! Proper test mocking for new supply checking logic.

The addition of totalSupply variable and the GetSupply expectation correctly mocks the new functionality where the mint process queries current token supply to enforce maximum supply limits.

x/mint/keeper/migrator.go (2)

7-7: LGTM! Proper import for v3 migration package.


32-36: LGTM! Migration method follows established pattern.

The Migrate2to3 method correctly follows the same pattern as existing migrations and properly passes all required parameters to the v3 migration function.

x/mint/migrations/v3/migrate.go (2)

13-17: LGTM! Proper migration constants defined.

The ModuleName and ParamsKey constants are correctly defined for the migration context.


19-39: LGTM! Safe and well-structured migration implementation.

The migration correctly:

  • Retrieves existing parameters using the collections API
  • Sets the new MaxSupply field to zero (unlimited supply)
  • Validates the updated parameters before storing
  • Handles errors appropriately at each step
  • Uses the proper codec for marshaling

This follows Cosmos SDK migration best practices.

x/mint/module.go (2)

31-31: LGTM! Consensus version correctly incremented.

The consensus version bump from 2 to 3 properly reflects the state-breaking change with the addition of the MaxSupply parameter.


137-139: LGTM! Migration registration follows established pattern.

The migration from version 2 to 3 is properly registered with appropriate error handling, following the same pattern as the existing 1to2 migration.

x/mint/simulation/genesis.go (1)

67-67: LGTM!

The addition of math.ZeroInt() correctly updates the NewParams call to include the new maxSupply parameter, maintaining consistency with the updated function signature.

x/mint/README.md (1)

143-230: Documentation updates are comprehensive and accurate.

The documentation properly describes the new MaxSupply parameter, including:

  • Clear explanation that 0 indicates unlimited supply
  • Important note about MaxSupply being independent of external burning operations
  • Consistent updates across all example outputs
x/mint/keeper/mint.go (1)

54-80: Critical: Duplicate minting logic causes coins to be minted twice.

The current implementation has a serious bug where coins are minted twice when the max supply would be exceeded:

  1. First minting occurs at lines 67-71 when adjusting for max supply
  2. Second minting occurs at lines 77-79

Additionally:

  • The condition on line 75 is redundant since we've already handled the max supply exceeded case
  • The mintedCoins reassignment (line 70) doesn't update mintedCoin used for telemetry/events

Apply this fix to correct the minting logic:

-		maxSupply := params.MaxSupply
-		totalSupply := k.bankKeeper.GetSupply(ctx, params.MintDenom).Amount // fetch total supply from the bank module
-
-		// if maxSupply is not infinite, check against max_supply parameter
-		if !maxSupply.IsZero() {
-			if totalSupply.Add(mintedCoins.AmountOf(params.MintDenom)).GT(maxSupply) {
-				// calculate the difference between maxSupply and totalSupply
-				diff := maxSupply.Sub(totalSupply)
-				// mint the difference
-				diffCoin := sdk.NewCoin(params.MintDenom, diff)
-				diffCoins := sdk.NewCoins(diffCoin)
-
-				// mint coins
-				if err := k.MintCoins(ctx, diffCoins); err != nil {
-					return err
-				}
-				mintedCoins = diffCoins
-			}
-		}
-
-		// mint coins if maxSupply is infinite or total staking supply is less than maxSupply
-		if maxSupply.IsZero() || totalSupply.Add(mintedCoins.AmountOf(params.MintDenom)).LT(maxSupply) {
-			// mint coins
-			if err := k.MintCoins(ctx, mintedCoins); err != nil {
-				return err
-			}
+		maxSupply := params.MaxSupply
+		totalSupply := k.bankKeeper.GetSupply(ctx, params.MintDenom).Amount
+
+		// if maxSupply is not infinite, check against max_supply parameter
+		if !maxSupply.IsZero() && totalSupply.Add(mintedCoin.Amount).GT(maxSupply) {
+			// calculate the difference between maxSupply and totalSupply
+			diff := maxSupply.Sub(totalSupply)
+			if diff.IsPositive() {
+				// update minted amounts to not exceed max supply
+				mintedCoin = sdk.NewCoin(params.MintDenom, diff)
+				mintedCoins = sdk.NewCoins(mintedCoin)
+			} else {
+				// max supply already reached, don't mint anything
+				return nil
+			}
+		}
+
+		// mint coins
+		if err := k.MintCoins(ctx, mintedCoins); err != nil {
+			return err
 		}

Likely an incorrect or invalid review comment.

x/mint/types/params.go (1)

14-24: Constructor properly updated for new MaxSupply parameter.

The NewParams function correctly includes the new maxSupply parameter and assigns it to the struct field.

Comment on lines +177 to +188
func validateMaxSupply(i interface{}) error {
v, ok := i.(math.Int)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}

if v.IsNegative() {
return fmt.Errorf("max supply must be positive: %d", v)
}

return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix inconsistent error message in validateMaxSupply.

The error message states "max supply must be positive" but the validation allows zero values (which indicates unlimited supply). This is misleading.

Update the error message to be accurate:

 	if v.IsNegative() {
-		return fmt.Errorf("max supply must be positive: %d", v)
+		return fmt.Errorf("max supply must not be negative: %s", v)
 	}

Also note: Using %s instead of %d for math.Int ensures proper string representation.

📝 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 validateMaxSupply(i interface{}) error {
v, ok := i.(math.Int)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if v.IsNegative() {
return fmt.Errorf("max supply must be positive: %d", v)
}
return nil
}
func validateMaxSupply(i interface{}) error {
v, ok := i.(math.Int)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
if v.IsNegative() {
return fmt.Errorf("max supply must not be negative: %s", v)
}
return nil
}
🤖 Prompt for AI Agents
In x/mint/types/params.go lines 177 to 188, the error message for negative max
supply incorrectly states "max supply must be positive" while zero is allowed.
Update the error message to say "max supply must be non-negative" to reflect
this. Also, change the format specifier from %d to %s when printing the math.Int
value to ensure correct string representation.

@JayT106 JayT106 force-pushed the jt/mint-max-supply branch from 2daf046 to 1826ed7 Compare July 24, 2025 01:04
@JayT106 JayT106 marked this pull request as draft July 28, 2025 15:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants