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

feat(bank/v2): Basic CreateDenom #22264

Open
wants to merge 11 commits into
base: main
Choose a base branch
from
Open

Conversation

hieuvubk
Copy link
Contributor

@hieuvubk hieuvubk commented Oct 15, 2024

Description

Ref: #22251

  • add denomMetadata & authorityMetadata funcs
  • Update params
  • Add MsgCreateDenom & MsgChangeAdmin handlers
  • Tests

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, you can find examples of the prefixes below:
  • 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.

Please see Pull Request Reviewer section in the contributing guide for more information on how to review a pull request.

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 new Protocol Buffers definitions for managing token metadata and denominations.
    • Added functionalities for creating and changing token denominations.
    • Implemented validation for authority metadata and denomination parameters.
  • Bug Fixes

    • Added sentinel error variables to improve error handling for token factory operations.
  • Documentation

    • Enhanced validation methods for parameters and metadata associated with token denominations.

@hieuvubk hieuvubk marked this pull request as ready for review October 15, 2024 08:02
Copy link
Contributor

coderabbitai bot commented Oct 15, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request introduce new Protocol Buffers definitions and functionalities within the cosmos.bank.v2 package. Key additions include the DenomAuthorityMetadata message for managing token metadata, enhancements to the Params message, and new transaction messages for creating and modifying denominations. The keeper package is updated with methods for managing authority metadata, creating new denominations, and handling related transactions. The types package sees the introduction of validation methods and new error variables. Overall, these changes enhance the management of token denominations and their associated metadata.

Changes

File Path Change Summary
x/bank/proto/cosmos/bank/v2/authorityMetadata.proto, x/bank/proto/cosmos/bank/v2/bank.proto, x/bank/proto/cosmos/bank/v2/genesis.proto, x/bank/proto/cosmos/bank/v2/tx.proto Added new Protocol Buffers messages and modified existing ones for managing token metadata and transactions.
x/bank/v2/keeper/admins.go, x/bank/v2/keeper/createdenom.go, x/bank/v2/keeper/creators.go, x/bank/v2/keeper/genesis.go, x/bank/v2/keeper/handlers.go, x/bank/v2/keeper/keeper.go, x/bank/v2/keeper/params.go, x/bank/v2/keeper/keeper_test.go Introduced methods for managing authority metadata, creating denominations, and handling transactions; added tests for new functionalities.
x/bank/v2/types/authorityMetadata.go, x/bank/v2/types/denoms.go, x/bank/v2/types/errors.go, x/bank/v2/types/keys.go, x/bank/v2/types/params.go Added validation methods, new error variables, and updated parameter handling functions.

Possibly related PRs

Suggested labels

C:x/accounts

Suggested reviewers

  • sontrinh16
  • akhilkumarpilli
  • julienrbrt
  • kocubinski

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.

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
Contributor

@hieuvubk your pull request is missing a changelog!

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.

Actionable comments posted: 31

🧹 Outside diff range and nitpick comments (21)
x/bank/v2/types/authorityMetadata.go (1)

7-15: LGTM: The Validate() method is well-implemented.

The Validate() method correctly checks the Admin field of the DenomAuthorityMetadata type. It properly handles both empty and non-empty cases, and the error handling is correct. The implementation follows the Uber Go Style Guide by keeping the happy path on the left.

A minor suggestion for improvement:

Consider adding a comment to explain the purpose of this validation, especially why an empty Admin field is considered valid. This would enhance the code's readability and maintainability.

+// Validate checks if the Admin field is either empty or a valid Bech32 address.
+// An empty Admin field is considered valid.
 func (metadata DenomAuthorityMetadata) Validate() error {
     // ... (rest of the function remains the same)
 }
x/bank/v2/keeper/params.go (2)

9-12: Update the comment to match the method's functionality.

The current comment doesn't accurately describe the SetParams method. Consider updating it to:

// SetParams sets the parameters for the bank module

The method implementation looks good and correctly sets the parameters using k.params.Set.


14-21: Update the comment and consider logging the error.

  1. The current comment doesn't accurately describe the GetParams method. Consider updating it to:
// GetParams returns the current parameters for the bank module
  1. Consider logging the error before returning the default value. This can help with debugging in case of unexpected issues:
if err != nil {
    k.Logger(ctx).Error("failed to get params", "error", err)
    return types.Params{}
}

The overall implementation of the method looks good, retrieving the parameters and handling potential errors appropriately.

x/bank/proto/cosmos/bank/v2/authorityMetadata.proto (1)

9-17: LGTM: Well-defined DenomAuthorityMetadata message with room for future extensions.

The DenomAuthorityMetadata message is clearly defined and well-commented. The use of gogoproto options for equality checks and YAML serialization is appropriate. The admin field correctly allows for an empty string to represent "no admin".

For future consideration:
As the comment mentions planned extensions, consider adding a reserved block for future fields. This can help maintain backwards compatibility as the message evolves.

Example:

message DenomAuthorityMetadata {
  // ... existing fields ...
  
  // Reserved for future use
  reserved 2 to 10;
  reserved "future_field1", "future_field2";
}
x/bank/v2/types/errors.go (2)

3-3: Reconsider the use of // DONTCOVER comment

The // DONTCOVER comment is typically used to exclude files from test coverage reports. However, for an errors file, it's generally beneficial to include it in coverage reports to ensure all error cases are properly tested.

Consider removing this comment unless there's a specific reason for excluding this file from coverage reports.


11-19: Error definitions look good, with a minor suggestion for consistency

The error definitions are well-structured and follow best practices:

  • Each error has a unique code and descriptive message.
  • The use of errorsmod.Register is correct for defining sentinel errors.
  • Error codes are sequential, which is good for maintainability.

For consistency, consider using fmt.Sprintf for all error messages, even those without dynamic values. This would make future additions of dynamic content easier. For example:

ErrDenomExists = errorsmod.Register(ModuleName, 2, fmt.Sprintf("attempting to create a denom that already exists (has bank metadata)"))
ErrUnauthorized = errorsmod.Register(ModuleName, 3, fmt.Sprintf("unauthorized account"))
ErrInvalidDenom = errorsmod.Register(ModuleName, 4, fmt.Sprintf("invalid denom"))
ErrInvalidCreator = errorsmod.Register(ModuleName, 5, fmt.Sprintf("invalid creator"))
x/bank/v2/types/keys.go (1)

35-37: LGTM! Consider adding comments for new prefixes.

The new variables DenomMetadataPrefix and DenomAuthorityPrefix are correctly implemented and follow the existing naming conventions and prefix numbering sequence. This is consistent with the Uber Golang style guide.

To improve code documentation, consider adding brief comments explaining the purpose of these new prefixes, similar to the existing comments for other prefixes in this file.

+// DenomMetadataPrefix is the prefix for storing denomination metadata
 DenomMetadataPrefix = collections.NewPrefix(6)

+// DenomAuthorityPrefix is the prefix for storing denomination authority information
 DenomAuthorityPrefix = collections.NewPrefix(7)
x/bank/proto/cosmos/bank/v2/genesis.proto (3)

30-31: LGTM: New denom_metadata field is well-defined.

The addition of the denom_metadata field to the GenesisState message is appropriate and well-structured. It allows for the inclusion of metadata for different coins in the genesis state.

Consider adding a brief comment explaining the purpose and usage of this field, similar to the comments for other fields in the message. For example:

// denom_metadata defines the metadata of the different coins.
repeated Metadata denom_metadata = 4 [(gogoproto.nullable) = false, (amino.dont_omitempty) = true];

