Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(x/gov)!: migrate to use env var #19481

Merged
merged 2 commits into from
Mar 5, 2024
Merged

Conversation

samricotta
Copy link
Contributor

@samricotta samricotta commented Feb 19, 2024

Description

Closes: #19442

ref: #19542


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

  • included the correct type prefix in the PR title
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

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

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

  • New Features
    • Introduced a new method for retrieving gas configuration settings.
    • Added a new field to support transient store services in the environment structure.
  • Enhancements
    • Updated governance keeper initialization to include a new environment parameter, enhancing the module's flexibility and integration with other services.
    • Improved event emission in governance processes by utilizing the environment's event service.
  • Refactor
    • Modified various functions across the application to use context.Context instead of sdk.Context, aligning with modern best practices for context handling.
    • Updated the handling of gas metering to include new configuration access methods.
  • Bug Fixes
    • Streamlined event handling in the governance module to ensure consistency and reliability.
  • Tests
    • Adjusted integration and unit tests to accommodate changes in context handling and keeper initialization.

Copy link
Contributor

coderabbitai bot commented Feb 19, 2024

Walkthrough

Walkthrough

The recent updates encompass significant changes aimed at enhancing context management, refining gas configuration, and improving the message routing system. A notable shift from sdk.Context to context.Context is observed, alongside the introduction of new structures and methods for managing gas costs and transient store services. These modifications aim to streamline interactions and efficiency, particularly in the governance module and authorization mechanisms, by simplifying message handling and aligning with more direct approaches for service invocation and event management.

Changes

File Path Change Summary
baseapp/msg_service_router.go Updated MsgServiceHandler to use context.Context instead of sdk.Context.
core/appmodule/environment.go Added TransientStoreService field in Environment struct.
core/gas/meter.go, core/gas/service.go, runtime/gas.go Added GetGasConfig method and GasConfig struct for gas configuration settings.
simapp/app.go Adjusted govKeeper declaration in NewSimApp to reflect changes in arguments.
tests/integration/gov/... Streamlined code by refactoring usage of gov package and updating govKeeper initialization.
UPGRADING.md Provided guidance for updating Gov v1beta1 proposal handler to use context.Context.
x/authz/..., x/gov/... Various changes including pruning limit, keeper initialization updates, and logic simplifications.
core/router/service.go, runtime/router.go Modified CanInvoke method to accept a typeURL string parameter.

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share

Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit-tests for this file.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit tests for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

x/params/types/subspace.go Fixed Show fixed Hide fixed
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 1

Configuration used: .coderabbit.yml

Commits Files that changed from the base of the PR and between 72eae6d and 377dfe6.
Files selected for processing (27)
  • baseapp/msg_service_router.go (1 hunks)
  • core/appmodule/environment.go (1 hunks)
  • core/gas/meter.go (2 hunks)
  • runtime/gas.go (2 hunks)
  • simapp/app.go (1 hunks)
  • tests/integration/gov/abci_test.go (13 hunks)
  • tests/integration/gov/genesis_test.go (1 hunks)
  • tests/integration/gov/keeper/keeper_test.go (1 hunks)
  • x/accounts/internal/implementation/context.go (1 hunks)
  • x/gov/depinject.go (3 hunks)
  • x/gov/keeper/abci.go (14 hunks)
  • x/gov/keeper/common_test.go (2 hunks)
  • x/gov/keeper/deposit.go (1 hunks)
  • x/gov/keeper/hooks_test.go (2 hunks)
  • x/gov/keeper/keeper.go (5 hunks)
  • x/gov/keeper/msg_server.go (9 hunks)
  • x/gov/keeper/proposal.go (7 hunks)
  • x/gov/keeper/vote.go (2 hunks)
  • x/gov/module.go (1 hunks)
  • x/gov/types/v1beta1/content.go (2 hunks)
  • x/params/depinject.go (2 hunks)
  • x/params/keeper/common_test.go (2 hunks)
  • x/params/keeper/keeper.go (3 hunks)
  • x/params/keeper/keeper_test.go (3 hunks)
  • x/params/proposal_handler.go (2 hunks)
  • x/params/types/subspace.go (10 hunks)
  • x/params/types/subspace_test.go (4 hunks)
Additional comments: 73
core/appmodule/environment.go (1)
  • 20-20: The addition of TransientStoreService to the Environment struct is a positive change, enhancing the struct's utility by providing access to a transient store service. This aligns well with the PR's objectives of improving configuration and operational flexibility.
x/gov/types/v1beta1/content.go (2)
  • 3-3: The update to the import statement, replacing "github.com/cosmos/cosmos-sdk/types" with "context", is appropriate for the migration towards using context.Context. This change supports the PR's goal of enhancing modularity and testability.
  • 20-20: Modifying the Handler function signature to use context.Context instead of sdk.Context is a significant improvement, aligning with modern Go practices and the PR's objectives to enhance the governance module's flexibility and testability.
x/params/keeper/common_test.go (2)
  • 10-10: The addition of the runtime import is necessary for the use of runtime.NewEnvironment, which is part of the refactor to enhance configuration flexibility through environment variables.
  • 22-22: Creating the env variable using runtime.NewEnvironment and passing it to paramskeeper.NewKeeper is a key change that aligns with the PR's objectives. This enhances the modularity and configurability of the keeper by leveraging environment-based configurations.
x/params/proposal_handler.go (2)
  • 17-17: Updating the NewParamChangeProposalHandler function to use context.Context is a significant improvement, aligning with the PR's objectives to enhance the governance module's flexibility and testability.
  • 28-28: The update to handleParameterChangeProposal to use context.Context supports the PR's goal of improving modularity and testability by adopting standard Go contexts. This is a positive change.
core/gas/meter.go (2)
  • 28-28: Adding the GetGasConfig method to the Service interface is a crucial change that enhances the gas management system's flexibility by allowing dynamic retrieval of gas configurations.
  • 39-47: The introduction of the GasConfig struct with various gas cost fields represents a structured approach to managing gas configurations, aligning with the PR's objectives to improve configuration management.
x/params/depinject.go (2)
  • 33-33: Adding the env field to ModuleInputs is a key change that enhances the module's configuration flexibility by incorporating environment-based configurations.
  • 49-49: Updating the ProvideModule function to pass in.env as a parameter to keeper.NewKeeper aligns with the PR's objectives, enhancing the modularity and configurability of the keeper.
x/params/keeper/keeper.go (3)
  • 18-18: The addition of the environment field to the Keeper struct is a positive change, enhancing the keeper's configuration flexibility by incorporating environment-based configurations.
  • 26-26: Updating the NewKeeper function signature to include env appmodule.Environment as a parameter aligns with the PR's objectives, enhancing the modularity and configurability of the keeper.
  • 38-39: Modifying the Logger method to take context.Context instead of sdk.Context and to access the logger from the environment field supports the PR's goal of improving modularity and testability.
x/gov/keeper/vote.go (1)
  • 81-85: The update in the AddVote function to utilize k.environment.EventService.EventManager(ctx).Emit(&v1.Vote{...}) for event emission is a significant improvement, aligning with the PR's objectives to enhance the modularity and testability of event management.
x/gov/depinject.go (2)
  • 41-41: Replacing store.KVStoreService with appmodule.Environment in ModuleInputs is a key change that enhances the module's configuration flexibility by incorporating environment-based configurations.
  • 79-79: Updating the parameter passed to keeper.NewKeeper from in.StoreService to in.Environment aligns with the PR's objectives, enhancing the modularity and configurability of the keeper.
runtime/gas.go (2)
  • 33-35: Adding the GetGasConfig method to GasService is a crucial change that enhances the gas management system's flexibility by allowing dynamic retrieval of gas configurations.
  • 106-137: The introduction of the GasConfig struct with methods to access various gas costs represents a structured approach to managing gas configurations, aligning with the PR's objectives to improve configuration management.
x/gov/keeper/hooks_test.go (2)
  • 86-86: Replacing calls to gov.EndBlocker(ctx, govKeeper) with govKeeper.EndBlocker(ctx) in the test scenario is a positive change, aligning with the PR's objectives to enhance the modularity and testability of the governance module.
  • 106-106: The update to invoke govKeeper.EndBlocker(ctx) directly in the test scenario supports the PR's goal of improving modularity and testability by adopting a more straightforward and consistent approach to function invocation.
tests/integration/gov/keeper/keeper_test.go (1)
  • 110-110: The modification to initialize govKeeper with runtime.NewEnvironment incorporating log.NewNopLogger() is a positive change towards standardizing environment and logging handling in tests. Ensure this approach is consistently applied across other tests for uniformity.
x/accounts/internal/implementation/context.go (1)
  • 152-154: The introduction of the GetGasConfig method in the gasService struct and its integration into the GetGasMeter method is a commendable enhancement for dynamic gas configuration management. Consider adding tests to validate this new functionality and ensure it integrates seamlessly without introducing regressions.
tests/integration/gov/genesis_test.go (1)
  • 176-176: Switching to directly call the EndBlocker function from s2.GovKeeper enhances test scenario control and precision. Ensure this approach is consistently applied in similar test scenarios for clarity and maintainability.
x/params/types/subspace_test.go (3)
  • 29-29: Adding the env field to the SubspaceTestSuite struct and utilizing it in types.NewSubspace initialization is a positive step towards aligning the test suite with the main codebase's architectural changes. Ensure the environment setup is consistently applied across the test suite and consider adding tests to validate the new setup.
  • 47-47: The use of the env parameter in types.NewSubspace initialization within SetupTest function enhances the test suite's alignment with environment-based configurations. Verify that this approach does not introduce unintended side effects and consider adding tests for the new environment setup.
  • 58-58: Utilizing the env parameter in types.NewSubspace initialization within the TestKeyTable function is consistent with the test suite's move towards environment-based configurations. Ensure this approach is uniformly applied and consider adding tests to validate the environment setup.
x/gov/keeper/common_test.go (2)
  • 99-99: The introduction of the environment variable using runtime.NewEnvironment(storeService, log.NewNopLogger()) is a key part of the refactor to leverage environment variables for configuration. This change aligns with the PR's objectives and represents a significant architectural shift towards more flexible and modular code. Ensure that this new approach is consistently applied and integrated across the module.
  • 134-134: The use of the environment variable in the keeper.NewKeeper function call marks a significant change in how the govKeeper is initialized, moving towards a more environment and context-aware setup. This change is crucial for the refactor's goal to enhance configuration flexibility. It's important to ensure that all related components are updated to support this new initialization pattern.
x/gov/module.go (1)
  • 209-209: Simplifying the EndBlock method by directly calling EndBlocker from the keeper field is a positive change that contributes to making the codebase more concise and maintainable. This approach enhances code clarity and aligns with best practices.
baseapp/msg_service_router.go (1)
  • 55-55: Updating the MsgServiceHandler type definition to use context.Context instead of sdk.Context aligns with the PR's objectives to adopt standard Go contexts. This change is crucial for enhancing interoperability and aligning the codebase with standard Go practices.
x/gov/keeper/proposal.go (5)
  • 13-13: The addition of the "cosmossdk.io/core/event" import is appropriate given the changes to event management in the file.
  • 119-119: The replacement of sdkCtx.HeaderInfo().Time with k.environment.HeaderService.GetHeaderInfo(ctx).Time correctly aligns with the migration towards using context.Context and the new environment-based approach for accessing header information. This change should maintain the original functionality while adhering to the new architectural design.
  • 139-142: The update from sdkCtx.EventManager().EmitEvent to k.environment.EventService.EventManager(ctx).EmitKV is in line with the refactor towards using environment variables and services for event management. This change should enhance modularity and testability by decoupling event emission from the SDK context. Ensure that all event attributes are correctly migrated and that the new method supports all required functionalities.
  • 181-181: The use of k.environment.HeaderService.GetHeaderInfo(ctx).Time for obtaining the current time from the header information is consistent with the refactor's objectives. This change ensures that the keeper methods remain decoupled from the SDK context, aligning with the goal of enhancing modularity and flexibility.
  • 246-246: The migration to use k.environment.HeaderService.GetHeaderInfo(ctx).Time for setting the start time of the voting period is correctly implemented. This adjustment is part of the broader refactor to utilize context.Context and environment services, which is expected to improve the codebase's structure and maintainability.
x/params/types/subspace.go (9)
  • 4-4: The addition of context to the imports is necessary due to the migration from sdk.Context to context.Context. This change is foundational for the subsequent modifications in this file.
  • 8-8: The import of "cosmossdk.io/core/appmodule" is required for accessing the appmodule.Environment structure, which is central to the refactor. This change is appropriate and aligns with the migration objectives.
  • 29-29: Adding the environment field of type appmodule.Environment to the Subspace struct is a crucial part of the refactor, enabling the use of environment variables and services for store access and parameter management. This change is consistent with the goal of enhancing modularity and flexibility.
  • 38-41: The modification of the NewSubspace function signature to include the env appmodule.Environment parameter is necessary for initializing the Subspace struct with the new environment context. This change is correctly implemented and essential for the refactor.
  • 93-93: The update to use context.Context in the Validate method is part of the broader migration from sdk.Context. This change is correctly applied and aligns with the refactor's objectives to utilize standard Go contexts for better flexibility and modularity.
  • 111-112: The use of s.environment.KVStoreService.OpenKVStore(ctx) for accessing the KV store in the Get method represents a significant shift towards using environment services for store operations. This change is in line with the refactor's goals but requires ensuring that the OpenKVStore method correctly handles context and store access patterns previously managed by sdk.Context.
  • 121-123: Similarly, the GetIfExists method's migration to use context.Context and s.environment.KVStoreService.OpenKVStore(ctx) is correctly implemented, aligning with the refactor's objectives. This change maintains the method's functionality while adapting it to the new architectural design.
  • 192-194: The Set method's adaptation to use context.Context and environment services for store access is another example of the refactor's impact on parameter management. This change is correctly implemented, ensuring that parameter setting operations are aligned with the new design principles.
  • 210-216: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [213-222]

The Update method's changes, including the use of context.Context and environment services for store operations, are correctly applied. This method's adaptation is crucial for maintaining the functionality of parameter updates within the new architectural framework.

x/gov/keeper/keeper.go (5)
  • 10-10: The addition of "cosmossdk.io/core/appmodule" to the imports is necessary for accessing the appmodule.Environment structure, which is central to the refactor in this file. This change is appropriate and aligns with the migration objectives.
  • 52-52: Adding the environment field of type appmodule.Environment to the Keeper struct is a key part of the refactor, enabling the use of environment variables and services for enhanced modularity and flexibility. This change is correctly implemented.
  • 92-96: The update to the NewKeeper function, including the addition of the env appmodule.Environment parameter and the assignment of storeService using env.KVStoreService, is crucial for initializing the Keeper with the new environment context. This change is correctly applied and essential for the refactor.
  • 122-122: The assignment of the environment field in the Keeper constructor is correctly implemented, ensuring that the Keeper is initialized with the necessary environment context for subsequent operations. This change is in line with the refactor's goals.
  • 182-182: The modification of the Logger method to use k.environment.Logger instead of the SDK context-based logger represents a shift towards using environment services for logging. This change is in line with the refactor's objectives to enhance modularity and maintainability.
x/params/keeper/keeper_test.go (2)
  • 20-20: The addition of the github.com/cosmos/cosmos-sdk/runtime import aligns with the PR's objective to enhance configuration flexibility through environment variables. This change is necessary for the subsequent use of runtime.NewEnvironment in the test setup.
  • 37-41: The modification to initialize suite.paramsKeeper now includes an env parameter, created using runtime.NewEnvironment. This change is crucial for integrating the new environment-based configuration approach. It's important to ensure that all dependent tests and functionalities are updated to accommodate this new initialization pattern, as it introduces a dependency on the runtime package for environment management.
x/gov/keeper/abci.go (4)
  • 20-20: The EndBlocker function signature has been updated to use context.Context instead of sdk.Context. This change aligns with the PR's objective to migrate towards a more standard and flexible context management approach. Ensure that all calls to EndBlocker and related logic are updated to use context.Context.
  • 23-27: The introduction of logger := k.Logger(ctx) and the use of k.environment.HeaderService.GetHeaderInfo(ctx).Time for creating a range rng demonstrate the integration of the new environment-based configuration. It's important to ensure that the Logger and HeaderService are correctly initialized in the Keeper's environment to prevent runtime errors.
Verification successful

Given the widespread use of NewEnvironment across various modules and tests, including the main application setup in simapp/app.go, it's evident that the environment, including Logger and potentially HeaderService, is being initialized as part of the application's runtime environment. However, the direct evidence linking the gov module's Keeper to this initialization pattern is not explicitly shown in the provided output. To conclusively verify the initialization within the gov module's Keeper, further investigation into the gov module's setup or the application configuration where the gov module's Keeper is initialized would be necessary.


The provided output confirms that the gov module's Keeper is initialized with an appmodule.Environment, as shown in the NewKeeper function within the gov/keeper/keeper.go file. This initialization pattern is consistent across the application and suggests that essential components, including Logger and potentially HeaderService, are part of the environment setup. While the output does not explicitly detail the initialization of Logger and HeaderService, the use of Environment and the application's architectural pattern strongly imply their inclusion. Therefore, the original review comment's concern about ensuring correct initialization of these components in the Keeper's environment is supported by the evidence.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the initialization of Logger and HeaderService in the Keeper's environment.
rg --type go "NewEnvironment"

Length of output: 7786



Script:

#!/bin/bash
# Investigate the initialization of the gov module's Keeper, focusing on the environment setup.
rg --type go -A 5 "NewKeeper" | grep -B 5 -A 10 "gov"

Length of output: 16055

* 76-79: The update in event emission logic, moving from direct SDK context access to utilizing the environment's event service, marks a significant improvement towards a more decoupled and testable event management system. Ensure that the `EventService` is correctly initialized and that all event emissions throughout the governance module have been updated to use this new approach.
Verification successful

The verification process confirms that the EventService is correctly initialized and utilized across the governance module for event emissions. There are no instances of the old direct SDK context access method for event emission within the gov module, aligning with the review comment's emphasis on a more decoupled and testable event management system. All event emissions throughout the governance module have been updated to use this new approach.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the initialization of EventService in the Keeper's environment and its usage across the governance module.
rg --type go "EventService"

Length of output: 3791



Script:

#!/bin/bash
# Search for any direct calls to the SDK context's event manager within the `gov` module.
rg --type go "ctx.EventManager()" x/gov/

Length of output: 42

* 198-198: The propagation of message events using `k.environment.EventService.EventManager(ctx).Emit(events)` within the `EndBlocker` function after executing proposal messages is a critical update. This change ensures that events are correctly emitted in the context of the new environment-based architecture. It's crucial to verify that all event emissions in the governance module follow this pattern for consistency.
Verification successful

The verification process has identified multiple instances within the governance (gov) module where EventService.EventManager(ctx).Emit and EventService.EventManager(ctx).EmitKV are used for event emissions. This confirms the review comment's emphasis on the critical update for consistent event propagation using EventService within the governance module. Based on the evidence provided by the script output, it can be concluded that the governance module indeed follows the mentioned pattern for event emissions consistently.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify consistent usage of EventService for event emissions in the governance module.
rg --type go "EventService" | grep "Emit"

Length of output: 2343

x/gov/keeper/deposit.go (1)
  • 179-183: The refactored event emission logic now correctly utilizes the EventService from the keeper's environment, aligning with the PR's objective to enhance modularity and maintainability by decoupling from direct SDK context access. This change is consistent with the overall goal of migrating to use environment variables and context-based configurations. However, ensure that the EventManager method and the Emit function are properly defined and implemented in the EventService to avoid runtime errors.
x/gov/keeper/msg_server.go (4)
  • 105-118: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [31-114]

The changes in the SubmitProposal method, including the switch to ctx for context, adjustments in gas consumption handling, and updates in event emission, are well-aligned with the PR's objectives. However, ensure that the GetGasMeter and GetGasConfig methods are correctly implemented in the GasService to accurately manage gas consumption. Additionally, verify that the EventManager method in EventService properly handles the event emission to maintain consistency and avoid potential runtime issues.

  • 157-176: The modifications in the CancelProposal method, including the use of ctx for context and updates in event emission, enhance the method's clarity and maintainability. It's crucial to ensure that the HeaderService correctly retrieves header information, such as Time and Height, to accurately populate the CanceledTime and CanceledHeight fields in the response. This change supports the PR's goal of improving the governance module's configuration flexibility and operational efficiency.
  • 279-293: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [272-290]

The changes in the Deposit method, particularly the switch to ctx for context and the update in event emission, are consistent with the PR's objectives to utilize context.Context more extensively. Ensure that the EventService and its EventManager method are correctly implemented to handle event emissions properly. This adjustment contributes to the module's improved modularity and maintainability.

  • 378-387: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [370-384]

The SudoExec method's modifications, including the handler invocation and event emission updates, align with the PR's goals of enhancing the governance module's flexibility and maintainability. It's important to ensure that the router.Handler method correctly resolves the handler for the sudo-ed message and that the EventService accurately emits events to reflect the execution results. These changes contribute to a more modular and adaptable governance module.

tests/integration/gov/abci_test.go (11)
  • 43-43: The change from a direct call to gov.EndBlocker to using suite.GovKeeper.EndBlocker in the test TestUnregisteredProposal_InactiveProposalFails correctly reflects the refactor towards using the GovKeeper instance directly. This is a positive change for modularity and clarity.
  • 71-71: Similarly, in TestUnregisteredProposal_ActiveProposalFails, the update to use suite.GovKeeper.EndBlocker aligns with the refactor's goal to directly utilize the GovKeeper instance. This change enhances the test's clarity and maintainability.
  • 111-111: The modification in TestTickExpiredDepositPeriod to invoke EndBlocker through suite.GovKeeper instead of the previous approach is consistent with the refactor's objectives. It ensures that the test leverages the GovKeeper instance, improving code consistency across the test suite.
  • 161-161: In TestTickMultipleExpiredDepositPeriod, the use of suite.GovKeeper.EndBlocker for the first time point is correctly implemented, adhering to the refactor's direction. This change maintains the test's integrity while aligning with the new code structure.
  • 166-166: The subsequent call to suite.GovKeeper.EndBlocker within the same test function (TestTickMultipleExpiredDepositPeriod) further demonstrates consistency in applying the refactor across different scenarios within a single test. This ensures uniformity in how the EndBlocker logic is invoked.
  • 248-248: In TestProposalDepositRefundFailEndBlocker, the transition to suite.GovKeeper.EndBlocker is correctly applied, showcasing an adherence to the refactor's principles. This change is crucial for maintaining the test's functionality while embracing the new architectural approach.
  • 316-316: The update in TestTickPassedVotingPeriod to use suite.GovKeeper.EndBlocker is in line with the refactor, ensuring that the test accurately reflects the new code structure. This change is essential for the test's relevance and effectiveness.
  • 397-397: In TestProposalPassedEndblocker, the adoption of suite.GovKeeper.EndBlocker is correctly implemented, aligning with the refactor's goal to directly utilize the GovKeeper instance. This enhances the test's clarity and maintainability.
  • 452-452: The change in TestEndBlockerProposalHandlerFailed to invoke EndBlocker through suite.GovKeeper instead of the previous approach is consistent with the refactor's objectives. It ensures that the test leverages the GovKeeper instance, improving code consistency across the test suite.
  • 555-555: In TestExpeditedProposal_PassAndConversionToRegular, the use of suite.GovKeeper.EndBlocker for handling the expedited proposal scenario is correctly implemented, adhering to the refactor's direction. This change maintains the test's integrity while aligning with the new code structure.
  • 604-604: The subsequent call to suite.GovKeeper.EndBlocker within the same test function (TestExpeditedProposal_PassAndConversionToRegular) for validating the converted regular proposal is appropriately applied. This ensures uniformity in how the EndBlocker logic is invoked across different proposal scenarios.
simapp/app.go (1)
  • 389-389: The modification to the govKeeper declaration to include runtime.NewEnvironment(runtime.NewKVStoreService(keys[govtypes.StoreKey]), logger) as a parameter and remove appCodec aligns with the PR's objective to utilize environment variables more extensively. This change enhances the flexibility and configurability of the governance module by leveraging a more dynamic environment-based approach. Ensure that all references and usages of govKeeper throughout the codebase are updated to reflect this new signature.

Comment on lines 101 to 103
cacheCtx := k.environment.BranchService.Execute(ctx, func(ctx context.Context) error {
return nil
})
Copy link
Contributor

Choose a reason for hiding this comment

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

The replacement of sdkCtx.CacheContext() with k.environment.BranchService.Execute(ctx, func(ctx context.Context) error { return nil }) is a significant change. It's crucial to ensure that the branching logic previously handled by CacheContext is correctly implemented by BranchService.Execute. However, the provided lambda function does nothing, which might not replicate the original caching behavior intended for transaction simulation or temporary state changes. This needs further clarification or adjustment to ensure it fulfills its intended purpose.

Consider implementing the branching logic within the lambda function to accurately replicate the behavior of CacheContext.

x/gov/keeper/vote.go Fixed Show fixed Hide fixed
x/gov/keeper/abci.go Fixed Show fixed Hide fixed
x/gov/keeper/abci.go Fixed Show fixed Hide fixed
x/gov/keeper/abci.go Fixed Show fixed Hide fixed
x/gov/keeper/abci.go Fixed Show fixed Hide fixed
x/gov/keeper/abci.go Fixed Show fixed Hide fixed
@julienrbrt
Copy link
Member

I am taking over this as Sam is off, as I want to migrate x/gov to the message router service in #19571.

@julienrbrt julienrbrt self-assigned this Feb 27, 2024
@julienrbrt julienrbrt changed the base branch from main to julien/msgrouterservice March 4, 2024 08:48
x/gov/keeper/abci.go Fixed Show fixed Hide fixed
x/gov/keeper/abci.go Fixed Show fixed Hide fixed
Base automatically changed from julien/msgrouterservice to main March 4, 2024 10:29
@julienrbrt julienrbrt changed the title refactor(gov): migrate to use env var refactor(x/gov): migrate to use env var Mar 4, 2024
@julienrbrt julienrbrt marked this pull request as ready for review March 4, 2024 10:58
@julienrbrt julienrbrt removed their assignment Mar 4, 2024
@julienrbrt
Copy link
Member

As I did most of the changes in this PR, I'll refrain myself from reviewing.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 1

Configuration used: .coderabbit.yml

Commits Files that changed from the base of the PR and between 377dfe6 and 0051ae1.
Files selected for processing (5)
  • UPGRADING.md (1 hunks)
  • core/gas/service.go (2 hunks)
  • simapp/app.go (1 hunks)
  • tests/integration/gov/keeper/keeper_test.go (1 hunks)
  • x/accounts/internal/implementation/context.go (1 hunks)
Additional comments: 5
core/gas/service.go (1)
  • 43-43: The addition of the GetGasConfig method to the Service interface is a significant enhancement for dynamic gas configuration management. It's crucial to ensure that all implementations of the Service interface are updated to include this new method to maintain compatibility.
tests/integration/gov/keeper/keeper_test.go (1)
  • 109-109: The update to initialize govKeeper using runtime.NewEnvironment and log.NewNopLogger() aligns with the migration towards a more flexible configuration system. Ensure that this change is consistently applied across all tests and modules to maintain uniformity and leverage the benefits of the new environment-based configuration.
x/accounts/internal/implementation/context.go (1)
  • 159-161: The addition of the GetGasConfig method to the gasService struct is a valuable enhancement for accessing dynamic gas configurations. It's essential to ensure that this method is properly integrated and utilized wherever gas configurations are needed, enhancing the system's flexibility and adaptability.
