Skip to content

feat: custom x/mint minting function#24436

Merged
aljo242 merged 34 commits into
mainfrom
feat/custom-mint-2
Apr 14, 2025
Merged

feat: custom x/mint minting function#24436
aljo242 merged 34 commits into
mainfrom
feat/custom-mint-2

Conversation

@aljo242
Copy link
Copy Markdown
Contributor

@aljo242 aljo242 commented Apr 8, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a customizable minting process, allowing users to specify their own minting logic for token creation.
    • Enabled the application to use both a default and a user-defined minting function for improved flexibility.
  • Refactor

    • Streamlined the minting workflow by removing obsolete inflation calculations, resulting in a simpler and more predictable token minting operation.

@ironbird-prod
Copy link
Copy Markdown

ironbird-prod Bot commented Apr 8, 2025

Ironbird - launch a network To use Ironbird, you can use the following commands:
  • /ironbird start - Launch a testnet with the specified chain and load test configuration.
  • /ironbird chains - List of chain images that ironbird can use to spin-up testnet
  • /ironbird loadtests - List of load test modes that ironbird can run against testnet

@aljo242 aljo242 marked this pull request as ready for review April 8, 2025 19:29
@aljo242 aljo242 requested a review from a team April 8, 2025 19:29
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 8, 2025

📝 Walkthrough

Walkthrough

The changes enable a customizable minting process in the blockchain application by introducing a new minting function. The application initialization now accepts a minting function option, and the minting logic within the begin blocker has been refactored to directly invoke this function. The keeper now contains a dedicated field and associated options for setting or overriding the mint function, with a default implementation provided. Additionally, integration tests have been added to verify both default and custom minting behaviors, and legacy inflation calculation logic has been removed from the module.

Changes

File(s) Change Summary
CHANGELOG.md Added a new entry under the "Features" section documenting the custom minting function for the x/mint begin blocker.
simapp/app.go Updated NewSimApp to include mintkeeper.WithMintFn(mintkeeper.DefaultMintFn) for MintKeeper initialization.
x/mint/abci.go
x/mint/keeper/keeper.go
x/mint/keeper/mint.go
Refactored minting logic: removed inflation calculation from BeginBlocker, introduced a new mintFn field in the Keeper, defined an InitOption type with a WithMintFn function, and provided a DefaultMintFn implementation.
x/mint/keeper/mint_test.go Added an integration test suite verifying both default and custom mint functions, including tests for custom event emission and updated minter values.
x/mint/module.go Removed the inflationCalculator field and logic from the AppModule; updated module initialization to accept an optional MintFn parameter for injecting a custom mint function.

Sequence Diagram(s)

sequenceDiagram
    participant App as SimApp
    participant Keeper as MintKeeper
    participant Block as BeginBlocker
    participant MintFunc as MintFn (Default/Custom)

    App->>Keeper: Initialize with MintFn option
    Block->>Keeper: Call BeginBlocker
    Keeper->>MintFunc: Execute MintFn(ctx)
    MintFunc-->>Keeper: Return result
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

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 generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

Comment thread x/mint/module.go Outdated
Comment on lines +103 to +104
// This input is unused as of Cosmos SDK v0.53 and will be removed in a future release of the Cosmos SDK.
_ types.InflationCalculationFn,
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The only clean way I could think to do this was to keep this input to this function but not use it. This could be confusing to users though. It is more clear, but breaking to users if the argument is just removed alltogether

Copy link
Copy Markdown
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: 2

♻️ Duplicate comments (2)
x/mint/abci.go (1)

13-13: Consider removing or deprecating the unused parameter.

You are currently keeping _ types.InflationCalculationFn in the signature even though it isn't used. This helps avoid breaking changes but could still cause confusion. Eventually removing it in a major version might be clearer.

x/mint/module.go (1)

103-104: Parameter marked for future removal.

As noted, _ types.InflationCalculationFn is unused and scheduled for deprecation. Consider fully removing it in the next major release to reduce confusion.

🧹 Nitpick comments (4)
x/mint/keeper/mint.go (1)

9-81: Add a fallback for amounts exceeding 64 bits in telemetry.

The current logic only defers a telemetry gauge when mintedCoin.Amount.IsInt64(). Amounts that exceed the 64-bit integer range will skip the gauge entirely. Consider adding a fallback or a separate metric to handle big integer amounts properly, so as not to lose monitoring data for very large minted amounts.

x/mint/module.go (1)

107-107: File not properly formatted.