33-33: LGTM: New factory_denoms field is well-defined.

The addition of the factory_denoms field to the GenesisState message is appropriate and well-structured. It allows for the inclusion of token factory denominations in the genesis state.

Consider adding a brief comment explaining the purpose and usage of this field, similar to the comments for other fields in the message. For example:

// factory_denoms defines the denominations created through the tokenfactory module.
repeated GenesisDenom factory_denoms = 5 [(gogoproto.nullable) = false];

54-61: LGTM: New GenesisDenom message is well-defined.

The addition of the GenesisDenom message is appropriate and well-structured. It provides a clear representation of token factory denominations in the genesis state.

Consider renaming the authority_metadata field to admin_metadata for consistency with the admin terminology used in other parts of the Cosmos SDK. This would make the field name more intuitive and aligned with the broader SDK conventions. For example:

message GenesisDenom {
  option (gogoproto.equal) = true;

  string                 denom          = 1;
  DenomAuthorityMetadata admin_metadata = 2 [(gogoproto.nullable) = false];
}
x/bank/v2/module.go (1)

101-102: LGTM! Consider grouping related handlers together.

The addition of MsgCreateDenom and MsgChangeAdmin handlers is correct and follows the existing pattern. These new handlers align with the PR objectives of introducing functionalities for creating denominations.

For better code organization, consider grouping related handlers together. For example:

appmodulev2.RegisterMsgHandler(router, handlers.MsgUpdateParams)
appmodulev2.RegisterMsgHandler(router, handlers.MsgSend)
appmodulev2.RegisterMsgHandler(router, handlers.MsgMint)
appmodulev2.RegisterMsgHandler(router, handlers.MsgCreateDenom)
appmodulev2.RegisterMsgHandler(router, handlers.MsgChangeAdmin)

This grouping improves readability by keeping denomination-related handlers adjacent to each other.

x/bank/v2/types/params.go (2)

4-4: Remove unnecessary import alias for fmt package.

The alias fmt "fmt" is redundant since the package name is the same as the imported package. You can simplify the import statement to:

import (
	"fmt"
	// other imports
)

18-18: Define a constant for the default gas consumption value.

Using a constant for the default gas consumption improves readability and maintainability.

Example:

const DefaultDenomCreationGasConsume uint64 = 1_000_000

func DefaultParams() Params {
	return NewParams(sdk.NewCoins(), DefaultDenomCreationGasConsume)
}
x/bank/proto/cosmos/bank/v2/bank.proto (2)

16-18: Ensure consistent use of (gogoproto.nullable) option

For the field denom_creation_fee, you've set (gogoproto.nullable) = false, making it non-nullable. Please verify that this is intentional and consistent with how other fields are handled. Non-nullable fields generate more straightforward Go code without pointer references.


26-26: Consider setting (gogoproto.nullable) to false for scalar types

For the field denom_creation_gas_consume, you've set (gogoproto.nullable) = true. Since uint64 is a scalar type, making it nullable will generate a pointer to uint64 in the Go code, which may not be necessary. For consistency and to simplify the generated code, consider setting (gogoproto.nullable) = false.

x/bank/v2/keeper/createdenom.go (1)

59-60: Enhance TODO comment with actionable details

The TODO comment lacks a ticket reference or a clear description of the task. As per the Uber Go Style Guide, TODO comments should include a reference or a concise explanation of the work to be done.

Consider updating the TODO comment:

-// TODO: do we need map creator => denom
+// TODO(#IssueNumber): Assess the necessity of mapping from creator to denom.

Replace #IssueNumber with the relevant issue tracker number for better traceability.

x/bank/proto/cosmos/bank/v2/tx.proto (2)

52-53: Add field comments for 'sender' and 'subdenom'.

For clarity and better documentation, please add comments to the sender and subdenom fields explaining their purpose and any expected formats or constraints.


66-68: Add field comments for 'sender', 'denom', and 'new_admin'.

Including descriptive comments for the sender, denom, and new_admin fields will enhance readability and assist developers in understanding the role and expected values of each field.

x/bank/v2/keeper/handlers.go (2)

55-66: Add function documentation for MsgCreateDenom

According to the Uber Go Style Guide, all exported functions should have a preceding comment that explains their purpose and usage. Please add a documentation comment for the MsgCreateDenom method to enhance code readability and maintainability.

Example:

// MsgCreateDenom handles the creation of a new denomination.

68-68: Clarify the TODO comment regarding governance

The TODO comment // TODO: should be gov? suggests uncertainty about whether the MsgChangeAdmin handler should be managed through governance. Consider clarifying this decision to ensure the code aligns with the intended design. If this action should be moved to the governance module, I can assist with the refactoring process.

Would you like help in integrating this functionality with the governance module or opening a GitHub issue to track this task?

x/bank/v2/keeper/keeper.go (1)

184-185: Update function comment for GetDenomMetaData to follow Go conventions

The comment for GetDenomMetaData should start with the function name and be properly capitalized and punctuated to conform with Go standards.

Consider updating the comment to:

// GetDenomMetaData retrieves the denomination metadata. It returns the metadata and true if the denom exists, false otherwise.
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 77254b7 and 007d595.

⛔ Files ignored due to path filters (4)
  • x/bank/v2/types/authorityMetadata.pb.go is excluded by !**/*.pb.go
  • x/bank/v2/types/bank.pb.go is excluded by !**/*.pb.go
  • x/bank/v2/types/genesis.pb.go is excluded by !**/*.pb.go
  • x/bank/v2/types/tx.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (18)
  • x/bank/proto/cosmos/bank/v2/authorityMetadata.proto (1 hunks)
  • x/bank/proto/cosmos/bank/v2/bank.proto (1 hunks)
  • x/bank/proto/cosmos/bank/v2/genesis.proto (3 hunks)
  • x/bank/proto/cosmos/bank/v2/tx.proto (1 hunks)
  • x/bank/v2/keeper/admins.go (1 hunks)
  • x/bank/v2/keeper/createdenom.go (1 hunks)
  • x/bank/v2/keeper/creators.go (1 hunks)
  • x/bank/v2/keeper/genesis.go (1 hunks)
  • x/bank/v2/keeper/handlers.go (1 hunks)
  • x/bank/v2/keeper/keeper.go (4 hunks)
  • x/bank/v2/keeper/keeper_test.go (1 hunks)
  • x/bank/v2/keeper/params.go (1 hunks)
  • x/bank/v2/module.go (1 hunks)
  • x/bank/v2/types/authorityMetadata.go (1 hunks)
  • x/bank/v2/types/denoms.go (1 hunks)
  • x/bank/v2/types/errors.go (1 hunks)
  • x/bank/v2/types/keys.go (1 hunks)
  • x/bank/v2/types/params.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • x/bank/v2/keeper/creators.go
🧰 Additional context used
📓 Path-based instructions (13)
x/bank/v2/keeper/admins.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/keeper/createdenom.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/keeper/genesis.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/keeper/handlers.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/keeper/keeper.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/keeper/keeper_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

x/bank/v2/keeper/params.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/module.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/types/authorityMetadata.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/types/denoms.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/types/errors.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/types/keys.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/types/params.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🪛 buf
x/bank/proto/cosmos/bank/v2/authorityMetadata.proto

4-4: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

x/bank/proto/cosmos/bank/v2/bank.proto

4-4: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

🔇 Additional comments (10)
x/bank/v2/types/authorityMetadata.go (2)

1-5: LGTM: Package declaration and imports are correct.

The package is correctly declared as types, which is appropriate for a types file in the bank module. The import of the sdk package is properly aliased and appears to be the only necessary import for this file.


1-15: Excellent implementation of the Validate() method.

The overall implementation of this file is clean, concise, and follows Go best practices. It adheres to the Single Responsibility Principle by focusing solely on validating the DenomAuthorityMetadata. The error handling is appropriate, and the code is easy to read and understand.

x/bank/v2/keeper/params.go (1)

3-7: LGTM: Import statements are correct and well-organized.

The import statements are properly structured and include only the necessary packages.

x/bank/proto/cosmos/bank/v2/authorityMetadata.proto (2)

2-2: LGTM: Package declaration and go_package option are correct.

The package declaration cosmos.bank.v2 and the go_package option "cosmossdk.io/x/bank/v2/types" are correctly specified and follow the expected format for Cosmos SDK modules.

Also applies to: 7-7


1-17: Overall: Well-structured and focused Protocol Buffers file.

This new file, authorityMetadata.proto, is well-structured and focused on its purpose of defining the DenomAuthorityMetadata message. It follows Protocol Buffers best practices and Cosmos SDK conventions. The message is clearly commented, and the use of gogoproto options enhances its functionality.

Key points:

  1. Correct syntax and package declarations.
  2. Appropriate imports (pending verification of gogoproto).
  3. Well-defined message with clear comments and correct use of options.
  4. Consideration for future extensibility.

Great job on maintaining clarity and following best practices in this new addition to the cosmos.bank.v2 package.

🧰 Tools
🪛 buf

4-4: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

x/bank/v2/types/errors.go (1)

1-19: Overall, well-structured and comprehensive error definitions

This file provides a clear and well-organized set of error definitions for the x/tokenfactory module. The errors cover various scenarios and are registered with unique codes, which is excellent for error handling and debugging.

The error messages are descriptive and will be helpful for developers using this module. Good job on maintaining consistency and following best practices in error definition.

x/bank/proto/cosmos/bank/v2/genesis.proto (1)

6-6: LGTM: New import statement is correct and necessary.

The addition of the import statement for "cosmos/bank/v2/authorityMetadata.proto" is appropriate and necessary to support the new GenesisDenom message which uses DenomAuthorityMetadata.

x/bank/v2/keeper/admins.go (1)

10-13: Function GetAuthorityMetadata is correctly implemented

The function effectively retrieves the authority metadata for a given denom and handles errors appropriately.

x/bank/v2/keeper/genesis.go (1)

47-52: SetDenomMetaData error handling check

The loop correctly iterates over state.DenomMetadata and attempts to set the denomination metadata using k.SetDenomMetaData(ctx, meta). However, ensure that SetDenomMetaData properly validates the metadata before setting it to prevent any invalid entries in the state.

x/bank/proto/cosmos/bank/v2/bank.proto (1)

47-65: Review the cosmos_proto.field_added_in annotations

The fields name, symbol, uri, and uri_hash in the Metadata message have annotations indicating they were added in earlier versions ("cosmos-sdk 0.43" and "cosmos-sdk 0.46"). Since these fields are being introduced now, please verify whether these annotations accurately reflect the version in which they are added. If these fields are new in this version, update the annotations accordingly.

Comment on lines +1 to +21
package keeper

import (
"context"

"cosmossdk.io/x/bank/v2/types"
)

// GetAuthorityMetadata returns the authority metadata for a specific denom
func (k Keeper) SetParams(ctx context.Context, params types.Params) error {
return k.params.Set(ctx, params)
}

// setAuthorityMetadata stores authority metadata for a specific denom
func (k Keeper) GetParams(ctx context.Context) types.Params {
params, err := k.params.Get(ctx)
if err != nil {
return types.Params{}
}
return params
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider consistent error handling across methods.

Both SetParams and GetParams methods deal with potential errors, but they handle them differently. For consistency, consider either:

  1. Propagating errors in both methods:
func (k Keeper) GetParams(ctx context.Context) (types.Params, error) {
    return k.params.Get(ctx)
}
  1. Or handling errors internally in both methods:
func (k Keeper) SetParams(ctx context.Context, params types.Params) {
    if err := k.params.Set(ctx, params); err != nil {
        k.Logger(ctx).Error("failed to set params", "error", err)
    }
}

Choose the approach that best fits the module's error handling strategy.

Overall, the file structure is good, with related methods grouped together and following standard Go formatting.

Comment on lines +1 to +5
syntax = "proto3";
package cosmos.bank.v2;

import "gogoproto/gogo.proto";
import "cosmos/base/v1beta1/coin.proto";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Import gogoproto/gogo.proto not found in the repository.

The import gogoproto/gogo.proto is specified in authorityMetadata.proto, but the file does not exist in the repository. Please ensure that the gogoproto dependency is correctly included and that the gogo.proto file is present in the expected location. Additionally, verify that the protobuf generator protoc-gen-gogo is installed in your development environment to support the compilation process.

🔗 Analysis chain

Verify the gogoproto import.

The import of gogoproto/gogo.proto is common in Cosmos SDK projects, but our static analysis tool reports that this file does not exist. Please ensure that the gogoproto package is correctly set up in your development environment and build process.

Run the following script to check for the presence of gogoproto in the project:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for the presence of gogoproto in the project

# Test 1: Search for gogoproto in go.mod
echo "Searching for gogoproto in go.mod:"
rg 'github.com/gogo/protobuf' go.mod

# Test 2: Search for other imports of gogoproto
echo "Searching for other imports of gogoproto:"
rg --type proto 'import "gogoproto/gogo.proto"'

# Test 3: Check if protoc-gen-gogo is installed
echo "Checking if protoc-gen-gogo is installed:"
which protoc-gen-gogo || echo "protoc-gen-gogo not found in PATH"

Length of output: 601


Script:

#!/bin/bash
# Description: Verify the existence of gogoproto/gogo.proto in the repository

echo "Searching for gogoproto/gogo.proto in the repository:"
fd 'gogoproto/gogo.proto' . --case-sensitive

Length of output: 161

🧰 Tools
🪛 buf

4-4: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

Comment on lines +17 to +20
err := metadata.Validate()
if err != nil {
return err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Wrap validation error with contextual information

To enhance error traceability, consider wrapping the error returned from metadata.Validate() with additional context.

Modify the error handling as follows:

err := metadata.Validate()
if err != nil {
-    return err
+    return fmt.Errorf("validation failed for DenomAuthorityMetadata: %w", err)
}

Remember to import the "fmt" package at the top of the file:

 import (
 	"context"
+	"fmt"

 	"cosmossdk.io/x/bank/v2/types"
 )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
err := metadata.Validate()
if err != nil {
return err
}
err := metadata.Validate()
if err != nil {
return fmt.Errorf("validation failed for DenomAuthorityMetadata: %w", err)
}

Comment on lines +26 to +29
metadata, err := k.GetAuthorityMetadata(ctx, denom)
if err != nil {
return err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Provide context when returning error from GetAuthorityMetadata

Adding context to the error can help with debugging when failures occur.

Update the error handling:

if err != nil {
-    return err
+    return fmt.Errorf("failed to get authority metadata for denom %s: %w", denom, err)
}

Ensure that "fmt" is imported.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
metadata, err := k.GetAuthorityMetadata(ctx, denom)
if err != nil {
return err
}
metadata, err := k.GetAuthorityMetadata(ctx, denom)
if err != nil {
return fmt.Errorf("failed to get authority metadata for denom %s: %w", denom, err)
}

Comment on lines +49 to +52
_, ok := i.(uint64)
if !ok {
return fmt.Errorf("invalid parameter type: %T", i)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Validate that DenomCreationGasConsume is greater than zero.

Currently, validateDenomCreationGasConsume only checks the type of the parameter. To ensure meaningful values, consider validating that DenomCreationGasConsume is greater than zero.

You can add a check like:

value, _ := i.(uint64)
if value == 0 {
	return fmt.Errorf("denom creation gas consume must be greater than zero")
}

Comment on lines +279 to +291
valid: true,
},
{
desc: "success case: twoDenomCreationFee",
denomCreationFee: twoDenomCreationFee,
subdenom: "catcoin",
valid: true,
},
{
desc: "success case: nilCreationFee",
denomCreationFee: nilCreationFee,
subdenom: "czcoin",
valid: true,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use Generic Names Instead of Real Project Names in Tests

The subdenoms "evmos", "catcoin", and "czcoin" may refer to actual projects or entities. To prevent any potential legal or branding issues, consider replacing them with generic names.

For example:

-subdenom: "evmos",
+subdenom: "denom1",

-subdenom: "catcoin",
+subdenom: "denom2",

-subdenom: "czcoin",
+subdenom: "denom3",
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
valid: true,
},
{
desc: "success case: twoDenomCreationFee",
denomCreationFee: twoDenomCreationFee,
subdenom: "catcoin",
valid: true,
},
{
desc: "success case: nilCreationFee",
denomCreationFee: nilCreationFee,
subdenom: "czcoin",
valid: true,
valid: true,
},
{
desc: "success case: twoDenomCreationFee",
denomCreationFee: twoDenomCreationFee,
subdenom: "denom2",
valid: true,
},
{
desc: "success case: nilCreationFee",
denomCreationFee: nilCreationFee,
subdenom: "denom3",
valid: true,

Comment on lines +145 to +149
// HasSupply checks if the supply coin exists in store.
func (k Keeper) HasSupply(ctx context.Context, denom string) bool {
has, err := k.supply.Has(ctx, denom)
return has && 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.

⚠️ Potential issue

Handle errors explicitly in HasSupply

In the HasSupply function, errors from k.supply.Has are implicitly handled by returning has && err == nil. This might suppress underlying errors that should be addressed.

Consider modifying the function to handle the error explicitly and return it:

func (k Keeper) HasSupply(ctx context.Context, denom string) (bool, error) {
	has, err := k.supply.Has(ctx, denom)
	if err != nil {
		return false, err
	}
	return has, nil
}

This change allows callers to handle errors appropriately.

Comment on lines +175 to +182
func (k Keeper) IterateAccountBalances(ctx context.Context, addr sdk.AccAddress, cb func(sdk.Coin) bool) {
err := k.balances.Walk(ctx, collections.NewPrefixedPairRange[[]byte, string](addr), func(key collections.Pair[[]byte, string], value math.Int) (stop bool, err error) {
return cb(sdk.NewCoin(key.K2(), value)), nil
})
if err != nil {
panic(err)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid panicking in IterateAccountBalances; return errors instead

In IterateAccountBalances, the function panics if an error occurs during iteration. According to best practices and the Uber Go Style Guide, panicking in library code is discouraged.

Consider changing the function signature to return an error:

func (k Keeper) IterateAccountBalances(ctx context.Context, addr sdk.AccAddress, cb func(sdk.Coin) bool) error {
	err := k.balances.Walk(ctx, collections.NewPrefixedPairRange[[]byte, string](addr), func(key collections.Pair[[]byte, string], value math.Int) (stop bool, err error) {
		return cb(sdk.NewCoin(key.K2(), value)), nil
	})
	if err != nil {
		return err
	}
	return nil
}

Callers can then handle the error appropriately without unexpected panics.

Comment on lines +191 to +195
// HasDenomMetaData checks if the denomination metadata exists in store.
func (k Keeper) HasDenomMetaData(ctx context.Context, denom string) bool {
has, err := k.denomMetadata.Has(ctx, denom)
return has && 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.

⚠️ Potential issue

Handle errors explicitly in HasDenomMetaData

Similar to HasSupply, the HasDenomMetaData function implicitly handles errors, which could suppress important error information.

Modify the function to handle and return errors explicitly:

func (k Keeper) HasDenomMetaData(ctx context.Context, denom string) (bool, error) {
	has, err := k.denomMetadata.Has(ctx, denom)
	if err != nil {
		return false, err
	}
	return has, nil
}

This change ensures that any errors are properly propagated to the caller.

Comment on lines +211 to +218
func (k Keeper) IterateAllDenomMetaData(ctx context.Context, cb func(types.Metadata) bool) {
err := k.denomMetadata.Walk(ctx, nil, func(_ string, metadata types.Metadata) (stop bool, err error) {
return cb(metadata), nil
})
if err != nil {
panic(err)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid panicking in IterateAllDenomMetaData; return errors instead

In IterateAllDenomMetaData, the function panics if an error occurs during iteration. Per the Uber Go Style Guide, panics should be avoided in library code.

Consider modifying the function to return an error:

func (k Keeper) IterateAllDenomMetaData(ctx context.Context, cb func(types.Metadata) bool) error {
	err := k.denomMetadata.Walk(ctx, nil, func(_ string, metadata types.Metadata) (stop bool, err error) {
		return cb(metadata), nil
	})
	if err != nil {
		return err
	}
	return nil
}

This approach allows callers to handle errors without unexpected panics.

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.

Actionable comments posted: 29

🧹 Outside diff range and nitpick comments (21)
x/bank/v2/types/authorityMetadata.go (1)

7-15: LGTM: The Validate() method is well-implemented.

The method correctly validates the Admin field of DenomAuthorityMetadata when it's not empty, using the SDK's AccAddressFromBech32 function. Error handling is appropriate, and the method returns nil when there are no validation errors.

Consider adding a comment to explain the purpose of this validation method, especially for other developers who might use this type. For example:

// Validate checks if the Admin field, if set, is a valid Bech32 address.
// It returns an error if the Admin is set but invalid, otherwise nil.
func (metadata DenomAuthorityMetadata) Validate() error {
    // ... (existing implementation)
}
x/bank/v2/keeper/params.go (2)

9-12: Approve implementation, but fix comment.

The SetParams method is correctly implemented. However, the comment above the function doesn't match its functionality.

Please update the comment to accurately describe the SetParams function:

-// GetAuthorityMetadata returns the authority metadata for a specific denom
+// SetParams sets the parameters for the bank module
 func (k Keeper) SetParams(ctx context.Context, params types.Params) error {

14-21: Approve implementation, but fix comment.

The GetParams method is correctly implemented with proper error handling. However, the comment above the function doesn't match its functionality.

Please update the comment to accurately describe the GetParams function:

-// setAuthorityMetadata stores authority metadata for a specific denom
+// GetParams retrieves the parameters for the bank module
 func (k Keeper) GetParams(ctx context.Context) types.Params {
x/bank/proto/cosmos/bank/v2/authorityMetadata.proto (1)

5-5: Remove unused import

The import cosmos/base/v1beta1/coin.proto is not used in this file. Consider removing it to keep the imports clean and avoid potential confusion.

x/bank/v2/types/errors.go (2)

1-9: LGTM! Consider clarifying the DONTCOVER comment.

The package declaration and imports look good. The errorsmod import with a custom path is correctly used.

Consider adding a brief explanation for the // DONTCOVER comment, e.g.:

// DONTCOVER - This file is excluded from test coverage reports

This will help other developers understand why this file is excluded from coverage.


11-19: LGTM! Consider updating the module name in the comment.

The error variable definitions look good. Each error has a unique code and a descriptive message, which is excellent for error handling and debugging.

The comment on line 11 mentions the "x/tokenfactory" module, but this file is in the "bank" module. Consider updating the comment to:

// x/bank module sentinel errors

This will ensure consistency with the actual module name.

x/bank/v2/types/keys.go (1)

35-37: Consider adding comments for the new prefix variables.

The new variables DenomMetadataPrefix and DenomAuthorityPrefix are consistent with the existing naming conventions and initialization patterns. However, to improve code readability and maintainability, consider adding brief comments explaining the purpose of these prefixes, similar to the comments for other prefix variables in this file.

Here's a suggested addition:

// DenomMetadataPrefix is the prefix for storing denomination metadata
DenomMetadataPrefix = collections.NewPrefix(6)

// DenomAuthorityPrefix is the prefix for storing denomination authority information
DenomAuthorityPrefix = collections.NewPrefix(7)
x/bank/v2/module.go (1)

101-102: LGTM! Consider grouping related handlers.

The addition of MsgCreateDenom and MsgChangeAdmin handlers is consistent with the existing pattern and adheres to the Uber Golang style guide.

For improved readability and organization, consider grouping related handlers together. For example:

// Token-related handlers
appmodulev2.RegisterMsgHandler(router, handlers.MsgMint)
appmodulev2.RegisterMsgHandler(router, handlers.MsgCreateDenom)
appmodulev2.RegisterMsgHandler(router, handlers.MsgChangeAdmin)

// Transaction-related handlers
appmodulev2.RegisterMsgHandler(router, handlers.MsgSend)

// Admin-related handlers
appmodulev2.RegisterMsgHandler(router, handlers.MsgUpdateParams)

This grouping can make it easier to understand the different categories of handlers at a glance.

x/bank/v2/keeper/admins.go (2)

25-34: Add a comment to unexported function for clarity

Although setAdmin is an unexported function, adding a brief comment explaining its purpose enhances code readability and maintenance.

Consider adding a comment like:

// setAdmin updates the admin field in the authority metadata for a specific denom.

3-7: Group import statements according to Go conventions

The import statements should be grouped with standard library packages separated from external packages by a blank line. According to the Uber Go Style Guide, this improves readability.

Apply this diff to group imports properly:

 import (
 	"context"
+
 	"cosmossdk.io/x/bank/v2/types"
 )
x/bank/v2/types/params.go (1)

3-7: Organize import statements according to style guidelines

Per the Uber Go Style Guide, import statements should be grouped into standard library packages, third-party packages, and then project packages, separated by blank lines. Ensure that imports are properly organized.

Apply this change:

 import (
-	fmt "fmt"

-	sdk "github.com/cosmos/cosmos-sdk/types"
+	"fmt"

+	sdk "github.com/cosmos/cosmos-sdk/types"
 )
x/bank/proto/cosmos/bank/v2/genesis.proto (3)

33-33: Consider adding '(amino.dont_omitempty) = true' to 'factory_denoms'

In the GenesisState message, other repeated fields like balances, supply, and denom_metadata have the option (amino.dont_omitempty) = true. For consistency and to prevent omitting empty fields during amino encoding, consider adding (amino.dont_omitempty) = true to the factory_denoms field.


54-56: Enhance documentation for 'GenesisDenom' to improve clarity

The current comment for GenesisDenom contains redundancy and could be clearer. Consider rephrasing it to:

// GenesisDenom represents a token factory denomination included in the genesis
// state. It contains DenomAuthorityMetadata, which defines the denom's admin.

This revision eliminates redundancy and provides a clearer explanation.


61-61: Consider adding '(amino.dont_omitempty) = true' to 'authority_metadata'

The field authority_metadata in GenesisDenom is marked with [(gogoproto.nullable) = false]. For consistency with other non-nullable fields and to ensure proper amino encoding, consider adding (amino.dont_omitempty) = true to this field's options.

x/bank/v2/types/denoms.go (1)

53-55: Standardize error message formatting

Consider rephrasing the error message to align with Go error handling conventions, which recommend starting messages with a lowercase letter and avoiding punctuation at the end.

Apply this diff to adjust the error message:

-	return "", "", errors.Wrapf(ErrInvalidDenom, "denom prefix is incorrect. Is: %s.  Should be: %s", strParts[0], ModuleDenomPrefix)
+	return "", "", errors.Wrapf(ErrInvalidDenom, "denom prefix is incorrect: expected %s, got %s", ModuleDenomPrefix, strParts[0])
x/bank/proto/cosmos/bank/v2/bank.proto (1)

47-65: Ensure 'cosmos_proto.field_added_in' annotations are up-to-date

The Metadata message includes fields with the (cosmos_proto.field_added_in) annotation specifying versions like "cosmos-sdk 0.43" and "cosmos-sdk 0.46". Since this file is for cosmos.bank.v2, please confirm that these annotations accurately reflect when these fields were added relative to this module version.

x/bank/v2/keeper/createdenom.go (1)

59-60: Address the TODO comment or create a tracking issue

There's a TODO comment at line 59 regarding the mapping from creator to denom. It's recommended to resolve TODOs or create GitHub issues to track them before merging.

Would you like me to open a GitHub issue to track this task?

x/bank/v2/keeper/handlers.go (2)

68-68: Consider handling admin changes via governance

The comment // TODO: should be gov? suggests that changing the admin of a denomination might be better managed through the governance module. Since changing the admin can have significant implications, routing this action through governance could ensure broader consensus and security.

Would you like assistance in proposing a governance-based implementation for admin changes?


55-66: Wrap errors with contextual information

When returning errors, it's helpful to wrap them with additional context to aid in debugging and error tracing. This practice aligns with the Uber Go Style Guide's recommendations for error handling.

For example, in line 60~:

 if err != nil {
-    return nil, err
+    return nil, fmt.Errorf("failed to create denom: %w", err)
 }

This approach provides clarity on where and why the error occurred.

x/bank/v2/keeper/keeper.go (2)

31-32: Maintain consistent ordering of struct fields

In the Keeper struct, consider grouping related fields together for better readability. Since denomMetadata and denomAuthority are related to denominations, they can be placed adjacent to other denomination-related fields.

Adjust the struct field ordering:

 type Keeper struct {
     appmodulev2.Environment

     authority     []byte
     addressCodec  address.Codec
     schema        collections.Schema
     params        collections.Item[types.Params]
+    denomMetadata  collections.Map[string, types.Metadata]
+    denomAuthority collections.Map[string, types.DenomAuthorityMetadata]
     balances      *collections.IndexedMap[collections.Pair[[]byte, string], math.Int, BalancesIndexes]
     supply        collections.Map[string, math.Int]

     sendRestriction *sendRestriction
 }

187-188: Use consistent naming conventions

The term "metadata" is used inconsistently in method names (GetDenomMetaData vs. denomMetadata). For clarity and consistency, consider using either MetaData or Metadata throughout.

Rename the method to match the field name:

-func (k Keeper) GetDenomMetaData(ctx context.Context, denom string) (types.Metadata, error) {
+func (k Keeper) GetDenomMetadata(ctx context.Context, denom string) (types.Metadata, error) {

Apply similar changes to other methods and variables where applicable.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 77254b7 and 007d595.

⛔ Files ignored due to path filters (4)
  • x/bank/v2/types/authorityMetadata.pb.go is excluded by !**/*.pb.go
  • x/bank/v2/types/bank.pb.go is excluded by !**/*.pb.go
  • x/bank/v2/types/genesis.pb.go is excluded by !**/*.pb.go
  • x/bank/v2/types/tx.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (18)
  • x/bank/proto/cosmos/bank/v2/authorityMetadata.proto (1 hunks)
  • x/bank/proto/cosmos/bank/v2/bank.proto (1 hunks)
  • x/bank/proto/cosmos/bank/v2/genesis.proto (3 hunks)
  • x/bank/proto/cosmos/bank/v2/tx.proto (1 hunks)
  • x/bank/v2/keeper/admins.go (1 hunks)
  • x/bank/v2/keeper/createdenom.go (1 hunks)
  • x/bank/v2/keeper/creators.go (1 hunks)
  • x/bank/v2/keeper/genesis.go (1 hunks)
  • x/bank/v2/keeper/handlers.go (1 hunks)
  • x/bank/v2/keeper/keeper.go (4 hunks)
  • x/bank/v2/keeper/keeper_test.go (1 hunks)
  • x/bank/v2/keeper/params.go (1 hunks)
  • x/bank/v2/module.go (1 hunks)
  • x/bank/v2/types/authorityMetadata.go (1 hunks)
  • x/bank/v2/types/denoms.go (1 hunks)
  • x/bank/v2/types/errors.go (1 hunks)
  • x/bank/v2/types/keys.go (1 hunks)
  • x/bank/v2/types/params.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • x/bank/v2/keeper/creators.go
🧰 Additional context used
📓 Path-based instructions (13)
x/bank/v2/keeper/admins.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/keeper/createdenom.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/keeper/genesis.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/keeper/handlers.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/keeper/keeper.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/keeper/keeper_test.go (2)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.


Pattern **/*_test.go: "Assess the unit test code assessing sufficient code coverage for the changes associated in the pull request"

x/bank/v2/keeper/params.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/module.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/types/authorityMetadata.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/types/denoms.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/types/errors.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/types/keys.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

x/bank/v2/types/params.go (1)

Pattern **/*.go: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.

🪛 buf
x/bank/proto/cosmos/bank/v2/authorityMetadata.proto

4-4: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

x/bank/proto/cosmos/bank/v2/bank.proto

4-4: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

🔇 Additional comments (18)
x/bank/v2/types/authorityMetadata.go (2)

1-5: LGTM: Package declaration and imports are correct.

The package is correctly declared as types, and the necessary sdk package is properly imported from cosmos-sdk.


1-15: Overall, excellent implementation of DenomAuthorityMetadata validation.

This file is well-structured, concise, and follows Go best practices. It adheres to the Single Responsibility Principle by focusing solely on validating the DenomAuthorityMetadata. The code is clean, readable, and efficiently implements the necessary validation logic.

x/bank/v2/keeper/params.go (2)

1-7: LGTM: Package declaration and imports are correct.

The package declaration and imports are appropriate for this keeper file. The necessary packages are imported, and the import block is correctly formatted.


1-21: LGTM: Overall structure and style are good.

The file structure, formatting, and style adhere to the Uber Golang style guide. The code is clean, well-organized, and easy to read.

x/bank/proto/cosmos/bank/v2/authorityMetadata.proto (1)

9-14: LGTM: Clear message definition with appropriate option

The DenomAuthorityMetadata message is well-defined with a clear and informative comment. The use of the gogoproto.equal option is appropriate for enabling equality checks on this message type.

x/bank/v2/keeper/admins.go (1)

1-34: Verify the accessibility of unexported methods

The methods setAuthorityMetadata and setAdmin are unexported. If these methods need to be accessed from other packages, they should be exported. Confirm whether they are intended to be unexported.

Please ensure that these methods are correctly scoped. If they are only used within the keeper package, then unexported methods are appropriate.

x/bank/v2/keeper/genesis.go (2)

55-59: Validate the creator's address format when deconstructing denom

When deconstructing the denom using types.DeconstructDenom, ensure that the creator address is valid and conforms to the expected format. An invalid address could cause issues downstream.

Add a validation step to confirm the creator address:

 creator, _, err := types.DeconstructDenom(genDenom.GetDenom())
 if err != nil {
     return fmt.Errorf("failed to deconstruct denom %s: %w", genDenom.GetDenom(), err)
 }
+if _, err := sdk.AccAddressFromBech32(creator); err != nil {
+    return fmt.Errorf("invalid creator address %s for denom %s: %w", creator, genDenom.GetDenom(), err)
+}

54-67: ⚠️ Potential issue

Ensure validation and uniqueness of factory denominations

While processing factory denominations, there is no explicit check for duplicate denominations or invalid entries. This could lead to issues during runtime if duplicates exist or if denominations are malformed.

Consider adding validation to ensure all factory denominations are unique and valid. You might also want to handle errors with more context.

 for _, genDenom := range state.GetFactoryDenoms() {
     creator, _, err := types.DeconstructDenom(genDenom.GetDenom())
     if err != nil {
-        return err
+        return fmt.Errorf("failed to deconstruct denom %s: %w", genDenom.GetDenom(), err)
     }
     err = k.createDenomAfterValidation(ctx, creator, genDenom.GetDenom())
     if err != nil {
-        return err
+        return fmt.Errorf("failed to create denom %s: %w", genDenom.GetDenom(), err)
     }
     err = k.setAuthorityMetadata(ctx, genDenom.GetDenom(), genDenom.GetAuthorityMetadata())
     if err != nil {
-        return err
+        return fmt.Errorf("failed to set authority metadata for denom %s: %w", genDenom.GetDenom(), err)
     }
 }

Run the following script to check for duplicate factory denominations:

This script assumes that your genesis.json has an app_state.bank.factory_denoms field containing the factory denominations.

x/bank/proto/cosmos/bank/v2/genesis.proto (2)

58-58: Verify the necessity of '(gogoproto.equal) = true' in 'GenesisDenom'

In the Balance message, (gogoproto.equal) = false is set, and (gogoproto.goproto_getters) = false is included to control code generation. Ensure that setting (gogoproto.equal) = true in GenesisDenom is intentional and that equality methods are required for this message. If not necessary, consider aligning with the Balance message settings for consistency.


6-6: Import statement for 'authorityMetadata.proto' seems appropriate

The addition of the import statement for "cosmos/bank/v2/authorityMetadata.proto" correctly brings in dependencies required for DenomAuthorityMetadata. This import is necessary for the newly added authority_metadata field in GenesisDenom.

x/bank/v2/types/denoms.go (1)

25-37: GetTokenDenom function looks good

The function correctly constructs the denom and validates it properly.

x/bank/proto/cosmos/bank/v2/bank.proto (1)

25-26: Verify the necessity of 'nullable' option on scalar field

The denom_creation_gas_consume field is of type uint64, which is a scalar. The (gogoproto.nullable) = true option may not have the intended effect on scalar types in Protobuf 3, as scalar fields are non-nullable by default. Please review whether this option is needed.

Run the following script to search for instances where nullable is used with scalar fields:

✅ Verification successful

Nullable option unnecessary on scalar field

The (gogoproto.nullable) = true option on the uint64 scalar field denom_creation_gas_consume in x/bank/proto/cosmos/bank/v2/bank.proto (lines 25-26) is unnecessary, as scalar fields are non-nullable by default in Protobuf 3.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of 'nullable' option with scalar types in .proto files.

# Expected: Such usages should be rare; this helps verify if it's a common practice in the codebase.
grep -nr "(gogoproto.nullable)" x/

Length of output: 42691

x/bank/v2/keeper/createdenom.go (2)

85-86: Check for nil pointers in params.DenomCreationFee

At line 89, you check if params.DenomCreationFee != nil to determine if there is a fee to charge. Ensure that DenomCreationFee is a pointer type and correctly initialized to prevent nil pointer dereferences.

Run the following script to inspect the definition of DenomCreationFee:

#!/bin/bash
# Description: Find the definition of DenomCreationFee in Params.

rg --type go 'DenomCreationFee\s+\*sdk\.Coins' -A 5

104-108: Ensure GasMeter is properly initialized before consumption

In the chargeForCreateDenom function, you consume gas using k.Environment.GasService.GasMeter(ctx). Please ensure that GasService and GasMeter are properly initialized in the context to avoid runtime panics.

Run the following script to verify the initialization of GasService:

x/bank/proto/cosmos/bank/v2/tx.proto (1)

71-72: Definition of MsgChangeAdminResponse is appropriate

The MsgChangeAdminResponse message is correctly defined and follows the pattern established in the module.

x/bank/v2/keeper/keeper.go (1)

47-48: ⚠️ Potential issue

Check for errors during schema building

In the NewKeeper function, after building the schema, any errors are checked and cause a panic. Consider handling the error instead of panicking to maintain application stability.

However, if panicking is the accepted practice in this initialization context within your codebase, this can be acceptable. Please ensure it aligns with your project's error-handling strategy.

If not already established, confirm whether panicking is acceptable here.

x/bank/v2/keeper/keeper_test.go (2)

240-350: Comprehensive test cases in TestCreateDenom

The added test cases thoroughly cover various scenarios for denom creation, including edge cases and error conditions, which enhances the robustness of the denom creation logic and ensures proper validation.


352-415: Accurate gas consumption testing in TestCreateDenom_GasConsume

The test effectively verifies that the gas consumed during denom creation falls within expected ranges under different gas parameters. This is crucial for performance optimization and ensures that gas consumption adheres to expected norms.

Comment on lines +15 to +17
// Can be empty for no admin, or a valid osmosis address
string admin = 1 [(gogoproto.moretags) = "yaml:\"admin\""];
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding a validation rule for the admin address

The admin field is well-defined and commented. However, to ensure data integrity, consider adding a validation rule to check if the admin address is either empty or a valid osmosis address. This can be done using the validate.rules option from the protoc-gen-validate plugin.

Example:

string admin = 1 [
  (gogoproto.moretags) = "yaml:\"admin\"",
  (validate.rules).string = {
    pattern: "^$|^osmo[a-zA-Z0-9]{39}$"
  }
];

This regex pattern allows either an empty string or a valid osmosis address.

Would you like me to provide more information on implementing this validation?

syntax = "proto3";
package cosmos.bank.v2;

import "gogoproto/gogo.proto";
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Missing gogoproto Dependency

The gogoproto/gogo.proto import is present in multiple .proto files, but the gogoproto directory and gogo.proto file are not found in the repository. This indicates that the necessary gogoproto dependency is missing and needs to be properly installed or included in the project.

  • Ensure that gogoproto is added to your project's dependency management system.
  • Verify that all dependencies are correctly installed and included in the repository.
🔗 Analysis chain

Verify the existence of the gogoproto import

The static analysis tool indicates that the file gogoproto/gogo.proto does not exist. Please ensure that this import is correctly set up in your project. If it's a third-party dependency, make sure it's properly installed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence of the gogoproto import

# Test: Check if the gogoproto directory exists
if [ -d "gogoproto" ]; then
    echo "gogoproto directory exists"
    # Check if the gogo.proto file exists
    if [ -f "gogoproto/gogo.proto" ]; then
        echo "gogo.proto file exists"
    else
        echo "gogo.proto file not found in gogoproto directory"
    fi
else
    echo "gogoproto directory not found"
fi

# Test: Search for other occurrences of gogoproto import
echo "Other files importing gogoproto:"
rg --type proto 'import "gogoproto/gogo.proto"'

Length of output: 246


Script:

#!/bin/bash
# Description: Re-verify the existence of the gogoproto import with corrected search

# Search for the gogo.proto file anywhere in the repository
echo "Searching for gogo.proto file in the repository..."
fd "gogo.proto" --type f

# Check if any gogo.proto files were found
if fd "gogo.proto" --type f | grep -q "gogo.proto"; then
    echo "gogo.proto file found."
else
    echo "gogo.proto file not found in the repository."
fi

# Search for import statements importing gogo.proto
echo "Searching for import statements with gogoproto/gogo.proto..."
rg 'import "gogoproto/gogo.proto"' --glob "*.proto" --no-filename

Length of output: 3176

🧰 Tools
🪛 buf

4-4: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

Comment on lines +10 to +13
func (k Keeper) GetAuthorityMetadata(ctx context.Context, denom string) (types.DenomAuthorityMetadata, error) {
authority, err := k.denomAuthority.Get(ctx, denom)
return authority, err
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use consistent variable naming for clarity

In the GetAuthorityMetadata function, the variable authority is assigned the DenomAuthorityMetadata, but in other functions like setAdmin, the same type is referred to as metadata. For consistency and readability, consider renaming authority to metadata.

Apply this diff to rename the variable:

 func (k Keeper) GetAuthorityMetadata(ctx context.Context, denom string) (types.DenomAuthorityMetadata, error) {
-	authority, err := k.denomAuthority.Get(ctx, denom)
-	return authority, err
+	metadata, err := k.denomAuthority.Get(ctx, denom)
+	return metadata, err
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (k Keeper) GetAuthorityMetadata(ctx context.Context, denom string) (types.DenomAuthorityMetadata, error) {
authority, err := k.denomAuthority.Get(ctx, denom)
return authority, err
}
func (k Keeper) GetAuthorityMetadata(ctx context.Context, denom string) (types.DenomAuthorityMetadata, error) {
metadata, err := k.denomAuthority.Get(ctx, denom)
return metadata, err
}

Comment on lines +15 to +23
// setAuthorityMetadata stores authority metadata for a specific denom
func (k Keeper) setAuthorityMetadata(ctx context.Context, denom string, metadata types.DenomAuthorityMetadata) error {
err := metadata.Validate()
if err != nil {
return err
}

return k.denomAuthority.Set(ctx, denom, metadata)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling by wrapping validation errors

In the setAuthorityMetadata function, when metadata.Validate() returns an error, it is returned directly. To provide more context and improve debugging, consider wrapping the error with additional information.

Apply this diff to wrap the error:

 func (k Keeper) setAuthorityMetadata(ctx context.Context, denom string, metadata types.DenomAuthorityMetadata) error {
 	err := metadata.Validate()
 	if err != nil {
-		return err
+		return fmt.Errorf("failed to validate metadata for denom %s: %w", denom, err)
 	}

 	return k.denomAuthority.Set(ctx, denom, metadata)
 }

Ensure you have imported the fmt package at the top of the file:

 import (
 	"context"

+	"fmt"
 	"cosmossdk.io/x/bank/v2/types"
 )
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// setAuthorityMetadata stores authority metadata for a specific denom
func (k Keeper) setAuthorityMetadata(ctx context.Context, denom string, metadata types.DenomAuthorityMetadata) error {
err := metadata.Validate()
if err != nil {
return err
}
return k.denomAuthority.Set(ctx, denom, metadata)
}
// setAuthorityMetadata stores authority metadata for a specific denom
func (k Keeper) setAuthorityMetadata(ctx context.Context, denom string, metadata types.DenomAuthorityMetadata) error {
err := metadata.Validate()
if err != nil {
return fmt.Errorf("failed to validate metadata for denom %s: %w", denom, err)
}
return k.denomAuthority.Set(ctx, denom, metadata)
}

}

// DefaultParams is the default parameter configuration for the bank/v2 module
func DefaultParams() Params {
return NewParams()
return NewParams(sdk.NewCoins(), 1_000_000)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Define default gas consumption as a constant for clarity

In the DefaultParams function, the hard-coded value 1_000_000 for DenomCreationGasConsume can be extracted into a named constant. This enhances readability and makes it easier to manage default values.

Apply this change:

+const DefaultDenomCreationGasConsume uint64 = 1_000_000

func DefaultParams() Params {
-	return NewParams(sdk.NewCoins(), 1_000_000)
+	return NewParams(sdk.NewCoins(), DefaultDenomCreationGasConsume)
}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
return NewParams(sdk.NewCoins(), 1_000_000)
const DefaultDenomCreationGasConsume uint64 = 1_000_000
func DefaultParams() Params {
return NewParams(sdk.NewCoins(), DefaultDenomCreationGasConsume)
}

Comment on lines +201 to +205
denomMetaData = append(denomMetaData, metadata)
return false
})

return denomMetaData
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle errors returned by IterateAllDenomMetaData in GetAllDenomMetaData

With IterateAllDenomMetaData now returning an error, GetAllDenomMetaData should handle this error to ensure proper error propagation.

Update GetAllDenomMetaData as follows:

-func (k Keeper) GetAllDenomMetaData(ctx context.Context) []types.Metadata {
+func (k Keeper) GetAllDenomMetaData(ctx context.Context) ([]types.Metadata, error) {
    denomMetaData := make([]types.Metadata, 0)
-   k.IterateAllDenomMetaData(ctx, func(metadata types.Metadata) bool {
+   err := k.IterateAllDenomMetaData(ctx, func(metadata types.Metadata) bool {
        denomMetaData = append(denomMetaData, metadata)
        return false
    })
+   if err != nil {
+       // Handle or log the error as needed
+       return nil, err
+   }

    return denomMetaData
}

Ensure that any callers of GetAllDenomMetaData are updated to handle the returned error.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
denomMetaData = append(denomMetaData, metadata)
return false
})
return denomMetaData
func (k Keeper) GetAllDenomMetaData(ctx context.Context) ([]types.Metadata, error) {
denomMetaData := make([]types.Metadata, 0)
err := k.IterateAllDenomMetaData(ctx, func(metadata types.Metadata) bool {
denomMetaData = append(denomMetaData, metadata)
return false
})
if err != nil {
// Handle or log the error as needed
return nil, err
}
return denomMetaData, nil
}

Comment on lines +180 to +181
panic(err)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using panic in IterateAccountBalances

In the IterateAccountBalances method, calling panic when an error occurs is discouraged. Using panic can cause the entire application to crash, which is undesirable in production code.

Modify the method to return the error instead:

-func (k Keeper) IterateAccountBalances(ctx context.Context, addr sdk.AccAddress, cb func(sdk.Coin) bool) {
+func (k Keeper) IterateAccountBalances(ctx context.Context, addr sdk.AccAddress, cb func(sdk.Coin) bool) error {
    err := k.balances.Walk(ctx, collections.NewPrefixedPairRange[[]byte, string](addr), func(key collections.Pair[[]byte, string], value math.Int) (stop bool, err error) {
        return cb(sdk.NewCoin(key.K2(), value)), nil
    })
    if err != nil {
-       panic(err)
+       return err
    }
+   return nil
}

Remember to update any callers of this method to handle the returned error appropriately.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
panic(err)
}
func (k Keeper) IterateAccountBalances(ctx context.Context, addr sdk.AccAddress, cb func(sdk.Coin) bool) error {
err := k.balances.Walk(ctx, collections.NewPrefixedPairRange[[]byte, string](addr), func(key collections.Pair[[]byte, string], value math.Int) (stop bool, err error) {
return cb(sdk.NewCoin(key.K2(), value)), nil
})
if err != nil {
return err
}
return nil
}

Comment on lines +187 to +189
m, err := k.denomMetadata.Get(ctx, denom)
return m, 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.

⚠️ Potential issue

Return errors explicitly in GetDenomMetaData

In GetDenomMetaData, the error from k.denomMetadata.Get(ctx, denom) is converted to a boolean. For clearer error handling, consider returning the error directly.

Modify the method:

-func (k Keeper) GetDenomMetaData(ctx context.Context, denom string) (types.Metadata, bool) {
+func (k Keeper) GetDenomMetaData(ctx context.Context, denom string) (types.Metadata, error) {
    m, err := k.denomMetadata.Get(ctx, denom)
-   return m, err == nil
+   if err != nil {
+       return types.Metadata{}, err
+   }
+   return m, nil
}

Update any code that calls GetDenomMetaData to handle the returned error.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
m, err := k.denomMetadata.Get(ctx, denom)
return m, err == nil
}
func (k Keeper) GetDenomMetaData(ctx context.Context, denom string) (types.Metadata, error) {
m, err := k.denomMetadata.Get(ctx, denom)
if err != nil {
return types.Metadata{}, err
}
return m, nil
}

Comment on lines +163 to +170
balances := sdk.NewCoins()
k.IterateAccountBalances(ctx, addr, func(balance sdk.Coin) bool {
balances = balances.Add(balance)
return false
})

return balances.Sort()
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle errors returned by IterateAccountBalances in GetAllBalances

After modifying IterateAccountBalances to return an error, the GetAllBalances method should handle this error to maintain robustness.

Update GetAllBalances to handle the error:

func (k Keeper) GetAllBalances(ctx context.Context, addr sdk.AccAddress) sdk.Coins {
    balances := sdk.NewCoins()
-   k.IterateAccountBalances(ctx, addr, func(balance sdk.Coin) bool {
+   err := k.IterateAccountBalances(ctx, addr, func(balance sdk.Coin) bool {
        balances = balances.Add(balance)
        return false
    })
+   if err != nil {
+       // Handle or log the error as needed
+       return balances
+   }

    return balances.Sort()
}

Committable suggestion was skipped due to low confidence.

// the range [gasConsume, gasConsume + offset]. If the actual gas consumption
// falls within the range for all test cases, we consider the test passed.
//
// In experience, the total amount of gas consumed should consume be ~30k more
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Typo in comment: Remove duplicate word 'consume'

In the comment on line 361, the word "consume" is duplicated.

Apply this diff to correct the typo:

-// In experience, the total amount of gas consumed should consume be ~30k more
+// In experience, the total amount of gas consumed should be ~30k more
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// In experience, the total amount of gas consumed should consume be ~30k more
// In experience, the total amount of gas consumed should be ~30k more

@julienrbrt julienrbrt changed the title Feat(bank/v2): Basic CreateDenom feat(bank/v2): Basic CreateDenom Oct 15, 2024
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.

4 participants