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

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

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 QueryDenomAuthorityMetadata. 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, QueryDenomsFromCreatorRequest, QueryDenomsFromCreatorResponse.
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

Suggested labels

C:x/protocolpool, backport/v0.52.x

Suggested reviewers

  • facundomedica
  • akhilkumarpilli
  • sontrinh16
  • testinginprod
  • julienrbrt

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

@julienrbrt
Copy link
Member

Is it R4R again?

@hieuvubk
Copy link
Contributor Author

hieuvubk commented Nov 13, 2024

Is it R4R again?

not yet Im testing in local

@julienrbrt julienrbrt marked this pull request as draft November 13, 2024 09:17
Copy link
Contributor

@alpe alpe left a comment

Choose a reason for hiding this comment

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

Good start!
Some quick review notes. I have not looked at all the code, yet

balances *collections.IndexedMap[collections.Pair[[]byte, string], math.Int, BalancesIndexes]
supply collections.Map[string, math.Int]
accountsKeeper types.AccountsModKeeper
authority []byte
Copy link
Contributor

Choose a reason for hiding this comment

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

q: I noticed you are using bytes instead of an sdk address or string. This is not consistent with the auth, bank, gov and other modules. It can be a design decision though. I just want to check what is correct here?

Copy link
Member

Choose a reason for hiding this comment

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

This is good to have it byte, we want to avoid to have bech32 anywhere in a module. It is basically an sdk.AccAddress (which is a byte alias), but this forces use to the address codec to go to string.

func (k Keeper) GetAllBalances(ctx context.Context, addr sdk.AccAddress) sdk.Coins {
balances := sdk.NewCoins()
k.IterateAccountBalances(ctx, addr, func(balance sdk.Coin) bool {
balances = balances.Add(balance)
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: The Add method comes with some checks that ensure uniqueness and other constraints. Would it make sense to simply add the coins to a slice and cast and sort it later?

return cb(sdk.NewCoin(key.K2(), value)), nil
})
if err != nil {
panic(err)
Copy link
Contributor

Choose a reason for hiding this comment

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

Panics are an anti pattern and may cause trouble begin/end-blockers when called. Instead the error should be returned so that the caller can decide on the appropriate action. Don't let the control flow loose.

return cb(metadata), nil
})
if err != nil {
panic(err)
Copy link
Contributor

Choose a reason for hiding this comment

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

No panic. See my comment above


// SetDenomMetaData sets the denominations metadata
func (k Keeper) SetDenomMetaData(ctx context.Context, denomMetaData types.Metadata) error {
return k.denomMetadata.Set(ctx, denomMetaData.Base, denomMetaData)
Copy link
Contributor

Choose a reason for hiding this comment

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

personal preference: can this be a private method? There are no guards or functionality other than storing the data. It should not be used from outside the module in this state.

Name: denom,
Symbol: denom,
Display: denom,
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Would it make sense to let the caller define other metadata as well? I understand that there must be a trade-off between supported functionality and fraud prevention. Some code comment would be helpful, when this is limited for some reason.

}

// Create denom admin account
_, accountAddr, err := k.accountsKeeper.Init(ctx, admin.Type, creatorAddrBz, msgInitAdmin, sdk.NewCoins())
Copy link
Contributor

Choose a reason for hiding this comment

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

The motivation the the xaccounts, I don't fully understand. I can see some benefit in using them but on the other hand, there can be rich contracts on chain that have their custom rulesets.
When you drop the constraint, the users can still decide on an the authority and don't have to pipe every operation through this proxy account. WDYT?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That long story about x/account 😅.
Before we just save the admin addr in state and keeper just compare if sender == admin to mint/burn (orginal Osmosis impl)
Then I moved that admin part the x/account layer to be compatible with the AssetInterface, which will also be implemented by x/account.
Rn me & @julienrbrt considering should we need x/account or not so this comment is nice TBD

}

// TODO: do we need map creator => denom
// k.addDenomFromCreator(ctx, creatorAddr, denom)
Copy link
Contributor

Choose a reason for hiding this comment

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

Are you going to do this in this PR?

// if DenomCreationFee is non-zero, transfer the tokens from the creator
// account to community pool
if params.DenomCreationFee != nil {
accAddr, err := sdk.AccAddressFromBech32(creatorAddr)
Copy link
Contributor

Choose a reason for hiding this comment

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

AccAddressFromBech32 is deprecated. You can use the address codec instead

func (k Keeper) GetParams(ctx context.Context) types.Params {
params, err := k.params.Get(ctx)
if err != nil {
return types.Params{}
Copy link
Contributor

Choose a reason for hiding this comment

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

Why not return the error?

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

🧹 Outside diff range and nitpick comments (1)
x/bank/v2/keeper/createdenom.go (1)

82-83: Address the TODO comment regarding mapping creator to denom

There's a TODO comment at line 82 suggesting a potential need to map creators to denominations. Consider implementing this mapping if it's required for your application's logic.

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

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 989643f and 710a95a.

📒 Files selected for processing (1)
  • x/bank/v2/keeper/createdenom.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
x/bank/v2/keeper/createdenom.go (1)

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

}

// Create denom admin account
_, accountAddr, err := k.accountsKeeper.Init(ctx, admin.Type, creatorAddrBz, msgInitAdmin, sdk.NewCoins())
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 variable shadowing of err

At line 64, the declaration of err using := shadows the named return variable err. This can lead to confusion and potential bugs. Assign to the existing err variable instead.

Apply this diff to fix the variable shadowing:

-	_, accountAddr, err := k.accountsKeeper.Init(ctx, admin.Type, creatorAddrBz, msgInitAdmin, sdk.NewCoins())
+	_, accountAddr, err = k.accountsKeeper.Init(ctx, admin.Type, creatorAddrBz, msgInitAdmin, sdk.NewCoins())
📝 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
_, accountAddr, err := k.accountsKeeper.Init(ctx, admin.Type, creatorAddrBz, msgInitAdmin, sdk.NewCoins())
_, accountAddr, err = k.accountsKeeper.Init(ctx, admin.Type, creatorAddrBz, msgInitAdmin, sdk.NewCoins())

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.

7 participants