A static analysis check indicates that this file needs formatting with gofumpt. Please run gofumpt or ensure your tooling is configured accordingly.

🧰 Tools
🪛 GitHub Check: golangci-lint

[failure] 107-107:
File is not properly formatted (gofumpt)

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

40-74: Good test setup, but fix comment formatting.

The setup effectively configures the test environment with mocks and default values. However, there's a minor formatting issue in the comment on line 65.

-	//keeper.WithMintFn(CUSTOM MINT FN HERE),
+	// keeper.WithMintFn(CUSTOM MINT FN HERE),
🧰 Tools
🪛 GitHub Check: golangci-lint

[failure] 65-65:
commentFormatting: put a space between // and comment text (gocritic)


157-213: Consider refactoring to reduce setup duplication.

The test is well-written but duplicates much of the setup logic from SetupTest(). Consider refactoring to extract a helper method that accepts a mint function parameter to reduce code duplication.

 // TestCustomMintFn tests the custom mint function.
 func (s *MintFnTestSuite) TestCustomMintFn() {
-	// Reinitialize the keeper with the custom mint function.
-	encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModuleBasic{})
-	key := storetypes.NewKVStoreKey(types.StoreKey)
-	storeService := runtime.NewKVStoreService(key)
-	s.ctx = testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")).Ctx
-
-	ctrl := gomock.NewController(s.T())
-	accountKeeper := minttestutil.NewMockAccountKeeper(ctrl)
-	// Use fresh mocks for account keeper if needed.
-	accountKeeper.EXPECT().GetModuleAddress(types.ModuleName).Return(sdk.AccAddress{}).AnyTimes()
-
-	// Reuse the existing stakingKeeper and bankKeeper from the suite.
-	s.mintKeeper = keeper.NewKeeper(
-		encCfg.Codec,
-		storeService,
-		s.stakingKeeper,
-		accountKeeper,
-		s.bankKeeper,
-		authtypes.FeeCollectorName,
-		authtypes.NewModuleAddress(govtypes.ModuleName).String(),
-		keeper.WithMintFn(customMintFn),
-	)
-
-	// Set default parameters and initial minter.
-	err := s.mintKeeper.Params.Set(s.ctx, types.DefaultParams())
-	s.Require().NoError(err)
-	s.Require().NoError(s.mintKeeper.Minter.Set(s.ctx, types.DefaultInitialMinter()))
+	// Reset the suite and use custom mint function
+	s.SetupTest()
+	s.setupKeeperWithMintFn(customMintFn)

Add this helper method to the test suite:

