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

chore: clean up code by removing unused sections and formatting #732

Merged
merged 1 commit into from
Oct 12, 2024

Conversation

zakir-code
Copy link
Contributor

@zakir-code zakir-code commented Oct 11, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new SubmitProposal method in the msgServer for enhanced proposal submission functionality.
    • Added methods for handling deposits and updates to store and parameters.
  • Deprecations

    • Marked several methods and types as deprecated in the gas price modules for clarity.
  • Improvements

    • Optimized memory allocation in the deposit validation method.
    • Streamlined handling of CustomParams by changing function return types.
  • Removals

    • Removed the AttributeKeyRecvError constant from the IBC middleware.

Copy link

coderabbitai bot commented Oct 11, 2024

Walkthrough

The changes involve updates to several Go files across different packages, primarily focusing on marking various components as deprecated in the gas_price.go files of both legacy v1 and v2. Additionally, new methods have been added to the msgServer struct in the x/gov/keeper/msg_server.go file, enhancing its functionality. Other modifications include changes to method receivers, type adjustments, and the removal of certain constants and functions, all aimed at improving clarity and performance without altering existing functionality.

Changes

File Path Change Summary
server/grpc/gasprice/legacy/v1/gas_price.go Marked Querier struct, FxGasPrice, GasPrice methods, and RegisterGRPCGatewayRoutes as deprecated.
server/grpc/gasprice/legacy/v2/gas_price.go Marked Querier type, GetGasPrice method, and RegisterGRPCGatewayRoutes as deprecated.
x/gov/keeper/deposit.go Optimized validateDepositDenom by initializing denoms slice with a capacity equal to params.MinDeposit.
x/gov/keeper/msg_server.go Added methods: SubmitProposal, Deposit, UpdateStore, UpdateSwitchParams, UpdateCustomParams.
x/gov/types/params.go Removed certain imports/functions and changed NewCustomParams return type from pointer to value.
x/ibc/middleware/types/events.go Removed constant AttributeKeyRecvError.
x/ibc/middleware/types/packet.go Updated method receivers in IbcCallEvmPacket from value to pointer.

Possibly related PRs

🐰 In the code, we hop and play,
Marking old paths, clearing the way.
With new methods added, we grow and thrive,
In this land of code, we come alive!
So here’s to the changes, both big and small,
A joyful leap for one and all! 🐇✨


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>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (10)
server/grpc/gasprice/legacy/v2/gas_price.go (3)

12-12: Approved: Clearer deprecation comment

The updated comment format provides more clarity about the deprecated entity. This change aligns well with the PR objective of cleaning up the code.

Consider adding a brief explanation of why this type is deprecated and, if applicable, what should be used instead. For example:

// Deprecated: Querier is no longer supported. Use NewQuerier() from the v3 package instead.

17-17: Approved: Consistent deprecation comment

The updated comment for GetGasPrice is consistent with the previous change and clearly indicates which method is deprecated.

Similar to the previous suggestion, consider adding a brief explanation and alternative if available:

// Deprecated: GetGasPrice will be removed in the next major version. Use GetGasPriceV3() from the v3 package for improved functionality.

Line range hint 27-32: Approved with suggestions: Consistent deprecation comment and error handling concern

The updated comment for RegisterGRPCGatewayRoutes is consistent with the previous changes and clearly indicates which function is deprecated.

Consider adding a brief explanation and alternative if available:

// Deprecated: RegisterGRPCGatewayRoutes will be removed in the next major version. Use RegisterGRPCGatewayRoutesV3() from the v3 package for improved routing.

The function still uses a panic for error handling, which might not be ideal for a deprecated function. Consider updating the error handling to return an error instead of panicking:

-func RegisterGRPCGatewayRoutes(clientConn grpc.ClientConn, mux *runtime.ServeMux) {
+func RegisterGRPCGatewayRoutes(clientConn grpc.ClientConn, mux *runtime.ServeMux) error {
 	if err := RegisterQueryHandlerClient(context.Background(), mux, NewQueryClient(clientConn)); err != nil {
-		panic(fmt.Sprintf("failed to %s register grpc gateway routes: %s", "legacy gas price", err.Error()))
+		return fmt.Errorf("failed to register legacy gas price grpc gateway routes: %w", err)
 	}
+	return nil
 }

This change would allow callers to handle the error more gracefully, especially important for a deprecated function where unexpected behavior might occur.

x/ibc/middleware/types/packet.go (3)

25-35: LGTM: Pointer receiver change and formatting improvements for ValidateBasic

The change to a pointer receiver is consistent with the other methods and improves potential performance. The formatting changes enhance readability.

Consider using errors.Join for combining multiple validation errors, which could make the code more maintainable if additional validations are added in the future.


Line range hint 43-49: LGTM: Pointer receiver change for MustGetData, with a suggestion

The change to a pointer receiver is consistent with the other methods and aligns with the PR objectives. This change potentially improves performance without altering the method's functionality.

Consider renaming this method to GetData and returning an error instead of using a panic. This would allow for more graceful error handling:

func (m *IbcCallEvmPacket) GetData() ([]byte, error) {
	return hex.DecodeString(m.Data)
}

This change would make the method safer to use and more consistent with Go's error handling conventions.


Line range hint 21-49: Summary: Consistent optimization of IbcCallEvmPacket methods

The changes in this file consistently update the method receivers for IbcCallEvmPacket from value receivers to pointer receivers. This optimization can potentially improve performance by avoiding unnecessary struct copying.

Key points:

  1. All four methods (GetType, ValidateBasic, GetToAddress, and MustGetData) now use pointer receivers.
  2. The functionality of the methods remains unchanged.
  3. These changes align well with the PR objectives of cleaning up and optimizing the code.

Consider reviewing the entire IbcCallEvmPacket struct and its usage throughout the codebase to ensure consistency with these changes. It might be beneficial to update any remaining methods or function parameters that still use value semantics for this struct.

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

Line range hint 73-88: LGTM: Correct adaptation to NewCustomParams change with a minor suggestion.

The update to the NewCustomParams call in newOtherCustomParams correctly reflects the change in the NewCustomParams function signature. The removal of the dereferencing operator * is appropriate and maintains the intended functionality.

Consider renaming the defaultParams variable to defaultParam (singular) to better reflect that it's now a value type rather than a pointer. This might improve code clarity:

-	defaultParams := NewCustomParams(DefaultCustomParamDepositRatio.String(), DefaultCustomParamVotingPeriod, DefaultCustomParamQuorum25.String())
+	defaultParam := NewCustomParams(DefaultCustomParamDepositRatio.String(), DefaultCustomParamVotingPeriod, DefaultCustomParamQuorum25.String())
 	customMsgTypes := []string{
 		// erc20 proposal
 		sdk.MsgTypeURL(&erc20types.MsgRegisterCoin{}),
 		sdk.MsgTypeURL(&erc20types.MsgRegisterERC20{}),
 		sdk.MsgTypeURL(&erc20types.MsgToggleTokenConversion{}),
 		sdk.MsgTypeURL(&erc20types.MsgUpdateDenomAlias{}),

 		// evm proposal
 		sdk.MsgTypeURL(&evmtypes.MsgCallContract{}),
 	}
 	params := make([]InitGenesisCustomParams, 0, len(customMsgTypes))
 	for _, msgType := range customMsgTypes {
-		params = append(params, NewInitGenesisCustomParams(msgType, defaultParams))
+		params = append(params, NewInitGenesisCustomParams(msgType, defaultParam))
 	}
x/gov/keeper/msg_server.go (3)

Line range hint 70-72: Enhance Error Message for Invalid Store Space

In the UpdateStore method, when an invalid store space is encountered, the error message could be more informative by including the invalid space name. This improves debugging and user experience.

Apply this change to include the invalid store space in the error message:

 if !ok {
-    return nil, sdkerrors.ErrInvalidRequest.Wrap("invalid store space")
+    return nil, sdkerrors.ErrInvalidRequest.Wrapf("invalid store space: %s", updateStore.Space)
 }

Line range hint 100-106: Incorrect Struct Comparison in UpdateCustomParams

In UpdateCustomParams, the comparison req.GetCustomParams() == (types.CustomParams{}) may not work as intended. In Go, struct comparisons require that all fields are comparable. If CustomParams contains non-comparable fields (e.g., slices, maps), this comparison will result in a compilation error or unexpected behavior.

To fix this, consider implementing an IsEmpty() method on CustomParams that checks if all fields are zero values, or compare each field individually. For example:

func (cp CustomParams) IsEmpty() bool {
    // Replace with actual field checks
    return cp.Field1 == "" && cp.Field2 == 0 && len(cp.Field3) == 0
}

Then update the condition:

- if req.GetCustomParams() == (types.CustomParams{}) {
+ if req.GetCustomParams().IsEmpty() {

Line range hint 180-188: Use Case-Sensitive Comparison for Message Type URLs

In the checkProposalMsgs function, strings.EqualFold is used to compare message type URLs in a case-insensitive manner. Since MsgTypeURL values are case-sensitive identifiers, using a case-insensitive comparison may result in incorrect validations.

Replace strings.EqualFold with a case-sensitive comparison to ensure accurate validation:

 if msgType != "" && !strings.EqualFold(msgType, sdk.MsgTypeURL(pMsg)) {
+    if msgType != "" && msgType != sdk.MsgTypeURL(pMsg) {
         return govtypes.ErrInvalidProposalType.Wrapf("proposal MsgTypeURL is different")
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 33e8831 and 93d37d9.

📒 Files selected for processing (7)
  • server/grpc/gasprice/legacy/v1/gas_price.go (2 hunks)
  • server/grpc/gasprice/legacy/v2/gas_price.go (2 hunks)
  • x/gov/keeper/deposit.go (1 hunks)
  • x/gov/keeper/msg_server.go (1 hunks)
  • x/gov/types/params.go (3 hunks)
  • x/ibc/middleware/types/events.go (1 hunks)
  • x/ibc/middleware/types/packet.go (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • server/grpc/gasprice/legacy/v1/gas_price.go
  • x/gov/keeper/deposit.go
  • x/ibc/middleware/types/events.go
🧰 Additional context used
🔇 Additional comments (5)
x/ibc/middleware/types/packet.go (2)

21-23: LGTM: Pointer receiver change for GetType

The change from a value receiver to a pointer receiver is a good optimization. It avoids unnecessary copying of the struct, potentially improving performance without altering the method's functionality.


38-41: LGTM: Pointer receiver change for GetToAddress

The change from a value receiver to a pointer receiver is consistent with the other methods and aligns with the PR objectives. This change potentially improves performance without altering the method's functionality.

x/gov/types/params.go (3)

68-68: LGTM: Correct adaptation to NewCustomParams change.

The update to the NewCustomParams call in newEGFCustomParams correctly reflects the change in the NewCustomParams function signature. The removal of the dereferencing operator * is appropriate and maintains the intended functionality.


Line range hint 50-55: Approve the change to NewCustomParams function.

The modification from returning a pointer to returning a value is a good improvement. It simplifies memory management and potentially improves performance for small structs. This change aligns well with the PR objective of cleaning up the code.

To ensure this change doesn't introduce any issues, let's verify its usage across the codebase:

#!/bin/bash
# Description: Check for any remaining dereferences of NewCustomParams calls

# Test: Search for any remaining dereferences of NewCustomParams calls
# Expect: No results, as all calls should now use the value directly
rg --type go '&NewCustomParams\('

# Test: Verify all calls to NewCustomParams have been updated
# Expect: All calls should now use the value directly without dereferencing
rg --type go 'NewCustomParams\('

Line range hint 1-108: Note on potential removals mentioned in the AI summary.

The AI-generated summary mentioned the removal of the ExtractMsgTypeURL function and changes to import statements, particularly the removal of strings and codectypes packages. These changes are not visible in the provided code snippet, possibly because removed lines are not shown.

To confirm these changes, please run the following script:

If these elements have indeed been removed, it aligns with the PR objective of cleaning up the code by removing unused sections. However, please ensure that the removal of the ExtractMsgTypeURL function doesn't negatively impact any other parts of the codebase that might have depended on it.

✅ Verification successful

Removal of ExtractMsgTypeURL and Specified Imports Confirmed

The ExtractMsgTypeURL function and the imports for "strings" and "github.com/cosmos/cosmos-sdk/codec/types" have been successfully removed from x/gov/types/params.go.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the removal of ExtractMsgTypeURL function and import changes

# Test: Check for the presence of ExtractMsgTypeURL function
# Expect: No results if the function has been removed
rg --type go 'func ExtractMsgTypeURL' x/gov/types/params.go

# Test: Check for the presence of strings and codectypes imports
# Expect: No results if these imports have been removed
rg --type go '^import \($|    "strings"|    "github.com/cosmos/cosmos-sdk/codec/types"' x/gov/types/params.go

Length of output: 603


Script:

#!/bin/bash
# Description: Verify the removal of ExtractMsgTypeURL function and import changes

# Test: Check for the presence of ExtractMsgTypeURL function
# Expect: No results if the function has been removed
rg --type go 'func ExtractMsgTypeURL' x/gov/types/params.go

# Test: Check for the presence of "strings" and "codec/types" imports
# Expect: No results if these imports have been removed
rg --type go 'import \(\n\s+"strings"\n\s+"github.com/cosmos/cosmos-sdk/codec/types"\n\)' x/gov/types/params.go

Length of output: 367


Script:

#!/bin/bash
# Description: Verify the removal of ExtractMsgTypeURL function and import changes with multiline support

# Test: Check for the presence of ExtractMsgTypeURL function
# Expect: No results if the function has been removed
rg --type go 'func ExtractMsgTypeURL' x/gov/types/params.go

# Test: Check for the presence of "strings" and "codec/types" imports
# Expect: No results if these imports have been removed
rg -U --type go 'import \(\n\s+"strings"\n\s+"github.com/cosmos/cosmos-sdk/codec/types"\n\)' x/gov/types/params.go

Length of output: 178

x/gov/keeper/msg_server.go Show resolved Hide resolved
@fx0x55 fx0x55 merged commit 7fd9cc7 into main Oct 12, 2024
10 checks passed
@fx0x55 fx0x55 deleted the zakir/chore branch October 12, 2024 01:22
@coderabbitai coderabbitai bot mentioned this pull request Oct 19, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants