-
Notifications
You must be signed in to change notification settings - Fork 4.1k
refactor(x/mint): remove staking as a required module #21858
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
Conversation
WalkthroughWalkthroughThe changes primarily involve modifications to the minting process within the Cosmos SDK's mint module. Key updates include the removal of the Changes
Possibly related PRs
Suggested labels
Suggested reviewers
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? TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 11
Outside diff range and nitpick comments (6)
x/mint/epoch_hooks.go (1)
20-20: LGTM! Consider enhancing error handling.The change from
am.mintFntoam.keeper.MintFnaligns well with the PR objective of removing staking as a required module for minting. This refactoring improves encapsulation by moving the minting function into the keeper.Consider wrapping the error returned from
am.keeper.MintFnwith additional context to aid in debugging:-err = am.keeper.MintFn(ctx, &minter, epochIdentifier, epochNumber) +err = am.keeper.MintFn(ctx, &minter, epochIdentifier, epochNumber) +if err != nil { + return fmt.Errorf("failed to execute MintFn: %w", err) +}This change would provide more context in case of an error, making it easier to trace the source of the problem.
x/mint/keeper/abci.go (1)
12-12: Approve function signature change and suggest documentation updateThe removal of the
mintFnparameter from theBeginBlockerfunction signature aligns with the PR objective of decoupling the mint module from the staking module. This change improves encapsulation by making the minting function an internal part of the Keeper.Consider updating the function's documentation to reflect this change in behavior, explaining that the minting function is now internal to the Keeper.
x/mint/depinject.go (1)
Line range hint
1-85: Overall assessment of changes in x/mint/depinject.goThe changes in this file successfully remove the dependency on the staking module for minting, aligning with the PR objectives. The modifications simplify the minting logic and make it more flexible by requiring a non-nil
MintFnto be provided.Key points:
- The addition of a nil check for
MintFnensures that a minting function is always provided, though the error handling could be improved.- The direct setting of
MintFnwithout a fallback mechanism simplifies the logic.- The
NewAppModuleinstantiation has been updated to reflect these changes.These changes enhance the modularity of the minting functionality, allowing for greater flexibility in how minting is implemented. However, consider improving the error handling as suggested in the earlier comment.
x/mint/module_test.go (2)
67-67: LGTM! Consider adding a test forSetMintFn.The addition of
SetMintFnaligns with the PR objective of making the staking module optional for minting. This change enhances flexibility in setting the mint function.To improve test coverage, consider adding a specific test case for
SetMintFnto ensure it correctly sets the minting function.
78-78: LGTM! Consider adding a test for the newNewAppModulesignature.The simplification of
NewAppModuleinitialization by removing themintFnparameter aligns with the PR objective of decoupling the mint module from the staking module.To ensure comprehensive test coverage, consider adding a specific test case for the new
NewAppModulefunction signature to verify that it correctly initializes theAppModulewithout themintFnparameter.x/mint/keeper/genesis_test.go (1)
Line range hint
1-101: Improve test coverage for new functionalityWhile the existing tests cover the basic genesis functionality, they don't adequately test the new
SetMintFnfeature or its impact on the minting process. Consider adding the following test cases:
- Test different
SetMintFnimplementations and their effect on minting.- Verify that genesis import/export correctly handles the new minting function.
- Test error scenarios, such as setting an invalid minting function.
Example additional test:
func (s *GenesisTestSuite) TestGenesisWithCustomMintFn() { customMintFn := func(ctx context.Context, env appmodule.Environment, minter *types.Minter, epochId string, epochNumber int64) error { // Custom minting logic return nil } err := s.keeper.SetMintFn(customMintFn) s.NoError(err) genesisState := types.DefaultGenesisState() err = s.keeper.InitGenesis(s.sdkCtx, s.accountKeeper, genesisState) s.NoError(err) // Verify that the custom mint function is used during minting operations // ... exportedState, err := s.keeper.ExportGenesis(s.sdkCtx) s.NoError(err) // Verify that the exported state reflects the use of the custom mint function // ... }These additional tests will help ensure that the new
SetMintFnfunctionality is working as expected and properly integrated with the existing genesis operations.
Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
Files selected for processing (11)
- simapp/app.go (2 hunks)
- x/mint/depinject.go (1 hunks)
- x/mint/epoch_hooks.go (1 hunks)
- x/mint/keeper/abci.go (2 hunks)
- x/mint/keeper/genesis.go (1 hunks)
- x/mint/keeper/genesis_test.go (2 hunks)
- x/mint/keeper/grpc_query_test.go (0 hunks)
- x/mint/keeper/keeper.go (4 hunks)
- x/mint/keeper/keeper_test.go (5 hunks)
- x/mint/module.go (3 hunks)
- x/mint/module_test.go (2 hunks)
Files not reviewed due to no reviewable changes (1)
- x/mint/keeper/grpc_query_test.go
Additional context used
Path-based instructions (10)
simapp/app.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.x/mint/depinject.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.x/mint/epoch_hooks.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.x/mint/keeper/abci.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.x/mint/keeper/genesis.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.x/mint/keeper/genesis_test.go (2)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
Pattern
**/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"x/mint/keeper/keeper.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.x/mint/keeper/keeper_test.go (2)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
Pattern
**/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"x/mint/module.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.x/mint/module_test.go (2)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
Pattern
**/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"
Additional comments not posted (17)
x/mint/epoch_hooks.go (1)
Line range hint
35-37: Verify the intended behavior of AfterEpochEndThe
AfterEpochEndmethod is currently a no-op. While this might be intentional, it's worth confirming that no actions are required after an epoch ends for the mint module.Could you please confirm if this is the intended behavior? If actions are needed after an epoch ends, we should implement them here.
x/mint/keeper/abci.go (2)
Line range hint
1-34: Summary of changes and their impactThe modifications to
x/mint/keeper/abci.gosuccessfully remove the dependency on an external minting function, aligning with the PR objective of decoupling the mint module from the staking module. The changes are minimal, focused, and maintain the overall structure and logic of theBeginBlockerfunction.Key points:
- The function signature has been updated to remove the
mintFnparameter.- The internal logic now uses
k.MintFninstead of the passedmintFn.- These changes improve encapsulation while potentially allowing for more flexibility in minting function implementation.
The code adheres to the Uber Golang style guide, and there are no apparent issues with naming conventions or code structure.
25-25: Approve internal logic change and suggest verificationThe replacement of
mintFnwithk.MintFnis consistent with the function signature change and maintains the existing behavior. This modification enhances the modularity of the mint module.Please ensure that
k.MintFnis properly implemented within the Keeper struct and provides the same functionality as the previousmintFn. You can verify this by running the following command:x/mint/depinject.go (2)
80-80: Simplified MintFn setting looks goodThe direct setting of
MintFnwithout a fallback mechanism aligns well with the new requirement ofMintFnbeing non-nil. This change simplifies the logic and makes the code more straightforward.
82-82: Modified NewAppModule instantiation looks correctThe removal of the
MintFnparameter from theNewAppModulecall is consistent with the earlier changes and reflects the removal of the default minting function logic.To ensure this change is consistent throughout the codebase, please run the following command:
This will help verify that all
NewAppModulecalls have been updated correctly.Verification successful
Verification successful: No remaining
NewAppModulecalls withMintFnparameter found.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for any remaining NewAppModule calls with MintFn parameter rg --type go 'NewAppModule.*MintFn'Length of output: 37
Script:
#!/bin/bash # Enhanced search for NewAppModule calls with MintFn parameter rg --type go 'NewAppModule\s*\([^)]*MintFn[^)]*\)'Length of output: 52
x/mint/module_test.go (1)
Line range hint
1-96: Enhance test coverage for the new changes.While the existing tests provide good coverage for the basic functionality of the mint module, they don't specifically target the changes introduced in this PR. To ensure the robustness of the new implementation:
- Add test cases that verify the mint module's behavior without the staking module.
- Include tests that cover different scenarios of setting custom mint functions using
SetMintFn.- Ensure that the
TestEpochHooksfunction adequately tests the module's behavior with the new changes.These additions will help maintain high code quality and prevent potential regressions.
To assist in identifying areas that may need additional test coverage, you can run the following command:
This will generate a coverage report, helping to identify specific areas that may need more test cases.
x/mint/keeper/genesis_test.go (1)
62-62: LGTM: Keeper initialization updatedThe
NewKeeperfunction call has been updated to remove thestakingKeeper, which aligns with the PR objective of removing staking as a required module for minting.x/mint/module.go (4)
14-14: LGTM: Import statement added correctly.The new import statement for
mintKeeperis necessary and correctly aligns with the changes made to thekeeperfield type in theAppModulestruct.
43-43: LGTM: AppModule struct updated correctly.The
keeperfield type has been appropriately updated tomintKeeper.Keeper, which is consistent with the new import statement and the overall refactoring goal. The removal of themintFnfield aligns with the PR objective of decoupling the mint module from the staking module.
151-151: LGTM: BeginBlock method updated correctly.The
BeginBlockmethod has been appropriately updated to callam.keeper.BeginBlocker(ctx)without passingam.mintFn, which is consistent with the removal of themintFnfield from theAppModulestruct. This change aligns with the PR objective of decoupling the mint module from the staking module.Please verify that the
BeginBlockermethod in thekeeperpackage has been updated to handle this change:#!/bin/bash # Description: Verify that the BeginBlocker method in the keeper package has been updated. rg --type go -A 10 'func \(k Keeper\) BeginBlocker\(' x/mint/keeper/
51-51: LGTM: NewAppModule function signature updated correctly.The
keeperparameter type has been appropriately updated tomintKeeper.Keeper, which is consistent with the changes in theAppModulestruct. The removal of themintFnparameter aligns with the PR objective of decoupling the mint module from the staking module.Please verify that the function body has been updated to reflect these changes:
Verification successful
Verified: NewAppModule function has been correctly updated.
The
keeperparameter type is nowmintKeeper.Keeper, and themintFnparameter has been successfully removed. The function body reflects these changes appropriately.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that the NewAppModule function body has been updated. rg --type go -A 10 'func NewAppModule\(' x/mint/module.goLength of output: 598
Script:
#!/bin/bash # Description: Verify that the NewAppModule function body has been updated. rg --type go -A 10 'func NewAppModule\(' x/mint/module.goLength of output: 244
simapp/app.go (2)
375-376: LGTM! Decoupling of MintKeeper from StakingKeeperThe changes successfully remove the direct dependency of MintKeeper on StakingKeeper during initialization, aligning with the PR objective. The new
SetMintFnmethod provides a flexible way to set the minting function, allowing for easier customization and potential future changes to the minting logic.
471-471: LGTM! Simplified mint AppModule initializationThe removal of the StakingKeeper parameter (previously passed as nil) from the
mint.NewAppModulefunction call is consistent with the decoupling of the mint module from the staking module. This change simplifies the AppModule initialization and reduces unnecessary dependencies.To ensure this change is consistent with the mint module's internal implementation, please run the following command:
Verification successful
Verified: StakingKeeper parameter successfully removed
The
NewAppModulefunction inx/mint/module.gono longer includes theStakingKeeperparameter. This confirms the decoupling of the mint module from the staking module, simplifying the AppModule initialization as intended.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Verify that the mint module no longer requires StakingKeeper in its NewAppModule function rg --type go 'func NewAppModule' x/mint/Length of output: 78
Script:
#!/bin/bash # Check if NewAppModule function includes StakingKeeper as a parameter rg --type go 'func NewAppModule\(.*StakingKeeper' x/mint/module.goLength of output: 68
Script:
#!/bin/bash # Retrieve the NewAppModule function signature to verify its parameters rg --type go 'func NewAppModule' x/mint/module.go -A 5Length of output: 160
x/mint/keeper/keeper.go (2)
73-81: SetMintFn method correctly enforces non-nil 'mintFn'The
SetMintFnmethod appropriately checks for a nilmintFnand ensures that theKeeperhas a valid mint function set, preventing potential runtime panics.
120-125: Error handling is properly implemented when retrieving staking dataThe retrieval of
stakingTokenSupplyandbondedRatioincludes appropriate error checks, ensuring that issues are caught and handled effectively.x/mint/keeper/keeper_test.go (2)
125-126: Consistent Initialization of Mint FunctionSetting the Mint function at the start of
TestBeginBlockeris a good practice. This ensures that the test uses the correct Mint function and reduces the risk of unintended side effects from previous tests.
140-145: Confirm Minter State Remains Unchanged with No-op Mint FunctionYou've set a Mint function that performs no operation. It's good that you retrieve
unchangedMinterafter callingBeginBlocker. Ensure that your assertions.Equal(newMinter, unchangedMinter)verifies that the minter's state remains unchanged, confirming the no-op Mint function behaves as intended.
x/mint/keeper/genesis.go
Outdated
| if keeper.mintFn == nil { | ||
| panic("mintFn cannot be nil") | ||
| } | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Approve the nil check for mintFn, but consider moving it.
The addition of a nil check for keeper.mintFn is a good safeguard against uninitialized minting functions. This aligns with the principle of failing fast and explicitly.
However, consider moving this check to the beginning of the function. This would prevent unnecessary operations if mintFn is nil and follows the pattern of validating inputs early. Here's a suggested refactor:
func (keeper Keeper) InitGenesis(ctx context.Context, ak types.AccountKeeper, data *types.GenesisState) error {
+ if keeper.mintFn == nil {
+ panic("mintFn cannot be nil")
+ }
+
if err := keeper.Minter.Set(ctx, data.Minter); err != nil {
return err
}
if err := keeper.Params.Set(ctx, data.Params); err != nil {
return err
}
ak.GetModuleAccount(ctx, types.ModuleName)
- if keeper.mintFn == nil {
- panic("mintFn cannot be nil")
- }
return nil
}This change would improve the function's efficiency and readability.
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.
| if keeper.mintFn == nil { | |
| panic("mintFn cannot be nil") | |
| } | |
| func (keeper Keeper) InitGenesis(ctx context.Context, ak types.AccountKeeper, data *types.GenesisState) error { | |
| if keeper.mintFn == nil { | |
| panic("mintFn cannot be nil") | |
| } | |
| if err := keeper.Minter.Set(ctx, data.Minter); err != nil { | |
| return err | |
| } | |
| if err := keeper.Params.Set(ctx, data.Params); err != nil { | |
| return err | |
| } | |
| ak.GetModuleAccount(ctx, types.ModuleName) | |
| return nil | |
| } |
| err := s.keeper.SetMintFn(func(ctx context.Context, env appmodule.Environment, minter *types.Minter, epochId string, epochNumber int64) error { | ||
| return nil | ||
| }) | ||
| s.NoError(err) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Enhance test coverage for SetMintFn
While the SetMintFn is being set, the current implementation is a no-op function. Consider adding more comprehensive tests to verify the behavior of this new functionality.
Suggestions:
- Add test cases that use different
SetMintFnimplementations to ensure it's correctly integrated. - Verify that the
SetMintFnis called during relevant mint operations in other test cases.
Example test case:
func (s *GenesisTestSuite) TestSetMintFn() {
called := false
err := s.keeper.SetMintFn(func(ctx context.Context, env appmodule.Environment, minter *types.Minter, epochId string, epochNumber int64) error {
called = true
return nil
})
s.NoError(err)
// Trigger a mint operation
// ...
s.True(called, "SetMintFn was not called during minting operation")
}| // mintFn is used to mint new coins during BeginBlock. This function is in charge of | ||
| // minting new coins based on arbitrary logic, previously done through InflationCalculationFn. | ||
| // If mintFn is nil, the default minting logic is used. | ||
| mintFn types.MintFn |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Clarify the behavior when 'mintFn' is nil to avoid inconsistency
The comment states: "If mintFn is nil, the default minting logic is used." However, the SetMintFn method prevents mintFn from being nil by returning an error if it is. This might cause confusion. Please update the comment to accurately reflect that mintFn must be set and cannot be nil.
x/mint/keeper/keeper.go
Outdated
| // DefaultMintFn returns a default mint function. It requires the Staking module and the mint keeper. | ||
| // The default Mintfn has a requirement on staking as it uses bond to calculate inflation. | ||
| func DefaultMintFn(ic types.InflationCalculationFn, staking types.StakingKeeper, k Keeper) types.MintFn { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Initialize 'mintFn' with default logic to improve safety
Consider initializing mintFn with a default mint function during Keeper construction. This provides a safe fallback and ensures that minting operations have valid logic even if SetMintFn is not called.
Apply this refactor to set a default mintFn:
func NewKeeper(
cdc codec.BinaryCodec,
env appmodule.Environment,
ak types.AccountKeeper,
bk types.BankKeeper,
feeCollectorName string,
authority string,
+ staking types.StakingKeeper,
) Keeper {
// ensure mint module account is set
if addr := ak.GetModuleAddress(types.ModuleName); addr == nil {
panic(fmt.Sprintf("the x/%s module account has not been set", types.ModuleName))
}
sb := collections.NewSchemaBuilder(env.KVStoreService)
k := Keeper{
Environment: env,
cdc: cdc,
bankKeeper: bk,
feeCollectorName: feeCollectorName,
authority: authority,
Params: collections.NewItem(sb, types.ParamsKey, "params", codec.CollValue[types.Params](cdc)),
Minter: collections.NewItem(sb, types.MinterKey, "minter", codec.CollValue[types.Minter](cdc)),
+ mintFn: DefaultMintFn(DefaultInflationCalculationFn, staking, nil),
}
// [existing code]
return k
}This refactor requires passing staking to NewKeeper and sets mintFn to the default implementation if no custom function is provided.
Committable suggestion was skipped due to low confidence.
| err := s.mintKeeper.SetMintFn(keeper.DefaultMintFn(types.DefaultInflationCalculationFn, s.stakingKeeper, s.mintKeeper)) | ||
| s.NoError(err) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add Assertions to Confirm Mint Function Is Set Correctly
While you are checking for errors after setting the Mint function, consider adding assertions to verify that the Mint function has been set as intended. This will ensure that SetMintFn has properly initialized the Mint function before proceeding with the test.
| s.NoError(err) | ||
|
|
||
| err = s.mintKeeper.DefaultMintFn(types.DefaultInflationCalculationFn)(s.ctx, s.mintKeeper.Environment, &minter, "block", 0) | ||
| err = s.mintKeeper.MintFn(s.ctx, &minter, "block", 0) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Enhance Test by Verifying Mint Operation Results
After calling s.mintKeeper.MintFn(s.ctx, &minter, "block", 0), it's beneficial to add assertions to verify that the expected state changes have occurred. For example, you can check if the total supply has increased appropriately or if the minter's properties have been updated. This will strengthen the test by confirming the Mint function behaves as expected.
| s.NoError(err) | ||
|
|
||
| err = s.mintKeeper.DefaultMintFn(types.DefaultInflationCalculationFn)(s.ctx, s.mintKeeper.Environment, &minter, "block", 0) | ||
| err = s.mintKeeper.MintFn(s.ctx, &minter, "block", 0) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Verify Behavior When Total Supply Exceeds Max Supply
In this scenario where the total supply exceeds the max supply, consider adding assertions to check that no additional coins are minted and that the minter's state reflects this condition. Confirming this behavior in your test ensures that the Mint function correctly handles cases where minting should be limited.
| s.bankKeeper.EXPECT().SendCoinsFromModuleToModule(s.ctx, types.ModuleName, authtypes.FeeCollectorName, gomock.Any()).Return(nil) | ||
|
|
||
| err = s.mintKeeper.DefaultMintFn(types.DefaultInflationCalculationFn)(s.ctx, s.mintKeeper.Environment, &minter, "block", 0) | ||
| err = s.mintKeeper.MintFn(s.ctx, &minter, "block", 0) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Assert Minted Amount Matches Adjusted Parameters
Given the adjustments to MaxSupply and BlocksPerYear, after calling s.mintKeeper.MintFn(s.ctx, &minter, "block", 0), add assertions to verify that the minted amount is as expected (e.g., 2000 stake). This ensures the Mint function correctly calculates the mint amount based on the new parameters.
| s.NoError(err) | ||
|
|
||
| err = s.mintKeeper.BeginBlocker(s.ctx, s.mintKeeper.DefaultMintFn(types.DefaultInflationCalculationFn)) | ||
| err = s.mintKeeper.BeginBlocker(s.ctx) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Enhance Test by Asserting State Changes After BeginBlocker
After invoking s.mintKeeper.BeginBlocker(s.ctx), consider adding assertions to verify that the minter state has been updated appropriately. For instance, you can compare specific fields of newMinter and minter to confirm the expected changes occurred due to the BeginBlocker execution.
| // BeginBlock returns the begin blocker for the mint module. | ||
| func (am AppModule) BeginBlock(ctx context.Context) error { | ||
| return am.keeper.BeginBlocker(ctx, am.mintFn) | ||
| return am.keeper.BeginBlocker(ctx) |
Check warning
Code scanning / CodeQL
Panic in BeginBock or EndBlock consensus methods
julienrbrt
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe that setter isn't that bad if we can optimize for depinject so the user notices no difference.
x/mint/module.go
Outdated
| "cosmossdk.io/core/appmodule" | ||
| "cosmossdk.io/core/registry" | ||
| "cosmossdk.io/x/mint/keeper" | ||
| mintKeeper "cosmossdk.io/x/mint/keeper" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
can we just say keeper? we always do that for the keeper of the module we are in.
sontrinh16
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lgtm
There was a problem hiding this 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
Outside diff range and nitpick comments (3)
x/mint/CHANGELOG.md (1)
41-41: Consider adding more detail to the changelog entry.While the entry for PR #19896 is correctly formatted, it could benefit from a bit more detail. Consider expanding on the purpose or impact of this new genesis parameter.
Suggested improvement:
- Added a new max supply genesis param to existing params. + Added a new max supply genesis parameter to existing params, allowing for better control over the total token supply.x/mint/depinject.go (1)
81-91: LGTM: New InvokeMintFnCreation function addedThe new
InvokeMintFnCreationfunction is well-implemented and aligns with the PR objective of making staking optional. It provides appropriate fallback behavior and error handling.Consider using
fmt.Errorffor consistent error message formatting:- return fmt.Errorf("custom minting function or staking keeper must be supplied or available") + return fmt.Errorf("custom minting function or staking keeper must be supplied or available")x/mint/keeper/keeper_test.go (1)
83-84: LGTM! Consider adding an assertion for the set mint function.The addition of
SetMintFnis a good practice, explicitly setting the mint function before use in the test. This change aligns well with the refactoring mentioned in the PR summary.Consider adding an assertion to verify that the mint function has been set correctly. For example:
s.NotNil(s.mintKeeper.MintFn)This will ensure that
SetMintFnhas properly initialized the Mint function before proceeding with the test.
Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
Files selected for processing (6)
- simapp/app.go (2 hunks)
- x/mint/CHANGELOG.md (1 hunks)
- x/mint/depinject.go (3 hunks)
- x/mint/keeper/keeper.go (3 hunks)
- x/mint/keeper/keeper_test.go (5 hunks)
- x/mint/module_test.go (1 hunks)
Files skipped from review as they are similar to previous changes (3)
- simapp/app.go
- x/mint/keeper/keeper.go
- x/mint/module_test.go
Additional context used
Path-based instructions (3)
x/mint/CHANGELOG.md (1)
Pattern
**/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"x/mint/depinject.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.x/mint/keeper/keeper_test.go (2)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
Pattern
**/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"
Additional comments not posted (10)
x/mint/CHANGELOG.md (2)
39-40: LGTM: Clear and well-formatted changelog entry.The entry for PR #20363 is well-written, following the correct format and providing a clear description of the new feature.
39-41: LGTM: Comprehensive changelog entry for API breaking change.The entry for PR #21858 is well-written, providing a clear explanation of the changes to
DefaultMintFnand the introduction ofSetMintFn. It effectively communicates the API breaking changes.x/mint/depinject.go (4)
4-5: LGTM: New import addedThe addition of the "fmt" package is appropriate, likely for improved error handling or string formatting in the updated code.
26-26: LGTM: New initialization step addedThe addition of
appconfig.Invoke(InvokeMintFnCreation)is appropriate for initializing the minting function, aligning with the module's refactoring to make staking optional.
33-36: LGTM: ModuleInputs struct updatedThe removal of
StakingKeeper,MintFn, andInflationCalculationFnfields from theModuleInputsstruct aligns with the PR objective of making staking optional and suggests a new approach to handling the minting function and inflation calculation.
45-45: LGTM: MintKeeper field updated to pointer typeChanging the
MintKeeperfield type fromkeeper.Keeperto*keeper.Keeperis a good optimization. It can improve performance by avoiding unnecessary copying and allows for potential nil checks, which aligns with the optional staking functionality.x/mint/keeper/keeper_test.go (4)
89-89: LGTM! Consider enhancing the test with result verification.The change from
DefaultMintFntoMintFnis consistent with the refactoring mentioned in the PR summary.As suggested in a previous review, consider enhancing this test by verifying the results of the mint operation. For example, you could add assertions to check if the total supply has increased appropriately or if the minter's properties have been updated as expected.
99-99: LGTM! Consider verifying behavior for max supply scenario.The change from
DefaultMintFntoMintFnis consistent with the refactoring mentioned in the PR summary.As suggested in a previous review, consider adding assertions to verify the behavior when the total supply exceeds the max supply. This could include checking that no additional coins are minted and that the minter's state reflects this condition.
115-115: LGTM! Consider asserting minted amount for adjusted parameters.The change from
DefaultMintFntoMintFnis consistent with the refactoring mentioned in the PR summary.As suggested in a previous review, consider adding assertions to verify that the minted amount matches the expected value based on the adjusted
MaxSupplyandBlocksPerYearparameters. This will ensure that the Mint function correctly calculates the mint amount under these new conditions.
125-126: LGTM! Consider asserting state changes after BeginBlocker.The changes to set the mint function explicitly and remove the
DefaultMintFnparameter fromBeginBlockerare consistent with the refactoring mentioned in the PR summary. The addition of a test case with a no-op mint function is a good practice to verify the system's behavior in different scenarios.As suggested in a previous review, consider enhancing the test by asserting state changes after calling
BeginBlocker. This could include comparing specific fields ofnewMinterandminterto confirm the expected changes occurred due to theBeginBlockerexecution.For the new test case with the no-op mint function, consider adding a comment explaining the purpose of this test to improve code readability.
Also applies to: 131-131, 140-145
x/mint/CHANGELOG.md
Outdated
| * [#21858](https://github.com/cosmos/cosmos-sdk/pull/21858) `DefaultMintFn` now takes `StakingKeeper` and `MintKeeper` as arguments to avoid staking keeper being required by mint. | ||
| * `SetMintFn` is used to replace the default minting function. | ||
| * `InflationCalculationFn` is not passed through depinject any longer, a MintFn is required instead. | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Improve format and detail of the changelog entry.
This entry lacks the standard PR number reference and could benefit from more detail.
Consider the following improvements:
- Add the corresponding PR number.
- Provide more context on the impact of this change.
Suggested revision:
- InflationCalculationFn is not passed through depinject any longer, a MintFn is required instead.
+ * [#XXXXX] `InflationCalculationFn` is no longer passed through dependency injection. Users must now provide a `MintFn` instead, which offers more flexibility in defining custom minting logic.Replace #XXXXX with the actual PR number for this change.
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.
| * [#XXXXX] `InflationCalculationFn` is no longer passed through dependency injection. Users must now provide a `MintFn` instead, which offers more flexibility in defining custom minting logic. |
There was a problem hiding this 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
Outside diff range and nitpick comments (6)
x/mint/keeper/grpc_query.go (1)
11-13: LGTM! Consider adding a nil check for robustness.The change to use a pointer to
Keeperis a good improvement. It aligns with Go best practices for larger structs and can potentially improve performance by avoiding unnecessary copying.For added robustness, consider adding a nil check:
func NewQueryServerImpl(k *Keeper) types.QueryServer { + if k == nil { + panic("NewQueryServerImpl: keeper cannot be nil") + } return queryServer{k} }This ensures that the function panics early if a nil
Keeperis passed, making debugging easier.x/mint/CHANGELOG.md (3)
35-36: Consider removing empty sections from the changelog.The "Improvements" and "Bug Fixes" sections are currently empty. It's generally better to omit empty sections in changelogs to maintain clarity and conciseness.
Consider removing these lines if there are no entries for these categories:
-### Improvements - -### Bug Fixes
44-44: Improve format and detail of the changelog entry.This entry lacks the standard PR number reference and could benefit from more detail.
Consider the following improvements:
- Add the corresponding PR number.
- Provide more context on the impact of this change.
Suggested revision:
- InflationCalculationFn is not passed through depinject any longer, a MintFn is required instead. + * [#21858] `InflationCalculationFn` is no longer passed through dependency injection. Users must now provide a `MintFn` instead, which offers more flexibility in defining custom minting logic.
39-39: Consider rephrasing for conciseness.The phrase "in order to" can often be replaced with "to" without losing meaning, making the sentence more concise.
Suggested revision:
- `keeper.DefaultMintFn` wrapper must be used in order to continue using it in `NewAppModule`. + `keeper.DefaultMintFn` wrapper must be used to continue using it in `NewAppModule`.Tools
LanguageTool
[style] ~39-~39: Consider a shorter alternative to avoid wordiness.
Context: ...per.DefaultMintFnwrapper must be used in order to continue using it inNewAppModule`. Th...(IN_ORDER_TO_PREMIUM)
x/mint/keeper/keeper_test.go (2)
125-126: LGTM: Consistent setup of mint functionThe addition of
SetMintFnhere is consistent with the changes inTestDefaultMintFnand ensures the correct minting function is set before testing theBeginBlocker.Consider extracting this setup to a helper method to reduce duplication across test methods.
140-145: LGTM with suggestions: Additional test case for no-op mint functionThe addition of this test case improves coverage by checking the
BeginBlockerbehavior with a no-op mint function. This is a good practice.To further enhance this test:
- Consider adding a comment explaining the purpose of this specific test case.
- Add more specific assertions to verify that no state changes occur when using the no-op mint function.
Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
Files selected for processing (12)
- simapp/app.go (3 hunks)
- x/mint/CHANGELOG.md (1 hunks)
- x/mint/depinject.go (3 hunks)
- x/mint/keeper/genesis_test.go (3 hunks)
- x/mint/keeper/grpc_query.go (1 hunks)
- x/mint/keeper/grpc_query_test.go (1 hunks)
- x/mint/keeper/keeper.go (3 hunks)
- x/mint/keeper/keeper_test.go (6 hunks)
- x/mint/keeper/migrator.go (1 hunks)
- x/mint/keeper/msg_server.go (1 hunks)
- x/mint/module.go (2 hunks)
- x/mint/module_test.go (2 hunks)
Files skipped from review as they are similar to previous changes (6)
- simapp/app.go
- x/mint/depinject.go
- x/mint/keeper/genesis_test.go
- x/mint/keeper/keeper.go
- x/mint/module.go
- x/mint/module_test.go
Additional context used
Path-based instructions (6)
x/mint/CHANGELOG.md (1)
Pattern
**/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"x/mint/keeper/grpc_query.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.x/mint/keeper/grpc_query_test.go (2)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
Pattern
**/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"x/mint/keeper/keeper_test.go (2)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
Pattern
**/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"x/mint/keeper/migrator.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.x/mint/keeper/msg_server.go (1)
Pattern
**/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
LanguageTool
x/mint/CHANGELOG.md
[style] ~39-~39: Consider a shorter alternative to avoid wordiness.
Context: ...per.DefaultMintFnwrapper must be used in order to continue using it inNewAppModule`. Th...(IN_ORDER_TO_PREMIUM)
Additional comments not posted (10)
x/mint/keeper/msg_server.go (1)
18-18: LGTM! VerifyNewMsgServerImplfunction calls.The change in the parameter type from
Keeperto*Keeperis consistent with the modification in themsgServerstruct. This improves consistency throughout the code.To ensure this change doesn't break any existing code, please run the following script to check all calls to
NewMsgServerImpl:#!/bin/bash # Description: Check calls to NewMsgServerImpl in the codebase # Search for NewMsgServerImpl function calls rg --type go 'NewMsgServerImpl\(' -C 3x/mint/keeper/migrator.go (3)
11-11: Approved: Efficient use of pointer forkeeperfieldThe change from
keeper Keepertokeeper *Keeperis a good optimization. Using a pointer:
- Improves efficiency by avoiding unnecessary copying of the
Keeperstruct.- Allows for potential modification of the
Keeperinstance if needed.- Aligns with Go best practices for larger structs or shared state.
This change enhances the overall design and performance of the
Migratorstruct.
15-15: Approved: Consistent use of*KeeperinNewMigratorfunctionThe change in the
NewMigratorfunction signature fromfunc NewMigrator(k Keeper) Migratortofunc NewMigrator(k *Keeper) Migratoris appropriate and consistent with the previous change in theMigratorstruct. This modification:
- Ensures that a pointer to a
Keeperis passed when creating a newMigrator.- Maintains consistency throughout the codebase.
- Prevents unnecessary copying of the
Keeperstruct.This change complements the earlier modification and contributes to a more efficient and consistent design.
11-15: Verify usage ofNewMigratoracross the codebaseThe changes to the
Migratorstruct andNewMigratorfunction are consistent and improve efficiency. However, these modifications may impact other parts of the codebase that interact withMigratoror callNewMigrator.To ensure a smooth transition:
- Verify that all calls to
NewMigratoracross the codebase are updated to pass a pointer toKeeper.- Check for any direct usage of the
Migrator.keeperfield to ensure it's treated as a pointer.Run the following script to identify potential areas that need updating:
Please review the script output and update any inconsistent usages.
Verification successful
Verified all
NewMigratorusages pass a pointer toKeeper. No inconsistencies found.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Search for NewMigrator calls and Migrator.keeper usages echo "Searching for NewMigrator calls:" rg --type go "NewMigrator\(" -A 2 echo "\nSearching for Migrator.keeper usages:" rg --type go "Migrator.*\.keeper"Length of output: 5819
x/mint/keeper/grpc_query.go (1)
15-17: LGTM! Consistent use of pointer type.The change to use a pointer to
Keeperin thequeryServerstruct is consistent with the update in theNewQueryServerImplfunction. This ensures that all methods onqueryServerwork with the same instance ofKeeper, which is a good practice.x/mint/keeper/grpc_query_test.go (2)
31-31: LGTM: Appropriate use of pointer for keeper instanceThe change from
keeper.Keeperto*keeper.Keeperfor themintKeeperfield is a good practice. Using a pointer for the keeper instance is more efficient and allows for nil checks if needed.
31-31: Verify test coverage after removing stakingKeeper dependencyThe removal of the
stakingKeepermock object and its associated setup aligns with the PR objective of decoupling the mint module from the staking module. This simplification is good for maintainability. However, please ensure that this change doesn't reduce the test coverage or miss important interactions that were previously tested.To verify the test coverage, please run the following command and compare the results with the previous version:
Please review the output to ensure that the test coverage for the mint module hasn't decreased significantly, especially for areas that might have previously involved interactions with the staking module.
x/mint/keeper/keeper_test.go (3)
32-32: LGTM: Minor change in variable declarationThe change in the
mintKeeperdeclaration is consistent with the Uber Go Style Guide and doesn't affect the functionality of the test suite.
83-84: Consider adding assertions for mint function setupThe addition of
SetMintFnis a good improvement. However, as suggested in a previous review, consider adding assertions to verify that the Mint function has been set as intended. This will ensure thatSetMintFnhas properly initialized the Mint function before proceeding with the test.
89-89: Verify results of mint operationThe direct call to
MintFnsimplifies the code. However, as suggested in a previous review, consider adding assertions after this call to verify that the expected state changes have occurred. This could include checking if the total supply has increased appropriately or if the minter's properties have been updated.
| // msgServer is a wrapper of Keeper. | ||
| type msgServer struct { | ||
| Keeper | ||
| *Keeper |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
Action Required: Update NewMsgServerImpl Calls to Use *Keeper
The recent change to use a pointer type (*Keeper) for the Keeper field in x/mint/keeper/msg_server.go requires that all calls to NewMsgServerImpl pass a pointer to Keeper instead of a value. The following instances have been identified where NewMsgServerImpl may still be receiving Keeper by value:
-
Modules:
x/slashing/module.gox/protocolpool/module.gox/upgrade/module.gox/staking/module.gox/gov/module.gox/feegrant/module/module.gox/circuit/module.gox/auth/module.gox/distribution/module.gox/bank/module.gox/evidence/module.go
-
Test Files:
- Various test files across
keeper_test.goandmsg_server_test.gofor modules likeslashing,protocolpool,staking,gov,feegrant,circuit,auth,distribution,bank, andevidence.
- Various test files across
Please review each listed file to ensure that NewMsgServerImpl is invoked with a *Keeper. Update any instances where a Keeper is passed by value to use a pointer instead.
Analysis chain
LGTM! Verify usage of Keeper throughout the codebase.
The change from value type to pointer type for the Keeper field is a good improvement. It aligns with Go's preference for using pointers to structs for better performance and to allow modifications.
To ensure this change doesn't introduce any issues, please run the following script to check the usage of Keeper throughout the codebase:
To ensure that changing Keeper from a value type to a pointer type doesn't introduce inconsistencies in the usage of NewMsgServerImpl, please run the following script to verify the arguments passed to NewMsgServerImpl across the codebase:
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check usage of Keeper in the codebase
# Search for Keeper usage
rg --type go 'Keeper' -C 3
Length of output: 43458
Script:
#!/bin/bash
# Description: Check the arguments passed to NewMsgServerImpl in the codebase
# Search for NewMsgServerImpl function calls and display their arguments
rg --type go 'NewMsgServerImpl\(' -C 3
Length of output: 43458
|
@Mergifyio backport release/v0.52.x |
✅ Backports have been created
|
Co-authored-by: Julien Robert <[email protected]> (cherry picked from commit f6d7a92) # Conflicts: # x/accounts/README.md # x/mint/keeper/abci.go
… (#22979) Co-authored-by: Marko <[email protected]> Co-authored-by: Julien Robert <[email protected]>
… (#22979) Co-authored-by: Marko <[email protected]> Co-authored-by: Julien Robert <[email protected]>
Description
this pr is part of the staking requirements in the repo. Reducing it allows more people to use the module without needing to use the default staking module
Author Checklist
All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.
I have...
!in the type prefix if API or client breaking changeCHANGELOG.mdReviewers Checklist
All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.
Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.
I have...
Summary by CodeRabbit
New Features
SetMintFnto define the minting function for enhanced flexibility.MintKeeperandAppModuleto simplify setup.Bug Fixes
Refactor
Keeperand related structs to use pointer types for improved memory management.