-
Notifications
You must be signed in to change notification settings - Fork 3.7k
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
refactor(client/v2)!: remove client.Context #22493
Conversation
📝 Walkthrough📝 WalkthroughWalkthroughThe changes in this pull request involve significant modifications to the Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant CLI
participant Context
participant Keyring
participant Codec
participant Broadcaster
User->>CLI: Execute command
CLI->>Context: Set up context
Context->>Keyring: Retrieve keyring
Context->>Codec: Retrieve codec
CLI->>Broadcaster: Broadcast transaction
Broadcaster->>User: Return response
Possibly related PRs
Suggested labels
Suggested reviewers
📜 Recent review detailsConfiguration used: .coderabbit.yml 📒 Files selected for processing (1)
✅ Files skipped from review due to trivial changes (1)
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
|
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: 8
🧹 Outside diff range and nitpick comments (10)
client/v2/tx/flags.go (1)
Line range hint
1-52
: Consider consistent visibility for all constantsWhile the transaction-related flags are now exported,
defaultGasLimit
andgasFlagAuto
remain unexported. Consider if these should also be exported for consistency, or document why they should remain package-private.client/v2/internal/flags/flags.go (2)
23-27
: Consider enhancing keyring backend documentation.While the documentation is good, it would be helpful to list all supported backend types and their security implications in the comment for
FlagKeyringBackend
.Consider updating the comment like this:
-// FlagKeyringBackend is the flag to specify which backend to use for the keyring (e.g. os, file, test). +// FlagKeyringBackend is the flag to specify which backend to use for the keyring. +// Supported backends: +// - os: use the operating system's default credentials store +// - file: encrypted file-based keyring +// - test: insecure, for testing purposes only +// - kwallet: KDE Wallet Manager +// - pass: Unix password manager
32-36
: Enhance documentation for node and broadcast mode flags.The documentation could be more specific about:
- Expected node URL format
- Available broadcast modes and their implications
Consider updating the comments like this:
-// FlagNode is the flag to specify the node address to connect to. +// FlagNode is the flag to specify the node address to connect to (e.g., tcp://localhost:26657). -// FlagBroadcastMode is the flag to specify the broadcast mode for transactions. +// FlagBroadcastMode is the flag to specify the broadcast mode for transactions. +// Available modes: +// - sync: wait for the tx to be broadcast to the network +// - async: return immediately after the tx is broadcast +// - block: wait for the tx to be committed in a blockclient/v2/context/context.go (2)
16-20
: Consider a more specific name for the context key variable.While the implementation is correct, consider renaming
ContextKey
to something more specific likeClientContextKey
orAutoCliContextKey
to avoid potential naming conflicts in the broader codebase.-var ContextKey contextKey +var ClientContextKey contextKey
22-36
: Consider adding validation and constructor method.The Context struct is well-designed, but it would benefit from having:
- A constructor method to ensure all required fields are properly initialized
- A validation method to check for nil fields before use
This would help prevent runtime errors from uninitialized fields.
Here's a suggested addition:
// NewContext creates a new Context with validation func NewContext(flags *pflag.FlagSet, addressCodec address.Codec, validatorCodec address.ValidatorAddressCodec, consensusCodec address.ConsensusAddressCodec, cdc codec.Codec, keyring keyring.Keyring, signModes []apisigning.SignMode) (*Context, error) { if addressCodec == nil || validatorCodec == nil || consensusCodec == nil || cdc == nil { return nil, errors.New("required codecs cannot be nil") } return &Context{ Flags: flags, AddressCodec: addressCodec, ValidatorAddressCodec: validatorCodec, ConsensusAddressCodec: consensusCodec, Cdc: cdc, Keyring: keyring, EnabledSignmodes: signModes, }, nil }client/v2/tx/tx.go (1)
31-39
: Improve error handling with contextThe error handling could be more descriptive by wrapping errors with additional context.
txf, err := initFactory(ctx, conn, msgs...) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to initialize transaction factory: %w", err) } err = generateTx(txf, msgs...) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to generate transaction: %w", err) }client/v2/autocli/common.go (3)
315-324
: Consider using map literal initializationThe map initialization could be more concise using a map literal, improving readability.
- flagsToSet := map[string]string{ - flags.FlagChainID: conf.ChainID, - flags.FlagKeyringBackend: conf.KeyringBackend, - flags.FlagFrom: conf.KeyringDefaultKeyName, - flags.FlagOutput: conf.Output, - flags.FlagNode: conf.Node, - flags.FlagBroadcastMode: conf.BroadcastMode, - flags.FlagGrpcAddress: conf.GRPC.Address, - flags.FlagGrpcInsecure: strconv.FormatBool(conf.GRPC.Insecure), - } + flagsToSet := map[string]string{flags.FlagChainID: conf.ChainID, flags.FlagKeyringBackend: conf.KeyringBackend, + flags.FlagFrom: conf.KeyringDefaultKeyName, flags.FlagOutput: conf.Output, flags.FlagNode: conf.Node, + flags.FlagBroadcastMode: conf.BroadcastMode, flags.FlagGrpcAddress: conf.GRPC.Address, + flags.FlagGrpcInsecure: strconv.FormatBool(conf.GRPC.Insecure)}
365-365
: Consider documenting the default CometBFT behaviorThe TODO comment could be more descriptive about why CometBFT is the default and what implications this has.
- // TODO: default is comet + // TODO: Using CometBFT as default for backward compatibility with legacy implementations
377-384
: Consider using make with length and capacityFor better performance, pre-allocate the slice with both length and capacity.
- r := make([]apitxsigning.SignMode, len(modes)) + r := make([]apitxsigning.SignMode, len(modes), len(modes))client/v2/autocli/msg.go (1)
257-268
: Simplify conditional logic for better readabilityThe nested
if-else
statements handlinggenOnly
,isDryRun
, andskipConfirm
can be refactored to improve code readability and maintainability.Consider refactoring the conditionals as follows:
if genOnly { bz, err = v2tx.GenerateOnly(ctx, cConn, msgs...) } else if isDryRun { bz, err = v2tx.DryRun(ctx, cConn, msgs...) } else { skipConfirm, _ := cmd.Flags().GetBool("yes") if skipConfirm { bz, err = v2tx.GenerateAndBroadcastTxCLI(ctx, cConn, msgs...) } else { bz, err = v2tx.GenerateAndBroadcastTxCLIWithPrompt(ctx, cConn, b.userConfirmation(cmd), msgs...) } }This refactoring flattens the conditional structure, making it easier to follow the logic.
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
📒 Files selected for processing (15)
client/v2/autocli/common.go
(3 hunks)client/v2/autocli/config/config.go
(1 hunks)client/v2/autocli/flag/address.go
(5 hunks)client/v2/autocli/msg.go
(5 hunks)client/v2/context/context.go
(1 hunks)client/v2/go.mod
(4 hunks)client/v2/internal/flags/flags.go
(2 hunks)client/v2/offchain/cli.go
(5 hunks)client/v2/offchain/sign.go
(3 hunks)client/v2/offchain/sign_test.go
(2 hunks)client/v2/offchain/verify.go
(3 hunks)client/v2/offchain/verify_test.go
(2 hunks)client/v2/tx/flags.go
(1 hunks)client/v2/tx/tx.go
(4 hunks)client/v2/tx/types.go
(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
- client/v2/autocli/config/config.go
- client/v2/go.mod
- client/v2/offchain/cli.go
- client/v2/offchain/sign_test.go
- client/v2/offchain/verify_test.go
- client/v2/tx/types.go
🧰 Additional context used
📓 Path-based instructions (9)
client/v2/autocli/common.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
client/v2/autocli/flag/address.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
client/v2/autocli/msg.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
client/v2/context/context.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
client/v2/internal/flags/flags.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
client/v2/offchain/sign.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
client/v2/offchain/verify.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
client/v2/tx/flags.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
client/v2/tx/tx.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
🪛 golangci-lint (1.62.2)
client/v2/autocli/msg.go
242-242: directive //nolint:unused // It'll be used once BuildMsgMethodCommand is updated to use factory v2.
is unused for linter "unused"
(nolintlint)
🔇 Additional comments (20)
client/v2/tx/flags.go (1)
13-29
: LGTM! Note: This is a breaking change.
The conversion of flag constants from unexported to exported is well-structured and follows Go naming conventions. This change improves reusability by allowing external packages to access these flags directly.
Let's verify the impact of this breaking change:
✅ Verification successful
Let me analyze the search results. The flags in client/v2/tx/flags.go
are being used extensively throughout the codebase, but primarily in test files and in the v2 client implementation itself. The key observations are:
- Most usages are in test files (
_test.go
) - The flags are used in the v2 client implementation (
client/v2/tx/types.go
,client/v2/tx/factory.go
) - The flags are referenced from other packages using the
flags
package name, suggesting proper import usage
Let me verify if there are any direct string literal usages that might break:
Breaking change is safe to proceed with
The change to export flag constants in client/v2/tx/flags.go
is well-structured and safe. The analysis shows:
- Most direct flag usages are in test files
- Production code references are properly importing and using the flag constants through the package
- String literals found in other files are primarily in:
- Generated files (
.pulsar.go
) - Internal implementation files that define the constants
- Configuration files that consume these values
- Generated files (
The change aligns with the v2 client refactoring goals and follows Go's idioms for exported constants. No compatibility issues were found that would prevent this change.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for any direct usage of these flags in their previous lowercase form
# This helps identify any code that needs to be updated
rg -i "flag(timeoutTimestamp|chainID|note|signMode|accountNumber|sequence|from|dryRun|gas|gasAdjustment|gasPrices|fees|feePayer|feeGranter|unordered|offline|generateOnly)[^A-Z]"
Length of output: 42640
Script:
#!/bin/bash
# Search for direct string literals matching the flag names
rg -l '"timeout-timestamp"|"chain-id"|"note"|"sign-mode"|"account-number"|"sequence"|"from"|"dry-run"|"gas"|"gas-adjustment"|"gas-prices"|"fees"|"fee-payer"|"fee-granter"|"unordered"|"offline"|"generate-only"' --type go | grep -v "_test.go"
Length of output: 1305
client/v2/internal/flags/flags.go (1)
5-10
: LGTM! Well-documented home and chain ID flags.
The flag constants follow Go naming conventions and include clear documentation.
client/v2/context/context.go (2)
1-14
: LGTM! Clean package structure and imports.
The package structure follows Go conventions, and imports are well-organized with clear aliases where needed.
1-55
: Verify migration from old client.Context.
Since this is part of removing client.Context
, we should verify that all callers are properly migrated to the new context package.
client/v2/offchain/sign.go (5)
7-10
: LGTM: Import changes are well-organized and necessary.
The new imports support the transition from client.Context
to clientcontext.Context
and the addition of gRPC client functionality.
Line range hint 91-91
: Use the parent context instead of context.Background().
Skipping detailed explanation as this issue was already raised in a previous review.
54-54
: LGTM: Explicit dependency initialization.
The account retriever initialization is now more explicit about its dependencies, which improves code clarity.
70-70
: LGTM: Clear dependency injection in factory creation.
The transaction factory initialization clearly shows its dependencies through the new context structure.
75-78
: LGTM: Clean keyring access with proper error handling.
The keyring access is straightforward and includes appropriate error handling.
client/v2/offchain/verify.go (2)
Line range hint 21-37
: LGTM! Clean refactor of the Verify function.
The changes properly migrate from client.Context
to clientcontext.Context
while maintaining the necessary functionality. The new TxConfig
creation correctly utilizes the context fields.
Line range hint 41-91
: LGTM! Good improvement in dependency management.
The refactored verify
function now explicitly accepts its dependencies (addressCodec
and txConfig
) instead of extracting them from a context. This change:
- Improves testability
- Makes dependencies explicit
- Reduces coupling with the context structure
client/v2/autocli/flag/address.go (5)
10-10
: LGTM: Import aligns with refactoring goals
The new import supports the transition away from client.Context as per PR objectives.
46-52
: LGTM: Appropriate use of pointer receivers
The conversion to pointer receivers is a good practice for consistency and efficiency.
57-58
: LGTM: Keyring initialization timing issue resolved
The implementation correctly addresses the keyring initialization timing concerns raised in previous reviews while maintaining the desired functionality.
112-113
: LGTM: Consistent implementation with addressValue
The changes maintain consistency with the addressValue implementation while preserving the required keyring functionality.
149-162
: Consider fallback to client.Context v1
The implementation handles nil checks and invalid contexts gracefully. However, as suggested in the previous review, consider adding a fallback to check client.Context v1 for better backward compatibility.
Let's check if there are any direct uses of client.Context v1 in the codebase:
client/v2/tx/tx.go (1)
140-144
:
Handle flag retrieval errors
The function ignores potential errors from flag retrieval which could lead to silent failures.
func getCometBroadcaster(cdc codec.Codec, flagSet *pflag.FlagSet) (broadcast.Broadcaster, error) {
- url, _ := flagSet.GetString(flags.FlagNode)
- mode, _ := flagSet.GetString(flags.FlagBroadcastMode)
+ if cdc == nil {
+ return nil, fmt.Errorf("codec cannot be nil")
+ }
+ if flagSet == nil {
+ return nil, fmt.Errorf("flag set cannot be nil")
+ }
+
+ url, err := flagSet.GetString(flags.FlagNode)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get node URL: %w", err)
+ }
+ if url == "" {
+ return nil, fmt.Errorf("node URL is required")
+ }
+
+ mode, err := flagSet.GetString(flags.FlagBroadcastMode)
+ if err != nil {
+ return nil, fmt.Errorf("failed to get broadcast mode: %w", err)
+ }
+ if mode == "" {
+ return nil, fmt.Errorf("broadcast mode is required")
+ }
+
return comet.NewCometBFTBroadcaster(url, mode, cdc)
}
Likely invalid or redundant comment.
client/v2/autocli/common.go (3)
256-261
: LGTM: Clean printer implementation
The refactored implementation properly handles errors and uses the new printer abstraction.
263-291
: LGTM: Well-structured context initialization
The function properly handles keyring initialization based on flags and creates a comprehensive client context with all necessary codecs.
293-305
: LGTM: Clean PreRunE implementation
The function follows the single responsibility principle and properly handles error propagation.
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: 0
🧹 Outside diff range and nitpick comments (2)
client/v2/autocli/msg.go (2)
240-240
: Remove unnecessary nolint directiveThe
//nolint:unused
directive is no longer needed as this function will be used in the updatedBuildMsgMethodCommand
.-//nolint:unused // It'll be used once BuildMsgMethodCommand is updated to use factory v2.
241-278
: Consider enhancing error handling with specific error typesThe error handling could be more specific to help users better understand and debug issues. Consider wrapping errors with context.
func (b *Builder) generateOrBroadcastTxWithV2(cmd *cobra.Command, msgs ...transaction.Msg) error { ctx, err := b.getContext(cmd) if err != nil { - return err + return fmt.Errorf("failed to get context: %w", err) } cConn, err := b.GetClientConn(cmd) if err != nil { - return err + return fmt.Errorf("failed to get client connection: %w", err) }
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
📒 Files selected for processing (1)
client/v2/autocli/msg.go
(4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
client/v2/autocli/msg.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
🪛 golangci-lint (1.62.2)
client/v2/autocli/msg.go
282-282: func (*Builder).userConfirmation
is unused
(unused)
🔇 Additional comments (1)
client/v2/autocli/msg.go (1)
282-307
: 🛠️ Refactor suggestion
Use command I/O streams for better testability
Using os.Stdin
and os.Stderr
directly makes testing difficult. Instead, use the command's input and error output streams.
func (b *Builder) userConfirmation(cmd *cobra.Command) func([]byte) (bool, error) {
format, _ := cmd.Flags().GetString(flags.FlagOutput)
printer := print.Printer{
Output: cmd.OutOrStdout(),
OutputFormat: format,
}
return func(bz []byte) (bool, error) {
err := printer.PrintBytes(bz)
if err != nil {
return false, err
}
- buf := bufio.NewReader(os.Stdin)
+ buf := bufio.NewReader(cmd.InOrStdin())
ok, err := input.GetConfirmation(
"confirm transaction before signing and broadcasting",
- buf, os.Stderr
+ buf, cmd.ErrOrStderr(),
)
if err != nil {
- _, _ = fmt.Fprintf(os.Stderr, "error: %v\ncanceled transaction\n", err)
+ _, _ = fmt.Fprintf(cmd.ErrOrStderr(), "error: %v\ncanceled transaction\n", err)
return false, err
}
if !ok {
- _, _ = fmt.Fprintln(os.Stderr, "canceled transaction")
+ _, _ = fmt.Fprintln(cmd.ErrOrStderr(), "canceled transaction")
return false, nil
}
return true, nil
}
}
Likely invalid or redundant comment.
🧰 Tools
🪛 golangci-lint (1.62.2)
282-282: func (*Builder).userConfirmation
is unused
(unused)
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: 0
🧹 Outside diff range and nitpick comments (2)
client/v2/autocli/msg.go (2)
239-239
: Remove unnecessary nolint directiveThe
nolint:unused
directive is no longer needed as this function will be used whenBuildMsgMethodCommand
is updated to use factory v2.Apply this diff to remove the directive:
-//nolint:unused // It'll be used once BuildMsgMethodCommand is updated to use factory v2.
240-277
: LGTM! Consider enhancing error handlingThe implementation is well-structured and handles different transaction scenarios appropriately. Consider wrapping errors with more context for better debugging.
Example enhancement:
if err != nil { - return err + return fmt.Errorf("failed to get context: %w", err) }
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
📒 Files selected for processing (2)
client/v2/autocli/msg.go
(4 hunks)client/v2/autocli/query.go
(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- client/v2/autocli/query.go
🧰 Additional context used
📓 Path-based instructions (1)
client/v2/autocli/msg.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
🪛 golangci-lint (1.62.2)
client/v2/autocli/msg.go
281-281: func (*Builder).userConfirmation
is unused
(unused)
🔇 Additional comments (1)
client/v2/autocli/msg.go (1)
281-306
: LGTM! Well-implemented user confirmation flow
The implementation follows best practices:
- Uses command's I/O streams for better testability
- Provides clear user feedback
- Properly handles errors with user-friendly messages
🧰 Tools
🪛 golangci-lint (1.62.2)
281-281: func (*Builder).userConfirmation
is unused
(unused)
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: 0
🧹 Outside diff range and nitpick comments (1)
client/v2/autocli/msg.go (1)
282-282
: Remove unnecessarynolint:unused
directiveThe
nolint:unused
directive is no longer needed as the function is being used ingenerateOrBroadcastTxWithV2
.
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
📒 Files selected for processing (1)
client/v2/autocli/msg.go
(4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
client/v2/autocli/msg.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
🔇 Additional comments (3)
client/v2/autocli/msg.go (3)
239-239
: Remove unnecessary nolint:unused
directive
The nolint:unused
directive is no longer needed as the function is being used.
283-308
: Well-implemented user confirmation flow with proper I/O handling
The implementation follows best practices:
- Uses command's I/O streams for better testability
- Properly handles user input and error cases
- Clear error messages and user feedback
240-277
: Implementation looks good with comprehensive transaction handling
The method properly handles different transaction modes (generate-only, dry-run, broadcast) with appropriate error handling and user confirmation flow.
Let's verify the error handling paths:
✅ Verification successful
Based on the extensive error handling patterns shown in the codebase, particularly in the transaction-related code, I can now generate the final response:
Error handling implementation is robust and comprehensive
The transaction handling in generateOrBroadcastTxWithV2
follows established error handling patterns seen throughout the codebase:
- Immediate error checking after context and client connection initialization
- Proper error propagation from all transaction modes (generate-only, dry-run, broadcast)
- Consistent error handling pattern with early returns
- No swallowed errors or unhandled edge cases
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify error handling in transaction-related code
# Look for error handling patterns in transaction-related code
# Check for error handling in transaction operations
rg -A 2 'if err [!:=]' --type go
# Check for potential error paths that might be missed
ast-grep --pattern 'if $cond {
$$$
return $err
}'
Length of output: 113963
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.
utACK. Let's add a changelog and could you check this: https://github.com/cosmos/cosmos-sdk/pull/22493/files#r1848398289
I don’t think it makes much sense to pass the context to create the keyring, as it is the context creation function that actually uses this function to create its keyring. |
Ok! Makes sense |
Can we still get 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: 0
🧹 Outside diff range and nitpick comments (2)
client/v2/tx/tx.go (2)
59-89
: Consider splitting the prompt logic into a separate packageThe prompt functionality should be moved to a dedicated UI/interaction package to maintain better separation of concerns. This transaction package should focus solely on transaction handling.
Consider creating a new package like
client/v2/interaction
to handle user prompts and confirmations.
293-310
: Add timeout to confirmation promptThe confirmation prompt should have a timeout to prevent indefinite waiting.
Consider adding a timeout context to the prompter function:
-func askConfirmation(txf Factory, prompter func([]byte) (bool, error)) (bool, error) { +func askConfirmation(ctx context.Context, txf Factory, prompter func(context.Context, []byte) (bool, error)) (bool, error) { encoder := txf.txConfig.TxJSONEncoder() if encoder == nil { return false, errors.New("failed to encode transaction: tx json encoder is nil") } tx, err := txf.getTx() if err != nil { return false, err } txBytes, err := encoder(tx) if err != nil { return false, fmt.Errorf("failed to encode transaction: %w", err) } - return prompter(txBytes) + return prompter(ctx, txBytes) }
📜 Review details
Configuration used: .coderabbit.yml
Review profile: CHILL
📒 Files selected for processing (5)
client/v2/autocli/common.go
(3 hunks)client/v2/broadcast/comet/comet.go
(1 hunks)client/v2/context/context.go
(1 hunks)client/v2/tx/tx.go
(4 hunks)tests/systemtests/mint_test.go
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- client/v2/broadcast/comet/comet.go
- client/v2/context/context.go
- tests/systemtests/mint_test.go
🧰 Additional context used
📓 Path-based instructions (2)
client/v2/autocli/common.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
client/v2/tx/tx.go (1)
Pattern **/*.go
: Review the Golang code for conformity with the Uber Golang style guide, highlighting any deviations.
🔇 Additional comments (9)
client/v2/tx/tx.go (3)
140-144
: 🛠️ Refactor suggestion
Add validation for required flag values
The function should validate that required flag values are present and valid.
Apply this diff:
func getCometBroadcaster(cdc codec.Codec, flagSet *pflag.FlagSet) (broadcast.Broadcaster, error) {
+ if cdc == nil {
+ return nil, fmt.Errorf("codec cannot be nil")
+ }
+ if flagSet == nil {
+ return nil, fmt.Errorf("flag set cannot be nil")
+ }
url, _ := flagSet.GetString(flags.FlagNode)
+ if url == "" {
+ return nil, fmt.Errorf("node URL is required")
+ }
mode, _ := flagSet.GetString(flags.FlagBroadcastMode)
+ if mode == "" {
+ return nil, fmt.Errorf("broadcast mode is required")
+ }
return comet.NewCometBFTBroadcaster(url, mode, cdc)
}
Likely invalid or redundant comment.
241-256
: 🛠️ Refactor suggestion
Improve error handling and context cancellation checks
The function should handle context cancellation and provide better error context.
Apply this diff:
func BroadcastTx(ctx context.Context, txf Factory, broadcaster broadcast.Broadcaster) ([]byte, error) {
+ if ctx == nil {
+ return nil, fmt.Errorf("context cannot be nil")
+ }
+ if broadcaster == nil {
+ return nil, fmt.Errorf("broadcaster cannot be nil")
+ }
+
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ default:
+ }
+
if len(txf.tx.msgs) == 0 {
return nil, errors.New("no messages to broadcast")
}
signedTx, err := txf.sign(ctx, true)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("failed to sign transaction: %w", err)
}
txBytes, err := txf.txConfig.TxEncoder()(signedTx)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("failed to encode transaction: %w", err)
}
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ default:
+ }
+
return broadcaster.Broadcast(ctx, txBytes)
Likely invalid or redundant comment.
25-42
: 🛠️ Refactor suggestion
Add parameter validation and improve error handling
The function needs validation for its input parameters and better error wrapping.
Apply this diff:
func GenerateAndBroadcastTxCLIWithBroadcaster(
ctx context.Context,
conn grpc.ClientConn,
broadcaster broadcast.Broadcaster,
msgs ...transaction.Msg,
) ([]byte, error) {
+ if ctx == nil {
+ return nil, fmt.Errorf("context cannot be nil")
+ }
+ if conn == nil {
+ return nil, fmt.Errorf("connection cannot be nil")
+ }
+ if broadcaster == nil {
+ return nil, fmt.Errorf("broadcaster cannot be nil")
+ }
+ if len(msgs) == 0 {
+ return nil, fmt.Errorf("at least one message is required")
+ }
+
txf, err := initFactory(ctx, conn, msgs...)
if err != nil {
- return nil, err
+ return nil, fmt.Errorf("failed to initialize factory: %w", err)
}
Likely invalid or redundant comment.
client/v2/autocli/common.go (6)
256-261
: LGTM: Clean printer implementation
The refactored implementation using print.NewPrinter
is clean and handles errors appropriately.
326-332
: LGTM: Proper error handling in flag operations
The implementation correctly handles errors from flag operations in a clean loop structure.
377-384
: LGTM: Clean type conversion implementation
The function provides a clean implementation for converting between sign mode types.
79-82
:
Fix variable shadowing of ctx
The reassignment of ctx
shadows the previously declared variable. This can lead to confusion and potential bugs.
Apply this diff to fix the shadowing:
-ctx, err = b.getContext(cmd)
+newCtx, err := b.getContext(cmd)
if err != nil {
return err
}
+ctx = newCtx
343-345
:
Security: Default to secure gRPC connections
Defaulting to insecure gRPC connections (insecure := true
) poses security risks. Consider defaulting to secure connections.
Apply this diff to prioritize security:
-creds := grpcinsecure.NewCredentials()
-
-insecure := true
+insecure := false
+creds := credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12})
373-373
:
Fix incorrect gRPC client creation
The function grpc.NewClient
doesn't exist in the google.golang.org/grpc
package. Use grpc.Dial
instead.
Apply this diff:
-return grpc.NewClient(addr, []grpc.DialOption{grpc.WithTransportCredentials(creds)}...)
+return grpc.Dial(addr, grpc.WithTransportCredentials(creds))
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.
utACK 👍
Looks like you need to run the go mod tidy all script |
Description
Closes:
#22397
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...
!
in the type prefix if API or client breaking changeCHANGELOG.md
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...
Summary by CodeRabbit
Release Notes
New Features
KeyType
andKeyInfo
.Bug Fixes
*big.Int
unmarshalling in transactions.autocli
when custom commands have different names than the module name.Documentation
Refactor
Tests