-
Notifications
You must be signed in to change notification settings - Fork 4.1k
feat(bank/v2): port tokenfactory into bank/v2 #22264
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
Conversation
📝 Walkthrough📝 WalkthroughWalkthroughThe pull request introduces several new message types and modifies existing structures in the Changes
Possibly related PRs
Suggested labels
Suggested reviewers
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
Documentation and Community
|
|
@hieuvubk your pull request is missing a changelog! |
There was a problem hiding this 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: TheValidate()method is well-implemented.The
Validate()method correctly checks theAdminfield of theDenomAuthorityMetadatatype. 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
Adminfield 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
SetParamsmethod. Consider updating it to:// SetParams sets the parameters for the bank moduleThe method implementation looks good and correctly sets the parameters using
k.params.Set.
14-21: Update the comment and consider logging the error.
- The current comment doesn't accurately describe the
GetParamsmethod. Consider updating it to:// GetParams returns the current parameters for the bank module
- 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-definedDenomAuthorityMetadatamessage with room for future extensions.The
DenomAuthorityMetadatamessage is clearly defined and well-commented. The use ofgogoprotooptions for equality checks and YAML serialization is appropriate. Theadminfield correctly allows for an empty string to represent "no admin".For future consideration:
As the comment mentions planned extensions, consider adding areservedblock 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// DONTCOVERcommentThe
// DONTCOVERcomment 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 consistencyThe error definitions are well-structured and follow best practices:
- Each error has a unique code and descriptive message.
- The use of
errorsmod.Registeris correct for defining sentinel errors.- Error codes are sequential, which is good for maintainability.
For consistency, consider using
fmt.Sprintffor 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
DenomMetadataPrefixandDenomAuthorityPrefixare 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_metadatafield 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_denomsfield 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_metadatafield toadmin_metadatafor consistency with theadminterminology 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
MsgCreateDenomandMsgChangeAdminhandlers 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 forfmtpackage.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)optionFor 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 typesFor the field
denom_creation_gas_consume, you've set(gogoproto.nullable) = true. Sinceuint64is a scalar type, making it nullable will generate a pointer touint64in 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 detailsThe 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
#IssueNumberwith 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
senderandsubdenomfields 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, andnew_adminfields 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 forMsgCreateDenomAccording 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
MsgCreateDenommethod to enhance code readability and maintainability.Example:
// MsgCreateDenom handles the creation of a new denomination.
68-68: Clarify the TODO comment regarding governanceThe TODO comment
// TODO: should be gov?suggests uncertainty about whether theMsgChangeAdminhandler 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 forGetDenomMetaDatato follow Go conventionsThe comment for
GetDenomMetaDatashould 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
⛔ Files ignored due to path filters (4)
x/bank/v2/types/authorityMetadata.pb.gois excluded by!**/*.pb.gox/bank/v2/types/bank.pb.gois excluded by!**/*.pb.gox/bank/v2/types/genesis.pb.gois excluded by!**/*.pb.gox/bank/v2/types/tx.pb.gois 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 thesdkpackage is properly aliased and appears to be the only necessary import for this file.
1-15: Excellent implementation of theValidate()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.v2and thego_packageoption"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 theDenomAuthorityMetadatamessage. It follows Protocol Buffers best practices and Cosmos SDK conventions. The message is clearly commented, and the use ofgogoprotooptions enhances its functionality.Key points:
- Correct syntax and package declarations.
- Appropriate imports (pending verification of
gogoproto).- Well-defined message with clear comments and correct use of options.
- Consideration for future extensibility.
Great job on maintaining clarity and following best practices in this new addition to the
cosmos.bank.v2package.🧰 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 definitionsThis file provides a clear and well-organized set of error definitions for the
x/tokenfactorymodule. 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: FunctionGetAuthorityMetadatais correctly implementedThe 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 checkThe loop correctly iterates over
state.DenomMetadataand attempts to set the denomination metadata usingk.SetDenomMetaData(ctx, meta). However, ensure thatSetDenomMetaDataproperly 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 thecosmos_proto.field_added_inannotationsThe fields
name,symbol,uri, anduri_hashin theMetadatamessage 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.
| syntax = "proto3"; | ||
| package cosmos.bank.v2; | ||
|
|
||
| import "gogoproto/gogo.proto"; | ||
| import "cosmos/base/v1beta1/coin.proto"; |
There was a problem hiding this comment.
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)
| _, ok := i.(uint64) | ||
| if !ok { | ||
| return fmt.Errorf("invalid parameter type: %T", i) | ||
| } |
There was a problem hiding this comment.
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")
}There was a problem hiding this 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: TheValidate()method is well-implemented.The method correctly validates the
Adminfield ofDenomAuthorityMetadatawhen it's not empty, using the SDK'sAccAddressFromBech32function. Error handling is appropriate, and the method returnsnilwhen 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
SetParamsmethod is correctly implemented. However, the comment above the function doesn't match its functionality.Please update the comment to accurately describe the
SetParamsfunction:-// 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
GetParamsmethod 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
GetParamsfunction:-// 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 importThe import
cosmos/base/v1beta1/coin.protois 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
errorsmodimport with a custom path is correctly used.Consider adding a brief explanation for the
// DONTCOVERcomment, e.g.:// DONTCOVER - This file is excluded from test coverage reportsThis 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 errorsThis 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
DenomMetadataPrefixandDenomAuthorityPrefixare 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
MsgCreateDenomandMsgChangeAdminhandlers 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 clarityAlthough
setAdminis 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 conventionsThe 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 guidelinesPer 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
GenesisStatemessage, other repeated fields likebalances,supply, anddenom_metadatahave the option(amino.dont_omitempty) = true. For consistency and to prevent omitting empty fields during amino encoding, consider adding(amino.dont_omitempty) = trueto thefactory_denomsfield.
54-56: Enhance documentation for 'GenesisDenom' to improve clarityThe current comment for
GenesisDenomcontains 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_metadatainGenesisDenomis marked with[(gogoproto.nullable) = false]. For consistency with other non-nullable fields and to ensure proper amino encoding, consider adding(amino.dont_omitempty) = trueto this field's options.x/bank/v2/types/denoms.go (1)
53-55: Standardize error message formattingConsider 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-dateThe
Metadatamessage 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 forcosmos.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 issueThere'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 governanceThe 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 informationWhen 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 fieldsIn the
Keeperstruct, consider grouping related fields together for better readability. SincedenomMetadataanddenomAuthorityare 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 conventionsThe term "metadata" is used inconsistently in method names (
GetDenomMetaDatavs.denomMetadata). For clarity and consistency, consider using eitherMetaDataorMetadatathroughout.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
⛔ Files ignored due to path filters (4)
x/bank/v2/types/authorityMetadata.pb.gois excluded by!**/*.pb.gox/bank/v2/types/bank.pb.gois excluded by!**/*.pb.gox/bank/v2/types/genesis.pb.gois excluded by!**/*.pb.gox/bank/v2/types/tx.pb.gois 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 necessarysdkpackage is properly imported from cosmos-sdk.
1-15: Overall, excellent implementation ofDenomAuthorityMetadatavalidation.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 optionThe
DenomAuthorityMetadatamessage is well-defined with a clear and informative comment. The use of thegogoproto.equaloption is appropriate for enabling equality checks on this message type.x/bank/v2/keeper/admins.go (1)
1-34: Verify the accessibility of unexported methodsThe methods
setAuthorityMetadataandsetAdminare 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
keeperpackage, then unexported methods are appropriate.x/bank/v2/keeper/genesis.go (2)
55-59: Validate the creator's address format when deconstructing denomWhen deconstructing the denom using
types.DeconstructDenom, ensure that thecreatoraddress is valid and conforms to the expected format. An invalid address could cause issues downstream.Add a validation step to confirm the
creatoraddress: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 issueEnsure 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.jsonhas anapp_state.bank.factory_denomsfield 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
Balancemessage,(gogoproto.equal) = falseis set, and(gogoproto.goproto_getters) = falseis included to control code generation. Ensure that setting(gogoproto.equal) = trueinGenesisDenomis intentional and that equality methods are required for this message. If not necessary, consider aligning with theBalancemessage settings for consistency.
6-6: Import statement for 'authorityMetadata.proto' seems appropriateThe addition of the import statement for
"cosmos/bank/v2/authorityMetadata.proto"correctly brings in dependencies required forDenomAuthorityMetadata. This import is necessary for the newly addedauthority_metadatafield inGenesisDenom.x/bank/v2/types/denoms.go (1)
25-37:GetTokenDenomfunction looks goodThe 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 fieldThe
denom_creation_gas_consumefield is of typeuint64, which is a scalar. The(gogoproto.nullable) = trueoption 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
nullableis used with scalar fields:✅ Verification successful
Nullable option unnecessary on scalar field
The
(gogoproto.nullable) = trueoption on theuint64scalar fielddenom_creation_gas_consumeinx/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 inparams.DenomCreationFeeAt line 89, you check if
params.DenomCreationFee != nilto determine if there is a fee to charge. Ensure thatDenomCreationFeeis 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: EnsureGasMeteris properly initialized before consumptionIn the
chargeForCreateDenomfunction, you consume gas usingk.Environment.GasService.GasMeter(ctx). Please ensure thatGasServiceandGasMeterare 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 ofMsgChangeAdminResponseis appropriateThe
MsgChangeAdminResponsemessage is correctly defined and follows the pattern established in the module.x/bank/v2/keeper/keeper.go (1)
47-48:⚠️ Potential issueCheck for errors during schema building
In the
NewKeeperfunction, 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 inTestCreateDenomThe 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 inTestCreateDenom_GasConsumeThe 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.
| // Can be empty for no admin, or a valid osmosis address | ||
| string admin = 1 [(gogoproto.moretags) = "yaml:\"admin\""]; | ||
| } |
There was a problem hiding this comment.
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"; |
There was a problem hiding this comment.
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
gogoprotois 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)
| func (k Keeper) GetAuthorityMetadata(ctx context.Context, denom string) (types.DenomAuthorityMetadata, error) { | ||
| authority, err := k.denomAuthority.Get(ctx, denom) | ||
| return authority, err | ||
| } |
There was a problem hiding this comment.
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.
| 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 | |
| } |
| // 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) | ||
| } |
There was a problem hiding this comment.
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.
| // 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) | |
| } |
x/bank/v2/types/params.go
Outdated
| // DefaultParams is the default parameter configuration for the bank/v2 module | ||
| func DefaultParams() Params { | ||
| return NewParams() | ||
| return NewParams(sdk.NewCoins(), 1_000_000) |
There was a problem hiding this comment.
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.
| return NewParams(sdk.NewCoins(), 1_000_000) | |
| const DefaultDenomCreationGasConsume uint64 = 1_000_000 | |
| func DefaultParams() Params { | |
| return NewParams(sdk.NewCoins(), DefaultDenomCreationGasConsume) | |
| } |
| denomMetaData = append(denomMetaData, metadata) | ||
| return false | ||
| }) | ||
|
|
||
| return denomMetaData |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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 | |
| } |
| panic(err) | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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 | |
| } |
| m, err := k.denomMetadata.Get(ctx, denom) | ||
| return m, err == nil | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| 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 | |
| } |
| balances := sdk.NewCoins() | ||
| k.IterateAccountBalances(ctx, addr, func(balance sdk.Coin) bool { | ||
| balances = balances.Add(balance) | ||
| return false | ||
| }) | ||
|
|
||
| return balances.Sort() | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| // 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 |
|
I'm out for a week, let's not block this, and get some reviews. @facundomedica or @testinginprod, could you give a look? |
not yet Im testing in local |
alpe
left a comment
There was a problem hiding this 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 |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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, | ||
| } |
There was a problem hiding this comment.
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()) |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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?
x/bank/v2/keeper/createdenom.go
Outdated
| // if DenomCreationFee is non-zero, transfer the tokens from the creator | ||
| // account to community pool | ||
| if params.DenomCreationFee != nil { | ||
| accAddr, err := sdk.AccAddressFromBech32(creatorAddr) |
There was a problem hiding this comment.
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{} |
There was a problem hiding this comment.
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?
There was a problem hiding this 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 denomThere'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
📒 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()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
| _, accountAddr, err := k.accountsKeeper.Init(ctx, admin.Type, creatorAddrBz, msgInitAdmin, sdk.NewCoins()) | |
| _, accountAddr, err = k.accountsKeeper.Init(ctx, admin.Type, creatorAddrBz, msgInitAdmin, sdk.NewCoins()) |
|
Closing this as stale. Hopefully it will get picked by up in the future. |
Description
Ref: #22251
denomMetadata&authorityMetadatafuncsMsgMint,MsgBurninto bank/v2mint,burnAuthor 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...
!in the type prefix if API or client breaking changeCHANGELOG.mdReviewers 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...
Summary by CodeRabbit
Summary by CodeRabbit
New Features
MsgCreateDenom,MsgChangeAdmin,MsgBurn, and their corresponding response types.Bug Fixes
Tests
Documentation