// setupKeeperWithMintFn reinitializes the keeper with a custom mint function
func (s *MintFnTestSuite) setupKeeperWithMintFn(mintFn keeper.MintFn) {
	encCfg := moduletestutil.MakeTestEncodingConfig(mint.AppModuleBasic{})
	key := storetypes.NewKVStoreKey(types.StoreKey)
	storeService := runtime.NewKVStoreService(key)
	s.ctx = testutil.DefaultContextWithDB(s.T(), key, storetypes.NewTransientStoreKey("transient_test")).Ctx

	ctrl := gomock.NewController(s.T())
	accountKeeper := minttestutil.NewMockAccountKeeper(ctrl)
	accountKeeper.EXPECT().GetModuleAddress(types.ModuleName).Return(sdk.AccAddress{}).AnyTimes()

	s.mintKeeper = keeper.NewKeeper(
		encCfg.Codec,
		storeService,
		s.stakingKeeper,
		accountKeeper,
		s.bankKeeper,
		authtypes.FeeCollectorName,
		authtypes.NewModuleAddress(govtypes.ModuleName).String(),
		keeper.WithMintFn(mintFn),
	)

	// Set default parameters and initial minter.
	err := s.mintKeeper.Params.Set(s.ctx, types.DefaultParams())
	s.Require().NoError(err)
	s.Require().NoError(s.mintKeeper.Minter.Set(s.ctx, types.DefaultInitialMinter()))
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 29083cb and 90c72a9.

📒 Files selected for processing (7)
  • CHANGELOG.md (1 hunks)
  • simapp/app.go (1 hunks)
  • x/mint/abci.go (1 hunks)
  • x/mint/keeper/keeper.go (3 hunks)
  • x/mint/keeper/mint.go (1 hunks)
  • x/mint/keeper/mint_test.go (1 hunks)
  • x/mint/module.go (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (5)
simapp/app.go (2)
x/mint/keeper/keeper.go (1)
  • WithMintFn (40-44)
x/mint/keeper/mint.go (1)
  • DefaultMintFn (18-80)
x/mint/module.go (3)
x/mint/abci.go (1)
  • BeginBlocker (13-18)
x/mint/keeper/mint.go (1)
  • MintFn (10-10)
x/mint/keeper/keeper.go (2)
  • InitOption (37-37)
  • WithMintFn (40-44)
x/mint/keeper/keeper.go (2)
x/mint/keeper/mint.go (1)
  • MintFn (10-10)
collections/schema.go (1)
  • Schema (126-131)
x/mint/keeper/mint.go (5)
x/mint/keeper/keeper.go (1)
  • Keeper (18-35)
types/coin.go (1)
  • NewCoins (194-201)
telemetry/wrapper.go (1)
  • ModuleSetGauge (39-49)
types/context.go (1)
  • UnwrapSDKContext (392-397)
types/events.go (4)
  • EventManager (35-37)
  • NewEvent (171-179)
  • NewAttribute (182-184)
  • AttributeKeyAmount (267-267)
x/mint/keeper/mint_test.go (7)
x/mint/keeper/keeper.go (3)
  • Keeper (18-35)
  • NewKeeper (47-86)
  • WithMintFn (40-44)
x/auth/types/keys.go (1)
  • FeeCollectorName (15-15)
x/mint/types/minter.go (1)
  • DefaultInitialMinter (30-34)
math/int.go (1)
  • NewInt (119-121)
types/coin.go (1)
  • NewCoin (19-30)
types/events.go (1)
  • EventManager (35-37)
types/context.go (1)
  • UnwrapSDKContext (392-397)
🪛 GitHub Check: golangci-lint
x/mint/module.go

[failure] 107-107:
File is not properly formatted (gofumpt)

x/mint/keeper/mint_test.go

[failure] 6-6:
File is not properly formatted (gci)


[failure] 65-65:
commentFormatting: put a space between // and comment text (gocritic)

🪛 GitHub Actions: Lint
x/mint/keeper/mint_test.go

[error] 6-6: File is not properly formatted (gci)

⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: tests (03)
  • GitHub Check: tests (02)
  • GitHub Check: tests (01)
  • GitHub Check: tests (00)
  • GitHub Check: test-system
  • GitHub Check: test-sim-nondeterminism
  • GitHub Check: test-integration
  • GitHub Check: test-e2e
  • GitHub Check: Analyze
  • GitHub Check: Gosec
  • GitHub Check: Summary
🔇 Additional comments (19)
CHANGELOG.md (1)

63-63: Good addition documenting the new minting function feature.

Includes a clear reference to the PR number with a concise explanation. No further changes needed.

simapp/app.go (1)

355-355: Properly initializes MintKeeper with the default minting function.

This call to mintkeeper.WithMintFn(mintkeeper.DefaultMintFn) is consistent with the new custom minting logic. It will allow future overrides or custom mint functions without complicating the rest of the code.

x/mint/abci.go (1)

17-17: Straightforward mint call approach.

Returning k.MintFn(sdkCtx) directly simplifies the logic. This is a clean design choice.

x/mint/keeper/keeper.go (7)

33-35: New field for custom minting logic.

The addition of mintFn MintFn to the keeper cleanly centralizes the minting logic. Great approach.


37-37: Functional options pattern.

Introducing type InitOption func(*Keeper) is an idiomatic approach for modular keeper configuration.


39-44: Customizable mint function for the keeper.

WithMintFn empowers users to override the default minting logic. This fosters clean extensibility.


46-49: Documenting default vs. custom behavior.

Clarifying that a default minting function is always set, but can be overridden via options, is very helpful for developers.


58-59: Variadic initialization options.

Allowing opts ...InitOption keeps NewKeeper flexible. This is a standard design that enhances maintainability.


75-76: Setting the default mint function.

Initializing mintFn with DefaultMintFn(types.DefaultInflationCalculationFn) ensures a functional default without requiring user intervention.


83-86: Applying user overrides.

Looping through and applying each InitOption in NewKeeper is straightforward and keeps configuration consistent.

x/mint/module.go (6)

109-112: Module fields set successfully.

Assigning AppModuleBasic, keeper, authKeeper, and legacySubspace is consistent with the new approach. No issues found.


156-156: Passing nil inflation function.

Calling BeginBlocker(ctx, am.keeper, nil) keeps the interface consistent with your updated design.


168-169: Ignoring the unused parameter.

The ProposalMsgs method discards its argument but otherwise looks correct. No functional concerns.


200-207: Optional MintFn field in ModuleInputs.

Exposing MintFn as an optional field provides a convenient mechanism to inject custom minting logic. Nicely done.


235-238: Appending custom mint function option.

Conditionally building the opts slice with WithMintFn is a clean, idiomatic way to enable user customization.


252-252: Consistent with the inflation function removal.

Passing nil for the inflation calculator in NewAppModule aligns with the rest of the refactor that deprecates it.

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

25-33: LGTM - Well-structured test suite definition.

The test suite is properly structured with all necessary components: the keeper under test, context, and mock dependencies for staking and banking operations.


76-114: LGTM - Thorough test for default mint function.

The test properly verifies all aspects of the default minting behavior:

  1. Sets up expectations for dependencies
  2. Executes the mint function
  3. Verifies the updated state
  4. Ensures events are correctly emitted

116-155: LGTM - Well-implemented custom mint function.

The custom mint function serves as a good example of how to implement a custom minting strategy. It:

  1. Reads and modifies minter values
  2. Mints custom coins
  3. Emits a different event type
  4. Follows proper error handling

Comment thread x/mint/keeper/mint.go
Comment on lines +9 to +81
// MintFn defines the function that needs to be implemented in order to customize the minting process.
type MintFn func(ctx sdk.Context, k *Keeper) error

// MintFn runs the mintFn of the keeper.
func (k *Keeper) MintFn(ctx sdk.Context) error {
return k.mintFn(ctx, k)
}

// DefaultMintFn returns a default mint function.
// The default MintFn has a requirement on staking as it uses bond to calculate inflation.
func DefaultMintFn(ic types.InflationCalculationFn) MintFn {
return func(ctx sdk.Context, k *Keeper) error {
// fetch stored minter & params
minter, err := k.Minter.Get(ctx)
if err != nil {
return err
}

params, err := k.Params.Get(ctx)
if err != nil {
return err
}

// recalculate inflation rate
totalStakingSupply, err := k.StakingTokenSupply(ctx)
if err != nil {
return err
}

bondedRatio, err := k.BondedRatio(ctx)
if err != nil {
return err
}

minter.Inflation = ic(ctx, minter, params, bondedRatio)
minter.AnnualProvisions = minter.NextAnnualProvisions(params, totalStakingSupply)
if err = k.Minter.Set(ctx, minter); err != nil {
return err
}

// mint coins, update supply
mintedCoin := minter.BlockProvision(params)
mintedCoins := sdk.NewCoins(mintedCoin)

err = k.MintCoins(ctx, mintedCoins)
if err != nil {
return err
}

// send the minted coins to the fee collector account
err = k.AddCollectedFees(ctx, mintedCoins)
if err != nil {
return err
}

if mintedCoin.Amount.IsInt64() {
defer telemetry.ModuleSetGauge(types.ModuleName, float32(mintedCoin.Amount.Int64()), "minted_tokens")
}

sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeMint,
sdk.NewAttribute(types.AttributeKeyBondedRatio, bondedRatio.String()),
sdk.NewAttribute(types.AttributeKeyInflation, minter.Inflation.String()),
sdk.NewAttribute(types.AttributeKeyAnnualProvisions, minter.AnnualProvisions.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, mintedCoin.Amount.String()),
),
)

return nil
}
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider edge cases for negative minted amounts.

Currently, the code does not guard against the possibility (even if theoretically low) of receiving a negative minted amount from “BlockProvision”. If code external to this function inadvertently computes a negative inflation or block provision, this would silently fail only when minting coins. It may be safer to assert that the minted amount is non-negative before proceeding to mint coins.

Add a check to ensure the minted amount is non-negative, for example:

+ if mintedCoin.Amount.IsNegative() {
+   return fmt.Errorf("cannot mint a negative amount: %s", mintedCoin.Amount.String())
+ }
📝 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
// MintFn defines the function that needs to be implemented in order to customize the minting process.
type MintFn func(ctx sdk.Context, k *Keeper) error
// MintFn runs the mintFn of the keeper.
func (k *Keeper) MintFn(ctx sdk.Context) error {
return k.mintFn(ctx, k)
}
// DefaultMintFn returns a default mint function.
// The default MintFn has a requirement on staking as it uses bond to calculate inflation.
func DefaultMintFn(ic types.InflationCalculationFn) MintFn {
return func(ctx sdk.Context, k *Keeper) error {
// fetch stored minter & params
minter, err := k.Minter.Get(ctx)
if err != nil {
return err
}
params, err := k.Params.Get(ctx)
if err != nil {
return err
}
// recalculate inflation rate
totalStakingSupply, err := k.StakingTokenSupply(ctx)
if err != nil {
return err
}
bondedRatio, err := k.BondedRatio(ctx)
if err != nil {
return err
}
minter.Inflation = ic(ctx, minter, params, bondedRatio)
minter.AnnualProvisions = minter.NextAnnualProvisions(params, totalStakingSupply)
if err = k.Minter.Set(ctx, minter); err != nil {
return err
}
// mint coins, update supply
mintedCoin := minter.BlockProvision(params)
mintedCoins := sdk.NewCoins(mintedCoin)
err = k.MintCoins(ctx, mintedCoins)
if err != nil {
return err
}
// send the minted coins to the fee collector account
err = k.AddCollectedFees(ctx, mintedCoins)
if err != nil {
return err
}
if mintedCoin.Amount.IsInt64() {
defer telemetry.ModuleSetGauge(types.ModuleName, float32(mintedCoin.Amount.Int64()), "minted_tokens")
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeMint,
sdk.NewAttribute(types.AttributeKeyBondedRatio, bondedRatio.String()),
sdk.NewAttribute(types.AttributeKeyInflation, minter.Inflation.String()),
sdk.NewAttribute(types.AttributeKeyAnnualProvisions, minter.AnnualProvisions.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, mintedCoin.Amount.String()),
),
)
return nil
}
}
// MintFn defines the function that needs to be implemented in order to customize the minting process.
type MintFn func(ctx sdk.Context, k *Keeper) error
// MintFn runs the mintFn of the keeper.
func (k *Keeper) MintFn(ctx sdk.Context) error {
return k.mintFn(ctx, k)
}
// DefaultMintFn returns a default mint function.
// The default MintFn has a requirement on staking as it uses bond to calculate inflation.
func DefaultMintFn(ic types.InflationCalculationFn) MintFn {
return func(ctx sdk.Context, k *Keeper) error {
// fetch stored minter & params
minter, err := k.Minter.Get(ctx)
if err != nil {
return err
}
params, err := k.Params.Get(ctx)
if err != nil {
return err
}
// recalculate inflation rate
totalStakingSupply, err := k.StakingTokenSupply(ctx)
if err != nil {
return err
}
bondedRatio, err := k.BondedRatio(ctx)
if err != nil {
return err
}
minter.Inflation = ic(ctx, minter, params, bondedRatio)
minter.AnnualProvisions = minter.NextAnnualProvisions(params, totalStakingSupply)
if err = k.Minter.Set(ctx, minter); err != nil {
return err
}
// mint coins, update supply
mintedCoin := minter.BlockProvision(params)
+ if mintedCoin.Amount.IsNegative() {
+ return fmt.Errorf("cannot mint a negative amount: %s", mintedCoin.Amount.String())
+ }
mintedCoins := sdk.NewCoins(mintedCoin)
err = k.MintCoins(ctx, mintedCoins)
if err != nil {
return err
}
// send the minted coins to the fee collector account
err = k.AddCollectedFees(ctx, mintedCoins)
if err != nil {
return err
}
if mintedCoin.Amount.IsInt64() {
defer telemetry.ModuleSetGauge(types.ModuleName, float32(mintedCoin.Amount.Int64()), "minted_tokens")
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeMint,
sdk.NewAttribute(types.AttributeKeyBondedRatio, bondedRatio.String()),
sdk.NewAttribute(types.AttributeKeyInflation, minter.Inflation.String()),
sdk.NewAttribute(types.AttributeKeyAnnualProvisions, minter.AnnualProvisions.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, mintedCoin.Amount.String()),
),
)
return nil
}
}