simapp/app.go (1)
  • 383-384: The modification of the govKeeper declaration to include runtime.NewEnvironment(runtime.NewKVStoreService(keys[govtypes.StoreKey]), logger) instead of the previous parameters (runtime.NewKVStoreService(keys[govtypes.StoreKey]), app.AuthKeeper, app.BankKeeper) aligns with the PR's objective to enhance configuration flexibility and operational manageability by leveraging environment variables. This change simplifies the initialization by encapsulating the environment setup within a single Environment struct, which is a positive step towards a more modular and maintainable codebase.

However, ensure that the removal of direct references to app.AuthKeeper and app.BankKeeper in the govKeeper initialization does not impact any governance module functionalities that might rely on these keepers. It's crucial to verify that all necessary functionalities are either preserved or suitably adapted within the new Environment struct to maintain the module's integrity and capabilities.

UPGRADING.md (1)
  • 213-217: The documentation correctly updates the Gov v1beta1 proposal handler to accept a context.Context instead of sdk.Context. This change aligns with the migration towards more standard context management and compatibility with server/v2. However, it's crucial to ensure that developers are aware of the need to unwrap the sdk context when continuing to use baseapp, as this might be a common source of confusion during the migration process.

Comment on lines +54 to +62
type GasConfig struct {
HasCost Gas
DeleteCost Gas
ReadCostFlat Gas
ReadCostPerByte Gas
WriteCostFlat Gas
WriteCostPerByte Gas
IterNextCostFlat Gas
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The GasConfig struct introduces various fields to manage gas costs dynamically. It's well-structured and covers a comprehensive range of gas-related configurations. However, consider adding documentation comments for each field to explain their purpose and usage clearly, enhancing code readability and maintainability.

+ // GasConfig holds the configuration for gas costs in the system.
type GasConfig struct {
+ // HasCost defines the gas cost for checking the existence of an item.
	HasCost          Gas
+ // DeleteCost defines the gas cost for deleting an item.
	DeleteCost       Gas
+ // ReadCostFlat defines the flat gas cost for reading an item.
	ReadCostFlat     Gas
+ // ReadCostPerByte defines the gas cost per byte for reading an item.
	ReadCostPerByte  Gas
+ // WriteCostFlat defines the flat gas cost for writing an item.
	WriteCostFlat    Gas
+ // WriteCostPerByte defines the gas cost per byte for writing an item.
	WriteCostPerByte Gas
+ // IterNextCostFlat defines the flat gas cost for iterating to the next item.
	IterNextCostFlat Gas
}

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.

Suggested change
type GasConfig struct {
HasCost Gas
DeleteCost Gas
ReadCostFlat Gas
ReadCostPerByte Gas
WriteCostFlat Gas
WriteCostPerByte Gas
IterNextCostFlat Gas
}
// GasConfig holds the configuration for gas costs in the system.
type GasConfig struct {
// HasCost defines the gas cost for checking the existence of an item.
HasCost Gas
// DeleteCost defines the gas cost for deleting an item.
DeleteCost Gas
// ReadCostFlat defines the flat gas cost for reading an item.
ReadCostFlat Gas
// ReadCostPerByte defines the gas cost per byte for reading an item.
ReadCostPerByte Gas
// WriteCostFlat defines the flat gas cost for writing an item.
WriteCostFlat Gas
// WriteCostPerByte defines the gas cost per byte for writing an item.
WriteCostPerByte Gas
// IterNextCostFlat defines the flat gas cost for iterating to the next item.
IterNextCostFlat Gas
}

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 4

Configuration used: .coderabbit.yml

Commits Files that changed from the base of the PR and between 0051ae1 and 1ef95f6.
Files selected for processing (7)
  • runtime/gas.go (2 hunks)
  • simapp/app.go (1 hunks)
  • tests/integration/gov/abci_test.go (11 hunks)
  • tests/integration/gov/keeper/keeper_test.go (1 hunks)
  • x/gov/keeper/abci.go (11 hunks)
  • x/gov/keeper/abci_internal_test.go (1 hunks)
  • x/gov/keeper/msg_server.go (9 hunks)
Files skipped from review as they are similar to previous changes (2)
  • simapp/app.go
  • tests/integration/gov/keeper/keeper_test.go
Additional comments: 24
x/gov/keeper/abci_internal_test.go (1)
  • 19-25: The implementation of InvokeUntyped in mockRouter correctly simulates the behavior of causing a panic based on the panic field. This is a good practice for testing error handling in functions that interact with external components. No changes are needed here.
runtime/gas.go (2)
  • 33-35: The GetGasConfig method in GasService provides a structured way to retrieve gas configurations. This is a good addition for enhancing flexibility in gas management. Ensure that sdk.UnwrapSDKContext(ctx).KVGasConfig() is properly implemented and tested to avoid runtime errors.
  • 106-136: The GasConfig struct and its methods provide a clear and accessible way to interact with gas cost parameters. This is a significant improvement for code readability and maintainability. However, ensure that the underlying gas.GasConfig struct fields are correctly initialized and that there's comprehensive test coverage for these methods to prevent unexpected behavior.
x/gov/keeper/abci.go (2)
  • 23-23: The updated function signature of EndBlocker to accept context.Context and return an error aligns with Go's standard context management and error handling practices. This change enhances the function's flexibility and error reporting capabilities.
  • 273-281: The safeExecuteHandler function provides a robust way to execute messages while safely handling panics. This is a critical addition for ensuring the stability of the governance module. The use of defer for panic recovery is a good practice. Ensure comprehensive testing of this function to cover various panic scenarios.
x/gov/keeper/msg_server.go (8)
  • 8-10: The addition of new imports, including google.golang.org/protobuf/runtime/protoiface and various cosmossdk.io packages, aligns with the PR's objectives to refactor the governance module to utilize environment variables and context-based configurations more extensively. Ensure that these new dependencies are properly managed and versioned to avoid potential conflicts or issues.
  • 34-34: The method signature for SubmitProposal has been updated to use context.Context instead of the previous sdk.Context. This change is consistent with the PR's goal of migrating towards a more standard and flexible context management approach. It's crucial to verify that all invocations of this method throughout the codebase have been updated accordingly to prevent runtime errors.
  • 100-101: The gas consumption logic has been adjusted to use the new GasService and GasConfig structs, which is a positive change towards a more structured and dynamic approach to handling gas configurations. However, ensure that the gas consumption values are appropriately calibrated to prevent over or underestimation of gas costs, which could impact transaction processing efficiency.
  • 111-116: The event emission logic has been modified to utilize the environment's event service instead of direct SDK context access. This decouples the event management from the SDK context, making it more testable and maintainable. Ensure that all events are correctly emitted and captured by the system's event listeners to maintain functionality.
  • 164-164: The CancelProposal method's signature has been updated similarly to SubmitProposal, reflecting the migration to context.Context. This consistency in context usage across methods is commendable. Again, ensure that all calls to this method are updated to use the new context type.
Verification successful

Given the script did not produce any output, it suggests that there are no invocations of CancelProposal using an outdated context type. This aligns with the expectation that the method's signature has been updated to use context.Context and that all calls to this method have been correctly updated across the codebase. Therefore, the review comment appears to be consistent with the codebase as verified.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Search for invocations of CancelProposal with the old context type.
ast-grep --lang go --pattern $'CancelProposal($_, $_)'

Length of output: 55

* 190-190: The introduction of the `ExecLegacyContent` method is part of the efforts to maintain backward compatibility while transitioning to the new architecture. It's important to ensure that the legacy content is correctly handled and that the respective handlers are properly invoked to maintain the integrity of the governance process. * 280-280: The `Deposit` method has been updated to reflect the new context management approach and the refined logic for handling deposits. This change is in line with the PR's objectives to streamline the governance module's code structure and logic. Ensure that the deposit validation logic (`validateDeposit`) is robust and correctly prevents invalid or negative deposit amounts. * 376-387: The `SudoExec` method introduces a branching logic using the `BranchService`. This is a significant change that requires careful testing to ensure that the branching logic is correctly implemented and that the sudo-ed messages are executed as expected without unintended side effects.
tests/integration/gov/abci_test.go (11)
  • 43-43: The call to suite.GovKeeper.EndBlocker(ctx) is correctly used to simulate the end of a block and process any pending governance actions. However, it's important to ensure that the context (ctx) passed to EndBlocker is correctly prepared for the test scenario, including setting the appropriate block time and height.
  • 71-71: Similar to the previous comment, the use of suite.GovKeeper.EndBlocker(ctx) here is appropriate for testing the governance module's logic at the end of a block. Ensure that the test context is accurately set up to reflect the scenario being tested, especially regarding the block time and any other relevant state.
  • 111-111: The use of suite.GovKeeper.EndBlocker(ctx) in this test case is correct for simulating the governance logic at block end. It's crucial to verify that the test setup, including the context and any mock data, accurately represents the test conditions to ensure meaningful test results.
  • 161-161: The call to suite.GovKeeper.EndBlocker(ctx) is used appropriately to test the governance module's end-of-block logic. As with other tests, ensure that the context and test setup accurately reflect the intended test scenario, including the timing of proposal submission and deposit periods.
  • 166-166: This additional call to suite.GovKeeper.EndBlocker(ctx) within the same test function is used to simulate another block end. It's important to ensure that the context (ctx) is correctly updated between calls to EndBlocker to reflect the passage of time or any other changes relevant to the test scenario.
  • 248-248: The call to suite.GovKeeper.EndBlocker(ctx) here is used to simulate the end of the voting period and process the proposal. The test checks for the correct handling of deposit refunds or burns in case of errors. It's crucial to ensure that the test setup accurately simulates the conditions under which the deposit refund or burn would fail, including the state of the governance module account.
  • 316-316: The use of suite.GovKeeper.EndBlocker(ctx) in this test case is appropriate for simulating the governance logic at the end of the voting period. Ensure that the test context is set up correctly, especially regarding the proposal type and the timing of the voting period, to accurately test the intended behavior.
  • 397-397: This call to suite.GovKeeper.EndBlocker(ctx) is used to simulate the governance logic at the end of the voting period for a proposal. It's important to ensure that the test setup, including the context and any mock data, accurately represents the conditions under which the proposal is expected to pass or fail.
  • 452-452: The call to suite.GovKeeper.EndBlocker(ctx) here is used to simulate the governance logic at the end of the voting period, specifically testing the handling of proposals that fail execution. Ensure that the test setup accurately represents the conditions under which a proposal would fail execution, including the state of the governance module account and any relevant message handlers.
  • 555-555: The use of suite.GovKeeper.EndBlocker(ctx) in this test case is correct for simulating the governance logic at the end of the expedited voting period. It's crucial to ensure that the test setup, including the context and any mock data, accurately represents the conditions under which an expedited proposal is expected to pass or fail and be converted to a regular proposal.
  • 604-604: This call to suite.GovKeeper.EndBlocker(ctx) is used to simulate the governance logic at the end of the voting period for a converted regular proposal. Ensure that the test setup, including the context and any mock data, accurately represents the conditions under which the converted regular proposal is expected to pass or fail.

x/gov/keeper/abci_internal_test.go Show resolved Hide resolved
x/gov/keeper/abci_internal_test.go Show resolved Hide resolved
x/gov/keeper/abci.go Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 4

Configuration used: .coderabbit.yml

Commits Files that changed from the base of the PR and between 1ef95f6 and e1fdef9.
Files selected for processing (2)
  • UPGRADING.md (2 hunks)
  • simapp/app.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • simapp/app.go
Additional comments: 66
UPGRADING.md (66)
  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [4-4]

The term "SimApp" is correctly used in the context of Cosmos SDK and does not require correction.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [18-18]

The diff block correctly demonstrates how to update the client.Context with new codecs. The instructions are clear and concise.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [27-27]

The term "depinject" is specific to the Cosmos SDK's dependency injection mechanism and is used correctly here.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [38-38]

The term "depinject" is specific to the Cosmos SDK's dependency injection mechanism and is used correctly here.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [42-42]

The diff block correctly demonstrates how to refactor the module manager registration in app.go. The instructions are clear and concise.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [52-52]

The term "AnteHandlers" is specific to the Cosmos SDK and refers to a set of decorators used in transaction processing. The term is used correctly here.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [60-60]

The term "nonces" is used correctly in the context of blockchain transactions, referring to numbers used once to ensure transactions are processed in order.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [132-132]

The term "Protobuf" is correctly used here to refer to Protocol Buffers, a method of serializing structured data.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [134-134]

The term "CometBFT" is correctly used in the context of the Cosmos SDK, referring to the consensus engine.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [145-145]

The term "baseapp" is specific to the Cosmos SDK and is used correctly here to refer to the basic application framework.

  • 151-151: The code snippet correctly demonstrates how to instantiate a new keeper with the environment passed in. The example is clear and relevant.
  • 166-166: The term "depinject" is specific to the Cosmos SDK's dependency injection mechanism and is used correctly here.
  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [170-170]

The term "Params" is correctly used here to refer to module parameters within the Cosmos SDK.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [176-176]

The code snippet correctly demonstrates how to update the genesis interface to use context.Context instead of sdk.Context. This change aligns with the migration towards standard Go contexts for better flexibility and interoperability.

  • 224-224: The term "baseapp" is specific to the Cosmos SDK and is used correctly here to refer to the basic application framework.
  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [273-273]

The term "CometBFT" is correctly used in the context of the Cosmos SDK, referring to the consensus engine.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [313-313]

The term "BaseApp" is specific to the Cosmos SDK and is used correctly here to refer to the basic application framework.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [322-322]

The terms "BeginBlock" and "Endblock" are specific to the Cosmos SDK's lifecycle of a block. The usage here is correct, indicating changes in their accessibility.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [327-327]

The sequence of operations described here is accurate and relevant for understanding the execution order within the Cosmos SDK's block processing.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [329-329]

The introduction of ExtendVote and VerifyVoteExtension methods is correctly described, highlighting their role in extending and verifying pre-commit votes within the Cosmos SDK.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [337-337]

The explanation of the SetPreBlocker method and its significance in running PreBlock before other modules is clear and accurate.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [374-374]

The description of how events are now emitted through FinalizeBlock instead of directly populating the log section of abci.TxResult is accurate and reflects changes in the Cosmos SDK.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [384-384]

The term "Confix" is introduced as a new SDK tool for configuration management. While the name might seem like a typo, it is used correctly in the context of the Cosmos SDK.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [399-399]

The term "gRPC-Web" is correctly capitalized and used in the context of the Cosmos SDK to refer to the gRPC Web protocol.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [405-405]

The databases mentioned (ClevelDB, BoltDB, and BadgerDB) are correctly identified as no longer supported, aligning with the Cosmos SDK's move towards more efficient database solutions.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [408-408]

The term "Protobuf" is correctly used here to refer to Protocol Buffers, a method of serializing structured data.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [416-416]

The summary of proto annotation requirements is accurate and provides necessary guidance for module developers to ensure compatibility with both Amino JSON and Protobuf codecs.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [418-418]

The removal of the gogoproto.goproto_stringer = false annotation from most proto files is correctly described, indicating a change in how the String() method is generated for types.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [421-421]

The term "SimApp" is correctly used in the context of Cosmos SDK and does not require correction.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [428-428]

The explanation of module assertions and wiring changes is accurate and reflects the Cosmos SDK's evolution towards more modular and flexible app design.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [432-432]

The update to the NewKeeper function across various modules to take a KVStoreService instead of a StoreKey is correctly described, highlighting an important architectural change.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [450-450]

The code snippet correctly demonstrates how to update the ConsensusParamsKeeper instantiation in app.go. This change aligns with the Cosmos SDK's migration towards more explicit and modular keeper management.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [463-463]

The term "CometBFT" is correctly used in the context of the Cosmos SDK, referring to the consensus engine.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [465-465]

The explanation of the changes required for depinject / app v2 users regarding logger supply is clear and accurately reflects the Cosmos SDK's dependency injection mechanism.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [486-486]

The term "ModuleBasics" is specific to the Cosmos SDK and is used correctly here to refer to the basic module manager.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [505-505]

The code snippet correctly demonstrates how to use the module.NewBasicManagerFromManager function for manual module wiring in app.go. This change aligns with the Cosmos SDK's move towards more explicit module management.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [509-509]

The introduction of AutoCLI and its automatic addition of custom module commands to the root command is correctly described, highlighting an important usability improvement in the Cosmos SDK.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [554-554]

The explanation of the store module extraction to a standalone module and the renaming of imports is accurate and reflects the Cosmos SDK's modularization efforts.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [561-561]

The update to state streaming service registration in app.go is correctly described, providing clear instructions for developers to adapt to the new method.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [571-571]

The changes to the TxConfig interface and the introduction of a new sign mode producing more human-readable output are accurately described, highlighting improvements in transaction handling within the Cosmos SDK.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [597-597]

The explanation of the x/authz module's updates, including changes to NewMsgGrant and NewGrant, is clear and accurately reflects the Cosmos SDK's enhancements in authorization management.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [610-610]

The description of the keyring refactor, including changes to interfaces and serialization, is accurate and provides necessary guidance for developers to adapt to the new keyring structure.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [627-627]

The introduction of a postHandler as a counterpart to the anteHandler for post-message execution logic is correctly described, highlighting an important addition to the Cosmos SDK's transaction processing flow.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [639-639]

The explanation of the IAVL "fast" index introduction and its impact on query performance is accurate and provides important information for node operators regarding the upgrade process.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [666-666]

The summary of changes in the x/params module and the migration towards module-specific parameter management is accurate and reflects the Cosmos SDK's architectural evolution.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [674-674]

The description of improvements in the x/gov module, including support for expedited proposals and proposal cancellation, is clear and accurately reflects the Cosmos SDK's governance enhancements.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [688-688]

The explanation of the x/consensus module introduction and the migration process for Tendermint consensus parameters is accurate and provides necessary guidance for developers to adapt to the new module.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [698-698]

The description of the x/nft module's changes regarding classID and nftID validation is accurate and highlights an important flexibility improvement for NFT developers within the Cosmos SDK.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [706-706]

The explanation of Ledger support generalization and the introduction of new key types is accurate and provides important information for developers integrating hardware wallets with the Cosmos SDK.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [716-716]

The summary of API changes, including package renamings and method updates, is accurate and provides a clear overview of the Cosmos SDK's evolution towards a more modular and flexible architecture.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [726-726]

The introduction of new packages for error handling, math types, and standalone modules is accurately described, highlighting the Cosmos SDK's ongoing efforts towards better modularity and clarity in its codebase.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [738-738]

The explanation of the x/evidence module extraction to a standalone module and the renaming of imports is accurate and reflects the Cosmos SDK's modularization efforts.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [746-746]

The description of the Rosetta tool's move to its own repository and the implications for node operators and developers is accurate and provides important information regarding the Cosmos SDK's tooling ecosystem.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [754-754]

The summary of the migration to CometBFT as the default consensus engine and the necessary steps for chains to adapt is accurate and provides necessary guidance for developers to ensure compatibility with the new consensus engine.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [762-762]

The explanation of simulation changes, including the removal of RandomizedParams from the AppModuleSimulation interface, is clear and accurately reflects the Cosmos SDK's enhancements in simulation testing.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [770-770]

The introduction of new gRPC services and the necessary steps for app developers to register these services in their application construction is accurately described, highlighting improvements in the Cosmos SDK's gRPC interface.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [778-778]

The summary of changes in the AppModule interface, including the removal of legacy methods and the migration to extension interfaces, is accurate and provides a clear overview of the Cosmos SDK's evolution towards a more modular app design.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [786-786]

The explanation of the simapp package's intended usage and the introduction of the runtime.AppI interface for application testing is accurate and provides important guidance for developers to leverage the Cosmos SDK's testing utilities effectively.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [794-794]

The description of the store module extraction to a standalone module and the renaming of imports is accurate and reflects the Cosmos SDK's modularization efforts.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [802-802]

The update to state streaming service registration in app.go is correctly described, providing clear instructions for developers to adapt to the new method.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [812-812]

The changes to the TxConfig interface and the introduction of a new sign mode producing more human-readable output are accurately described, highlighting improvements in transaction handling within the Cosmos SDK.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [828-828]

The explanation of the x/authz module's updates, including changes to NewMsgGrant and NewGrant, is clear and accurately reflects the Cosmos SDK's enhancements in authorization management.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [841-841]

The description of the keyring refactor, including changes to interfaces and serialization, is accurate and provides necessary guidance for developers to adapt to the new keyring structure.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [858-858]

The introduction of a postHandler as a counterpart to the anteHandler for post-message execution logic is correctly described, highlighting an important addition to the Cosmos SDK's transaction processing flow.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [870-870]

The explanation of the IAVL "fast" index introduction and its impact on query performance is accurate and provides important information for node operators regarding the upgrade process.

  • 148-167: > 📝 NOTE

This review was outside the diff hunks, and no overlapping diff hunk was found. Original lines [899-899]

The summary of changes in the x/params module and the migration towards module-specific parameter management is accurate and reflects the Cosmos SDK's architectural evolution.

UPGRADING.md Outdated Show resolved Hide resolved
UPGRADING.md Outdated Show resolved Hide resolved
@julienrbrt julienrbrt changed the title refactor(x/gov): migrate to use env var refactor(x/gov)!: migrate to use env var Mar 4, 2024
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 1

Configuration used: .coderabbit.yml

Commits Files that changed from the base of the PR and between e1fdef9 and 599279c.
Files selected for processing (5)
  • UPGRADING.md (2 hunks)
  • x/gov/keeper/common_test.go (2 hunks)
  • x/gov/keeper/msg_server.go (9 hunks)
  • x/gov/keeper/msg_server_test.go (1 hunks)
  • x/gov/keeper/proposal.go (8 hunks)
Files skipped from review as they are similar to previous changes (1)
  • x/gov/keeper/msg_server.go
Additional comments: 10
x/gov/keeper/common_test.go (2)
  • 115-115: The introduction of the environment variable using runtime.NewEnvironment is a significant change. It's crucial to ensure that all dependencies and services required by the govKeeper are correctly initialized and passed through this environment. This change aligns with the goal of enhancing configuration flexibility and operational manageability.
  • 135-135: The modification to initialize govKeeper with the environment parameter instead of storeService and baseApp.MsgServiceRouter() directly is a good practice. It encapsulates the dependencies within the environment, making the code cleaner and more modular. However, ensure that all functionalities previously provided by storeService and baseApp.MsgServiceRouter() are adequately handled by the environment.
x/gov/keeper/proposal.go (7)
  • 13-13: Adding the "cosmossdk.io/core/event" import is necessary for the updated event emission logic. This change supports the migration towards a more modular and context-based architecture by utilizing the event package for event management.
  • 86-87: Replacing k.router.Handler(msg) with k.environment.RouterService.MessageRouterService().CanInvoke(ctx, msg) is a significant change. It aligns with the goal of decoupling and modularizing the message routing logic. Ensure that the CanInvoke method correctly implements the logic previously handled by Handler to maintain the integrity of message processing.
  • 100-107: The introduction of v1.LegacyContentFromMessage(msg) and the use of k.legacyRouter for handling legacy content is a thoughtful approach to maintain backward compatibility while transitioning to the new architecture. It's important to verify that all legacy content types are correctly handled and that the transition does not introduce any regressions.
  • 127-127: The use of k.environment.HeaderService.GetHeaderInfo(ctx).Time to obtain the current time for setting the proposal submission time is a good practice. It ensures that the time is consistently sourced from the same context-based service across the application, enhancing maintainability and testability.
  • 147-150: Updating the event emission logic from sdkCtx.EventManager() to k.environment.EventService.EventManager(ctx).EmitKV() is a positive change. It decouples the event management from the SDK context, aligning with the overall goal of migrating towards a more modular and context-based architecture. Ensure that all events are correctly emitted and handled in the new system.
  • 189-189: The replacement of direct time access with k.environment.HeaderService.GetHeaderInfo(ctx).Time for determining the current time during proposal cancellation is consistent with the changes made elsewhere in the code. This consistency is crucial for maintainability and ensures that the time source remains uniform across the application.
  • 220-220: Replacing sdkCtx.Logger() with k.Logger().Info() for logging within the CancelProposal function is in line with the migration towards using the environment's logging service. This change enhances the modularity and flexibility of the logging mechanism. Ensure that the logging level and format are appropriately maintained.
x/gov/keeper/msg_server_test.go (1)
  • 2134-2134: The change in the expected error message from "unrecognized message route" to "unknown message" in the TestMsgSudoExec function likely reflects updates in the error handling or message routing logic within the governance module or the message router service. Ensure this change aligns with the updated logic and intended behavior.

UPGRADING.md Outdated Show resolved Hide resolved
UPGRADING.md Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Review Status

Actionable comments generated: 7

Configuration used: .coderabbit.yml

Commits Files that changed from the base of the PR and between 3e63309 and b457ce2.
Files selected for processing (25)
  • UPGRADING.md (2 hunks)
  • core/gas/service.go (2 hunks)
  • runtime/gas.go (2 hunks)
  • simapp/app.go (1 hunks)
  • tests/integration/gov/abci_test.go (11 hunks)
  • tests/integration/gov/genesis_test.go (1 hunks)
  • tests/integration/gov/keeper/keeper_test.go (1 hunks)
  • x/accounts/internal/implementation/context.go (1 hunks)
  • x/gov/CHANGELOG.md (1 hunks)
  • x/gov/depinject.go (4 hunks)
  • x/gov/keeper/abci.go (11 hunks)
  • x/gov/keeper/abci_internal_test.go (1 hunks)
  • x/gov/keeper/common_test.go (2 hunks)
  • x/gov/keeper/deposit.go (2 hunks)
  • x/gov/keeper/hooks_test.go (3 hunks)
  • x/gov/keeper/keeper.go (5 hunks)
  • x/gov/keeper/migrations.go (1 hunks)
  • x/gov/keeper/msg_server.go (9 hunks)
  • x/gov/keeper/msg_server_test.go (1 hunks)
  • x/gov/keeper/proposal.go (8 hunks)
  • x/gov/keeper/vote.go (2 hunks)
  • x/gov/module.go (1 hunks)
  • x/gov/types/v1beta1/content.go (2 hunks)
  • x/gov/types/v1beta1/proposal.go (2 hunks)
  • x/params/proposal_handler.go (2 hunks)
Files skipped from review as they are similar to previous changes (21)
  • core/gas/service.go
  • runtime/gas.go
  • simapp/app.go
  • tests/integration/gov/abci_test.go
  • tests/integration/gov/genesis_test.go
  • tests/integration/gov/keeper/keeper_test.go
  • x/accounts/internal/implementation/context.go
  • x/gov/depinject.go
  • x/gov/keeper/abci_internal_test.go
  • x/gov/keeper/common_test.go
  • x/gov/keeper/deposit.go
  • x/gov/keeper/hooks_test.go
  • x/gov/keeper/migrations.go
  • x/gov/keeper/msg_server.go
  • x/gov/keeper/msg_server_test.go
  • x/gov/keeper/proposal.go
  • x/gov/keeper/vote.go
  • x/gov/module.go
  • x/gov/types/v1beta1/content.go
  • x/gov/types/v1beta1/proposal.go
  • x/params/proposal_handler.go
Additional comments: 15
x/gov/CHANGELOG.md (1)
  • 60-67: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [63-73]

The changelog entries under "API Breaking Changes" and "Deprecated" sections provide a clear summary of the significant changes introduced in this PR. However, it's essential to ensure that all changes are accurately reflected and that the links to PRs/issues are correct and functional. Additionally, consider adding more context or examples for complex changes to aid understanding.

  • Ensure all PR and issue links are valid.
  • For complex changes, consider adding a brief explanation or example directly in the changelog or linking to documentation that does.
x/gov/keeper/keeper.go (4)
  • 34-36: The addition of the environment field to the Keeper struct is a significant change that aligns with the PR's objective to migrate module configuration to use environment variables. This change enhances the flexibility and manageability of the governance module by leveraging the appmodule.Environment struct for configuration.
  • Ensure that the environment field is properly initialized and used throughout the module to access environment-specific settings and services.
  • 85-87: The update to the NewKeeper function signature to accept appmodule.Environment as a parameter is a critical change that supports the migration to environment variable-based configuration. This change simplifies the module's configuration management and aligns with best practices for modern application development.
  • Verify that all calls to NewKeeper throughout the Cosmos SDK codebase have been updated to pass the appmodule.Environment parameter.
  • Ensure that the environment parameter is used effectively within the Keeper to access and manage module-specific settings and services.
  • 112-114: The initialization of the Keeper struct with the environment parameter is correctly implemented. This change is part of the broader effort to migrate the module to use environment variables for configuration, enhancing the module's flexibility and manageability.
  • Confirm that the environment field is utilized appropriately within the Keeper methods to access environment-specific settings and services.
  • 172-173: The modification to the Logger method to access the logger from the environment field instead of the context directly is a good practice. It centralizes the logging configuration and makes it easier to manage across the module.
  • Ensure that the logger obtained from the environment is used consistently for logging within the x/gov module.
x/gov/keeper/abci.go (7)
  • 23-23: The function signature of EndBlocker has been updated to use context.Context instead of sdk.Context. This aligns with modern Go practices and improves compatibility with other Go libraries and frameworks. However, ensure that all callers of this function are updated to pass the correct context type.
  • 29-30: The use of collections.NewPrefixUntilPairRange with k.environment.HeaderService.GetHeaderInfo(ctx).Time as a parameter is a good approach to query proposals based on time. However, ensure that the HeaderService and its method GetHeaderInfo are thoroughly tested, especially for edge cases around time zones and leap seconds.
  • 56-63: The conditional logic for refunding or burning deposits based on params.BurnProposalDepositPrevote is clear and concise. However, ensure that the RefundAndDeleteDeposits and DeleteAndBurnDeposits methods are well-documented and tested, particularly for their side effects on the proposal's state and the overall system's state.
Verification successful

The verification process has identified that both RefundAndDeleteDeposits and DeleteAndBurnDeposits methods are indeed referenced in the deposit_test.go test file, indicating that tests have been written to cover these methods. This satisfies the initial request to ensure that these methods are well-documented and tested, particularly for their side effects on the proposal's state and the overall system's state. However, the quality and coverage of these tests were not assessed, and it is recommended to review the tests in deposit_test.go for comprehensiveness.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the RefundAndDeleteDeposits and DeleteAndBurnDeposits methods
# This is a placeholder for actual test commands or scripts
echo "Ensure comprehensive tests for RefundAndDeleteDeposits and DeleteAndBurnDeposits"

Length of output: 170



Script:

#!/bin/bash
# Locate the method definitions of RefundAndDeleteDeposits and DeleteAndBurnDeposits
rg "func (.*RefundAndDeleteDeposits|.*DeleteAndBurnDeposits)" -C 5

# Attempt to locate test files for these methods
fd "RefundAndDeleteDeposits|DeleteAndBurnDeposits" --glob "*_test.go"

Length of output: 1808



Script:

#!/bin/bash
# Correctly search for test files related to RefundAndDeleteDeposits and DeleteAndBurnDeposits
fd "test.go$" | xargs rg "RefundAndDeleteDeposits|DeleteAndBurnDeposits"

Length of output: 250

* 211-218: The logic for converting expedited or optimistic proposals to standard proposals upon failure is clear and follows the specified rules. Ensure that the implications of changing the proposal type and extending the voting period are well-documented and tested, especially regarding how they affect the proposal's lifecycle and governance processes.
Verification successful

The executed scripts aimed to verify the conversion of expedited/optimistic proposals to standard proposals and to check for tests covering this conversion and its implications on the proposal lifecycle. The scripts searched the codebase for mentions of expedited and optimistic proposals and their conversion to standard proposals. The output provided several references to documentation, code comments, and test cases that describe the behavior and implementation of expedited and optimistic proposals, including their conversion to standard proposals under certain conditions.

The references found in the UPGRADING.md, README.md, CHANGELOG.md, and various .go files confirm the implementation of expedited and optimistic proposals, their parameters, and the conditions under which they are converted to standard proposals. Additionally, the presence of test cases specifically mentioning expedited proposals and their conversion to standard proposals indicates that there is test coverage for this functionality.

Based on the information gathered from the script outputs, it can be concluded that the codebase does implement the logic for converting expedited/optimistic proposals to standard proposals upon failure, and there are tests covering this conversion and its implications on the proposal lifecycle.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the conversion of expedited/optimistic proposals to standard proposals
# This is a placeholder for actual test commands or scripts
echo "Ensure tests cover conversion and implications on proposal lifecycle"

Length of output: 146



Script:

#!/bin/bash
# Search for the implementation of the conversion logic in the codebase
rg "expedited|optimistic.*standard.*proposal" --context 5

# Search for tests related to the conversion of expedited/optimistic proposals to standard proposals
rg "test.*expedited|test.*optimistic.*standard.*proposal" --context 5

Length of output: 133273

* 239-239: Updating the proposal's status and other attributes after tallying votes is crucial. Ensure that the `Proposals.Set` method is robust, especially in handling concurrent updates to the same proposal, to prevent data races or inconsistencies. * 273-281: The `safeExecuteHandler` function is a good practice for preventing panics from affecting the chain's stability. Ensure that this function is thoroughly tested with various message types and scenarios that could potentially cause panics. * 295-305: > 📝 **NOTE** > This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [288-316]

The failUnsupportedProposal function encapsulates the logic for handling proposals that cannot be processed. This is a good example of code organization. Ensure that the implications of failing a proposal in this manner are well-understood and documented, especially regarding how it affects the proposal's lifecycle and governance processes.

UPGRADING.md (3)
  • 151-151: The example provided for x/circuit seems to be using a placeholder module name. Ensure that this is intentional and correctly represents a generic example, or update it with a real module name if necessary.
  • 157-157: The diff code snippet for updating the govKeeper instantiation correctly demonstrates the migration to using the runtime.NewEnvironment function. This change aligns with the broader SDK updates for environment handling and should improve modularity and testability.
  • 221-225: The update to the Gov v1beta1 proposal handler to accept a context.Context instead of sdk.Context is a significant change that aligns with the migration to server/v2. This change enhances compatibility and flexibility for proposal handlers. Ensure that all custom proposal handlers are updated accordingly to avoid runtime issues.

Comment on lines +1 to 45
package keeper

import (
"context"
"errors"
"fmt"
"time"

"google.golang.org/protobuf/runtime/protoiface"

"cosmossdk.io/collections"
"cosmossdk.io/core/event"
"cosmossdk.io/core/router"
"cosmossdk.io/log"
"cosmossdk.io/x/gov/keeper"
"cosmossdk.io/x/gov/types"
v1 "cosmossdk.io/x/gov/types/v1"

"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
)

// EndBlocker is called every block.
func EndBlocker(ctx sdk.Context, keeper *keeper.Keeper) error {
func (k Keeper) EndBlocker(ctx context.Context) error {
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)

logger := keeper.Logger(ctx)
logger := k.Logger()
// delete dead proposals from store and returns theirs deposits.
// A proposal is dead when it's inactive and didn't get enough deposit on time to get into voting phase.
rng := collections.NewPrefixUntilPairRange[time.Time, uint64](ctx.HeaderInfo().Time)
err := keeper.InactiveProposalsQueue.Walk(ctx, rng, func(key collections.Pair[time.Time, uint64], _ uint64) (bool, error) {
proposal, err := keeper.Proposals.Get(ctx, key.K2())
rng := collections.NewPrefixUntilPairRange[time.Time, uint64](k.environment.HeaderService.GetHeaderInfo(ctx).Time)
err := k.InactiveProposalsQueue.Walk(ctx, rng, func(key collections.Pair[time.Time, uint64], _ uint64) (bool, error) {
proposal, err := k.Proposals.Get(ctx, key.K2())
if err != nil {
// if the proposal has an encoding error, this means it cannot be processed by x/gov
// this could be due to some types missing their registration
// instead of returning an error (i.e, halting the chain), we fail the proposal
if errors.Is(err, collections.ErrEncoding) {
proposal.Id = key.K2()
if err := failUnsupportedProposal(logger, ctx, keeper, proposal, err.Error(), false); err != nil {
if err := failUnsupportedProposal(logger, ctx, k, proposal, err.Error(), false); err != nil {
return false, err
}

if err = keeper.DeleteProposal(ctx, proposal.Id); err != nil {
if err = k.DeleteProposal(ctx, proposal.Id); err != nil {
return false, err
}

Copy link
Contributor

Choose a reason for hiding this comment

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

📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [31-52]

The error handling logic within the InactiveProposalsQueue.Walk method call is comprehensive, especially the handling of collections.ErrEncoding errors. However, consider abstracting some of this logic into separate functions for clarity and maintainability. For instance, handling encoding errors and deleting proposals could be encapsulated in a function like handleEncodingError.

// Proposed refactor for handling encoding errors
func (k Keeper) handleEncodingError(ctx context.Context, proposalId uint64, err error) error {
    // Existing logic for handling encoding errors
}

Comment on lines +72 to +75
if err := k.environment.BranchService.Execute(ctx, func(ctx context.Context) error {
return k.Hooks().AfterProposalFailedMinDeposit(ctx, proposal.Id)
}); err != nil {
// purposely ignoring the error here not to halt the chain if the hook fails
Copy link
Contributor

Choose a reason for hiding this comment

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

Ignoring errors from hooks, such as AfterProposalFailedMinDeposit, might be necessary to prevent halting the chain, but it could lead to unnoticed issues. Consider logging more context or implementing a monitoring/alerting mechanism for these ignored errors to ensure they can be investigated if they occur frequently.

// Suggestion to enhance error logging for ignored hook errors
logger.Error("failed to execute AfterProposalFailedMinDeposit hook", "error", err, "proposal_id", proposal.Id)

Comment on lines +79 to +84
if err := k.environment.EventService.EventManager(ctx).EmitKV(types.EventTypeInactiveProposal,
event.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.Id)),
event.NewAttribute(types.AttributeKeyProposalResult, types.AttributeValueProposalDropped),
); err != nil {
logger.Error("failed to emit event", "error", err)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Emitting events for inactive proposals is crucial for transparency and auditability. However, ensure that the event attributes are comprehensive and accurately reflect the proposal's state. Additionally, consider adding more detailed error handling for event emission failures, possibly retrying or logging to an external system for further investigation.

// Suggestion to enhance error handling for event emission failures
if err := k.environment.EventService.EventManager(ctx).EmitKV(...); err != nil {
    // Enhanced error handling logic here
}

Comment on lines +104 to +115
proposal, err := k.Proposals.Get(ctx, key.K2())
if err != nil {
// if the proposal has an encoding error, this means it cannot be processed by x/gov
// this could be due to some types missing their registration
// instead of returning an error (i.e, halting the chain), we fail the proposal
if errors.Is(err, collections.ErrEncoding) {
proposal.Id = key.K2()
if err := failUnsupportedProposal(logger, ctx, keeper, proposal, err.Error(), true); err != nil {
if err := failUnsupportedProposal(logger, ctx, k, proposal, err.Error(), true); err != nil {
return false, err
}

if err = keeper.ActiveProposalsQueue.Remove(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id)); err != nil {
if err = k.ActiveProposalsQueue.Remove(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id)); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

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

Similar to the handling of inactive proposals, the logic for active proposals also handles encoding errors well. Again, consider abstracting repetitive logic into helper functions for better code reuse and readability.

// Proposed refactor for handling active proposal encoding errors
func (k Keeper) handleActiveProposalEncodingError(ctx context.Context, proposalId uint64, err error) error {
    // Existing logic for handling encoding errors for active proposals
}

Comment on lines 134 to 169
// If a proposal fails, and isn't spammy, deposits are refunded, unless the proposal is expedited or optimistic.
// An expedited or optimistic proposal that fails and isn't spammy is converted to a regular proposal.
if burnDeposits {
err = keeper.DeleteAndBurnDeposits(ctx, proposal.Id)
err = k.DeleteAndBurnDeposits(ctx, proposal.Id)
} else if passes || !(proposal.ProposalType == v1.ProposalType_PROPOSAL_TYPE_EXPEDITED || proposal.ProposalType == v1.ProposalType_PROPOSAL_TYPE_OPTIMISTIC) {
err = keeper.RefundAndDeleteDeposits(ctx, proposal.Id)
err = k.RefundAndDeleteDeposits(ctx, proposal.Id)
}
if err != nil {
// in case of an error, log it and emit an event
// we do not want to halt the chain if the refund/burn fails
// as it could happen due to a governance mistake (governance has let a proposal pass that sends gov funds that were from proposal deposits)

keeper.Logger(ctx).Error("failed to refund or burn deposits", "error", err)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeProposalDeposit,
sdk.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.Id)),
sdk.NewAttribute(types.AttributeKeyProposalDepositError, "failed to refund or burn deposits"),
sdk.NewAttribute("error", err.Error()),
),
)
k.Logger().Error("failed to refund or burn deposits", "error", err)

if err := k.environment.EventService.EventManager(ctx).EmitKV(types.EventTypeProposalDeposit,
event.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.Id)),
event.NewAttribute(types.AttributeKeyProposalDepositError, "failed to refund or burn deposits"),
event.NewAttribute("error", err.Error()),
); err != nil {
k.Logger().Error("failed to emit event", "error", err)
}
}

if err = keeper.ActiveProposalsQueue.Remove(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id)); err != nil {
if err = k.ActiveProposalsQueue.Remove(ctx, collections.Join(*proposal.VotingEndTime, proposal.Id)); err != nil {
return false, err
}

switch {
case passes:
var (
idx int
events sdk.Events
msg sdk.Msg
idx int
msg sdk.Msg
)

// attempt to execute all messages within the passed proposal
// Messages may mutate state thus we use a cached context. If one of
// the handlers fails, no state mutation is written and the error
// message is logged.
cacheCtx, writeCache := ctx.CacheContext()
messages, err := proposal.GetMsgs()
if err != nil {
proposal.Status = v1.StatusFailed
Copy link
Contributor

Choose a reason for hiding this comment

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

📝 NOTE
This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [127-147]

The logic for determining whether to burn or refund deposits based on the proposal's outcome is well-implemented. However, this block of code is complex and could benefit from being broken down into smaller, more manageable functions. This would improve readability and make the code easier to test.

// Suggested refactor for handling deposit outcomes
func (k Keeper) handleDepositOutcome(ctx context.Context, proposal v1.Proposal, passes bool, burnDeposits bool) error {
    // Logic for handling deposit outcomes
}

Comment on lines +177 to +201
// attempt to execute all messages within the passed proposal
// Messages may mutate state thus we use a cached context. If one of
// the handlers fails, no state mutation is written and the error
// message is logged.
if err := k.environment.BranchService.Execute(ctx, func(ctx context.Context) error {
// execute all messages
for idx, msg = range messages {
if _, err := safeExecuteHandler(ctx, msg, k.environment.RouterService.MessageRouterService()); err != nil {
// `idx` and `err` are populated with the msg index and error.
proposal.Status = v1.StatusFailed
proposal.FailedReason = err.Error()
tagValue = types.AttributeValueProposalFailed
logMsg = fmt.Sprintf("passed, but msg %d (%s) failed on execution: %s", idx, sdk.MsgTypeURL(msg), err)

return err
}
}

events = append(events, res.GetEvents()...)
}

// `err == nil` when all handlers passed.
// Or else, `idx` and `err` are populated with the msg index and error.
if err == nil {
proposal.Status = v1.StatusPassed
tagValue = types.AttributeValueProposalPassed
logMsg = "passed"

// write state to the underlying multi-store
writeCache()

// propagate the msg events to the current context
ctx.EventManager().EmitEvents(events)
} else {
proposal.Status = v1.StatusFailed
proposal.FailedReason = err.Error()
tagValue = types.AttributeValueProposalFailed
logMsg = fmt.Sprintf("passed, but msg %d (%s) failed on execution: %s", idx, sdk.MsgTypeURL(msg), err)
return nil
}); err != nil {
break // We do not anything with the error. Returning an error halts the chain, and proposal struct is already updated.
Copy link
Contributor

Choose a reason for hiding this comment

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

The execution of messages within a passed proposal is a critical operation. The use of a cached context to prevent state mutations in case of an error is a good practice. However, this complex logic should be encapsulated in a separate function or method to improve readability and maintainability.

// Suggested refactor for executing proposal messages
func (k Keeper) executeProposalMessages(ctx context.Context, proposal v1.Proposal) error {
    // Logic for executing proposal messages
}

Comment on lines +260 to +266
if err := k.environment.EventService.EventManager(ctx).EmitKV(types.EventTypeActiveProposal,
event.NewAttribute(types.AttributeKeyProposalID, fmt.Sprintf("%d", proposal.Id)),
event.NewAttribute(types.AttributeKeyProposalResult, tagValue),
event.NewAttribute(types.AttributeKeyProposalLog, logMsg),
); err != nil {
logger.Error("failed to emit event", "error", err)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Emitting events after tallying a proposal is important for transparency. As with previous event emission logic, ensure that error handling is robust and consider adding mechanisms for retrying or alerting in case of failures.

// Suggestion to enhance error handling for event emission failures after tallying
if err := k.environment.EventService.EventManager(ctx).EmitKV(...); err != nil {
    // Enhanced error handling logic here
}

Copy link
Contributor

@likhita-809 likhita-809 left a comment

Choose a reason for hiding this comment

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

left one question.
Otherwise good work @julienrbrt

sdkEvents := make([]sdk.Event, 0, len(events))
for _, event := range events {
sdkEvents = append(sdkEvents, sdk.Event(event))
// TODO(@julienrbrt): check if events are properly emitted
Copy link
Contributor

Choose a reason for hiding this comment

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

will this TODO be addressed as part of this pr ?

Copy link
Member

Choose a reason for hiding this comment

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

Will be done in another pr yes, as apparently this wasn't required at all using cache context (and isn't anymore with the branch service)

@julienrbrt julienrbrt added this pull request to the merge queue Mar 5, 2024
Merged via the queue into main with commit afcb62b Mar 5, 2024
63 of 64 checks passed
@julienrbrt julienrbrt deleted the sam/env-bundle-gov branch March 5, 2024 06:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[Feature]Migrate x/gov to use Environment
6 participants