-
Notifications
You must be signed in to change notification settings - Fork 109
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
refactor: remove unused functions from emissions module #2826
Conversation
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughWalkthroughThe changes involve a significant refactoring of the emissions module within the codebase. Key modifications include the removal of unused parameters, the introduction of a new fixed block reward parameter, and the restructuring of related API endpoints and documentation. Additionally, adjustments have been made to the migration logic to accommodate the new parameter structure while ensuring backward compatibility. Changes
Assessment against linked issues
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
|
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #2826 +/- ##
===========================================
- Coverage 66.91% 66.81% -0.10%
===========================================
Files 370 371 +1
Lines 20983 20910 -73
===========================================
- Hits 14041 13972 -69
+ Misses 6302 6300 -2
+ Partials 640 638 -2
|
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: 15
Outside diff range, codebase verification and nitpick comments (4)
docs/releases/v20_breaking_changes.md (1)
6-9
: List Style Consistency.The markdown linting issues indicate a preference for asterisks over dashes for list items. This is a minor style preference but helps maintain consistency across documentation.
Apply this diff to adjust the list style:
- - This results in the removal of the query `/zeta-chain/emissions/get_emissions_factors`. - - The fixed block reward amount can now be queried via `/zeta-chain/emissions/params`.This is constant for every block and does not depend on any factors. + * This results in the removal of the query `/zeta-chain/emissions/get_emissions_factors`. + * The fixed block reward amount can now be queried via `/zeta-chain/emissions/params`. This is constant for every block and does not depend on any factors.Tools
Markdownlint
7-7: Expected: asterisk; Actual: dash
Unordered list style(MD004, ul-style)
8-8: Expected: asterisk; Actual: dash
Unordered list style(MD004, ul-style)
x/emissions/types/errors.go (1)
16-16
: Address the removal ofErrUnableToSetParams
.The removal of
ErrUnableToSetParams
fromx/emissions/types/errors.go
has left references in the following files that need to be updated or replaced with an appropriate error handling mechanism:
x/emissions/keeper/msg_server_update_params_test.go
x/emissions/keeper/msg_server_update_params.go
Please ensure that these references are updated to prevent any compilation errors or unhandled scenarios. Consider replacing them with
ErrMigrationFailed
or another suitable error to maintain the integrity of the error handling logic.Analysis chain
Verify the removal of
ErrUnableToSetParams
.Please ensure that the removal of
ErrUnableToSetParams
does not affect any existing error handling where this error was previously used. It's crucial to check that all scenarios previously covered by this error are now adequately handled by other errors or by the newErrMigrationFailed
.Run the following script to verify the usage of
ErrUnableToSetParams
:Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of `ErrUnableToSetParams` in the codebase. # Test: Search for the error usage. Expect: No occurrences. rg --type go -A 5 $'ErrUnableToSetParams'Length of output: 868
x/emissions/types/params_legacy.go (1)
Line range hint
1-5
: Note on Deprecation:The comment at the beginning of the file mentions the deprecation of
x/params
in favor ofx/gov
. It's crucial to ensure that there is a clear migration path or timeline for this deprecation to avoid future technical debt.x/emissions/migrations/v3/migrate_test.go (1)
71-79
: Approved: Validation logic for negative emission percentage.The test case effectively checks the new validation logic by introducing a negative
ValidatorEmissionPercentage
. The error message is clear and aids in understanding the expected behavior. However, consider enhancing the error message for even greater clarity.Consider enhancing the error message to specify the exact invalid value that triggered the error, which can help in debugging and clarity:
-require.ErrorContains(t, err, "validator emission percentage cannot be less than 0 percent") +require.ErrorContains(t, err, "validator emission percentage cannot be less than 0 percent: received -00.50")
Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Files ignored due to path filters (5)
typescript/zetachain/zetacore/emissions/params_pb.d.ts
is excluded by!**/*_pb.d.ts
typescript/zetachain/zetacore/emissions/query_pb.d.ts
is excluded by!**/*_pb.d.ts
x/emissions/types/params.pb.go
is excluded by!**/*.pb.go
,!**/*.pb.go
x/emissions/types/query.pb.go
is excluded by!**/*.pb.go
,!**/*.pb.go
x/emissions/types/query.pb.gw.go
is excluded by!**/*.pb.gw.go
,!**/*.pb.gw.go
Files selected for processing (30)
- changelog.md (1 hunks)
- docs/cli/zetacored/cli.md (1 hunks)
- docs/openapi/openapi.swagger.yaml (3 hunks)
- docs/releases/v20_breaking_changes.md (1 hunks)
- precompiles/prototype/IPrototype.go (2 hunks)
- proto/zetachain/zetacore/emissions/params.proto (1 hunks)
- proto/zetachain/zetacore/emissions/query.proto (2 hunks)
- testutil/sample/sample.go (1 hunks)
- x/emissions/abci.go (1 hunks)
- x/emissions/abci_test.go (4 hunks)
- x/emissions/client/cli/query.go (1 hunks)
- x/emissions/genesis_test.go (2 hunks)
- x/emissions/keeper/block_rewards_components.go (1 hunks)
- x/emissions/keeper/block_rewards_components_test.go (1 hunks)
- x/emissions/keeper/keeper.go (1 hunks)
- x/emissions/keeper/migrator.go (2 hunks)
- x/emissions/keeper/params_test.go (1 hunks)
- x/emissions/migrations/v3/migrate.go (2 hunks)
- x/emissions/migrations/v3/migrate_test.go (4 hunks)
- x/emissions/migrations/v4/migrate.go (1 hunks)
- x/emissions/migrations/v4/migrate_test.go (1 hunks)
- x/emissions/module.go (2 hunks)
- x/emissions/types/errors.go (1 hunks)
- x/emissions/types/keys.go (2 hunks)
- x/emissions/types/legacy_params.go (1 hunks)
- x/emissions/types/legacy_params_test.go (1 hunks)
- x/emissions/types/message_update_params_test.go (1 hunks)
- x/emissions/types/params.go (6 hunks)
- x/emissions/types/params_legacy.go (2 hunks)
- x/emissions/types/params_test.go (4 hunks)
Files skipped from review due to trivial changes (1)
- docs/cli/zetacored/cli.md
Additional context used
Path-based instructions (26)
x/emissions/types/legacy_params.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/keeper/block_rewards_components.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/client/cli/query.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/types/errors.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/keeper/block_rewards_components_test.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/keeper/migrator.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/types/legacy_params_test.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/types/params_legacy.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.proto/zetachain/zetacore/emissions/params.proto (1)
Pattern
**/*.proto
: Review the Protobuf definitions, point out issues relative to compatibility, and expressiveness.x/emissions/migrations/v3/migrate.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/genesis_test.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.proto/zetachain/zetacore/emissions/query.proto (1)
Pattern
**/*.proto
: Review the Protobuf definitions, point out issues relative to compatibility, and expressiveness.x/emissions/types/keys.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/keeper/keeper.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/migrations/v4/migrate.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/types/message_update_params_test.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/migrations/v3/migrate_test.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/types/params.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/types/params_test.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/module.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/keeper/params_test.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/abci.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/migrations/v4/migrate_test.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.precompiles/prototype/IPrototype.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.x/emissions/abci_test.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.testutil/sample/sample.go (1)
Pattern
**/*.go
: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.
GitHub Check: codecov/patch
x/emissions/types/legacy_params.go
[warning] 8-8: x/emissions/types/legacy_params.go#L8
Added line #L8 was not covered by tests
Markdownlint
docs/releases/v20_breaking_changes.md
4-4: Expected: h2; Actual: h3
Heading levels should only increment by one level at a time(MD001, heading-increment)
7-7: Expected: asterisk; Actual: dash
Unordered list style(MD004, ul-style)
8-8: Expected: asterisk; Actual: dash
Unordered list style(MD004, ul-style)
Additional comments not posted (51)
x/emissions/keeper/block_rewards_components.go (1)
Line range hint
1-11
: Review ofGetReservesFactor
function.The
GetReservesFactor
function is implemented correctly and follows good Go practices. It retrieves the balance from the bank keeper and converts it to asdk.Dec
type, which is appropriate for handling decimal values in the Cosmos SDK.However, given the significant refactoring noted in the PR summary and the removal of related functions, it's crucial to verify that this function is still necessary and properly integrated within the broader module.
Verification successful
Verification of
GetReservesFactor
Function IntegrationThe
GetReservesFactor
function is well-integrated within the module. It is utilized inx/emissions/abci.go
, indicating its role in emissions logic, and is covered by tests inblock_rewards_components_test.go
. Additionally, its reference inevents.pb.go
suggests its importance in event handling. The function is necessary and correctly implemented.
- Integration Points:
x/emissions/abci.go
: Used for emissions logic.x/emissions/keeper/block_rewards_components_test.go
: Test coverage ensures functionality.x/emissions/types/events.pb.go
: Part of event data structure.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of `GetReservesFactor` in the broader module context. # Test: Search for the function usage. Expect: Integration points that justify the function's existence. rg --type go -A 5 $'GetReservesFactor'Length of output: 2049
docs/releases/v20_breaking_changes.md (1)
6-9
: Documentation of API Changes and Deprecations.The documentation clearly states the deprecation of
EmissionsFactors
and the associated API endpoint changes. However, ensure that the new endpoint/zeta-chain/emissions/params
is correctly implemented and documented elsewhere in the API documentation.Tools
Markdownlint
7-7: Expected: asterisk; Actual: dash
Unordered list style(MD004, ul-style)
8-8: Expected: asterisk; Actual: dash
Unordered list style(MD004, ul-style)
x/emissions/client/cli/query.go (1)
Line range hint
12-25
: Review ofGetQueryCmd
function after removal ofCmdGetEmmisonsFactors()
.The removal of
CmdGetEmmisonsFactors()
from theGetQueryCmd
function aligns with the PR's objective to streamline the emissions module by eliminating unused functions. This change simplifies the command structure and potentially reduces maintenance overhead. However, it's crucial to ensure that this removal does not impact any dependent features or integrations.
- Verification Needed: Confirm that the removal of
CmdGetEmmisonsFactors()
does not affect other modules or functionalities that might rely on it. This can be done by checking references to this command in other parts of the codebase.- Documentation Update: Ensure that any documentation related to the emissions module is updated to reflect this change. Removing a command should also involve updating the user guides, API documentation, and help commands that might list or describe
CmdGetEmmisonsFactors()
.Please update the documentation to reflect the removal of
CmdGetEmmisonsFactors()
from the CLI commands.Verification successful
Removal of
CmdGetEmmisonsFactors()
VerifiedThe removal of
CmdGetEmmisonsFactors()
from theGetQueryCmd
function is confirmed to be safe, as it is neither defined nor referenced elsewhere in the codebase. This aligns with the PR's objective to streamline the emissions module by removing unused elements. Please ensure that any related documentation is updated to reflect this change.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify if `CmdGetEmmisonsFactors()` is referenced in other parts of the codebase. # Test: Search for references to `CmdGetEmmisonsFactors`. Expect: No occurrences outside this file. rg --type go 'CmdGetEmmisonsFactors'Length of output: 36
Script:
#!/bin/bash # Re-run the search for references to `CmdGetEmmisonsFactors` to ensure no errors occurred. rg --type go 'CmdGetEmmisonsFactors' # Check for the definition of `CmdGetEmmisonsFactors` to confirm its removal. rg --type go 'func CmdGetEmmisonsFactors'Length of output: 80
x/emissions/types/errors.go (1)
16-16
: Approval of new error declaration:ErrMigrationFailed
.The addition of
ErrMigrationFailed
with a unique error code (1007) and a clear descriptive message enhances the module's error handling capabilities, particularly for migration-related issues. This change aligns well with the PR's objectives to streamline error management in the emissions module.x/emissions/keeper/block_rewards_components_test.go (1)
13-23
: Well-structured test for reserves factor retrievalThe test
TestKeeper_GetReservesFactor
is well-structured and follows the Arrange-Act-Assert pattern effectively. The use ofrequire.NoError
for error handling andrequire.Equal
for asserting the expected results are best practices that enhance the test's reliability.However, the minting of coins is a significant operation within the test setup. It's crucial to ensure that this operation does not have unintended side effects on the global state, especially in a testing environment.
Additionally, considering the PR's focus on streamlining the module, this test's narrow focus on the reserves factor is appropriate. It aligns with the objectives of simplifying and enhancing the module's functionality.
Verification successful
Verification of MintCoins Impact on Global State
The
MintCoins
operation is a critical setup step used across multiple test files in different modules, such asemissions
,crosschain
, andfungible
. The consistent use ofrequire.NoError
ensures that tests will fail fast if any issues arise during the minting process, which is a best practice. Additionally, the presence of mock implementations forMintCoins
in some tests helps isolate them from global state changes.The test
TestKeeper_GetReservesFactor
is well-structured and effectively usesMintCoins
without causing unintended side effects on the global state. It aligns with the module's objectives of streamlining and enhancing functionality.
- Ensure that the integrity of the
MintCoins
operation is maintained to prevent side effects in other tests.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the impact of MintCoins on the global state in other tests. # Test: Search for other tests that might be affected by global state changes due to MintCoins. rg --type go -A 5 $'MintCoins'Length of output: 15626
x/emissions/keeper/migrator.go (2)
8-8
: Review the new import for the v4 package.The import of the
v4
package is correctly placed and used in the newly addedMigrate3to4
function. This ensures that the migration logic is modular and version-specific, which is a good practice for maintainability and scalability.
30-33
: Review the newMigrate3to4
function.The function
Migrate3to4
correctly follows the established pattern of delegating the store migration logic to a version-specific package. This approach enhances modularity and maintainability. The function directly returns the result of theMigrateStore
method, which is acceptable if theMigrateStore
method itself handles all necessary error checking and logging. Ensure thatMigrateStore
in thev4
package is robust against possible migration failures and adequately logs errors for troubleshooting.Consider verifying the robustness and error handling of the
MigrateStore
method in thev4
package:Verification successful
Ensure robust error handling and consider adding logging in
MigrateStore
.The
MigrateStore
function in thev4
package appears to handle errors effectively, as evidenced by the comprehensive test cases that check for both successful migrations and specific error conditions. However, the function does not explicitly log errors, which could be beneficial for troubleshooting and monitoring. Consider adding logging to capture error details during the migration process.
- Review the
MigrateStore
function inx/emissions/migrations/v4/migrate.go
for potential logging enhancements.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the error handling and logging in the `MigrateStore` method of the `v4` package. # Test: Search for error handling and logging mechanisms. Expect: Adequate error handling and logging. rg --type go -A 5 $'MigrateStore' ./x/emissions/migrations/v4Length of output: 4372
x/emissions/types/params_legacy.go (2)
Line range hint
14-14
: Review ofParamKeyTable
Function:This function correctly sets up the parameter key table for the module. It's well-implemented and adheres to the expected standards for such functionality in the Cosmos SDK.
Line range hint
16-30
: Refinement ofParamSetPairs
Function:The
ParamSetPairs
function has been correctly updated to reflect the removal of unused parameters, aligning with the PR's objectives. However, it's important to ensure that all dependencies and references to the removed parameters are also updated throughout the codebase to prevent any runtime errors or inconsistencies.Verification successful
Verification Successful: Removed Parameters Not Referenced Elsewhere
The search for the removed parameters
ParamMaxBondFactor
,ParamMinBondFactor
,ParamAvgBlockTime
,ParamTargetBondRatio
, andParamDurationFactorConstant
returned no results, confirming that they are not referenced elsewhere in the codebase. This aligns with the PR's objectives and ensures that the codebase is free from potential issues related to these parameters.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that removed parameters are not referenced elsewhere in the codebase. # Test: Search for removed parameter references. Expect: No occurrences. rg --type go "ParamMaxBondFactor|ParamMinBondFactor|ParamAvgBlockTime|ParamTargetBondRatio|ParamDurationFactorConstant"Length of output: 121
Script:
#!/bin/bash # Re-run the search for removed parameter references to confirm their absence in the codebase. rg --type go "ParamMaxBondFactor|ParamMinBondFactor|ParamAvgBlockTime|ParamTargetBondRatio|ParamDurationFactorConstant"Length of output: 121
x/emissions/migrations/v3/migrate.go (1)
Line range hint
31-43
: Review of theMigrateStore
function:
Parameter Initialization:
- The function initializes
currParams
by fetching parameters fromlegacySubspace
. This is a standard approach in migrations to ensure that existing configurations are not lost.- The conditional checks for empty string values for
ValidatorEmissionPercentage
,ObserverEmissionPercentage
, andTssSignerEmissionPercentage
ensure that these essential parameters are not left uninitialized if they are missing from the legacy configuration. This is crucial for maintaining the integrity of the module's operation post-migration.Introduction of New Parameter:
- The introduction of
BlockRewardAmount
at line 43 is well-documented with a comment explaining its purpose. This is a good practice as it aids in understanding the changes made during the migration.- The assignment of
BlockRewardAmount
fromtypes.BlockReward
suggests that this value is predefined, likely in thetypes
package. It's important to ensure thattypes.BlockReward
is properly initialized and documented elsewhere in the module.Error Handling and Parameter Validation:
- The call to
currParams.Validate()
immediately after setting the new parameter is a good practice. It ensures that all parameters meet the module's requirements before they are saved to the state.- Proper error handling is implemented by returning the error from
currParams.Validate()
if it is not nil. This prevents the migration from proceeding with invalid parameters.Finalization of Migration:
- The final call to
emissionsKeeper.SetParams(ctx, currParams)
updates the module's state with the new parameters. This is a critical step in the migration process and appears to be correctly implemented.Suggestions:
- Ensure that
types.BlockReward
is well-defined and consider adding a check or comment regarding its initialization to avoid potential issues during runtime.- It might be beneficial to log the successful completion of the migration process for better traceability in production environments.
x/emissions/genesis_test.go (1)
43-43
: Ensure proper handling of negative values forObserverSlashAmount
.The test correctly sets the
ObserverSlashAmount
to a negative value to check for system robustness against invalid configurations. This aligns with the PR's focus on refining parameter validation. However, it's crucial to ensure that the corresponding logic in theInitGenesis
function explicitly handles this case to prevent any unintended behavior in production.Verification successful
Negative
ObserverSlashAmount
is properly validated.The codebase includes a validation function
validateObserverSlashAmount
that ensuresObserverSlashAmount
cannot be negative. This validation is integrated into the parameter setting process, and multiple test cases confirm its effectiveness. Therefore, the system is robust against negative values forObserverSlashAmount
.
- Validation logic is present in
x/emissions/types/params.go
.- Test cases in
x/emissions/types/params_test.go
confirm the validation.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that the InitGenesis function handles negative ObserverSlashAmount values appropriately. # Test: Search for the handling of negative ObserverSlashAmount in InitGenesis. Expect: Explicit checks or error handling. rg --type go -A 5 $'InitGenesis' | rg 'ObserverSlashAmount'Length of output: 56
Script:
#!/bin/bash # Description: Perform a comprehensive search for handling of ObserverSlashAmount in the codebase. # Search for the definition and usage of InitGenesis to locate its implementation. rg --type go 'func InitGenesis' -A 20 # Search for any handling or checks related to ObserverSlashAmount in the codebase. rg --type go 'ObserverSlashAmount' -A 5Length of output: 30271
proto/zetachain/zetacore/emissions/query.proto (10)
Line range hint
1-1
: File Header and Syntax DeclarationThe file correctly specifies the syntax version as
proto3
, which is the latest major version of the protocol buffers language. This is appropriate and ensures compatibility with modern tooling and libraries.
Line range hint
2-2
: Package DeclarationThe package name
zetachain.zetacore.emissions
is well-structured and follows conventional naming practices for Protobuf files, which helps in organizing and accessing the protobuf definitions within the project.
Line range hint
3-6
: Imports ReviewThe imports are essential for the definitions used in the file:
pagination.proto
for pagination support.params.proto
for emissions parameters.gogo.proto
for Go-specific enhancements.annotations.proto
for HTTP mapping.These imports are correctly specified and are necessary for the functionality described in the service definitions.
Line range hint
8-8
: Go Package OptionThe
go_package
option is set to"github.com/zeta-chain/node/x/emissions/types"
, which specifies the Go package where the compiled code will reside. This is a standard practice to ensure that the generated Go code is placed in the correct package.
Line range hint
10-10
: Service Definition: QueryThe
Query
service is well-defined. It provides a clear interface for querying emissions-related data. The remaining RPC methods (Params
,ListPoolAddresses
,ShowAvailableEmissions
) are still present, indicating that the service continues to support other functionalities despite the removal ofGetEmissionsFactors
.
Line range hint
11-11
: RPC Method: ParamsThis method allows querying the parameters of the emissions module. The HTTP mapping is correctly defined, which enables RESTful access to this RPC method. This is crucial for external clients and aligns with modern API design practices.
Line range hint
14-14
: RPC Method: ListPoolAddressesThis method provides functionality to list pool addresses related to emissions. The HTTP mapping is correctly set up, facilitating easy access through RESTful APIs.
Line range hint
18-18
: RPC Method: ShowAvailableEmissionsThis method is crucial for showing available emissions for a given address. The HTTP mapping includes a path parameter, which is a good practice for REST APIs as it allows for direct resource access.
22-22
: Message DefinitionsThe remaining message definitions (
QueryParamsRequest
,QueryParamsResponse
,QueryListPoolAddressesRequest
,QueryListPoolAddressesResponse
,QueryShowAvailableEmissionsRequest
,QueryShowAvailableEmissionsResponse
) are essential for the functionality of the respective RPC methods. They are well-defined and include necessary fields, ensuring that the service can operate effectively without the removed functionality.
20-20
: Removal of GetEmissionsFactorsThe removal of the
GetEmissionsFactors
RPC method and its associated request and response types is a significant change. It is important to ensure that this does not adversely affect any clients that might rely on this functionality. Given the PR's objectives, this removal should be aligned with the goal of streamlining the module. However, it's crucial to verify that all client-side and documentation references to this method are also updated to prevent confusion.Verification successful
Removal of GetEmissionsFactors Verified
The search for references to the
GetEmissionsFactors
RPC method in both.proto
files and markdown documentation yielded no results. This indicates that the removal has been successfully completed, with no lingering references in the codebase or documentation. This aligns with the goal of streamlining the module.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify that all client-side and documentation references to `GetEmissionsFactors` are updated or removed. # Test: Search for references to `GetEmissionsFactors`. Expect: No occurrences. rg --type proto -A 5 $'GetEmissionsFactors'Length of output: 72
Script:
#!/bin/bash # Find all .proto files and search for references to `GetEmissionsFactors`. fd --extension proto --exec rg 'GetEmissionsFactors' {} # Additionally, search for references in common documentation file types. rg 'GetEmissionsFactors' --type mdLength of output: 92
x/emissions/types/keys.go (4)
Line range hint
1-24
: Review of Module Constants and ImportsThe constants
ModuleName
,UndistributedObserverRewardsPool
,UndistributedTssRewardsPool
,StoreKey
,RouterKey
,QuerierRoute
,MemStoreKey
,WithdrawableEmissionsKey
, andBlockRewardsInZeta
are well-defined and align with the module's purpose. The use ofModuleName
to construct other key constants ensures consistency and reduces the likelihood of typos or mismatches in string literals across the module.The imports are appropriate for the module's functionality, leveraging the Cosmos SDK and its
math
library for precise calculations. This setup supports the module's need to handle blockchain-specific data types and operations.
Line range hint
26-34
: Review of Key Prefix FunctionThe
KeyPrefix
function is a utility that converts a string to a byte slice. This function is crucial for handling store operations where byte slices are used as keys. The implementation is straightforward and efficient, making it suitable for its intended use.
Line range hint
36-45
: Review of Emission Parameters and Tracker KeyThe constants
EmissionsTrackerKey
,ParamValidatorEmissionPercentage
,ParamObserverEmissionPercentage
,ParamTssSignerEmissionPercentage
, andParamObserverSlashAmount
are crucial for configuring the emissions logic. These parameters are clearly named, which aids in understanding their role within the module. It's important to ensure that these parameters are used consistently throughout the module and that their removal or modification is reflected in all relevant parts of the application to avoid runtime errors or logical inconsistencies.
Line range hint
47-58
: Review of Module Addresses and Block Reward ConfigurationThe module addresses such as
EmissionsModuleAddress
,UndistributedObserverRewardsPoolAddress
, andUndistributedTssRewardsPoolAddress
are correctly derived from the module name and specific pools. This ensures that the addresses are unique and scoped to their respective functionalities.The
BlockReward
andObserverSlashAmount
are set with precise values, which is crucial for maintaining the economic model of the blockchain. The use ofsdk.MustNewDecFromStr
andsdkmath.NewInt
ensures that these values are safely converted from strings and integers, respectively, minimizing the risk of errors during these conversions.The
BallotMaturityBlocks
constant is set to a sensible default and is crucial for the governance aspect of the module, ensuring that ballots have a defined maturity period.x/emissions/keeper/keeper.go (3)
58-60
: Review: NewGetCodec
MethodThe addition of the
GetCodec
method is a good practice as it encapsulates the access to thecdc
field of theKeeper
struct, promoting better modularity and encapsulation. This method is straightforward and correctly returns thecdc
field, which is of typecodec.BinaryCodec
.
62-64
: Review: NewGetStoreKey
MethodSimilarly, the
GetStoreKey
method is well-implemented, providing encapsulated access to thestoreKey
field of theKeeper
struct. This method allows other parts of the application to retrieve the store key without directly accessing the struct's field, adhering to the principles of good object-oriented design.
58-64
: Verify Alignment with PR ObjectivesThe addition of new methods
GetCodec
andGetStoreKey
appears to be well-implemented. However, it's important to verify how these additions align with the PR's stated objective of removing unused functions. If these methods are replacing older, now-removed methods that performed similar functions, the changes are justified. Otherwise, it might be beneficial to clarify the connection between these additions and the overall refactoring effort.x/emissions/migrations/v4/migrate.go (2)
12-16
: Interface Definition: EmissionsKeeperThe
EmissionsKeeper
interface is well-defined, encapsulating the necessary operations for the migration process. It includes methods for setting parameters, getting the codec, and accessing the store key. This design adheres to the principle of encapsulation and ensures that the migration logic is decoupled from the specific storage and serialization implementations.
18-48
: Function: MigrateStoreThis function handles the migration of emission parameters from version 3 to version 4. The logic is clear and follows the outlined objectives of removing unused parameters and introducing a new one. However, there are a few areas that could be improved for better error handling and maintainability:
Error Handling: The function uses
errorsmod.Wrap
to wrap errors, which is good practice as it provides more context to the error. However, it's important to ensure that the original error message does not contain sensitive information before wrapping it, as this could lead to information leakage.Magic Strings: The function uses empty string checks (e.g.,
v3Params.ValidatorEmissionPercentage != ""
). It would be more robust and maintainable to define these as constants or use a dedicated method to check for non-empty values.Default Values: The function sets
BlockRewardAmount
to a default value, but this is not explicitly shown in the code provided. It's crucial to ensure that default values are set correctly and documented either in the code or in the function comments.Logging: Consider adding logging at key steps in the migration process to aid in debugging and provide audit trails for the migration.
Consider these improvements for better maintainability and security. Would you like a more detailed code snippet to illustrate these suggestions?
x/emissions/types/message_update_params_test.go (6)
26-32
: Test case correctly validates the new parameter constraints.The changes in the test case effectively validate the new rule that the
BlockRewardAmount
cannot be negative. The setup and the assertion are correctly implemented to ensure that the validation logic behaves as expected.
Line range hint
38-43
: Valid test case remains effective.The test case for valid parameters correctly verifies that the default parameters pass the validation without errors. This ensures that the basic functionality of the
ValidateBasic
method is intact and functioning as expected.
Line range hint
45-63
: Comprehensive testing of signers.The function
TestMsgUpdateParamsGetSigners
effectively tests theGetSigners
method under various scenarios, including both valid and invalid signers. The use ofrequire
assertions ensures that the tests are robust and correctly handle different cases.
Line range hint
65-67
: Type method correctly tested.The function
TestMsgUpdateParamsType
correctly verifies that theType
method returns the expected type name. This consistency is crucial for the correct functioning of message routing and handling.
Line range hint
69-71
: Route method correctly tested.The function
TestMsgUpdateParamsRoute
correctly verifies that theRoute
method returns the expected router key. This consistency is crucial for the correct functioning of message routing and handling.
Line range hint
73-75
: GetSignBytes method safely tested.The function
TestMsgUpdateParamsGetSignBytes
correctly verifies that theGetSignBytes
method does not cause any panics, ensuring that the method is safe and behaves as expected under normal conditions.x/emissions/migrations/v3/migrate_test.go (1)
47-47
: Approved: Addition ofBlockRewardAmount
in migration test.The introduction of
BlockRewardAmount
is well-handled in the test, ensuring that the new parameter is correctly integrated into the migration logic.x/emissions/types/params.go (4)
17-19
: Refactor: Simplification ofNewParams
function.The
NewParams
function has been refactored to include only essential parameters. This change aligns with the PR's objective to streamline theParams
structure by removing unused parameters. The inclusion ofObserverSlashAmount
,BallotMaturityBlocks
, andBlockRewardAmount
reflects a shift towards a more dynamic configuration, which should enhance maintainability and clarity in the codebase.
42-43
: New Validation Function for Block Rewards.The addition of
validateBlockRewardsAmount
in theValidate
method is a crucial update. This new validation function ensures that theBlockRewardAmount
adheres to the expected constraints, specifically checking that it is not less than zero. This is a positive change as it maintains the integrity of the new parameter structure and aligns with best practices for robust parameter validation.
126-134
: Implementation ofvalidateBlockRewardsAmount
.The implementation of
validateBlockRewardsAmount
correctly checks the type of the input and ensures that the block reward amount is non-negative. This method is essential for maintaining the integrity of the block reward parameter and preventing invalid configurations from being set. The use ofsdkmath.LegacyDec
and the clear error messages contribute to a robust validation process.
45-45
: Validation Logic Consolidation.The consolidation of validation logic in the
Validate
method, particularly the removal of several previously validated parameters, simplifies the parameter handling process. This change should make the codebase cleaner and more maintainable by focusing on the parameters that are actively used.x/emissions/types/params_test.go (1)
113-117
: Ensure proper error handling inTestValidate
for negative block reward amounts.The test case for negative block reward amounts uses
sdkmath.LegacyMustNewDecFromStr
to create a decimal from a string. This is a good practice as it ensures the input is in the expected format. However, the error message checked inrequire.ErrorContains
should be verified to ensure it matches the actual output of the validation logic.Consider adding a test case to ensure that the error message is consistent with the validation logic. If the error message is not as expected, update the validation logic or the test case to align them.
Verification successful
Verification Successful: Error Message Consistency Confirmed
The error message "block reward amount cannot be less than 0" in the test case is consistent with the validation logic in
params.go
. No changes are necessary as the test case correctly verifies the expected behavior.
- The error message is correctly implemented in the validation logic.
- The test case accurately checks for this error message.
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the error message for negative block reward amounts. # Test: Search for the error message in the validation logic. Expect: Consistent error message. rg --type go -A 5 $'block reward amount cannot be less than 0' x/emissions/types/Length of output: 1150
x/emissions/module.go (2)
166-166
: Consensus version update approved.The update to the
ConsensusVersion
method is correctly implemented. Ensure that all dependent components and documentation are updated to reflect this change.
135-137
: Improve error handling in migration registration.Using
panic
for error handling in the migration registration can lead to abrupt termination of the application. Consider using a more robust error handling strategy that logs the error and returns gracefully. Additionally, verify that the migration functionMigrate3to4
is implemented and tested thoroughly to ensure smooth transitions between versions.x/emissions/keeper/params_test.go (1)
26-27
: Review of New Parameter Tests inTestKeeper_GetParams
The addition of
BallotMaturityBlocks
andBlockRewardAmount
to the test cases is aligned with the PR objectives to streamline the emissions parameters. However, there are a few points to consider for improvement:
Consistency in Error Messages: The error messages should consistently reflect the tested condition. For instance, the error message for
BallotMaturityBlocks
being too low is "ballot maturity types must be gte 0". This could be made more consistent with other messages by changing it to "ballot maturity blocks must be greater than or equal to 0".Use of
int64
Conversion: The use ofint64(emissionstypes.BallotMaturityBlocks)
suggests thatBallotMaturityBlocks
might not be of typeint64
. If it is alreadyint64
, this conversion is redundant. If it's not, it would be better to ensure that the type inemissionstypes
matches the expected type in the tests to avoid unnecessary conversions.Negative Testing for New Parameters: The tests for negative values for
BallotMaturityBlocks
andBlockRewardAmount
are good. However, consider adding tests for edge cases like zero values or extremely high values to ensure robustness.Documentation and Comments: Adding comments to explain the rationale behind each test case, especially for the new parameters, would enhance readability and maintainability of the test suite.
Refactoring Suggestions: To reduce redundancy and improve clarity, consider using a helper function to create test cases, especially since many fields are repeated with the same values across different tests.
Consider the following improvements to enhance the test suite:
- Standardize error messages for consistency.
- Verify the necessity of type conversions and adjust the data types in
emissionstypes
if needed.- Expand tests to cover additional edge cases.
- Add comments to test cases to explain their purpose and expected outcomes.
- Refactor repetitive test case setups into a helper function.
If you would like, I can assist in implementing these changes or open a GitHub issue to track this task.
Also applies to: 38-39, 50-51, 62-63, 74-75, 86-87, 98-99, 110-111, 122-123, 134-135
x/emissions/abci.go (2)
19-22
: Good practice: Early exit on parameter retrieval failure.The implementation of an early exit if the block reward parameters are not found is a good practice. It prevents the function from proceeding with an invalid state, aligning with clean code principles.
24-24
: Approved: Logic to compare block rewards with emission pool balance.The check to ensure that block rewards do not exceed the emission pool balance is crucial for maintaining the integrity of the reward distribution process. The associated logging provides valuable information for debugging and operational monitoring.
x/emissions/migrations/v4/migrate_test.go (1)
16-185
: Comprehensive Review of Migration TestsThe migration tests are well-structured and cover a variety of scenarios, including successful migrations and error handling. Here are some specific observations and suggestions:
Duplication in Test Setup: The setup code in lines 19, 43, 69, 99, 129, 157, 191, 208, and 222 is repetitive across different test cases. Consider refactoring this into a helper function to reduce duplication and improve maintainability.
Error Handling: The tests for error scenarios (lines 155-167 and 169-185) effectively check for specific errors, which is good practice. However, ensure that all possible error paths in the migration logic are covered by tests.
Magic Numbers and Strings: There are several instances (e.g., lines 264, 280) where magic numbers and strings are used directly in the code. It's a good practice to define these as constants at the beginning of your test file or in a configuration file to improve readability and maintainability.
Use of Asserts: The use of
require
for assertions (e.g., lines 24, 28, 48, 52, etc.) is appropriate as it stops the test immediately if the condition is not met, which is suitable for conditions that must be true for the test to proceed correctly.Documentation and Comments: Adding comments explaining the purpose of each test case and the significance of the scenarios being tested can help future maintainers understand the test's intent more quickly.
Testing Edge Cases: Ensure that edge cases, especially around boundary values of the parameters, are tested. This might include parameters that are just above or below expected thresholds.
Overall, the tests are robust, but attention to the above points can enhance their effectiveness and maintainability.
x/emissions/abci_test.go (2)
22-54
: Review of New Test Case: "no distribution happens if params are not found"This test case is well-structured and follows a clear Arrange-Act-Assert pattern, which is good for readability and maintainability. Here are some observations and suggestions:
Initial Setup and Parameter Deletion (Lines 24-28): The test correctly sets up the necessary context and explicitly deletes the parameters to simulate their absence. This is a crucial step for the scenario being tested.
Observer Setup and Ballot Creation (Lines 30-41): The setup for observers and ballots is thorough, ensuring that the test environment mimics expected real-world conditions.
Execution and Assertions (Lines 44-53): The loop to simulate multiple blocks and the final assertion to check that no emissions are distributed are correctly implemented. The use of
require.False(t, found)
effectively confirms the test's intention.Suggestions:
- Enhance Documentation: While the test is well-implemented, adding more detailed comments explaining each step could improve understanding for future maintainers.
- Parameterize Test: Consider parameterizing this test with different scenarios, such as varying numbers of observers or ballots, to further ensure robustness.
Overall, the test addition is a valuable contribution to ensuring the emissions module behaves as expected under edge cases.
Line range hint
54-122
: Review of Existing Test Cases and Overall StructureThe test suite is comprehensive and covers a variety of scenarios that are crucial for the robustness of the emissions module. Here are some observations and suggestions:
Use of Test Utilities (e.g.,
keepertest
,sample
): The use of these utilities suggests a good level of abstraction and reuse in test setups, which is excellent for maintainability.Scenario Coverage: The tests cover scenarios like empty module accounts and various distribution failures, which are essential for ensuring the module's resilience.
Mocking and Assertions: The use of mocks and targeted assertions (e.g.,
require.True
,require.False
) is well done, providing clear, concise checks on the system's behavior.Suggestions:
- Increase Scenario Coverage: If not already covered, consider adding tests for scenarios where network conditions or unexpected inputs might affect emissions distribution.
- Continuous Integration: Ensure these tests are integrated into the CI pipeline to catch regressions or errors early.
Overall, the test suite is well-constructed and plays a vital role in the ongoing reliability of the emissions module.
changelog.md (1)
25-25
: Changelog Entry Review: PR #2826The changelog entry for PR #2826 correctly documents the significant changes made to the emissions module, including the removal of unused code and the introduction of a new parameter for fixed block reward amount. This entry provides clear information and links directly to the PR, which is good practice for traceability and further review.
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.
just minor comments
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.
It seems the changes go beyond the idea behind the PR title (new added params)? Do we have an issue describing the context of adding a new param
Added #1897 to linked issues |
Description
This pr
Closes: #1852
https://github.com/zeta-chain/protocol-private/issues/96
#1897
How Has This Been Tested?
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests