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): port tokenfactory into bank/v2 #22264

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

Conversation

hieuvubk
Copy link
Contributor

@hieuvubk hieuvubk commented Oct 15, 2024

Description

Ref: #22251

  • add denomMetadata & authorityMetadata funcs
  • Update params
  • Add MsgCreateDenom & MsgChangeAdmin handlers
  • Combining tokenfactory MsgMint, MsgBurn into bank/v2 mint, burn
  • cmd txs & queries
  • 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 message types for managing token denominations: MsgCreateDenom, MsgChangeAdmin, MsgBurn, and their corresponding response types.
    • Enhanced functionality for burning tokens, creating new denominations, and changing denomination admins.
    • Added new methods for retrieving and managing denomination metadata and balances, including querying authority metadata and denominations from a creator.
    • Implemented new CLI commands for creating token denominations and querying denomination metadata.
  • Bug Fixes

    • Improved validation logic for minting and burning tokens.
  • Tests

    • Expanded test coverage for new denomination creation, minting, burning, and sending functionalities.
    • Added tests to validate the creation of new denominations and gas consumption.
  • Documentation

    • Introduced sentinel error variables for clearer error handling related to denomination management.
    • Enhanced parameter validation for denomination creation fees and gas consumption.

@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
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several new message types and modifies existing structures in the x/bank/proto/cosmos/bank/v2/tx.proto file, enhancing denomination management capabilities. New messages include MsgCreateDenom, MsgCreateDenomResponse, MsgChangeAdmin, and MsgChangeAdminResponse. The MsgMint message is updated to change the amount field from repeated to a single instance. Corresponding handler methods are added in x/bank/v2/keeper/handlers.go, and new test cases are implemented in x/bank/v2/keeper/keeper_test.go. A new error handling file errors.go introduces sentinel errors for better error management.

Changes

File Change Summary
x/bank/proto/cosmos/bank/v2/tx.proto Added messages: MsgCreateDenom, MsgCreateDenomResponse, MsgChangeAdmin, MsgChangeAdminResponse. Updated MsgMint to change amount from repeated to single instance.
x/bank/v2/keeper/handlers.go Added methods: MsgCreateDenom, MsgChangeAdmin, MsgBurn, and a query method DenomAuthorityMetadata. Updated MsgMint for additional checks and refined error handling.
x/bank/v2/keeper/keeper_test.go Added tests: TestCreateDenom, TestCreateDenom_GasConsume, TestMintHandler, TestSendHandler_TokenfactoryDenom.
x/bank/v2/types/errors.go Introduced sentinel errors: ErrDenomExists, ErrUnauthorized, ErrInvalidDenom, ErrInvalidCreator, ErrSubdenomTooLong, ErrCreatorTooLong, ErrDenomDoesNotExist.
x/bank/proto/cosmos/bank/v2/query.proto Added messages: QueryDenomAuthorityMetadataRequest, QueryDenomAuthorityMetadataResponse.
x/bank/v2/client/cli/tx.go Added command handler for MsgCreateDenom in CLI.
x/bank/v2/keeper/keeper.go Added fields for denomMetadata and denomAuthority, and new methods for managing balances and metadata.
x/bank/v2/types/codec.go Registered &MsgCreateDenom{} in the RegisterInterfaces function.
x/bank/v2/types/params.go Updated NewParams and DefaultParams to include validation for denomCreationFee and gasConsume.

Possibly related PRs

  • feat(bank/v2): Send function #21606: The changes in this PR involve the addition of new message handling functions (MsgCreateDenom, MsgChangeAdmin, and MsgBurn) that directly relate to the new message types introduced in the main PR, enhancing denomination management.
  • test: migrate e2e/bank to system tests #21607: This PR includes tests for sending transactions, which are relevant to the new message types and functionalities introduced in the main PR, particularly around the management of denominations and coin transfers.
  • feat(bank/v2): Add MsgSend handler #21736: The addition of the MsgSend handler in this PR is directly related to the changes in the main PR, as it enhances the functionality for sending coins, which is a core aspect of the new message types introduced.
  • refactor(x/bank): swap sendrestriction check in InputOutputCoins #21976: This PR modifies the InputOutputCoins method to check send restrictions before deducting coins, which aligns with the new functionalities introduced in the main PR regarding coin management and restrictions.
  • docs: update bank docs #22053: The updates to the bank documentation in this PR clarify the changes made in the main PR, particularly regarding the new message types and their functionalities, ensuring that users understand the updated interfaces and methods.

Suggested labels

C:x/accounts, Type: Build, Type: CI

Suggested reviewers

  • akhilkumarpilli
  • julienrbrt
  • kocubinski
  • sontrinh16

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.

x/bank/v2/keeper/params.go Show resolved Hide resolved
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)

x/bank/v2/keeper/admins.go Show resolved Hide resolved
x/bank/v2/keeper/admins.go Show resolved Hide resolved
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")
}

x/bank/v2/keeper/keeper_test.go Show resolved Hide resolved
x/bank/v2/keeper/keeper.go Show resolved Hide resolved
x/bank/v2/keeper/keeper.go Show resolved Hide resolved
x/bank/v2/keeper/keeper.go Show resolved Hide resolved
x/bank/v2/keeper/keeper.go Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

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
@julienrbrt
Copy link
Member

I'm out for a week, let's not block this, and get some reviews. @facundomedica or @testinginprod, could you give a look?

@hieuvubk
Copy link
Contributor Author

I will add tokenfatory mint, burn, force transfer in this pr too

@julienrbrt
Copy link
Member

I will add tokenfatory mint, burn, force transfer in this pr too

I'm not sure we want force transfer tbh

@hieuvubk
Copy link
Contributor Author

I will add tokenfatory mint, burn, force transfer in this pr too

I'm not sure we want force transfer tbh

yes agree

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: 11

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

5-9: Consider removing unnecessary import alias for fmt.

According to the Uber Go Style Guide, we should avoid renaming imports except to avoid naming conflicts. The fmt package doesn't need an alias.

-	fmt "fmt"
+	"fmt"
x/bank/v2/keeper/handlers.go (5)

55-66: Add documentation for the exported method MsgCreateDenom.

The method MsgCreateDenom is exported but lacks a comment. According to the Uber Go Style Guide, all exported functions and methods should have a comment starting with the function name.

You may add a comment like:

// MsgCreateDenom handles the creation of a new denomination.

68-68: Clarify or address the TODO comment regarding governance.

The TODO comment // TODO: should be gov? suggests uncertainty about whether MsgChangeAdmin should be handled via governance. Please clarify this point. If governance integration is required, consider implementing it or create an issue to track this task.

Would you like assistance in integrating the governance module or opening a GitHub issue to track this requirement?


69-87: Add documentation for the exported method MsgChangeAdmin.

The method MsgChangeAdmin is exported but lacks a comment. As per the Uber Go Style Guide, adding a comment improves code readability and maintainability.

You may add a comment like:

// MsgChangeAdmin allows changing the admin of a specific denomination.

170-170: Address the TODO regarding minting to the module account.

The comment // TODO: should mint to mint module then transfer? suggests a consideration to mint tokens to the mint module before transferring them. Implementing this change could align the minting process with standard practices and improve security.

Would you like assistance in implementing this change or opening a GitHub issue to track this task?


178-230: Add documentation for the exported method MsgBurn.

The method MsgBurn is exported but lacks a comment. As recommended by the Uber Go Style Guide, documenting exported methods enhances code clarity.

You may add a comment like:

// MsgBurn handles burning tokens from a specified address.
x/bank/v2/keeper/keeper_test.go (6)

Line range hint 86-86: Correct typo in function names

The function names contain a typo. "Acount" should be corrected to "Account" for clarity and consistency.

Apply these diffs:

-func (suite *KeeperTestSuite) TestSendCoins_Acount_To_Account() {
+func (suite *KeeperTestSuite) TestSendCoins_Account_To_Account() {
-func (suite *KeeperTestSuite) TestSendCoins_Acount_To_Module() {
+func (suite *KeeperTestSuite) TestSendCoins_Account_To_Module() {

Also applies to: 120-120


Line range hint 218-220: Error messages should start with lowercase letters

In Go, error messages should start with a lowercase letter and should not end with punctuation. This aligns with the Go error formatting guidelines.

Apply these diffs:

-			return nil, fmt.Errorf("Can not send to same address")
+			return nil, fmt.Errorf("cannot send to same address")
-			return nil, fmt.Errorf("Allow only one denom per one send")
+			return nil, fmt.Errorf("allow only one denom per one send")

Also applies to: 227-229


240-351: Consider using predefined constants for magic numbers

In the test cases for TestCreateDenom, magic numbers like 50_000_000 and 5_000_000_000 are used directly. Defining these values as constants would improve readability and maintainability.

For example:

const (
	defaultCreationFeeAmount = 50_000_000
	largeCreationFeeAmount   = 5_000_000_000
)

And then use these constants in your Params definitions.


487-500: Ensure error messages are checked in test cases

In the TestMintHandler test cases, when an error is expected (expErr: true), consider checking the specific error message to ensure the correct error is being returned.

For example:

require.Error(err)
require.Contains(err.Error(), "expected error message")

603-604: Remove unnecessary blank lines at the end of functions

There are extra blank lines at the end of the TestBurnHandler, TestSendHandler_TokenfactoryDenom, and possibly other functions. Removing them can keep the code clean and consistent.

Apply these diffs:

-	}
-
-}
+	}
+}

Also applies to: 621-622, 685-686


241-351: Consider adding edge case test for maximum subdenom length

While there is a test case for a subdenom that is too long, consider adding a test case for a subdenom that is exactly at the maximum allowed length to ensure boundary conditions are handled correctly.

For example:

{
	desc:             "subdenom at maximum length",
	denomCreationFee: defaultDenomCreationFee,
	subdenom:         strings.Repeat("a", maxSubdenomLength),
	valid:            true,
},
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 007d595 and 767299a.

⛔ Files ignored due to path filters (1)
  • x/bank/v2/types/tx.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (5)
  • x/bank/proto/cosmos/bank/v2/tx.proto (2 hunks)
  • x/bank/v2/keeper/handlers.go (3 hunks)
  • x/bank/v2/keeper/keeper.go (5 hunks)
  • x/bank/v2/keeper/keeper_test.go (2 hunks)
  • x/bank/v2/types/errors.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
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/types/errors.go (1)

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

🔇 Additional comments (13)
x/bank/v2/types/errors.go (1)

13-20: Verify error code sequence and constant definitions.

A few concerns about the error definitions:

  1. Error codes have gaps (missing 6,7). Consider using sequential error codes for better maintenance.
  2. The code references undefined constants (ModuleName, MaxSubdenomLength, MaxCreatorLength).

Let's verify the constant definitions:

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

82-83: Verify impact of changing from repeated to single Coin

The change from repeated Coins to a single Coin in the amount field is a breaking change. Please ensure:

  1. This aligns with other mint message implementations
  2. All clients and dependent code are updated
#!/bin/bash
# Search for other mint message implementations
ast-grep --pattern 'message $$$Mint {
  $$$
  repeated cosmos.base.v1beta1.Coin $$$
  $$$
}'

47-54: Consider adding length and character set validations for subdenom

The subdenom field should have additional protobuf validations to ensure it meets the denomination requirements:

  • Maximum length constraints
  • Allowed character set restrictions
#!/bin/bash
# Search for existing denom validation patterns in the codebase
rg -g '*.proto' '(validate|validator).*denom'

61-69: Verify consistency with admin change messages in other modules

Please ensure this message structure aligns with similar admin change messages in other Cosmos SDK modules for consistency.

✅ Verification successful

Message structure aligns with SDK patterns for admin changes

The MsgChangeAdmin message structure follows consistent patterns found in other Cosmos SDK modules, particularly the group module:

  • Both use the cosmos.AddressString scalar for address fields
  • Similar field structure with current admin/sender and new admin
  • Consistent empty response message pattern

The main differences are contextual and justified:

  • Bank module uses "sender" vs "admin" to align with its domain
  • Bank module includes "denom" field specific to its token context
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for similar admin change messages in other modules
ast-grep --pattern 'message MsgChange$$$Admin {
  $$$
}'

Length of output: 94


Script:

#!/bin/bash
# Search for admin-related messages in proto files using ripgrep
rg -U "message Msg.*Admin.*\{[\s\S]*?\}" --type proto -A 10

# Also search for specific change admin patterns
rg "MsgChangeAdmin|MsgUpdateAdmin" --type proto

Length of output: 171


Script:

#!/bin/bash
# Search for admin-related messages in proto files
rg -U "message Msg.*Admin.*\{[\s\S]*?\}" "*.proto" -A 10

# Also search for specific change admin patterns in all files
rg "MsgChangeAdmin|MsgUpdateAdmin" --type-list
rg "MsgChangeAdmin|MsgUpdateAdmin"

Length of output: 5759


Script:

#!/bin/bash
# Let's search for similar patterns in other modules to find comparable message structures
fd -e proto -x cat {} \; | rg -U "message Msg.*Admin.*\{[\s\S]*?\}" -A 10

# Also search specifically in well-known module locations
fd -e proto -g "**/gov/**" -g "**/group/**" -g "**/authz/**" -x cat {} \; | rg -U "message Msg.*Admin.*\{[\s\S]*?\}" -A 10

Length of output: 3338

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

165-165: Ensure amount validation consistently uses IsPositive().

The code correctly uses msg.Amount.IsPositive() to check that the amount is strictly positive. This change from IsAllPositive() ensures that single coin amounts are validated properly.

Also applies to: 220-221

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

25-32: Fields added to the Keeper struct are appropriate

The new fields added to the Keeper struct for managing denomination metadata and authority (denomMetadata and denomAuthority) are correctly defined and enhance the module's functionality.


47-48: Initialization of new maps in NewKeeper is correct

The denomMetadata and denomAuthority maps are properly initialized in the NewKeeper function, ensuring they are ready for use within the keeper.


181-185: Handle errors explicitly in HasSupply

The HasSupply function suppresses errors from k.supply.Has by returning has && err == nil, which can mask underlying issues that should be handled.


211-218: Avoid panicking in IterateAccountBalances; return errors instead

The IterateAccountBalances function panics if an error occurs during iteration. Panicking in library code is discouraged as it can cause unexpected crashes. Errors should be returned and handled appropriately.


222-225: Return errors explicitly in GetDenomMetaData

In GetDenomMetaData, the error from k.denomMetadata.Get is converted to a boolean, which may suppress important error information.


247-254: Avoid panicking in IterateAllDenomMetaData; return errors instead

The IterateAllDenomMetaData function panics on errors during iteration. It's recommended to return errors and allow the caller to handle them.

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

353-416: ⚠️ Potential issue

Update comment to fix grammatical error

In the comment describing the TestCreateDenom_GasConsume function, there's a duplicate word "consume" that should be removed for clarity.

Apply this diff:

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

Likely invalid or redundant comment.


625-687: Verify handling of invalid addresses in TestSendHandler_TokenfactoryDenom

The current test cases do not cover scenarios where the FromAddress or ToAddress are invalid (e.g., improperly formatted or nonexistent). Consider adding test cases to cover these situations.

Run the following script to check for improper address handling:

Comment on lines +17 to +18
ErrSubdenomTooLong = errorsmod.Register(ModuleName, 8, fmt.Sprintf("subdenom too long, max length is %d bytes", MaxSubdenomLength))
ErrCreatorTooLong = errorsmod.Register(ModuleName, 9, fmt.Sprintf("creator too long, max length is %d bytes", MaxCreatorLength))
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 using constant error messages.

For error messages that use fmt.Sprintf, consider defining the formatted strings as constants to avoid runtime formatting overhead, especially since the max lengths are constants.

+const (
+    errSubdenomTooLong = "subdenom too long, max length is %d bytes"
+    errCreatorTooLong  = "creator too long, max length is %d bytes"
+)

var (
    // ... other errors ...
-    ErrSubdenomTooLong   = errorsmod.Register(ModuleName, 8, fmt.Sprintf("subdenom too long, max length is %d bytes", MaxSubdenomLength))
-    ErrCreatorTooLong    = errorsmod.Register(ModuleName, 9, fmt.Sprintf("creator too long, max length is %d bytes", MaxCreatorLength))
+    ErrSubdenomTooLong   = errorsmod.Register(ModuleName, 8, fmt.Sprintf(errSubdenomTooLong, MaxSubdenomLength))
+    ErrCreatorTooLong    = errorsmod.Register(ModuleName, 9, fmt.Sprintf(errCreatorTooLong, MaxCreatorLength))
    // ... other errors ...
)
📝 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
ErrSubdenomTooLong = errorsmod.Register(ModuleName, 8, fmt.Sprintf("subdenom too long, max length is %d bytes", MaxSubdenomLength))
ErrCreatorTooLong = errorsmod.Register(ModuleName, 9, fmt.Sprintf("creator too long, max length is %d bytes", MaxCreatorLength))
const (
errSubdenomTooLong = "subdenom too long, max length is %d bytes"
errCreatorTooLong = "creator too long, max length is %d bytes"
)
var (
ErrSubdenomTooLong = errorsmod.Register(ModuleName, 8, fmt.Sprintf(errSubdenomTooLong, MaxSubdenomLength))
ErrCreatorTooLong = errorsmod.Register(ModuleName, 9, fmt.Sprintf(errCreatorTooLong, MaxCreatorLength))
)

Comment on lines +137 to +139
if msg.Authority != authorityMetadata.GetAdmin() {
return nil, types.ErrUnauthorized
}
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

Ensure proper address comparison in authority checks.

Comparing addresses as strings may lead to incorrect results due to formatting differences or case sensitivity. It's safer to decode the addresses and compare their byte representations using bytes.Equal to ensure accurate validation.

Consider modifying the code in both MsgMint and MsgBurn as follows:

authorityAddr, err := h.addressCodec.StringToBytes(msg.Authority)
if err != nil {
    return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err)
}

adminAddr, err := h.addressCodec.StringToBytes(authorityMetadata.GetAdmin())
if err != nil {
    return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid admin address: %s", err)
}

if !bytes.Equal(authorityAddr, adminAddr) {
    return nil, types.ErrUnauthorized
}

Also applies to: 192-194

Comment on lines +211 to +214
from, err := h.addressCodec.StringToBytes(msg.BurnFromAddress)
if err != nil {
return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", 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

Correct the error message for invalid address in MsgBurn.

The error message references "invalid to address" when decoding msg.BurnFromAddress. It should say "invalid from address" to accurately reflect the source of the error.

Apply this diff to fix the error message:

if err != nil {
    - return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", err)
    + return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", 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
from, err := h.addressCodec.StringToBytes(msg.BurnFromAddress)
if err != nil {
return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid to address: %s", err)
}
from, err := h.addressCodec.StringToBytes(msg.BurnFromAddress)
if err != nil {
return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid from address: %s", err)
}

Comment on lines +109 to +113
for _, amount := range amounts {
supply := k.GetSupply(ctx, amount.GetDenom())
supply = supply.Sub(amount)
k.setSupply(ctx, supply)
}
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

Prevent negative total supply when burning coins

When burning coins, the supply is reduced by the burn amount without checking if the supply will become negative. This could lead to inconsistencies if the burn amount exceeds the current supply.

Add a check to ensure that the new supply does not become negative:

for _, amount := range amounts {
	supply := k.GetSupply(ctx, amount.GetDenom())
+	if supply.IsLT(amount) {
+		return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "burn amount exceeds current supply for denom %s", amount.Denom)
+	}
-	supply = supply.Sub(amount)
+	newSupply := supply.Sub(amount)
	k.setSupply(ctx, newSupply)
}
📝 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
for _, amount := range amounts {
supply := k.GetSupply(ctx, amount.GetDenom())
supply = supply.Sub(amount)
k.setSupply(ctx, supply)
}
for _, amount := range amounts {
supply := k.GetSupply(ctx, amount.GetDenom())
if supply.IsLT(amount) {
return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "burn amount exceeds current supply for denom %s", amount.Denom)
}
newSupply := supply.Sub(amount)
k.setSupply(ctx, newSupply)
}

expErr: true,
},
{
desc: "Mint tokenfatory denom, valid",
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

Correct typo in test case descriptions

The word "tokenfatory" in the test case descriptions should be corrected to "tokenfactory" to ensure clarity.

Apply these diffs:

-			desc: "Mint tokenfatory denom, valid",
+			desc: "Mint tokenfactory denom, valid",
-			desc: "Mint tokenfatory denom, invalid admin",
+			desc: "Mint tokenfactory denom, invalid admin",
-			desc: "Mint tokenfatory denom, denom not created",
+			desc: "Mint tokenfactory denom, denom not created",

Also applies to: 469-469, 478-478

Comment on lines +552 to +568
desc: "Burn foo denom, insufficient funds",
msg: &types.MsgBurn{
Authority: authority.String(),
BurnFromAddress: accAddrs[0].String(),
Amount: sdk.NewCoin(fooDenom, math.NewInt(200)),
},
expErr: true,
},
{
desc: "Burn bar denom, invalid denom",
msg: &types.MsgBurn{
Authority: authority.String(),
BurnFromAddress: accAddrs[0].String(),
Amount: sdk.NewCoin(barDenom, math.NewInt(50)),
},
expErr: 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

Add test case for burning with invalid amount

Currently, there is no test case for attempting to burn a negative or zero amount. Adding such a test case would ensure that the code correctly handles invalid burn amounts.

Consider adding a new test case:

{
	desc: "Burn with invalid amount",
	msg: &types.MsgBurn{
		Authority:       authority.String(),
		BurnFromAddress: accAddrs[0].String(),
		Amount:          sdk.NewCoin(fooDenom, math.NewInt(0)),
	},
	expErr: true,
},

Comment on lines 625 to 687
func (s *KeeperTestSuite) TestSendHandler_TokenfactoryDenom() {
s.SetupTest()
require := s.Require()
s.bankKeeper.SetParams(s.ctx, types.Params{
DenomCreationFee: sdk.NewCoins(sdk.NewCoin(fooDenom, math.NewInt(10))),
})
handler := keeper.NewHandlers(&s.bankKeeper)
require.NoError(banktestutil.FundAccount(s.ctx, s.bankKeeper, accAddrs[0], sdk.NewCoins(sdk.NewCoin(fooDenom, math.NewInt(100)))))

resp, err := handler.MsgCreateDenom(s.ctx, &types.MsgCreateDenom{
Sender: accAddrs[0].String(),
Subdenom: "test",
})
require.NoError(err)

newDenom := resp.NewTokenDenom

_, err = handler.MsgMint(s.ctx, &types.MsgMint{
Authority: accAddrs[0].String(),
ToAddress: accAddrs[0].String(),
Amount: sdk.NewCoin(newDenom, math.NewInt(100)),
})
require.NoError(err)

for _, tc := range []struct {
desc string
msg *types.MsgSend
expErr bool
}{
{
desc: "valid",
msg: &types.MsgSend{
FromAddress: accAddrs[0].String(),
ToAddress: accAddrs[1].String(),
Amount: sdk.NewCoins(sdk.NewCoin(newDenom, math.NewInt(50))),
},
expErr: false,
},
{
desc: "insufficient funds",
msg: &types.MsgSend{
FromAddress: accAddrs[0].String(),
ToAddress: accAddrs[1].String(),
Amount: sdk.NewCoins(sdk.NewCoin(newDenom, math.NewInt(150))),
},
expErr: true,
},
} {
s.Run(fmt.Sprintf("Case %s", tc.desc), func() {
_, err := handler.MsgSend(s.ctx, tc.msg)
if tc.expErr {
require.Error(err)
} else {
require.NoError(err)
// Check ToAddress balances after
toAddr, err := s.addressCodec.StringToBytes(tc.msg.ToAddress)
require.NoError(err)
balances := s.bankKeeper.GetAllBalances(s.ctx, toAddr)
require.Equal(balances, tc.msg.Amount)
}
})
}
}
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 test cases for sending zero or negative amounts

In the TestSendHandler_TokenfactoryDenom, there are no test cases for sending zero or negative amounts. Adding these tests can ensure the code correctly rejects invalid transactions.

For example:

{
	desc: "send zero amount",
	msg: &types.MsgSend{
		FromAddress: accAddrs[0].String(),
		ToAddress:   accAddrs[1].String(),
		Amount:      sdk.NewCoins(sdk.NewCoin(newDenom, math.NewInt(0))),
	},
	expErr: true,
},
{
	desc: "send negative amount",
	msg: &types.MsgSend{
		FromAddress: accAddrs[0].String(),
		ToAddress:   accAddrs[1].String(),
		Amount:      sdk.NewCoins(sdk.NewCoin(newDenom, math.NewInt(-10))),
	},
	expErr: true,
},

@@ -16,6 +16,7 @@
storetypes "cosmossdk.io/store/types"
"cosmossdk.io/x/bank/v2/keeper"
banktestutil "cosmossdk.io/x/bank/v2/testutil"
"cosmossdk.io/x/bank/v2/types"
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

Remove duplicate import of the same package

The package cosmossdk.io/x/bank/v2/types is imported twice, once without an alias and once as banktypes. This redundancy can lead to confusion and is unnecessary.

Apply this diff to remove the redundant import:

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

Committable suggestion was skipped due to low confidence.

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: 10

🧹 Outside diff range and nitpick comments (8)
x/bank/v2/types/errors.go (3)

3-3: Document the purpose of DONTCOVER.

The DONTCOVER comment typically indicates that this file should be excluded from coverage reports, but it's best practice to explain why coverage is not needed here.

Add a comment explaining why this file is excluded from coverage:

// DONTCOVER
+// This file is excluded from test coverage because error definitions are not testable.

1-2: Add package documentation.

The package lacks documentation explaining its purpose and usage.

Add package documentation:

package types

+// Package types provides type definitions and error handling for the bank/v2 module.
+// It includes sentinel errors for token factory operations and related functionality.

// DONTCOVER

Also applies to: 5-9


13-19: Improve error message consistency.

The error messages could be more consistent and descriptive:

-    ErrDenomExists       = errorsmod.Register(ModuleName, 2, "attempting to create a denom that already exists (has bank metadata)")
-    ErrUnauthorized      = errorsmod.Register(ModuleName, 3, "unauthorized account")
-    ErrInvalidDenom      = errorsmod.Register(ModuleName, 4, "invalid denom")
-    ErrInvalidCreator    = errorsmod.Register(ModuleName, 5, "invalid creator")
+    ErrDenomExists       = errorsmod.Register(ModuleName, 2, "denomination already exists")
+    ErrUnauthorized      = errorsmod.Register(ModuleName, 3, "unauthorized account: missing required permissions")
+    ErrInvalidDenom      = errorsmod.Register(ModuleName, 4, "invalid denomination format")
+    ErrInvalidCreator    = errorsmod.Register(ModuleName, 5, "invalid creator address")
x/bank/v2/keeper/handlers.go (2)

68-68: Address the TODO comment regarding governance

The comment // TODO: should be gov? suggests uncertainty about whether MsgChangeAdmin should be governed by governance procedures. Consider whether changing the admin of a denomination should require governance approval to enhance security and align with protocol standards.

Would you like assistance in evaluating if this operation should be controlled by governance, possibly by integrating it with the governance module?


124-125: Typo in comment

The comment // Check if is a tokenfatory denom contains a typo. It should be "tokenfactory" instead of "tokenfatory".

Apply this diff to fix the typo:

-    // Check if is a tokenfatory denom
+    // Check if it is a tokenfactory denom
x/bank/v2/keeper/keeper_test.go (3)

257-259: Consider Adding Test Case Descriptions

Adding comments to explain each test case enhances readability and provides context for future maintainers.

For example:

{
    desc: "subdenom too long",
    // Test with a subdenom exceeding the maximum allowed length.
    // Expectation: The creation should fail.
    ...
},

460-466: Typo in Test Description and Variable Name

There's a typo in the test description and variable name "tokenfatory" instead of "tokenfactory".

Correct the typos:

-desc: "Mint tokenfatory denom, valid",
+desc: "Mint tokenfactory denom, valid",

Also, ensure consistency in comments and variable naming throughout the code.


Line range hint 567-567: Ensure Test Coverage for Negative Cases

While the tests include cases for insufficient funds, consider adding test cases for invalid addresses or unsupported denominations to cover additional negative scenarios.

Add test cases like:

{
    desc: "invalid to address",
    msg: &types.MsgSend{
        FromAddress: accAddrs[0].String(),
        ToAddress:   "invalid_address",
        Amount:      sdk.NewCoins(sdk.NewCoin(newDenom, math.NewInt(50))),
    },
    expErr: true,
},
{
    desc: "unsupported denomination",
    msg: &types.MsgSend{
        FromAddress: accAddrs[0].String(),
        ToAddress:   accAddrs[1].String(),
        Amount:      sdk.NewCoins(sdk.NewCoin("unsupported_denom", math.NewInt(50))),
    },
    expErr: true,
},
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 007d595 and 498208a.

⛔ Files ignored due to path filters (1)
  • x/bank/v2/types/tx.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (4)
  • x/bank/proto/cosmos/bank/v2/tx.proto (2 hunks)
  • x/bank/v2/keeper/handlers.go (3 hunks)
  • x/bank/v2/keeper/keeper_test.go (2 hunks)
  • x/bank/v2/types/errors.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
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_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/types/errors.go (1)

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

🔇 Additional comments (8)
x/bank/v2/types/errors.go (1)

11-20: ⚠️ Potential issue

Review error definitions and constants.

Several issues to address:

  1. Error codes should be documented and sequential (currently jumps from 5 to 8)
  2. References undefined constants (ModuleName, MaxSubdenomLength, MaxCreatorLength)
  3. Consider using constants for error codes for better maintainability

Let's verify the missing constants:

Suggested improvements:

+// Error codes for bank/v2 module
+const (
+    ErrCodeDenomExists       = 2
+    ErrCodeUnauthorized      = 3
+    ErrCodeInvalidDenom      = 4
+    ErrCodeInvalidCreator    = 5
+    ErrCodeSubdenomTooLong   = 8
+    ErrCodeCreatorTooLong    = 9
+    ErrCodeDenomDoesNotExist = 10
+)

// x/tokenfactory module sentinel errors
var (
-    ErrDenomExists       = errorsmod.Register(ModuleName, 2, "attempting to create a denom that already exists (has bank metadata)")
+    ErrDenomExists       = errorsmod.Register(ModuleName, ErrCodeDenomExists, "attempting to create a denom that already exists (has bank metadata)")
    // ... apply similar changes for other errors
)
x/bank/v2/keeper/handlers.go (3)

55-66: Function MsgCreateDenom implementation looks good

The implementation correctly handles the creation of a new denomination and returns the appropriate response.


77-79: Duplicate comment: The issue regarding address comparison has been previously noted and is still applicable.


165-165: Validation check is appropriate

The use of msg.Amount.IsPositive() correctly ensures that the minted amount is positive.

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

353-416: Clarify Gas Consumption Comments and Calculations

The comments and calculations around gas consumption could be clarified to enhance understanding.

  • Correct the typo in the comment on line 362 by removing the duplicate word "consume".
  • Provide examples or references for where the ~30k additional gas consumption comes from.
  • Ensure that the test accurately reflects the intended gas usage checks.

Apply this diff to fix 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

494-496: 🛠️ Refactor suggestion

Simplify Address Conversion

The conversion from string to bytes for addresses can be simplified by using sdk.AccAddressFromBech32.

Update the code as follows:

-toAddr, err := s.addressCodec.StringToBytes(tc.msg.ToAddress)
+toAddr, err := sdk.AccAddressFromBech32(tc.msg.ToAddress)

This utilizes the SDK's built-in function for address conversion and improves code reliability.

Likely invalid or redundant comment.


313-314: ⚠️ Potential issue

Check for Errors When Setting Params

Currently, the code assumes that SetParams will succeed without error. It's safer to check for errors to handle unexpected failures.

Apply this change to handle potential errors:

-require.NoError(s.bankKeeper.SetParams(s.ctx, tc.denomCreationFee))
+err := s.bankKeeper.SetParams(s.ctx, tc.denomCreationFee)
+require.NoError(err)

Likely invalid or redundant comment.


295-299: Verify Insufficient Funds Handling

Ensure that the test case correctly verifies the behavior when the account doesn't have enough funds to pay the denom creation fee.

Run the following script to check if the account balance is less than the required denom creation fee:

Ensure that the account balance is indeed less than 5,000,000,000 units of the primary denom.

✅ Verification successful

Test Case Correctly Verifies Insufficient Funds Scenario

The test case is properly structured to verify insufficient funds handling. Here's why:

  • The account is funded with twoDenomCreationFee (50,000,000 tokens)
  • The test attempts to create a denom with largeCreationFee (5,000,000,000 tokens)
  • The valid: false expectation correctly anticipates the failure
  • The difference in amounts (5,000,000,000 > 50,000,000) ensures the account has insufficient funds

The test case effectively validates that denom creation fails when the account balance is less than the required fee.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify account balance prior to denom creation.

# Test: Check account balance.
# Expect: Balance is less than the largeCreationFee.

# Retrieve the account balance for accAddrs[0].
curl -s 'http://localhost:26657/abci_query?path="account/balance"&data="'$(echo -n "${accAddrs[0]}" | base64)'"' | jq '.result.response.value' | base64 --decode

# Compare the balance with the largeCreationFee (5,000,000,000).
# Ensure that the balance is insufficient.

Length of output: 294


Script:

#!/bin/bash
# Let's examine the test file to understand how the test case is structured
rg -A 20 "account doesn't have enough to pay for denom creation fee" x/bank/v2/keeper/keeper_test.go

# Also check how largeCreationFee is defined
rg "largeCreationFee.*:=" x/bank/v2/keeper/keeper_test.go

Length of output: 991


Script:

#!/bin/bash
# Let's find how largeCreationFee is defined in the test file
rg -B 10 "largeCreationFee" x/bank/v2/keeper/keeper_test.go

# Also check the test setup and funding
rg "FundAccount.*accAddrs" x/bank/v2/keeper/keeper_test.go

Length of output: 1744

Comment on lines +47 to +54
// MsgCreateDenom represents a message to create new denom.
message MsgCreateDenom {
option (cosmos.msg.v1.signer) = "sender";
option (amino.name) = "cosmos-sdk/x/bank/v2/MsgCreateDenom";

string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
string subdenom = 2;
}
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

Add validation rules for the subdenom field

To prevent malicious denom creation and ensure consistency, consider adding validation rules for the subdenom field using the gogoproto.moretags option with JSON validation tags.

Apply this addition to the subdenom field:

- string subdenom = 2;
+ string subdenom = 2 [(gogoproto.moretags) = "validate:\"subdenom\""];

This will enforce the standard Cosmos SDK denomination format rules.

Committable suggestion was skipped due to low confidence.

Comment on lines +61 to +69
// MsgChangeAdmin represents a message to change admin of denom.
message MsgChangeAdmin {
option (cosmos.msg.v1.signer) = "sender";
option (amino.name) = "cosmos-sdk/x/bank/v2/MsgChangeAdmin";

string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
string denom = 2;
string new_admin = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"];
}
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

Add validation and event documentation

Two improvements needed:

  1. The denom field should have proper validation
  2. Missing documentation about emitted events

Apply these changes:

 // MsgChangeAdmin represents a message to change admin of denom.
+// Events emitted:
+// - EventType: "change_admin"
+//   Attributes:
+//     - "denom": the denomination being modified
+//     - "old_admin": the previous admin address
+//     - "new_admin": the new admin address
 message MsgChangeAdmin {
   option (cosmos.msg.v1.signer) = "sender";
   option (amino.name)           = "cosmos-sdk/x/bank/v2/MsgChangeAdmin";

   string sender    = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
-  string denom     = 2;
+  string denom     = 2 [(cosmos_proto.scalar) = "cosmos.DenomString"];
   string new_admin = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"];
 }
📝 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
// MsgChangeAdmin represents a message to change admin of denom.
message MsgChangeAdmin {
option (cosmos.msg.v1.signer) = "sender";
option (amino.name) = "cosmos-sdk/x/bank/v2/MsgChangeAdmin";
string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
string denom = 2;
string new_admin = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"];
}
// MsgChangeAdmin represents a message to change admin of denom.
// Events emitted:
// - EventType: "change_admin"
// Attributes:
// - "denom": the denomination being modified
// - "old_admin": the previous admin address
// - "new_admin": the new admin address
message MsgChangeAdmin {
option (cosmos.msg.v1.signer) = "sender";
option (amino.name) = "cosmos-sdk/x/bank/v2/MsgChangeAdmin";
string sender = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
string denom = 2 [(cosmos_proto.scalar) = "cosmos.DenomString"];
string new_admin = 3 [(cosmos_proto.scalar) = "cosmos.AddressString"];
}

Comment on lines +137 to +139
if msg.Authority != authorityMetadata.GetAdmin() {
return nil, types.ErrUnauthorized
}
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

Ensure proper address comparison in MsgMint

Comparing addresses as strings (if msg.Authority != authorityMetadata.GetAdmin()) may lead to incorrect results due to formatting differences. To ensure accurate validation, decode the addresses and compare their byte representations using bytes.Equal.

Apply this diff to compare addresses correctly:

+    senderAddr, err := h.addressCodec.StringToBytes(msg.Authority)
+    if err != nil {
+        return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid authority address: %s", err)
+    }
+    adminAddr, err := h.addressCodec.StringToBytes(authorityMetadata.GetAdmin())
+    if err != nil {
+        return nil, sdkerrors.ErrInvalidAddress.Wrapf("invalid admin address: %s", err)
+    }
-    if msg.Authority != authorityMetadata.GetAdmin() {
+    if !bytes.Equal(senderAddr, adminAddr) {
         return nil, types.ErrUnauthorized
     }

Committable suggestion was skipped due to low confidence.

Comment on lines 244 to 251
var (
primaryDenom = "foo"
secondaryDenom = "bar"
defaultDenomCreationFee = banktypes.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(primaryDenom, math.NewInt(50_000_000)))}
twoDenomCreationFee = banktypes.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(primaryDenom, math.NewInt(50_000_000)), sdk.NewCoin(secondaryDenom, math.NewInt(50_000_000)))}
nilCreationFee = banktypes.Params{DenomCreationFee: nil}
largeCreationFee = banktypes.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(primaryDenom, math.NewInt(5_000_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

Simplify Denom Creation Fee Initialization

The initialization of the denom creation fees can be made more readable by defining the fees upfront and using them directly in the test cases. This improves clarity and reduces redundancy.

Consider defining the fees like so:

defaultFee := sdk.NewCoins(sdk.NewCoin(primaryDenom, math.NewInt(50_000_000)))
twoFees := sdk.NewCoins(
    sdk.NewCoin(primaryDenom, math.NewInt(50_000_000)),
    sdk.NewCoin(secondaryDenom, math.NewInt(50_000_000)),
)
largeFee := sdk.NewCoins(sdk.NewCoin(primaryDenom, math.NewInt(5_000_000_000)))

Then, update the params accordingly:

defaultDenomCreationFee: banktypes.Params{DenomCreationFee: defaultFee},
twoDenomCreationFee:     banktypes.Params{DenomCreationFee: twoFees},
largeCreationFee:        banktypes.Params{DenomCreationFee: largeFee},

Comment on lines +308 to +310
s.Run(fmt.Sprintf("Case %s", tc.desc), func() {
if tc.setup != nil {
tc.setup()
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

Avoid Repeated Setup in Loop

Calling s.SetupTest() inside the loop resets the entire test suite state for each test case, which might not be necessary and could increase test execution time.

Consider moving s.SetupTest() to the beginning of the TestCreateDenom function or resetting only the necessary parts within each test case.

Comment on lines +427 to +434
resp, err := handler.MsgCreateDenom(s.ctx, &types.MsgCreateDenom{
Sender: accAddrs[0].String(),
Subdenom: "test",
})
require.NoError(err)

newDenom := resp.NewTokenDenom
authority := authtypes.NewModuleAddress("gov")
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 Potential Errors After MsgCreateDenom

After calling MsgCreateDenom, it's good practice to check if newDenom is not empty and handle any unexpected scenarios.

Add a check to ensure newDenom is valid:

require.NotEmpty(newDenom, "NewTokenDenom should not be empty")

Comment on lines +478 to +485
desc: "Mint tokenfatory denom, denom not created",
msg: &types.MsgMint{
Authority: accAddrs[0].String(),
ToAddress: accAddrs[1].String(),
Amount: sdk.NewCoin(newDenom+"s", math.NewInt(100)),
},
expErr: 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

Test Case for Non-Existent Denom Should Verify Error Message

In the test case where the denom is not created, it would be beneficial to check that the error received is the expected one to ensure the code fails for the right reason.

Modify the test case to verify the error message:

if tc.expErr {
    require.Error(err)
    require.Contains(err.Error(), "denomination does not exist")
} else {
    ...
}

Comment on lines +558 to +561
toAddr, err := s.addressCodec.StringToBytes(tc.msg.ToAddress)
require.NoError(err)
balances := s.bankKeeper.GetAllBalances(s.ctx, toAddr)
require.Equal(balances, tc.msg.Amount)
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

Verify Complete Balance After Transfer

After sending coins, it's good practice to verify the sender's balance as well to ensure that the coins were deducted properly.

Add checks for the sender's balance:

fromAddr, err := sdk.AccAddressFromBech32(tc.msg.FromAddress)
require.NoError(err)
balances := s.bankKeeper.GetAllBalances(s.ctx, fromAddr)
expectedBalance := sdk.NewCoins(sdk.NewCoin(newDenom, math.NewInt(100).Sub(tc.msg.Amount[0].Amount)))
require.Equal(balances, expectedBalance)

x/bank/v2/keeper/keeper_test.go Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Outside diff range and nitpick comments (18)
x/bank/proto/cosmos/bank/v2/query.proto (1)

40-44: Consider adding scalar validation for denom field

While the request message is well-structured, consider adding the cosmos_proto.scalar option to validate the denom field format, similar to how address fields are validated in other messages.

 message QueryDenomAuthorityMetadataRequest {
-  string denom = 1 [(gogoproto.moretags) = "yaml:\"denom\""];
+  string denom = 1 [
+    (gogoproto.moretags) = "yaml:\"denom\"",
+    (cosmos_proto.scalar) = "cosmos.DenomString"
+  ];
 }
tests/systemtests/genesis_io.go (2)

12-13: Consider consolidating duplicate math imports

The file imports the same package twice with different aliases. Consider using the existing sdkmath alias consistently throughout the file to avoid confusion.

-import (
-	"cosmossdk.io/math"
-	sdkmath "cosmossdk.io/math"
-)
+import (
+	sdkmath "cosmossdk.io/math"
-)

46-53: Implementation looks good with minor consistency suggestion

The function follows the established pattern for genesis mutators and properly handles the creation of denomination fee settings.

Consider returning state directly instead of converting to []byte for consistency with other mutator functions:

 func SetDenomCreationFee(t *testing.T, denom string, amount math.Int) GenesisMutator {
 	t.Helper()
 	return func(genesis []byte) []byte {
 		state, err := sjson.SetBytes(genesis, "app_state.bankv2.params.denom_creation_fee", sdk.NewCoins(sdk.NewCoin(denom, amount)))
 		require.NoError(t, err)
-		return []byte(state)
+		return state
 	}
 }
tests/systemtests/bankv2_test.go (3)

89-89: Remove debug print statements.

Debug print statements should be removed from the test code.

-	fmt.Println("valBalance", valBalanceBefore)
-	fmt.Println("txResult", txResult)
-	fmt.Println("valBalanceAfter", valBalanceAfter)

Also applies to: 93-93, 99-99


61-102: Enhance test coverage for denom creation.

While the test verifies the basic functionality and fee deduction, consider adding these additional test cases:

  1. Verify that the created denom exists and has correct metadata
  2. Test creation with invalid subdenom
  3. Test creation without sufficient fee balance
  4. Verify that the same subdenom cannot be created twice

Here's a suggested addition to verify the created denom exists:

// Verify the created denom exists
denomPath := fmt.Sprintf("factory/%s/%s", valAddr, subDenom)
raw = cli.CustomQuery("q", "bankv2", "denom-metadata", denomPath)
require.True(t, gjson.Get(raw, "metadata.base").Exists(), "denom metadata should exist")

76-79: Consider extracting test configuration.

The fee configuration could be moved to a helper function or test constants for better reusability across tests.

const (
    defaultDenomCreationFee = 1000000
    defaultFeeDenom        = "stake"
)

func setupDenomCreationFee(t *testing.T, sut *SystemUnderTest) {
    sut.ModifyGenesisJSON(
        t,
        SetDenomCreationFee(t, defaultFeeDenom, math.NewInt(defaultDenomCreationFee)),
    )
}
x/bank/proto/cosmos/bank/v2/tx.proto (3)

47-54: Add event documentation for MsgCreateDenom

Please document the events emitted by this message handler. This helps clients properly handle and track denom creation events.

 // MsgCreateDenom represents a message to create new denom.
+// Events emitted:
+// - EventType: "create_denom"
+//   Attributes:
+//     - "sender": the address creating the denom
+//     - "new_token_denom": the full denomination of the created token
 message MsgCreateDenom {

82-83: Add validation for mint amount

Consider adding validation rules to ensure the mint amount is positive and within acceptable limits:

-  cosmos.base.v1beta1.Coin amount     = 3 [(gogoproto.nullable) = false];
+  cosmos.base.v1beta1.Coin amount     = 3 [
+    (gogoproto.nullable) = false,
+    (validate.rules).message = {
+      required: true
+    }
+  ];

89-99: Enhance MsgBurn documentation

Please add comprehensive documentation about:

  1. Events emitted during burn operation
  2. Authority requirements and restrictions
  3. Validation rules for burn amount
 // MsgBurn is the Msg/Burn request type.
+// Events emitted:
+// - EventType: "burn"
+//   Attributes:
+//     - "authority": the address authorized to burn tokens
+//     - "burn_from_address": the address from which tokens are burned
+//     - "amount": the amount of tokens burned
+//
+// The message fails if:
+// - The authority is not properly authorized
+// - The burn amount exceeds the balance of burn_from_address
+// - The burn amount is zero or negative
 message MsgBurn {
x/bank/v2/keeper/keeper_test.go (7)

244-251: Consider using test constants for better maintainability

The fee configurations could be moved to package-level constants to improve maintainability and reusability across tests.

+const (
+    defaultFeeAmount   = 50_000_000
+    largeFeeAmount     = 5_000_000_000
+)

-		defaultDenomCreationFee = banktypes.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(primaryDenom, math.NewInt(50_000_000)))}
+		defaultDenomCreationFee = banktypes.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(primaryDenom, math.NewInt(defaultFeeAmount)))}
-		largeCreationFee        = banktypes.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(primaryDenom, math.NewInt(5_000_000_000)))}
+		largeCreationFee        = banktypes.Params{DenomCreationFee: sdk.NewCoins(sdk.NewCoin(primaryDenom, math.NewInt(largeFeeAmount)))}

253-306: Add test cases for additional edge cases

Consider adding test cases for:

  1. Empty subdenom
  2. Subdenom with only spaces
  3. Unicode characters in subdenom
  4. Maximum allowed subdenom length (boundary test)

364-365: Improve documentation for the offset constant

The offset constant's purpose and calculation basis should be documented.

-	const offset = 50000
+	// offset represents the maximum additional gas that may be consumed by auxiliary operations
+	// during denom creation (e.g., state operations, string manipulations).
+	// This value was determined empirically through testing.
+	const offset = 50000

411-414: Add assertion messages for better test diagnostics

The require statements should include messages to clarify failures.

-			s.Require().Greater(gasConsumed, tc.gasConsume)
-			s.Require().Less(gasConsumed, tc.gasConsume+offset)
+			s.Require().Greater(gasConsumed, tc.gasConsume, 
+				"gas consumed should be greater than specified amount")
+			s.Require().Less(gasConsumed, tc.gasConsume+offset,
+				"gas consumed should be less than specified amount plus offset")

436-501: Enhance test coverage for MintHandler

Consider adding test cases for:

  1. Minting zero amount
  2. Minting to an invalid address
  3. Minting with empty denom
  4. Verifying total supply changes after mint

Also, enhance balance verification:

 				require.NoError(err)
 				// Check ToAddress balance after
 				toAddr, err := s.addressCodec.StringToBytes(tc.msg.ToAddress)
 				require.NoError(err)
 				balance := s.bankKeeper.GetBalance(s.ctx, toAddr, tc.msg.Amount.Denom)
 				require.Equal(balance, tc.msg.Amount)
+				// Verify total supply
+				supply := s.bankKeeper.GetSupply(s.ctx, tc.msg.Amount.Denom)
+				require.Equal(supply.Amount, tc.msg.Amount.Amount)

608-620: Enhance balance verification after burn

The balance verification could be more thorough by checking the total supply reduction.

 				require.NoError(err)
 				// Check ToAddress balance after
 				afterBalances := s.bankKeeper.GetAllBalances(s.ctx, fromAddr)
 				require.Equal(beforeBalances.Sub(afterBalances...), sdk.NewCoins(tc.msg.Amount))
+				// Verify total supply reduction
+				supply := s.bankKeeper.GetSupply(s.ctx, tc.msg.Amount.Denom)
+				require.Equal(supply.Amount, 
+					beforeBalances.AmountOf(tc.msg.Amount.Denom).Sub(tc.msg.Amount.Amount))

649-673: Add more test cases for send handler

Consider adding test cases for:

  1. Sending to self
  2. Sending to a module account
  3. Sending with invalid addresses
  4. Sending multiple denominations
x/bank/v2/keeper/handlers.go (2)

66-66: Clarify the responsibility of MsgChangeAdmin function

The TODO comment on line 66 suggests that changing the admin may be more appropriate within the governance module (gov). Consider whether this functionality should be handled via governance proposals to ensure proper community oversight and adherence to protocol governance practices.

Would you like assistance in integrating this functionality with the governance module or opening a GitHub issue to discuss this further?


122-122: Fix typo in comment: 'tokenfatory' should be 'token factory'

Minor typo on line 122. Correcting it enhances code readability.

Apply this diff to fix the typo:

-	// Check if is a tokenfatory denom
+	// Check if it is a token factory denom
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 498208a and 9ae0291.

⛔ Files ignored due to path filters (2)
  • x/bank/v2/types/query.pb.go is excluded by !**/*.pb.go
  • x/bank/v2/types/tx.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (9)
  • tests/systemtests/bankv2_test.go (2 hunks)
  • tests/systemtests/genesis_io.go (2 hunks)
  • x/bank/proto/cosmos/bank/v2/query.proto (2 hunks)
  • x/bank/proto/cosmos/bank/v2/tx.proto (2 hunks)
  • x/bank/v2/keeper/handlers.go (4 hunks)
  • x/bank/v2/keeper/keeper.go (5 hunks)
  • x/bank/v2/keeper/keeper_test.go (2 hunks)
  • x/bank/v2/types/codec.go (1 hunks)
  • x/bank/v2/types/params.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
tests/systemtests/bankv2_test.go (3)

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


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


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

tests/systemtests/genesis_io.go (2)

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


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"

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/types/codec.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.

🔇 Additional comments (18)
x/bank/v2/types/codec.go (1)

12-12: LGTM: Clean interface registration for MsgCreateDenom

The addition of MsgCreateDenom to the interface registry follows the established pattern and is necessary for the new denomination management functionality.

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

9-9: LGTM: Import statement is correctly structured

The new import for authority metadata is properly formatted and follows the module's package structure.


46-50: Verify DenomAuthorityMetadata type definition

The response message structure looks good with appropriate protobuf options. Let's verify the imported DenomAuthorityMetadata type definition.

✅ Verification successful

DenomAuthorityMetadata type is properly defined and imported

The DenomAuthorityMetadata message is well-defined in x/bank/proto/cosmos/bank/v2/authorityMetadata.proto and correctly imported in the query.proto file. The type contains an admin field with appropriate protobuf options and documentation. The usage in the QueryDenomAuthorityMetadataResponse is consistent with its definition.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the DenomAuthorityMetadata type definition
# Expected: Should find the type definition in the imported proto file

# Search for the DenomAuthorityMetadata message definition
rg -t proto "message DenomAuthorityMetadata" --glob "x/bank/proto/**/*.proto"

Length of output: 109


Script:

#!/bin/bash
# Let's try a different approach to find the DenomAuthorityMetadata definition
# Using fd to find proto files and grep for the definition

fd -e proto . x/bank/proto | xargs grep -l "message DenomAuthorityMetadata"

# Also let's check the imports in the query.proto file to see where this type might be defined
cat x/bank/proto/cosmos/bank/v2/query.proto | grep "import"

Length of output: 410


Script:

#!/bin/bash
# Let's verify the DenomAuthorityMetadata definition in authorityMetadata.proto
cat x/bank/proto/cosmos/bank/v2/authorityMetadata.proto

Length of output: 635

tests/systemtests/bankv2_test.go (1)

9-9: LGTM!

The new import is necessary for the math operations in the test and is correctly placed.

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

19-21: Duplicate import already flagged.

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

11-15: Proper Initialization of Parameters in NewParams.

The NewParams function correctly initializes the Params struct with DenomCreationFee and DenomCreationGasConsume, enhancing the configurability of the module.


23-33: Comprehensive Validation in Params.Validate().

The Validate method appropriately calls validateDenomCreationFee and validateDenomCreationGasConsume to ensure all parameters are properly validated, maintaining the integrity of the module's configuration.

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

31-32: LGTM!

The addition of denomMetadata and denomAuthority fields to the Keeper struct is a good way to manage denomination metadata and authority metadata. The use of collections.Map ensures efficient storage and retrieval of this data.


47-48: LGTM!

The initialization of denomMetadata and denomAuthority fields in the NewKeeper constructor is correct. Using collections.NewMap with appropriate prefixes and codecs ensures proper storage and serialization of the metadata.


181-185: ****

Handle errors explicitly in HasSupply method.

In the HasSupply method, the error returned from k.supply.Has(ctx, denom) is ignored. According to Go best practices and the Uber Golang style guide, errors should be handled explicitly to prevent unexpected behaviors.

Consider modifying the method to handle errors appropriately:

func (k Keeper) HasSupply(ctx context.Context, denom string) bool {
    has, err := k.supply.Has(ctx, denom)
-   return has && err == nil
+   if err != nil {
+       // Handle or log the error as needed  
+       return false
+   }
+   return has
}

This change ensures that any errors are not silently ignored, which could mask underlying issues with the supply store.


197-206: ****

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()
}

211-218: ****

Avoid using panic in IterateAccountBalances; return errors instead.

In IterateAccountBalances, 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) 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
}

This approach allows callers to handle errors without unexpected panics.


220-225: ****

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.


227-231: ****

Handle errors explicitly in HasDenomMetaData method.

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 {
    has, err := k.denomMetadata.Has(ctx, denom)
-   return has && err == nil
+   if err != nil {
+       // Handle or log the error as needed
+       return false
+   }
+   return has
}

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


233-242: ****

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.


247-254: ****

Avoid using panic in IterateAllDenomMetaData; return errors instead.

Similar to the previous comment, using panic in IterateAllDenomMetaData is not recommended. Errors should be propagated up to the caller to handle them gracefully.

Modify the method to return the error:

-func (k Keeper) IterateAllDenomMetaData(ctx context.Context, cb func(types.Metadata) bool) {
+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 {
-       panic(err)
+       return err
    }
+   return nil
}

Again, ensure that any code calling this method is updated to handle the returned error.


256-259: LGTM!

The SetDenomMetaData function correctly sets the denomination metadata using the denomMetadata.Set method. The use of denomMetaData.Base as the key ensures that the metadata is stored with the correct denomination.


109-113: ⚠️ Potential issue

Prevent negative total supply when burning coins.

When burning coins, the current implementation reduces the supply by the burn amount without checking if the supply will become negative. This could lead to inconsistencies if the burn amount exceeds the current supply.

Add a check to ensure that the new supply does not become negative:

for _, amount := range amounts {
	supply := k.GetSupply(ctx, amount.GetDenom())
+	if supply.IsLT(amount) {
+		return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "burn amount exceeds current supply for denom %s", amount.Denom)
+	}
-	supply = supply.Sub(amount)
+	newSupply := supply.Sub(amount)
	k.setSupply(ctx, newSupply)
}

Likely invalid or redundant comment.

tests/systemtests/bankv2_test.go Show resolved Hide resolved
x/bank/v2/keeper/keeper_test.go Show resolved Hide resolved
x/bank/v2/keeper/handlers.go Show resolved Hide resolved
x/bank/v2/keeper/handlers.go Outdated Show resolved Hide resolved
x/bank/v2/keeper/keeper.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 9

🧹 Outside diff range and nitpick comments (9)
x/bank/proto/cosmos/bank/v2/query.proto (1)

40-50: Consider adding field validation and examples

The new query messages are well-structured and properly documented. However, consider these improvements:

  1. Add field validation for the denom field to ensure it matches the expected format
  2. Include example values in the comments to guide API users

Example validation:

  string denom = 1 [
    (gogoproto.moretags) = "yaml:\"denom\"",
    (cosmos_proto.scalar) = "cosmos.Denom"  // Add denom validation
  ];
tests/systemtests/genesis_io.go (1)

46-53: LGTM with minor suggestions

The implementation follows the established pattern for genesis mutators and correctly integrates with the bank/v2 module. Consider adding:

  1. Input validation for the amount parameter
  2. Documentation explaining the purpose and usage of this function
+// SetDenomCreationFee sets the denomination creation fee in genesis state.
+// Parameters:
+//   - denom: the denomination of the fee token
+//   - amount: the amount of tokens required for denomination creation
 func SetDenomCreationFee(t *testing.T, denom string, amount math.Int) GenesisMutator {
+	if amount.IsNegative() {
+		t.Fatal("amount cannot be negative")
+	}
 	t.Helper()
x/bank/v2/client/cli/tx.go (1)

71-76: Enhance command documentation with examples.

Consider adding examples and subdenom format requirements to the Long description to improve user experience.

 		Long: `Create new tokenfactory denom.
 Note, the '--from' flag is ignored as it is implied from [from_key_or_address].
 When using '--dry-run' a key name cannot be used, only a bech32 address.
+
+Example:
+  $ %s tx bank create-denom mytoken
+
+The subdenom must be a valid denomination name consisting of alphanumeric characters,
+and may include slashes, colons, dots, and hyphens.
 `,
tests/systemtests/bankv2_test.go (2)

89-89: Remove debug print statements.

Debug print statements should be removed from the test as they add noise to the test output.

-	fmt.Println("valBalance", valBalanceBefore)
-	fmt.Println("txResult", txResult)
-	fmt.Println("valBalanceAfter", valBalanceAfter)

Also applies to: 93-93, 99-99


61-102: Enhance test coverage with error cases.

The test only covers the happy path. Consider adding test cases for:

  • Invalid subdenom format
  • Insufficient fee balance
  • Duplicate denom creation

Add test function documentation.

Add a function comment describing the test's purpose and test cases.

// TestCreateDenom verifies that:
// - A new denomination can be created with the correct fee deduction
// - The creation fee is correctly deducted from the creator's account
// - The newly created denomination is properly registered in the system
x/bank/proto/cosmos/bank/v2/tx.proto (1)

47-54: Add field documentation for MsgCreateDenom

Please add documentation comments for the fields to improve clarity:

  • sender: Document who can create denoms (authority, restrictions)
  • subdenom: Document the expected format, constraints, and examples
x/bank/v2/keeper/keeper_test.go (2)

308-310: Consider using test suite setup instead of per-test setup

s.SetupTest() is called for each test case, which might be inefficient. Consider moving common setup to a BeforeTest method.

+func (s *KeeperTestSuite) BeforeTest(suiteName, testName string) {
+    s.SetupTest()
+    // Common setup code here
+}

411-414: Enhance gas consumption validation

The current validation only checks if gas consumption falls within a range. Consider adding assertions for specific gas usage patterns.

Add these assertions:

 s.Require().Greater(gasConsumed, tc.gasConsume)
 s.Require().Less(gasConsumed, tc.gasConsume+offset)
+// Verify gas consumption increases with parameter value
+if tc.gasConsume > 0 {
+    s.Require().Greater(gasConsumed, previousGasConsumed)
+}
+previousGasConsumed = gasConsumed
x/bank/v2/types/params.go (1)

36-47: Refactor validation functions to accept explicit types

Currently, validateDenomCreationFee accepts an interface{} and performs a type assertion. Similarly, validateDenomCreationGasConsume does the same. For improved type safety and readability, consider changing these functions to accept explicit types.

Apply the following changes to validateDenomCreationFee:

-func validateDenomCreationFee(i interface{}) error {
-   v, ok := i.(sdk.Coins)
-   if !ok {
-       return fmt.Errorf("invalid parameter type: %T", i)
-   }

+func validateDenomCreationFee(v sdk.Coins) error {

    if v.Validate() != nil {
        return fmt.Errorf("invalid denom creation fee: %+v", v)
    }
    return nil
}

And modify validateDenomCreationGasConsume accordingly:

-func validateDenomCreationGasConsume(i interface{}) error {
-   v, ok := i.(uint64)
-   if !ok {
-       return fmt.Errorf("invalid parameter type: %T", i)
-   }

+func validateDenomCreationGasConsume(v uint64) error {

    return nil
}

Update the calls in Params.Validate():

 func (p Params) Validate() error {
-   if err := validateDenomCreationFee(p.DenomCreationFee); err != nil {
+   if err := validateDenomCreationFee(p.DenomCreationFee); err != nil {
        return err
    }
-   if err := validateDenomCreationGasConsume(p.DenomCreationGasConsume); err != nil {
+   if err := validateDenomCreationGasConsume(p.DenomCreationGasConsume); err != nil {
        return err
    }
    return nil
}

This refactoring enhances type safety by eliminating unnecessary type assertions and makes the code more idiomatic.

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 498208a and 3d937ca.

⛔ Files ignored due to path filters (2)
  • x/bank/v2/types/query.pb.go is excluded by !**/*.pb.go
  • x/bank/v2/types/tx.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (10)
  • tests/systemtests/bankv2_test.go (2 hunks)
  • tests/systemtests/genesis_io.go (2 hunks)
  • x/bank/proto/cosmos/bank/v2/query.proto (2 hunks)
  • x/bank/proto/cosmos/bank/v2/tx.proto (2 hunks)
  • x/bank/v2/client/cli/tx.go (2 hunks)
  • x/bank/v2/keeper/handlers.go (4 hunks)
  • x/bank/v2/keeper/keeper.go (5 hunks)
  • x/bank/v2/keeper/keeper_test.go (2 hunks)
  • x/bank/v2/types/codec.go (1 hunks)
  • x/bank/v2/types/params.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
tests/systemtests/bankv2_test.go (3)

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


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


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

tests/systemtests/genesis_io.go (2)

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


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"

x/bank/v2/client/cli/tx.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/types/codec.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.

🔇 Additional comments (23)
x/bank/v2/types/codec.go (1)

12-12: LGTM! Verify message type definition.

The registration of MsgCreateDenom follows the established pattern for message type implementations.

Let's verify the message type is properly defined:

✅ Verification successful

Message type is properly defined and follows SDK conventions

The MsgCreateDenom message type is well-defined in x/bank/proto/cosmos/bank/v2/tx.proto with:

  • Correct signer option and amino name annotations
  • Required sender field with proper cosmos address scalar
  • subdenom field for denomination creation
  • Corresponding response message with new_token_denom field
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify MsgCreateDenom type definition exists
# Expected: Find the message type definition in proto files

# Search for MsgCreateDenom definition
rg -A 5 "message MsgCreateDenom"

Length of output: 875

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

9-9: LGTM: Import statement is correctly placed and necessary

The new import for authorityMetadata.proto is required for the DenomAuthorityMetadata type and follows the package's conventions.

tests/systemtests/genesis_io.go (1)

46-53: Verify test coverage for denomination creation

Let's ensure this utility function is being used in relevant test cases for the new denomination creation features.

✅ Verification successful

Test coverage for denomination creation is adequate

The utility function SetDenomCreationFee is properly used in TestCreateDenom which tests the denomination creation functionality. The test sets up the genesis state with a specific denom creation fee, which is essential for testing the new denomination management features.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of SetDenomCreationFee in test files
echo "Searching for test cases using SetDenomCreationFee..."
rg -l "SetDenomCreationFee" --type go --type-add 'go:*.go' -g '*_test.go'

Length of output: 223


Script:

#!/bin/bash
# Check the test cases in bankv2_test.go that use SetDenomCreationFee
echo "Checking test cases in bankv2_test.go..."
rg "SetDenomCreationFee" tests/systemtests/bankv2_test.go -B 2 -A 5

Length of output: 363


Script:

#!/bin/bash
# Get more context around the test case to understand the test scenario
echo "Getting full test context..."
rg "func.*Test.*Denom" tests/systemtests/bankv2_test.go -B 5 -A 20

Length of output: 716

x/bank/v2/client/cli/tx.go (1)

27-27: Consider AutoCLI migration impact.

The command is correctly registered, but note the TODO comment above suggesting migration to AutoCLI (issue #21682). Ensure this new command is included in the AutoCLI migration plan.

✅ Verification successful

AutoCLI migration is already tracked and implementation is pending

The AutoCLI implementation for bank/v2 is intentionally disabled pending resolution of issue #21682. The new command is correctly registered in the traditional CLI structure, and its migration to AutoCLI will be handled as part of the broader module migration tracked in the mentioned issue.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if there are any related AutoCLI implementations or discussions
rg -l "AutoCLI.*bank.*v2" 

Length of output: 27


Script:

#!/bin/bash
# Let's try a broader search for AutoCLI references in bank module
rg -l "AutoCLI.*bank"

# Also search for any TODO comments related to AutoCLI
rg "TODO.*AutoCLI"

# Check if there are any existing AutoCLI implementations
fd -t f autocli

Length of output: 1215


Script:

#!/bin/bash
# Let's check the content of bank v2 AutoCLI implementation
cat x/bank/v2/autocli.go

# And check the TODO comment context in the file under review
rg -A 5 "TODO: Use AutoCLI commands" x/bank/v2/client/cli/tx.go

Length of output: 1647

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

61-69: Add access control validation

Consider adding validation to ensure that only the current admin can initiate the admin change. This could be done through a combination of:

  1. Keeper-level checks
  2. Documentation of access control requirements in the message definition
x/bank/v2/keeper/handlers.go (3)

55-64: LGTM! Clean and concise implementation.

The handler correctly delegates to the Keeper's CreateDenom method and properly handles errors.


168-168: Clarify the minting strategy

The TODO comment raises an important architectural question about the minting process. Consider documenting the decision and rationale about whether to mint directly or use an intermediate module.

#!/bin/bash
# Check how minting is handled in other modules
rg "MintCoins.*module" -A 5

66-66: Address the TODO comment about governance

The comment "TODO: should be gov?" suggests uncertainty about whether this functionality should be governed by the governance module. This architectural decision should be clarified before proceeding.

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

11-15: Function NewParams implementation is correct

The NewParams function appropriately initializes the Params struct with the provided denomCreationFee and gasConsume parameters.


20-20: DefaultParams uses sensible default values

The DefaultParams function correctly calls NewParams with default values for DenomCreationFee and DenomCreationGasConsume. This ensures that the module has valid default parameters.


25-34: Validation logic in Params.Validate() is sound

The Validate method properly checks both DenomCreationFee and DenomCreationGasConsume using their respective validation functions, ensuring that parameter values are valid.

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

25-32: LGTM!

The new fields authority, addressCodec, denomMetadata, and denomAuthority are added to the Keeper struct to support the management of denomination metadata and authorities. The types and naming conventions are consistent with the existing fields.


47-48: LGTM!

The denomMetadata and denomAuthority fields are initialized using collections.NewMap with appropriate prefixes, keys, and value codecs. This is consistent with the initialization of other fields in the NewKeeper function.


197-206: LGTM!

The GetAllBalances function retrieves all account balances for a given address by iterating over the account's balances using IterateAccountBalances. The balances are accumulated in a sdk.Coins object and sorted before being returned. The implementation is straightforward and follows the expected behavior.


233-242: LGTM!

The GetAllDenomMetaData function retrieves all denomination metadata by iterating over the metadata using IterateAllDenomMetaData. The metadata is collected in a slice and returned. The implementation is straightforward and follows the expected behavior.


256-259: LGTM!

The SetDenomMetaData function sets the denomination metadata by calling k.denomMetadata.Set with the appropriate key and value. The implementation is straightforward and follows the expected behavior.


94-128: ⚠️ Potential issue

Implement burn restrictions and permission checks.

The BurnCoins function includes a TODO comment for implementing burn restrictions and permissions. Currently, it lacks checks to prevent unauthorized burning of coins, which poses a significant security risk. According to the Uber Go Style Guide, TODO comments should be minimized and, if used, should include a reference to an issue tracker.

Please implement the necessary permission checks to ensure that only authorized entities can burn coins. If this functionality is to be added later, consider linking to an issue or removing the function until it is properly secured.

Do you want me to help implement the burn restrictions and permission checks or open a GitHub issue to track this task?


109-113: ⚠️ Potential issue

Prevent negative total supply when burning coins.

When burning coins, the supply is reduced by the burn amount without checking if the supply will become negative. This could lead to inconsistencies if the burn amount exceeds the current supply.

Add a check to ensure that the new supply does not become negative:

for _, amount := range amounts {
	supply := k.GetSupply(ctx, amount.GetDenom())
+	if supply.IsLT(amount) {
+		return errorsmod.Wrapf(sdkerrors.ErrInvalidCoins, "burn amount exceeds current supply for denom %s", amount.Denom)
+	}
-	supply = supply.Sub(amount)
+	newSupply := supply.Sub(amount)
	k.setSupply(ctx, newSupply)
}

181-185: 🛠️ Refactor suggestion

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.


211-218: ⚠️ 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.


220-225: 🛠️ Refactor suggestion

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.


227-231: 🛠️ Refactor suggestion

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.


247-254: ⚠️ Potential issue

Avoid panicking in IterateAllDenomMetaData; return errors instead.

Similar to the previous comment, using panic in IterateAllDenomMetaData is not recommended. Errors should be propagated up to the caller to handle them gracefully.

Modify the method to return the error:

-func (k Keeper) IterateAllDenomMetaData(ctx context.Context, cb func(types.Metadata) bool) {
+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 {
-       panic(err)
+       return err
    }
+   return nil
}

Again, ensure that any code calling this method is updated to handle the returned error.

tests/systemtests/genesis_io.go Outdated Show resolved Hide resolved
x/bank/v2/client/cli/tx.go Outdated Show resolved Hide resolved
tests/systemtests/bankv2_test.go Show resolved Hide resolved
x/bank/proto/cosmos/bank/v2/tx.proto Show resolved Hide resolved
x/bank/proto/cosmos/bank/v2/tx.proto Show resolved Hide resolved
x/bank/v2/keeper/handlers.go Outdated Show resolved Hide resolved
x/bank/v2/keeper/keeper_test.go Show resolved Hide resolved
x/bank/v2/keeper/keeper_test.go Outdated Show resolved Hide resolved
x/bank/v2/keeper/keeper_test.go Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 6

🧹 Outside diff range and nitpick comments (7)
tests/systemtests/bankv2_test.go (1)

89-89: Remove debug print statements.

Debug print statements should be removed from the test as they add noise to the test output.

-	fmt.Println("valBalance", valBalanceBefore)
-	fmt.Println("txResult", txResult)
-	fmt.Println("valBalanceAfter", valBalanceAfter)
-	fmt.Println("denoms", raw)
-	fmt.Println("authority", raw)

Also applies to: 93-93, 94-94, 99-99, 106-106, 111-111

x/bank/v2/client/cli/query.go (1)

83-118: Enhance error message for empty denom

While the implementation is solid, consider making the error message more descriptive to help users understand the issue better.

-				return errors.New("empty denom")
+				return errors.New("denom cannot be empty")
x/bank/v2/module.go (1)

Line range hint 119-127: Track TODOs for CLI command generation

There are TODO comments indicating a plan to migrate to autocli. It would be helpful to track these improvements.

Would you like me to create GitHub issues to track the migration of GetTxCmd and GetQueryCmd to autocli?

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

66-66: Address the TODO comment regarding governance.

The comment suggests uncertainty about whether this functionality should be controlled by governance. This architectural decision should be clarified and documented.

Should this operation be restricted to governance proposals? This would provide better security and community oversight for admin changes.

x/bank/proto/cosmos/bank/v2/query.proto (3)

43-43: Consider adding address validation annotation to denom field

For improved validation and consistency, consider adding the (cosmos_proto.scalar) = "cosmos.DenomString" annotation to the denom field in QueryDenomAuthorityMetadataRequest.

Apply this diff:

   message QueryDenomAuthorityMetadataRequest {
-    string denom = 1;
+    string denom = 1 [(cosmos_proto.scalar) = "cosmos.DenomString"];
   }

42-44: Add option statements for gogoproto settings for consistency

For consistency with other message definitions in this file, such as QueryBalanceRequest, consider adding the following option statements to the new messages to disable equality checking and getter generation:

Apply this diff:

   message QueryDenomAuthorityMetadataRequest {
+    option (gogoproto.equal)           = false;
+    option (gogoproto.goproto_getters) = false;
     string denom = 1;
   }

Repeat the same option statements for the other new messages:

   message QueryDenomAuthorityMetadataResponse {
+    option (gogoproto.equal)           = false;
+    option (gogoproto.goproto_getters) = false;
     DenomAuthorityMetadata authority_metadata = 1 [(gogoproto.nullable) = false];
   }

   message QueryDenomsFromCreatorRequest {
+    option (gogoproto.equal)           = false;
+    option (gogoproto.goproto_getters) = false;
     string creator = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];
   }

   message QueryDenomsFromCreatorResponse {
+    option (gogoproto.equal)           = false;
+    option (gogoproto.goproto_getters) = false;
     repeated string denoms = 1;
   }

49-49: Add (amino.dont_omitempty) = true to authority_metadata field

To ensure that the authority_metadata field is always serialized and not omitted when empty, add the (amino.dont_omitempty) = true annotation, similar to other responses in this file.

Apply this diff:

   message QueryDenomAuthorityMetadataResponse {
     DenomAuthorityMetadata authority_metadata = 1 [
       (gogoproto.nullable) = false,
+      (amino.dont_omitempty) = true
     ];
   }
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 3d937ca and 0bfe528.

⛔ Files ignored due to path filters (1)
  • x/bank/v2/types/query.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (5)
  • tests/systemtests/bankv2_test.go (2 hunks)
  • x/bank/proto/cosmos/bank/v2/query.proto (2 hunks)
  • x/bank/v2/client/cli/query.go (2 hunks)
  • x/bank/v2/keeper/handlers.go (4 hunks)
  • x/bank/v2/module.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
tests/systemtests/bankv2_test.go (3)

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


Pattern tests/**/*: "Assess the integration and e2e test code assessing sufficient code coverage for the changes associated in the pull request"


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

x/bank/v2/client/cli/query.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/module.go (1)

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

🔇 Additional comments (5)
x/bank/v2/client/cli/query.go (1)

34-35: LGTM: Commands properly registered

The new query commands are correctly registered with the parent command.

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

101-102: LGTM: Message handlers properly registered

The new message handlers for denomination management (MsgCreateDenom and MsgChangeAdmin) are correctly registered following the module's established patterns.

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

55-64: LGTM! Clean and concise implementation.

The implementation correctly delegates to the Keeper's CreateDenom method and handles errors appropriately.


75-77: Address comparison needs to be updated.

This issue has been previously identified in the past reviews. Please refer to the existing comments about using proper address comparison with byte representation.


264-297: LGTM! Well-implemented query handlers.

Both query handlers are implemented cleanly with proper error handling. The use of the Walk function for iterating over denoms is efficient and appropriate.

tests/systemtests/bankv2_test.go Outdated Show resolved Hide resolved
tests/systemtests/bankv2_test.go Outdated Show resolved Hide resolved
x/bank/v2/client/cli/query.go Show resolved Hide resolved
x/bank/v2/module.go Show resolved Hide resolved
x/bank/v2/keeper/handlers.go Show resolved Hide resolved
x/bank/proto/cosmos/bank/v2/query.proto Show resolved Hide resolved
@hieuvubk hieuvubk marked this pull request as draft November 4, 2024 16:29
@hieuvubk hieuvubk changed the title feat(bank/v2): Basic CreateDenom feat(bank/v2): port tokenfactory into bank/v2 Nov 7, 2024
@hieuvubk hieuvubk marked this pull request as ready for review November 7, 2024 08:37
// authority is the address that controls the module (defaults to x/gov unless overwritten).
string authority = 1 [(cosmos_proto.scalar) = "cosmos.AddressString"];

string burn_from_address = 2 [(cosmos_proto.scalar) = "cosmos.AddressString"];
Copy link
Contributor

Choose a reason for hiding this comment

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

I have some concerns about this feature. The original token factory was built for a permissioned chain which is always able to do this via migration code.
When a contract can use the TF to mint and burn tokens from any address, this opens the door to fraud.
The burn use-case is not new in other chains but what they do instead is providing transparency via metadata that the users know this is possible. See https://developers.stellar.org/docs/learn/encyclopedia/transactions-specialized/clawbacks for example

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.

5 participants