Comment thread x/mint/keeper/mint_test.go Outdated
import (
"testing"

"go.uber.org/mock/gomock"
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix import formatting to pass linter checks.

The import on line 6 is not properly formatted according to golangci-lint. Use goimports or gofmt to automatically format the imports section correctly.

#!/bin/bash
# Verify the import formatting issue
gofmt -d -e x/mint/keeper/mint_test.go
🧰 Tools
🪛 GitHub Check: golangci-lint

[failure] 6-6:
File is not properly formatted (gci)

🪛 GitHub Actions: Lint

[error] 6-6: File is not properly formatted (gci)

Copy link
Copy Markdown
Member

@technicallyty technicallyty left a comment

Choose a reason for hiding this comment

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

couple comments. also we should update the README.md in x/mint here

Comment thread x/mint/keeper/mint_test.go Outdated
Comment thread x/mint/keeper/mint_test.go Outdated
Comment thread x/mint/keeper/mint_test.go Outdated
Comment thread x/mint/keeper/mint_test.go Outdated
Comment thread x/mint/keeper/mint_test.go Outdated
Comment on lines +98 to +101
s.Require().Equal(math.LegacyMustNewDecFromStr("0.130000005226169707"), storedMinter.Inflation)

// The dummy minter's NextAnnualProvisions returns 100.
s.Require().Equal(math.LegacyMustNewDecFromStr("130000005.226169707000000000"), storedMinter.AnnualProvisions)
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

can you explain these values? in case this test breaks in the future, it would be nice to know where i should be looking and how this was calculated.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Comment thread x/mint/keeper/mint.go Outdated
Alex | Interchain Labs and others added 11 commits April 9, 2025 08:49
Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>
Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>
Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>
Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>
Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>
Comment thread x/mint/module.go Outdated
@aljo242 aljo242 requested a review from Copilot April 9, 2025 16:20
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 8 out of 8 changed files in this pull request and generated no comments.

Copy link
Copy Markdown
Member

@technicallyty technicallyty left a comment

Choose a reason for hiding this comment

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

looking good

Comment thread UPGRADING.md Outdated
Comment thread UPGRADING.md Outdated
Comment on lines +153 to +155
```go
mintkeeper.WithMintFn(mintkeeper.DefaultMintFn(customInflationFn))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

missing the closing ticks here ```

Comment thread UPGRADING.md Outdated
Comment on lines +162 to +173
```go
mintKeeper := mintkeeper.NewKeeper(
appCodec,
storeService,
stakingKeeper,
accountKeeper,
bankKeeper,
authtypes.FeeCollectorName,
authtypes.NewModuleAddress(govtypes.ModuleName).String(),
// mintkeeper.WithMintFn(customMintFn), // Use custom minting function
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

same here

Comment thread UPGRADING.md Outdated
Comment on lines +162 to +173
```go
mintKeeper := mintkeeper.NewKeeper(
appCodec,
storeService,
stakingKeeper,
accountKeeper,
bankKeeper,
authtypes.FeeCollectorName,
authtypes.NewModuleAddress(govtypes.ModuleName).String(),
// mintkeeper.WithMintFn(customMintFn), // Use custom minting function
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

maybe we can stub out a tiny example here, something like:

func myCustomMintFunc(...) {
   // do minting...
}

// ...
   mintKeeper := mintkeeper.NewKeeper(
       appCodec,
       storeService,
       stakingKeeper,
       accountKeeper,
       bankKeeper,
       authtypes.FeeCollectorName,
       authtypes.NewModuleAddress(govtypes.ModuleName).String(),
       mintkeeper.WithMintFn(myCustomMintFunc), // Use custom minting function
   )

Comment thread x/mint/module.go Outdated
Comment thread x/mint/module.go
Comment on lines -251 to +255
m := NewAppModule(in.Cdc, k, in.AccountKeeper, in.InflationCalculationFn, in.LegacySubspace)
m := NewAppModule(in.Cdc, k, in.AccountKeeper, nil, in.LegacySubspace)
Copy link
Copy Markdown
Member

@technicallyty technicallyty Apr 9, 2025

Choose a reason for hiding this comment

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

potential footgun. need to panic here too if in.InflationCalculationFn was set

Alex | Interchain Labs and others added 7 commits April 10, 2025 12:20
Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>
Co-authored-by: Tyler <48813565+technicallyty@users.noreply.github.com>
Comment thread x/mint/abci.go Outdated

// BeginBlocker mints new tokens for the previous block.
func BeginBlocker(ctx context.Context, k keeper.Keeper, ic types.InflationCalculationFn) error {
func BeginBlocker(ctx context.Context, k keeper.Keeper, _ types.InflationCalculationFn) error {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

can't we just remove the InflationCacluationFn arg? i cant imagine anyone uses this externally

@aljo242 aljo242 requested a review from technicallyty April 11, 2025 16:11
@aljo242 aljo242 enabled auto-merge April 14, 2025 15:47
@aljo242 aljo242 added this pull request to the merge queue Apr 14, 2025
Merged via the queue into main with commit c5cbda0 Apr 14, 2025
46 checks passed
@aljo242 aljo242 deleted the feat/custom-mint-2 branch April 14, 2025 16:03
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants