Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(client/v2)!: remove client.Context #22493

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

Conversation

JulianToledano
Copy link
Contributor

@JulianToledano JulianToledano commented Nov 8, 2024

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

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch (see PR Targeting)
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • added a changelog entry to CHANGELOG.md
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

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

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

Summary by CodeRabbit

Release Notes

  • New Features

    • Enhanced CLI with improved transaction handling and broadcasting capabilities.
    • Added support for signing and verifying files with a modular configuration approach.
    • Introduced a new Printer struct for formatted output handling.
  • Improvements

    • Streamlined command handling and configuration management, particularly for gRPC communication.
    • Updated transaction parameter extraction logic for better flexibility.
    • Enhanced error handling and output formatting across various components.
  • Bug Fixes

    • Corrected codec type usage in broadcasting and transaction functions.
  • Documentation

    • Updated command-line flags and usage documentation for improved clarity.

Copy link
Contributor

coderabbitai bot commented Nov 8, 2024

📝 Walkthrough

Walkthrough

This pull request introduces significant changes to the client/v2/autocli package, particularly focusing on the restructuring of the AppOptions and related components. The ClientCtx field has been removed from AppOptions, replaced by multiple new fields to enhance modularity. Additionally, several functions and methods have been updated to accommodate these changes, including modifications to command handling, transaction management, and configuration management. New files for configuration management and TOML handling have also been added, along with updates to various tests and the go.mod file for dependency management.

Changes

File Path Change Summary
client/v2/autocli/app.go Removed ClientCtx from AppOptions; added fields: InterfaceRegistry, AddressCodec, ValidatorAddressCodec, ConsensusAddressCodec, Cdc, TxConfigOpts. Updated EnhanceRootCommand and NewAppOptionsFromConfig.
client/v2/autocli/builder.go Added fields: Cdc and EnablesSignModes to Builder struct.
client/v2/autocli/common.go Added imports for gRPC and TLS; modified outOrStdoutFormat to use print.NewPrinter; introduced preRunE and setFlagsFromConfig methods. Added getQueryClientConn.
client/v2/autocli/common_test.go Updated fixture struct with new fields; modified initFixture to initialize new fields; replaced AddTxConnFlags function.
client/v2/autocli/config/config.go Introduced a new configuration management system with Config and GRPCConfig structs; added functions for creating client configurations.
client/v2/autocli/config/toml.go Added functions for managing TOML configuration files, including setting a custom template and writing configuration files.
client/v2/autocli/flag/address.go Enhanced addressValue and consensusAddressValue structs with caching logic; updated methods for address handling.
client/v2/autocli/flag/builder.go Added global variable keybase and SetKeyring method for key management.
client/v2/autocli/keyring/keyring.go Introduced NewKeyringFromFlags function for creating keyring instances from command-line flags.
client/v2/autocli/msg.go Added generateOrBroadcastTxWithV2 method for transaction handling.
client/v2/autocli/msg_test.go Added --chain-id and --keyring-backend flags to test command invocations.
client/v2/autocli/print/printer.go Introduced Printer struct for formatted output handling with methods for printing strings and bytes.
client/v2/autocli/query.go Simplified client connection retrieval in BuildQueryMethodCommand.
client/v2/autocli/testdata/help-echo-msg.golden Added --home flag to command usage documentation.
client/v2/broadcast/comet/clientConn.go Introduced CometBFTBroadcaster struct with methods for gRPC communication.
client/v2/broadcast/comet/comet.go Updated CometBFTBroadcaster to use codec.Codec and added an InterfaceRegistry field.
client/v2/broadcast/comet/comet_test.go Updated tests to reflect changes in CometBFTBroadcaster.
client/v2/go.mod Updated dependencies for the module.
client/v2/offchain/cli.go Enhanced SignFile and VerifyFile functions to use new configuration and keyring management.
client/v2/offchain/common_test.go Refactored test setup, removing dependencies on specific signing modes and configurations.
client/v2/offchain/sign.go Updated Sign function to accept new parameters for improved modularity.
client/v2/offchain/verify.go Modified Verify function to use direct parameters instead of context.
client/v2/tx/encoder.go Updated jsonMarshalOptions to include unpopulated fields in JSON output.
client/v2/tx/factory.go Enhanced validation logic in validateFlagSet function.
client/v2/tx/tx.go Updated transaction handling functions to accept new parameters, improving modularity and clarity.
client/v2/tx/types.go Added generateOnly flag to transaction parameter extraction logic.
simapp/simd/cmd/root.go Updated NewRootCmd to initialize autoCliOpts from initClientCtx.
x/authz/go.mod Updated dependency versions.
x/group/go.mod Updated dependency versions.
x/params/go.mod Updated dependency versions.
x/upgrade/go.mod Updated dependency versions.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant AppOptions
    participant Keyring
    participant Config

    User->>CLI: Execute Command
    CLI->>AppOptions: Retrieve Options
    AppOptions->>Keyring: Get Keyring Instance
    CLI->>Config: Load Configuration
    Config-->>CLI: Return Config
    CLI->>User: Display Output
Loading

Possibly related PRs

Suggested labels

C:x/tx, C:core/testing, C:server/v2, C:server/v2 api

Suggested reviewers

  • kocubinski
  • testinginprod
  • sontrinh16
  • julienrbrt

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 21

🧹 Outside diff range and nitpick comments (39)
client/v2/autocli/builder.go (2)

26-27: Add documentation for new fields

The new fields Cdc and EnablesSignModes lack documentation explaining their purpose and usage requirements.

Consider adding documentation like this:

+	// Cdc specifies the codec for serialization and deserialization
 	Cdc              codec.Codec
+	// EnablesSignModes defines the signing modes supported by this builder
 	EnablesSignModes []apisigning.SignMode

Line range hint 31-34: Consider validating new fields in ValidateAndComplete

The ValidateAndComplete method should validate the new required fields to ensure they are properly initialized.

Consider updating the method like this:

 func (b *Builder) ValidateAndComplete() error {
+	if b.Cdc == nil {
+		return fmt.Errorf("codec is required")
+	}
 	return b.Builder.ValidateAndComplete()
 }
client/v2/offchain/sign_test.go (2)

14-15: Consider using more descriptive variable names for the Bech32 codecs.

While the current names ac and vc are concise, more descriptive names would improve code readability.

-ac := address.NewBech32Codec("cosmos")
-vc := address.NewBech32Codec("cosmosvaloper")
+accountCodec := address.NewBech32Codec("cosmos")
+validatorCodec := address.NewBech32Codec("cosmosvaloper")

52-53: Improve readability of the Sign function call by breaking down parameters.

The current line is quite long and could be harder to read. Consider breaking down the parameters into multiple lines for better readability.

-			got, err := Sign(tt.rawBytes, mockClientConn{}, autoKeyring, getCodec(), ac, vc, getCodec().InterfaceRegistry(),
-				"signVerify", tt.encoding, tt.signMode, "json")
+			got, err := Sign(
+				tt.rawBytes,
+				mockClientConn{},
+				autoKeyring,
+				getCodec(),
+				accountCodec,
+				validatorCodec,
+				getCodec().InterfaceRegistry(),
+				"signVerify",
+				tt.encoding,
+				tt.signMode,
+				"json",
+			)
client/v2/autocli/print/printer.go (2)

12-15: Consider enhancing the constants definition.

The output format constants could be improved by:

  1. Adding documentation to explain their purpose
  2. Using an enumeration pattern with iota for better type safety
+// Output format constants
 const (
-	jsonOutput = "json"
-	textOutput = "text"
+	jsonOutput OutputFormat = iota // JSON format output
+	textOutput                     // Text format output (YAML)
 )
+
+// OutputFormat represents the supported output formats
+type OutputFormat int
+
+func (f OutputFormat) String() string {
+	return [...]string{"json", "text"}[f]
+}

17-21: Enhance struct documentation.

The struct documentation could be more descriptive and include field-level documentation.

-// Printer handles formatted output of different types of data
+// Printer handles formatted output of different types of data.
+// It supports multiple output formats (JSON, text) and can write to any io.Writer.
 type Printer struct {
+	// Output is the destination writer for the formatted data
 	Output       io.Writer
+	// OutputFormat specifies the format to use ("json" or "text")
 	OutputFormat string
 }
client/v2/autocli/keyring/keyring.go (1)

35-61: Enhance function documentation with parameter details.

The function implementation looks good and aligns with the PR objective of removing client.Context. However, the documentation could be more comprehensive.

Consider adding parameter descriptions:

 // NewKeyringFromFlags creates a new Keyring instance based on command-line flags.
 // It retrieves the keyring backend and directory from flags, creates a new keyring,
 // and wraps it with an AutoCLI-compatible interface.
+//
+// Parameters:
+// - flagSet: Command-line flags containing keyring configuration
+// - ac: Address codec for key address encoding/decoding
+// - input: Reader for interactive input (e.g., password prompts)
+// - cdc: Codec for key serialization
+// - opts: Optional keyring configuration options
client/v2/autocli/testdata/help-echo-msg.golden (1)

21-21: Consider enhancing the home flag description

The addition of the --home flag is well-placed and aligns with the removal of client.Context. However, the description could be more informative.

Consider this improved description:

-      --home string             home directory
+      --home string             The application home directory for config and data
client/v2/tx/encoder.go (1)

22-25: Consider documenting the marshaling behavior.

Adding a comment explaining why EmitUnpopulated is set to true would help future maintainers understand the rationale.

 jsonMarshalOptions = protojson.MarshalOptions{
+        // EmitUnpopulated ensures consistent transaction serialization by including
+        // zero-valued fields in the JSON output
 		Indent:          "",
 		UseProtoNames:   true,
 		UseEnumNumbers:  false,
 		EmitUnpopulated: true,
client/v2/broadcast/comet/comet.go (1)

Line range hint 75-94: Add nil check for InterfaceRegistry parameter

While there's a nil check for the codec parameter, we should also validate that the ir parameter isn't nil for consistency.

 func NewCometBFTBroadcaster(rpcURL, mode string, cdc codec.Codec, ir types.InterfaceRegistry) (*CometBFTBroadcaster, error) {
 	if cdc == nil {
 		return nil, errors.New("codec can't be nil")
 	}
+	if ir == nil {
+		return nil, errors.New("interface registry can't be nil")
+	}
 
 	if mode == "" {
 		mode = BroadcastSync
client/v2/offchain/verify_test.go (1)

69-69: Consider using a parameter struct for Sign function

While the refactoring successfully removes the client.Context dependency, the Sign function now takes many parameters. Consider introducing a parameter struct to improve readability and maintainability.

Example improvement:

+ type SignParams struct {
+     Data              []byte
+     ClientConn        ClientConnI
+     Keyring          keyring.Keyring
+     Codec            codec.Codec
+     AddressCodec     address.Codec
+     ValidatorCodec   address.Codec
+     Registry         codectypes.InterfaceRegistry
+     SignerName       string
+     DataEncoding     string
+     SignMode         string
+     OutputFormat     string
+ }

- tx, err := Sign([]byte("Hello World!"), mockClientConn{}, autoKeyring, getCodec(), ac, vc, getCodec().InterfaceRegistry(), "signVerify", "no-encoding", "direct", "json")
+ tx, err := Sign(SignParams{
+     Data:          []byte("Hello World!"),
+     ClientConn:    mockClientConn{},
+     Keyring:       autoKeyring,
+     Codec:         getCodec(),
+     AddressCodec:  ac,
+     ValidatorCodec: vc,
+     Registry:      getCodec().InterfaceRegistry(),
+     SignerName:    "signVerify",
+     DataEncoding:  "no-encoding",
+     SignMode:      "direct",
+     OutputFormat:  "json",
+ })

Also applies to: 72-72

client/v2/autocli/common_test.go (1)

108-112: Add documentation and improve flag description

While the implementation is correct, consider:

  1. Adding function documentation to explain its purpose
  2. Providing a more descriptive help text for the home flag, e.g., "The application home directory"
+// addTxAndGlobalFlagsToCmd adds transaction flags and global configuration flags to the provided command
 func addTxAndGlobalFlagsToCmd(cmd *cobra.Command) {
 	f := cmd.Flags()
-	f.String("home", "", "home directory")
+	f.String("home", "", "the application home directory")
 	flags.AddTxFlagsToCmd(cmd)
 }
client/v2/autocli/query.go (2)

Line range hint 137-140: Enhance error message with more context.

Consider improving the error message when invoking the gRPC method by including the method name for better debugging:

-			return err
+			return fmt.Errorf("failed to invoke gRPC method %s: %w", methodName, err)

Line range hint 241-242: Track TODO for SDK dependency removal.

There's a TODO comment about removing the SDK dependency in the encoder function.

Would you like me to create a GitHub issue to track the removal of this SDK dependency? This would help ensure alignment with the ongoing refactoring efforts.

client/v2/autocli/msg_test.go (2)

58-58: Maintain consistent flag ordering across test cases

The ordering of flags is inconsistent across test cases:

  • Some cases have --generate-only before --chain-id
  • Others have --generate-only after --chain-id

This inconsistency makes the tests harder to maintain. Consider standardizing the flag order across all test cases.

Apply this consistent ordering in all test cases:

  1. Output flags (--output)
  2. Transaction flags (--generate-only)
  3. Chain flags (--chain-id)
  4. Authentication flags (--keyring-backend)
- "--generate-only",
  "--output", "json",
+ "--chain-id", fixture.chainID,
+ "--generate-only"
- "--chain-id", fixture.chainID,

Also applies to: 78-78, 99-101, 124-125


Line range hint 1-238: Enhance test coverage for error scenarios

While the test file covers basic functionality and some error cases, it's missing tests for:

  1. Chain ID validation
  2. Keyring backend validation
  3. Error scenarios when chain-id is missing

Consider adding these test cases to ensure robust error handling.

Would you like me to help generate additional test cases for these scenarios?

client/v2/autocli/flag/builder.go (1)

Based on the shell script results, I can now provide a final response as there are several concerning findings regarding the global keybase variable:

Global keybase variable poses thread-safety risks and violates encapsulation

The global keybase variable in client/v2/autocli/flag/builder.go has several issues:

  1. No synchronization mechanisms (mutexes) are in place to protect concurrent access to the global variable
  2. The variable is package-level which violates encapsulation principles
  3. The keyring setup relies on side effects through PreRunE which is error-prone

Recommendations:

  • Move the keybase field into the Builder struct to maintain proper encapsulation
  • Pass the keyring instance through constructor parameters instead of global state
  • Add synchronization if concurrent access is required

Example locations needing changes:

  • client/v2/autocli/flag/builder.go: Move keybase into Builder struct
  • client/v2/tx/factory.go: Already uses proper encapsulation with keybase as struct field
  • client/tx/factory.go: Already uses proper encapsulation with keybase as struct field
🔗 Analysis chain

Line range hint 33-67: Verify keyring usage across the codebase

Let's verify the usage of the keyring functionality and potential race conditions.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for direct usage of the global keybase variable
rg -l "keybase\s*=" --type go

# Check for concurrent access patterns
rg -l "go\s+func|go\s+routine" --type go | xargs rg "keybase"

# Check for PreRunE implementations that might set the keyring
ast-grep --pattern 'PreRunE: func($_, $_) {
  $$$
  SetKeyring($$$)
  $$$
}'

Length of output: 267


Script:

#!/bin/bash
# Check the content of files that use keybase for potential race conditions
rg -A 5 -B 5 "keybase" client/tx/tx.go client/tx/factory.go client/v2/tx/factory.go client/v2/autocli/flag/builder.go

# Check for any mutex or sync primitives around keybase
rg "sync\." client/tx/tx.go client/tx/factory.go client/v2/tx/factory.go client/v2/autocli/flag/builder.go

# Look for root command initialization
rg -A 10 "NewRootCmd|RootCmd" --type go

Length of output: 26956

client/v2/tx/factory.go (1)

95-105: Fix indentation inconsistency in offline mode validation

The indentation of the conditions inside the if offline { block is inconsistent. Some conditions are properly indented while others are not.

Apply this diff to fix the indentation:

  if offline {
-		if !generateOnly && (!flags.Changed(flags2.FlagAccountNumber) || !flags.Changed(flags2.FlagSequence)) {
-			return errors.New("account-number and sequence must be set in offline mode")
-		}
+    if !generateOnly && (!flags.Changed(flags2.FlagAccountNumber) || !flags.Changed(flags2.FlagSequence)) {
+      return errors.New("account-number and sequence must be set in offline mode")
+    }

-		if generateOnly && chainID != "" {
-			return errors.New("chain ID cannot be used when offline and generate-only flags are set")
-		}
+    if generateOnly && chainID != "" {
+      return errors.New("chain ID cannot be used when offline and generate-only flags are set")
+    }
client/v2/offchain/common_test.go (2)

15-15: Ensure the test mnemonic is suitable for public use

The hardcoded mnemonic is present in the test code. Confirm that it is intended for testing purposes and does not contain any sensitive or real user data.


28-33: Consider enhancing mockClientConn methods for comprehensive testing

The Invoke and NewStream methods in mockClientConn return "not implemented" errors. If your tests require simulating gRPC interactions, consider implementing these methods to provide mock responses or behaviors.

client/v2/autocli/config/toml.go (1)

44-51: Eliminate duplicate code by reusing template parsing logic

Both init() and setConfigTemplate() contain similar code for parsing a template. This duplicates logic.

Consider extracting the template parsing code into a helper function to adhere to the DRY (Don't Repeat Yourself) principle.

Also applies to: 53-63

client/v2/offchain/sign.go (1)

36-43: Consider consolidating parameters into a struct to simplify the function signature.

The Sign function has a large number of parameters, which can affect readability and maintainability. According to the Uber Go Style Guide, consider grouping related parameters into a struct.

For example, you could define a SignOptions struct:

type SignOptions struct {
    Conn                  gogogrpc.ClientConn
    Keybase               keyring.Keyring
    Codec                 codec.BinaryCodec
    AddressCodec          address.Codec
    ValidatorAddressCodec address.Codec
    InterfaceRegistry     types.InterfaceRegistry
    FromName              string
    Encoding              string
    SignMode              string
    Output                string
}

Then modify the Sign function:

 func Sign(
+    ctx context.Context,
     rawBytes []byte,
-    conn gogogrpc.ClientConn,
-    keybase keyring.Keyring,
-    cdc codec.BinaryCodec,
-    addressCodec, validatorAddressCodec address.Codec,
-    ir types.InterfaceRegistry,
-    fromName, encoding, signMode, output string,
+    opts SignOptions,
 ) (string, error) {
     // Use opts.Conn, opts.Keybase, etc. within the function
 }

This refactoring enhances readability and allows for easier maintenance and future extensions.

client/v2/autocli/config/config.go (5)

15-23: Avoid aligning struct field tags.

Per the Uber Go Style Guide, aligning struct field tags adds unnecessary diff noise and increases maintenance effort. Removing the extra spaces enhances readability and facilitates future changes.

Apply this diff to adjust the struct tags:

 type Config struct {
-	ChainID               string     `mapstructure:"chain-id" json:"chain-id"`
-	KeyringBackend        string     `mapstructure:"keyring-backend" json:"keyring-backend"`
-	KeyringDefaultKeyName string     `mapstructure:"keyring-default-keyname" json:"keyring-default-keyname"`
-	Output                string     `mapstructure:"output" json:"output"`
-	Node                  string     `mapstructure:"node" json:"node"`
-	BroadcastMode         string     `mapstructure:"broadcast-mode" json:"broadcast-mode"`
+	ChainID string `mapstructure:"chain-id" json:"chain-id"`
+	KeyringBackend string `mapstructure:"keyring-backend" json:"keyring-backend"`
+	KeyringDefaultKeyName string `mapstructure:"keyring-default-keyname" json:"keyring-default-keyname"`
+	Output string `mapstructure:"output" json:"output"`
+	Node string `mapstructure:"node" json:"node"`
+	BroadcastMode string `mapstructure:"broadcast-mode" json:"broadcast-mode"`
 	GRPC GRPCConfig `mapstructure:",squash"`
 }

31-40: Use constants for default values to enhance maintainability.

Defining constants for the default values improves clarity and makes updates easier if the defaults change.

Consider introducing constants:

const (
	defaultKeyringBackend = "os"
	defaultOutput         = "text"
	defaultNode           = "tcp://localhost:26657"
	defaultBroadcastMode  = "sync"
)

func DefaultConfig() *Config {
	return &Config{
		ChainID:               "",
		KeyringBackend:        defaultKeyringBackend,
		KeyringDefaultKeyName: "",
		Output:                defaultOutput,
		Node:                  defaultNode,
		BroadcastMode:         defaultBroadcastMode,
	}
}

42-97: Refactor CreateClientConfig to reduce complexity.

The function exceeds 40 lines and contains deeply nested logic, which can hinder readability and maintainability. Breaking it into smaller helper functions can improve clarity.


56-58: Clarify the mutual dependency between customClientTemplate and customConfig.

The condition checks for one being nil while the other is not, but it might be clearer to explicitly state the expected relationship and validate accordingly.

Consider enhancing the error message for clarity.


112-114: Use a consistent environment variable prefix.

Using the executable name as the environment prefix can lead to inconsistencies if the executable is renamed. It's better to use a fixed prefix to ensure environment variables are correctly recognized.

For example:

v.SetEnvPrefix("APP")
client/v2/autocli/flag/address.go (2)

76-88: Validate Error Handling in the get Method

The get method correctly checks if cachedValue is not empty before attempting to retrieve the key. However, consider the following improvements:

  • Error Wrapping: When returning errors, wrap them with additional context to improve debugging.

  • Thread Safety: If addressValue may be accessed concurrently, consider adding synchronization mechanisms to protect cachedValue.

Apply the following diff to wrap the error with additional context:

 func (a *addressValue) get() (protoreflect.Value, error) {
   if a.cachedValue != "" {
     return protoreflect.ValueOfString(a.cachedValue), nil
   }

   addr, err := getKey(a.value, a.addressCodec)
   if err != nil {
-    return protoreflect.Value{}, err
+    return protoreflect.Value{}, fmt.Errorf("failed to get key for value '%s': %w", a.value, err)
   }
   a.cachedValue = addr

   return protoreflect.ValueOfString(addr), nil
 }

Line range hint 110-137: Inconsistent Receiver Type in consensusAddressValue Methods

The Get method for consensusAddressValue uses a value receiver, while it calls methods with pointer receivers from the embedded addressValue. This may lead to unexpected behavior due to method set differences in Go.

Suggested Fix: Use Pointer Receivers for Consistency

Change the receiver of the Get and String methods to use pointer receivers to ensure consistent behavior and proper access to embedded methods.

Apply the following diff:

-func (a consensusAddressValue) Get(protoreflect.Value) (protoreflect.Value, error) {
+func (a *consensusAddressValue) Get(protoreflect.Value) (protoreflect.Value, error) {

...

-func (a consensusAddressValue) String() string {
+func (a *consensusAddressValue) String() string {

This change ensures that the methods operate on the original consensusAddressValue instance and have access to all methods of the embedded addressValue.

client/v2/offchain/cli.go (3)

65-65: Check for errors when setting flag values.

At line 65, the error returned by cmd.Flags().Set(flags.FlagKeyringBackend, keyringBackend) is ignored. Handling this error ensures that the flag is set successfully and can help catch unexpected issues.

Apply this change:

-	_ = cmd.Flags().Set(flags.FlagKeyringBackend, keyringBackend)
+	if err := cmd.Flags().Set(flags.FlagKeyringBackend, keyringBackend); err != nil {
+		return err
+	}

92-92: Consider refactoring to reduce the number of function parameters.

At line 92, the Sign function is called with numerous parameters, which can decrease readability and maintainability. Consider refactoring the function signature to accept a struct or context containing these parameters.


139-139: Consider refactoring to reduce the number of function parameters.

Similarly, at line 139, the Verify function is called with multiple parameters. Refactoring to use a struct or context can improve code readability and reduce potential errors.

client/v2/broadcast/comet/clientConn.go (2)

32-34: Return a gRPC Unimplemented error in NewStream method

Instead of returning a generic error, consider returning a gRPC Unimplemented status error to provide consistent error handling for gRPC clients.

Apply this diff:

 return nil, errors.New("not implemented")
+// Replace with:
+return nil, status.Error(codes.Unimplemented, "method not implemented")

53-55: Avoid including function names in error messages

Per the Uber Go Style Guide, error messages should not include function names. Remove "client.Context.Invoke:" from the error message.

Apply this diff:

 return errorsmod.Wrapf(
     sdkerrors.ErrInvalidRequest,
-    "client.Context.Invoke: height (%d) from %q must be >= 0", height, grpctypes.GRPCBlockHeightHeader)
+    "height (%d) from %q must be >= 0", height, grpctypes.GRPCBlockHeightHeader)
client/v2/autocli/msg.go (2)

236-239: Update function comment to follow GoDoc conventions

The comment for generateOrBroadcastTxWithV2 should start with the function name and be a complete sentence. According to the Uber Go Style Guide, this enhances readability and generates better documentation.

Apply this change to the comment:

-// generateOrBroadcastTxWithV2 generates or broadcasts a transaction with the provided messages using v2 transaction handling.
+// generateOrBroadcastTxWithV2 generates or broadcasts a transaction with the provided messages using v2 transaction handling.

238-239: Consider deferring unused code until it's needed

Adding a function with //nolint:unused is generally discouraged, as it may introduce clutter and maintenance overhead. It might be better to add this function when it's actively used in BuildMsgMethodCommand.

client/v2/tx/tx.go (1)

Line range hint 232-239: Use provided context ctx instead of context.Background()

At line 239, the Broadcast method is called with context.Background(), which ignores the cancellation and timeout capabilities of the provided ctx context. To ensure proper context propagation and allow callers to control the request lifecycle, use the ctx parameter instead.

Apply this change:

-res, err := broadcaster.Broadcast(context.Background(), txBytes)
+res, err := broadcaster.Broadcast(ctx, txBytes)
client/v2/autocli/common.go (2)

268-307: Refactor repetitive flag-setting logic in setFlagsFromConfig

The setFlagsFromConfig function contains repetitive code blocks for setting various flags. Consider refactoring to reduce code duplication and enhance maintainability.

Apply this refactor to abstract the repetitive logic:

+func setFlagIfNotChanged(cmd *cobra.Command, flagName, value string) {
+    if cmd.Flags().Lookup(flagName) != nil && !cmd.Flags().Changed(flagName) {
+        _ = cmd.Flags().Set(flagName, value)
+    }
+}

 func (b *Builder) setFlagsFromConfig(cmd *cobra.Command, args []string) error {
     conf, err := config.CreateClientConfigFromFlags(cmd.Flags())
     if err != nil {
         return err
     }

-    if cmd.Flags().Lookup("chain-id") != nil && !cmd.Flags().Changed("chain-id") {
-        _ = cmd.Flags().Set("chain-id", conf.ChainID)
-    }
+    setFlagIfNotChanged(cmd, "chain-id", conf.ChainID)

-    if cmd.Flags().Lookup("keyring-backend") != nil && !cmd.Flags().Changed("keyring-backend") {
-        _ = cmd.Flags().Set("keyring-backend", conf.KeyringBackend)
-    }
+    setFlagIfNotChanged(cmd, "keyring-backend", conf.KeyringBackend)

    // Repeat for other flags...

338-342: Handle potential errors when retrieving the node flag

In the block where the default CometBFT broadcaster is used, ensure that the node flag is correctly retrieved and handle any potential errors.

Consider checking if the node flag exists before attempting to retrieve its value to prevent unexpected errors.

if cmd.Flags().Lookup("node") != nil {
    node, err := cmd.Flags().GetString("node")
    if err != nil {
        return nil, err
    }
    return comet.NewCometBFTBroadcaster(node, comet.BroadcastSync, cdc, ir)
} else {
    return nil, fmt.Errorf("node flag not defined")
}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f1bd0d8 and 879db32.

⛔ Files ignored due to path filters (4)
  • x/authz/go.sum is excluded by !**/*.sum
  • x/group/go.sum is excluded by !**/*.sum
  • x/params/go.sum is excluded by !**/*.sum
  • x/upgrade/go.sum is excluded by !**/*.sum
📒 Files selected for processing (33)
  • client/v2/autocli/app.go (4 hunks)
  • client/v2/autocli/builder.go (2 hunks)
  • client/v2/autocli/common.go (3 hunks)
  • client/v2/autocli/common_test.go (2 hunks)
  • client/v2/autocli/config/config.go (1 hunks)
  • client/v2/autocli/config/toml.go (1 hunks)
  • client/v2/autocli/flag/address.go (3 hunks)
  • client/v2/autocli/flag/builder.go (3 hunks)
  • client/v2/autocli/keyring/keyring.go (2 hunks)
  • client/v2/autocli/msg.go (2 hunks)
  • client/v2/autocli/msg_test.go (4 hunks)
  • client/v2/autocli/print/printer.go (1 hunks)
  • client/v2/autocli/query.go (1 hunks)
  • client/v2/autocli/testdata/help-echo-msg.golden (1 hunks)
  • client/v2/broadcast/comet/clientConn.go (1 hunks)
  • client/v2/broadcast/comet/comet.go (3 hunks)
  • client/v2/broadcast/comet/comet_test.go (2 hunks)
  • client/v2/go.mod (3 hunks)
  • client/v2/offchain/cli.go (5 hunks)
  • client/v2/offchain/common_test.go (2 hunks)
  • client/v2/offchain/sign.go (4 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/encoder.go (1 hunks)
  • client/v2/tx/factory.go (1 hunks)
  • client/v2/tx/tx.go (7 hunks)
  • client/v2/tx/types.go (1 hunks)
  • simapp/simd/cmd/root.go (1 hunks)
  • x/authz/go.mod (1 hunks)
  • x/group/go.mod (1 hunks)
  • x/params/go.mod (1 hunks)
  • x/upgrade/go.mod (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • client/v2/go.mod
  • x/authz/go.mod
  • x/group/go.mod
🧰 Additional context used
📓 Path-based instructions (27)
client/v2/autocli/app.go (1)

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

client/v2/autocli/builder.go (1)

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

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

client/v2/autocli/config/config.go (1)

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

client/v2/autocli/config/toml.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/flag/builder.go (1)

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

client/v2/autocli/keyring/keyring.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/autocli/msg_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"

client/v2/autocli/print/printer.go (1)

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

client/v2/autocli/query.go (1)

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

client/v2/broadcast/comet/clientConn.go (1)

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

client/v2/broadcast/comet/comet.go (1)

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

client/v2/broadcast/comet/comet_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"

client/v2/offchain/cli.go (1)

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

client/v2/offchain/common_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"

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

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/offchain/verify_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"

client/v2/tx/encoder.go (1)

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

client/v2/tx/factory.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.

client/v2/tx/types.go (1)

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

simapp/simd/cmd/root.go (1)

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

🔇 Additional comments (40)
client/v2/autocli/builder.go (2)

7-10: LGTM: Import changes are appropriate

The new imports are correctly organized and necessary for the new functionality being added.


26-27: Verify migration path for breaking changes

The addition of required fields Cdc and EnablesSignModes constitutes a breaking change.

Let's check for existing usages that need to be updated:

✅ Verification successful

Based on the search results, I can now provide a final response:

Breaking changes have proper migration examples

The breaking changes are well-documented in the codebase with proper examples:

  • The main instantiation in app.go shows the correct way to initialize the Builder with the new required fields
  • Test files demonstrate both minimal (Builder{}) and full initialization patterns
  • The primary implementation in app.go (lines 70-86) serves as a complete reference for migration, showing how to properly set both Cdc and EnablesSignModes
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing Builder instantiations that need to be updated
ast-grep --pattern 'Builder{$$$}'

# Search for any existing tests that might need updates
rg -l "Builder" -t go | xargs rg "func.*Test.*Builder"

Length of output: 4934

client/v2/offchain/sign_test.go (1)

20-22: LGTM! Proper initialization and error handling.

The AutoCLIKeyring initialization is well-structured with appropriate error handling.

client/v2/autocli/print/printer.go (2)

35-38: LGTM!

The method is simple, focused, and correctly delegates to PrintBytes.


40-43: LGTM!

The method is simple, focused, and correctly delegates to PrintBytes.

client/v2/autocli/keyring/keyring.go (2)

5-15: LGTM! Well-organized imports.

The imports are properly organized following Go conventions with standard library imports first, followed by third-party imports, and internal imports last.


55-55: Verify KeyringServiceName usage.

The function uses sdk.KeyringServiceName(). Let's verify if this is still the recommended approach or if there's a newer alternative.

✅ Verification successful

sdk.KeyringServiceName() usage is consistent and current

Based on the verification results:

  • KeyringServiceName() is actively used across the codebase in all keyring initializations
  • It's not marked as deprecated
  • The implementation in types/config.go shows it's a supported function that returns either a default value ("cosmos") or the version name
  • All keyring initializations consistently use this pattern: keyring.New(sdk.KeyringServiceName(), ...)
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if KeyringServiceName is marked as deprecated or if there are newer alternatives
rg -A 3 "KeyringServiceName" --type go

# Look for other instances of keyring initialization for consistency
ast-grep --pattern 'keyring.New($$$)'

Length of output: 7162

client/v2/broadcast/comet/comet_test.go (2)

25-25: LGTM: Codec type generalization

The change from codec.JSONCodec to codec.Codec provides better flexibility while maintaining type safety.


48-48: LGTM: Updated constructor call

The addition of interface registry parameter aligns with the removal of client.Context and maintains test coverage for the updated initialization flow.

client/v2/tx/encoder.go (1)

22-25: LGTM! Verify impact on API consumers.

The addition of EmitUnpopulated: true to include zero-valued fields in JSON output is correct for ensuring consistent transaction serialization.

Let's verify the impact on transaction encoding:

✅ Verification successful

Setting EmitUnpopulated: true is safe and consistent with existing usage

The change to include zero-valued fields in JSON output is verified to be safe because:

  1. The jsonMarshalOptions is only used in two places:

    • encodeJsonTx in encoder.go for transaction JSON encoding
    • MarshalSignatureJSON in config.go for signature descriptor encoding
  2. The change maintains consistency with existing JSON handling:

    • The decoder already accepts both populated and unpopulated fields
    • Existing tests verify JSON marshaling/unmarshaling roundtrips
    • No breaking changes to API consumers as this only adds more fields
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential breaking changes in transaction encoding
# Look for direct uses of jsonMarshalOptions in the codebase and tests that might need updates

# Find all Go files that might be affected by the JSON marshaling change
rg -l "jsonMarshalOptions" 

# Look for any tests that verify JSON transaction encoding
rg -A 5 "TestEncode.*Json.*Tx"

Length of output: 177


Script:

#!/bin/bash
# Let's analyze the usage of jsonMarshalOptions across the codebase

# Check the content of files using jsonMarshalOptions
echo "=== client/v2/tx/encoder.go ==="
cat client/v2/tx/encoder.go

echo -e "\n=== client/v2/tx/config.go ==="
cat client/v2/tx/config.go

echo -e "\n=== client/v2/autocli/flag/json_message.go ==="
cat client/v2/autocli/flag/json_message.go

# Look for existing JSON encoding tests
rg -A 10 "func.*Test.*JSON" client/v2/tx/

Length of output: 18929

simapp/simd/cmd/root.go (1)

124-128: LGTM! Field assignments align with the client.Context removal objective.

The changes correctly transfer the necessary fields from initClientCtx to autoCliOpts, maintaining proper type safety and ensuring all required context information is preserved after the removal of client.Context.

Let's verify that these are all the required fields that need to be transferred:

✅ Verification successful

Let me gather more information about the autoCliOpts usage to ensure we haven't missed any fields.


Let me check one more thing to verify the complete structure of AutoCLI options.


Field assignments from client.Context to autoCliOpts are complete and correct

The verification confirms that all necessary fields from client.Context have been properly transferred to autoCliOpts. The five fields being assigned:

  • InterfaceRegistry
  • AddressCodec
  • ValidatorAddressCodec
  • ConsensusAddressCodec
  • Codec (Cdc)

are the complete set of required fields needed for AutoCLI functionality, as evidenced by the codebase analysis. No additional fields need to be transferred.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if there are any other fields from client.Context that might need to be transferred
# by examining the usage of these fields in the autocli package

# Search for any remaining references to client.Context in the autocli package
rg -g '*.go' -B 3 -A 3 'client\.Context' 'client/v2/autocli'

# Search for field accesses on autoCliOpts to ensure we haven't missed any
ast-grep --pattern 'autoCliOpts.$_'

Length of output: 1443


Script:

#!/bin/bash
# Search for the definition and usage of autoCliOpts type
rg -g '*.go' -B 3 -A 3 'type.*AutoCLI.*Options'

# Search for any field assignments to autoCliOpts in the codebase
rg -g '*.go' -B 2 -A 2 'autoCliOpts\.' 

Length of output: 2377


Script:

#!/bin/bash
# Search for the AutoCLI options struct definition
rg -g '*.go' -B 5 -A 10 'type.*AppOptions.*struct'

# Also check for any Builder struct definition as it might contain required fields
rg -g '*.go' -B 5 -A 10 'type.*Builder.*struct'

Length of output: 23154

client/v2/broadcast/comet/comet.go (1)

70-71: Verify codec type change compatibility

The change from codec.JSONCodec to codec.Codec makes the type more generic. Let's verify this doesn't break existing callers.

✅ Verification successful

Let me analyze the findings from the search results to verify the codec type change compatibility.


Codec type change is safe and properly implemented

The change from codec.JSONCodec to codec.Codec is well-handled:

  • The code checks for codec capabilities via type assertion to GRPCCodecProvider
  • Falls back to ProtoCodec when needed using the new ir field
  • All callers (client/v2/offchain/cli.go, client/v2/tx/tx.go, client/v2/autocli/common.go) have been updated to pass both cdc and ir parameters
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for existing usages of CometBFTBroadcaster to ensure compatibility
rg -A 3 "NewCometBFTBroadcaster|CometBFTBroadcaster" --type go

Length of output: 5687


Script:

#!/bin/bash
# Let's check how the codec is being used within the CometBFTBroadcaster
ast-grep --pattern 'func ($_ *CometBFTBroadcaster) $$$'

Length of output: 57


Script:

#!/bin/bash
# Let's check how the codec is being used within the CometBFTBroadcaster methods
rg -A 5 "func \(c \*CometBFTBroadcaster\)" --type go

Length of output: 3428

client/v2/offchain/verify_test.go (3)

48-48: LGTM: Clean refactor of Verify function call

The updated function call correctly passes the required parameters directly instead of through a context object, maintaining the same functionality while reducing coupling.


59-61: LGTM: Clear initialization of address codecs

The address codec initialization is clean and follows standard Cosmos SDK conventions for address prefixes.


66-67: LGTM: Proper setup of auto keyring with error handling

The auto keyring initialization is well-structured with appropriate error handling.

client/v2/autocli/common_test.go (4)

35-38: LGTM: Good refactoring of fixture struct

The addition of explicit fields instead of accessing them through clientCtx improves clarity and aligns with the PR objective of removing client.Context dependencies.


101-104: LGTM: Consistent initialization of new fixture fields

The initialization values match those previously set in clientCtx, maintaining the same test environment.


92-93: LGTM: Appropriate Builder initialization changes

The changes to use addTxAndGlobalFlagsToCmd and initialize the Cdc field are consistent with the refactoring approach.


108-112: Add test coverage for new function

The new addTxAndGlobalFlagsToCmd function lacks direct test coverage. Consider adding tests to verify:

  1. The home flag is properly added
  2. The transaction flags are properly added
  3. The flags have correct default values
client/v2/autocli/query.go (1)

Line range hint 132-136: LGTM! Change aligns with PR objectives.

The direct use of b.GetClientConn(cmd) is a clean improvement that:

  • Simplifies the code by removing an unnecessary intermediate variable
  • Aligns with the PR objective of removing client.Context
  • Maintains proper error handling
client/v2/tx/types.go (2)

Line range hint 165-172: LGTM: Address resolution logic is sound

The updated condition properly handles address resolution for both dry-run and generate-only scenarios, while maintaining the existing keyring-based resolution for normal operation. The error handling is comprehensive and the change aligns well with the PR objective of removing client.Context.


164-165: Verify flag constant definition

The flagGenerateOnly constant is used but not visible in the provided code. Please ensure it's properly defined in the constants section of this file or imported from the correct package.

✅ Verification successful

The flagGenerateOnly constant is properly defined

The constant flagGenerateOnly is correctly defined in client/v2/tx/flags.go with the value "generate-only". The usage in types.go is valid.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for flagGenerateOnly constant definition
rg -l "flagGenerateOnly.*=.*" --type go

# Search for any potential imports that might define this constant
rg -l "^import.*flag" --type go

Length of output: 97


Script:

#!/bin/bash
# Let's check the content of flags.go to verify the constant definition
cat client/v2/tx/flags.go

Length of output: 1445

client/v2/autocli/msg_test.go (1)

Line range hint 21-28: Remove usage of client.Context to align with PR objectives

The buildModuleMsgCommand function still uses client.Context through the client.ClientContextKey, which contradicts the PR's objective of removing client.Context. This should be refactored to use the new approach without client.Context.

Let's verify other usages of client.Context in the codebase:

x/upgrade/go.mod (1)

43-43: Verify stability of pre-release dependency versions

The indirect dependencies have been updated to development snapshots:

  • cosmossdk.io/collectionsv0.4.1-0.20241104084251-838f1557af0a
  • cosmossdk.io/schemav0.3.1-0.20241010135032-192601639cac

Let's verify the stability and compatibility of these versions:

Also applies to: 45-45

✅ Verification successful

Let me try a different approach to verify these dependencies.


Pre-release dependency versions are consistently used across modules

The verification shows that these specific pre-release versions are used consistently across multiple modules in the codebase:

  • cosmossdk.io/collections v0.4.1-0.20241104084251-838f1557af0a is used in x/upgrade, x/group, x/params, x/authz, simapp, and other modules
  • cosmossdk.io/schema v0.3.1-0.20241010135032-192601639cac follows the same pattern

Both dependencies are properly integrated into the codebase with numerous direct imports and consistent usage patterns, indicating coordinated updates across modules.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any reported issues or breaking changes in the updated dependencies

# Check git history for breaking changes
echo "Checking collections module commits..."
gh api repos/cosmos/cosmos-sdk/commits \
  --jq '.[] | select(.commit.message | contains("collections")) | {sha: .sha, message: .commit.message}' \
  -H "Accept: application/vnd.github.v3+json"

echo "Checking schema module commits..."
gh api repos/cosmos/cosmos-sdk/commits \
  --jq '.[] | select(.commit.message | contains("schema")) | {sha: .sha, message: .commit.message}' \
  -H "Accept: application/vnd.github.v3+json"

# Check for open issues related to these modules
echo "Checking for related open issues..."
gh api search/issues \
  -X GET \
  -f q='repo:cosmos/cosmos-sdk is:issue is:open label:bug (collections OR schema)' \
  --jq '.items[] | {title: .title, url: .html_url}'

Length of output: 776


Script:

#!/bin/bash
# Check go.mod files across the repository for these specific versions
echo "Checking usage of collections version..."
rg "cosmossdk.io/collections v0.4.1-0.20241104084251-838f1557af0a" -A 2 -B 2

echo "Checking usage of schema version..."
rg "cosmossdk.io/schema v0.3.1-0.20241010135032-192601639cac" -A 2 -B 2

# Check for any direct imports of these packages
echo "Checking direct imports..."
rg "\"cosmossdk.io/collections\"" --type go
rg "\"cosmossdk.io/schema\"" --type go

# Check if these are consistent versions across modules
echo "Checking other versions of collections and schema..."
rg "cosmossdk.io/collections v\d" --type mod
rg "cosmossdk.io/schema v\d" --type mod

Length of output: 28460

client/v2/autocli/flag/builder.go (1)

19-19: LGTM: Import follows Go conventions

The new import for the keyring package follows the standard Go import grouping conventions.

client/v2/tx/factory.go (2)

90-93: LGTM: Proper validation for dry-run mode

The added check prevents using offline mode with dry-run, which is a logical constraint since dry-run requires network access.


111-111: LGTM: Proper chainID validation

The added condition ensures that chainID is required for online transactions, which is a necessary validation.

client/v2/offchain/common_test.go (2)

5-7: Approved addition of necessary imports

The imports of errors and gogogrpc are appropriate and necessary for the implementation of mockClientConn.


24-26: mockClientConn correctly implements gogogrpc.ClientConn interface

The declaration of mockClientConn and the interface assertion ensure compliance with the gogogrpc.ClientConn interface.

client/v2/autocli/flag/address.go (3)

45-48: Ensure Consistent Use of Pointer Receivers in Methods

The Get method for addressValue has been changed to use a pointer receiver, which is appropriate since it accesses the receiver's fields and may modify them. This is a good practice to avoid unnecessary copying of the struct.


72-74: Pointer Receiver Recommended for isEmpty Method

The isEmpty method currently has a pointer receiver, which is consistent with other methods that operate on addressValue. This ensures that any future modifications within the method will affect the original receiver.


154-171: Check for Potential Nil Pointer Dereference in getKey Function

The getKey function checks if keybase is not nil before using it. Ensure that keybase is properly initialized in all contexts where getKey might be called to prevent nil pointer dereference.

Run the following script to search for all initializations of keybase:

This script will help identify where keybase is declared and initialized to ensure that it is not nil when getKey is invoked.

✅ Verification successful

Let me gather more context about the initialization of keybase in the builder.


Let me check how the SetKeyring method is used and where getKey is called.


Nil Check in getKey is Properly Implemented

The code is correctly handling the potential nil case for keybase. The investigation shows:

  • keybase is a global variable initialized through Builder.SetKeyring
  • SetKeyring is called in PreRunE of the root command, ensuring initialization before CLI execution
  • getKey has a proper nil check before using keybase
  • If keybase is nil, the function falls back to treating the input as a direct address string

The current implementation follows a safe pattern where:

  1. The nil check guards the keyring lookup attempt
  2. If keyring is not available (nil), it validates and returns the raw input
  3. No nil pointer dereference is possible with this implementation
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that `keybase` is properly initialized.

# Search for declarations of `keybase` in the codebase.
rg -A 2 'var keybase'

# Search for initializations of `keybase`.
rg 'keybase\s*='

Length of output: 425


Script:

#!/bin/bash
# Check the initialization context in builder.go
rg -B 5 -A 5 'keybase = k' client/v2/autocli/flag/builder.go

# Check where and how the builder is used
ast-grep --pattern 'func $_($_, keyring.Keyring, $_) {
  $$$
}'

Length of output: 466


Script:

#!/bin/bash
# Find where SetKeyring is called
rg "SetKeyring\(" -B 2 -A 2

# Find where getKey is used
rg "getKey\(" -B 2 -A 2

# Check the Builder usage pattern
ast-grep --pattern 'NewBuilder($$$)'

Length of output: 1293

client/v2/autocli/app.go (4)

43-49: Addition of new fields enhances modularity

The introduction of InterfaceRegistry, AddressCodec, ValidatorAddressCodec, ConsensusAddressCodec, Cdc, and TxConfigOpts in the AppOptions struct improves modularity and separation of concerns within the application. This change facilitates better management of interfaces and codecs.


73-78: Builder initialization correctly leverages new 'AppOptions' fields

The updated initialization of the Builder struct now utilizes the newly added fields from AppOptions, aligning with the refactored design. This enhances clarity and maintainability by explicitly passing required dependencies.


83-85: Proper configuration of 'Builder' fields

The addition of AddTxConnFlags, Cdc, and EnablesSignModes to the Builder struct is correctly implemented. This ensures that transaction flags and signing modes are appropriately configured for the CLI commands.


179-182: Correct initialization of 'AppOptions' in 'NewAppOptionsFromConfig'

The AppOptions struct is properly initialized with the new fields, including Modules, InterfaceRegistry, ModuleOptions, and skipValidation. This setup ensures that the application options are accurately configured for further processing.

client/v2/autocli/msg.go (1)

240-255: Function generateOrBroadcastTxWithV2 implementation looks good

The function is well-structured, with proper error handling and resource initialization. It's ready for integration once BuildMsgMethodCommand is updated to use factory v2.

client/v2/autocli/common.go (3)

73-73: Confirm PreRunE assignment does not override existing configurations

Assigning cmd.PreRunE = b.preRunE() replaces any existing PreRunE functions previously set on the command. Ensure that this assignment does not unintentionally override other pre-run configurations or behaviors that may be necessary for the command's execution.

Would you like to verify if any existing PreRunE functions are being overridden?


241-246: Error handling and output formatting are correctly implemented

The refactored outOrStdoutFormat function correctly initializes the printer and handles potential errors from print.NewPrinter(cmd). The output is appropriately printed using p.PrintBytes(out).


248-266: Pre-run setup in preRunE is effective and error handling is appropriate

The new preRunE method effectively sets command flags from the configuration and initializes the keyring when required. Error handling is properly managed throughout the function.

Comment on lines +23 to +33
// NewPrinter creates a new Printer instance with default stdout
func NewPrinter(cmd *cobra.Command) (*Printer, error) {
outputFormat, err := cmd.Flags().GetString("output")
if err != nil {
return nil, err
}
return &Printer{
Output: cmd.OutOrStdout(),
OutputFormat: outputFormat,
}, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add output format validation.

The constructor should validate that the output format is one of the supported values.

 func NewPrinter(cmd *cobra.Command) (*Printer, error) {
 	outputFormat, err := cmd.Flags().GetString("output")
 	if err != nil {
 		return nil, err
 	}
+	if outputFormat != "" && outputFormat != jsonOutput && outputFormat != textOutput {
+		return nil, fmt.Errorf("unsupported output format %q, supported formats are: %s, %s", 
+			outputFormat, jsonOutput, textOutput)
+	}
 	return &Printer{
 		Output:       cmd.OutOrStdout(),
 		OutputFormat: outputFormat,
 	}, nil
 }

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +45 to +73
// PrintBytes prints and formats bytes
func (p *Printer) PrintBytes(out []byte) error {
var err error
if p.OutputFormat == textOutput {
out, err = yaml.JSONToYAML(out)
if err != nil {
return err
}
}

writer := p.Output
if writer == nil {
writer = os.Stdout
}

_, err = writer.Write(out)
if err != nil {
return err
}

if p.OutputFormat != textOutput {
_, err = writer.Write([]byte("\n"))
if err != nil {
return err
}
}

return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve error handling and input validation.

The method could benefit from several improvements:

  1. Validate JSON input when converting to YAML
  2. Consolidate error handling
  3. Consider using a buffer for atomic writes
 func (p *Printer) PrintBytes(out []byte) error {
-	var err error
+	// Validate JSON if converting to YAML
 	if p.OutputFormat == textOutput {
+		if !json.Valid(out) {
+			return fmt.Errorf("invalid JSON input")
+		}
 		out, err = yaml.JSONToYAML(out)
 		if err != nil {
 			return err
 		}
 	}

 	writer := p.Output
 	if writer == nil {
 		writer = os.Stdout
 	}

+	// Use buffer for atomic write
+	var buf bytes.Buffer
+	buf.Write(out)
+	if p.OutputFormat != textOutput {
+		buf.WriteByte('\n')
+	}
+
+	// Single write operation
+	_, err := writer.Write(buf.Bytes())
+	return err
-	_, err = writer.Write(out)
-	if err != nil {
-		return err
-	}
-
-	if p.OutputFormat != textOutput {
-		_, err = writer.Write([]byte("\n"))
-		if err != nil {
-			return err
-		}
-	}
-
-	return nil
 }

Committable suggestion skipped: line range outside the PR's diff.

@@ -161,7 +161,8 @@ func txParamsFromFlagSet(flags *pflag.FlagSet, keybase keyring2.Keyring, ac addr
var fromName, fromAddress string
var addr []byte
isDryRun, _ := flags.GetBool(flagDryRun)
if isDryRun {
generaOnly, _ := flags.GetBool(flagGenerateOnly)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix typo in variable name

The variable name generaOnly contains a typo and should be generateOnly to maintain code clarity and consistency.

Apply this diff to fix the typo:

-generaOnly, _ := flags.GetBool(flagGenerateOnly)
+generateOnly, _ := flags.GetBool(flagGenerateOnly)
📝 Committable suggestion

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

Suggested change
generaOnly, _ := flags.GetBool(flagGenerateOnly)
generateOnly, _ := flags.GetBool(flagGenerateOnly)

Comment on lines +31 to +32
cosmossdk.io/collections v0.4.1-0.20241104084251-838f1557af0a // indirect
cosmossdk.io/schema v0.3.1-0.20241010135032-192601639cac // indirect
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Version inconsistency detected across the codebase

The dependency updates in x/params/go.mod are part of a broader inconsistency in the codebase:

  • collections: Mixed usage of v0.4.0 (stable) and v0.4.1-0.20241104084251-838f1557af0a (pre-release)
  • schema: Multiple versions in use:
    • v0.3.0 (stable)
    • v0.3.1-0.20240930054013-7c6e0388a3f9 (pre-release)
    • v0.3.1-0.20241010135032-192601639cac (pre-release)

The commit messages reveal that these updates are not related to breaking changes:

  • collections update: Documentation changes only (Twitter to X links)
  • schema update: Minor configuration naming change

Please align all module dependencies to use consistent versions:

  • Either keep all modules on stable versions (v0.4.0 for collections, v0.3.0 for schema)
  • Or update all modules to use the same pre-release versions
🔗 Analysis chain

Verify compatibility of pre-release dependency versions

The update to pre-release versions of indirect dependencies requires verification:

  • collections is moving from a stable v0.4.0 to a pre-release version
  • Both dependencies are using specific commit hashes rather than release tags

Let me gather more information about the specific versions being used across the codebase.

This will help us verify if the versions are consistent across the codebase and if there are any potential version conflicts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify dependency version consistency across the codebase and check for any breaking changes

# Check if these exact versions are used consistently across all go.mod files
echo "Checking version consistency across go.mod files..."
fd -e mod -x grep -l "cosmossdk.io/collections" {}
fd -e mod -x grep -l "cosmossdk.io/schema" {}

# Get the commit messages for these specific versions to understand the changes
echo "Fetching commit details for collections..."
gh api repos/cosmos/cosmos-sdk/commits/838f1557af0a --jq '.commit.message'

echo "Fetching commit details for schema..."
gh api repos/cosmos/cosmos-sdk/commits/192601639cac --jq '.commit.message'

Length of output: 2265


Script:

#!/bin/bash
# Check the exact versions of these dependencies in other go.mod files
echo "Checking collections versions:"
fd -e mod -x grep "cosmossdk.io/collections" {}

echo -e "\nChecking schema versions:"
fd -e mod -x grep "cosmossdk.io/schema" {}

Length of output: 5401

Comment on lines +63 to +67
// SetKeyring sets the global keyring instance used for key management and signing operations.
// The keyring must be set in PreRunE of the root command.
func (b *Builder) SetKeyring(k keyring.Keyring) {
keybase = k
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation and thread safety to SetKeyring

The current implementation lacks validation and thread safety. Consider:

  1. Adding nil checks
  2. Adding thread safety mechanisms
  3. Adding cleanup functionality

Example refactor:

func (b *Builder) SetKeyring(k keyring.Keyring) error {
+    if k == nil {
+        return errors.New("keyring cannot be nil")
+    }
-    keybase = k
+    b.keybase = k
+    return nil
}

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +67 to +77
func GenerateOrBroadcastTxCLI(
ctx context.Context,
flagSet *pflag.FlagSet,
printer *print.Printer,
keybase keyring.Keyring,
cdc codec.Codec,
addressCodec, validatorCodec address.Codec,
enablesSignModes []apitxsigning.SignMode,
conn grpc.ClientConn,
msgs ...transaction.Msg,
) error {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor GenerateOrBroadcastTxCLI to reduce the number of parameters

The GenerateOrBroadcastTxCLI function has 10 parameters, exceeding the recommended limit. Grouping related parameters into a struct can enhance readability and maintainability.

Apply this refactor to group parameters:

// Reuse the TxParams struct defined earlier

// Update the function signature
-func GenerateOrBroadcastTxCLI(
-    ctx context.Context,
-    flagSet *pflag.FlagSet,
-    printer *print.Printer,
-    keybase keyring.Keyring,
-    cdc codec.Codec,
-    addressCodec, validatorCodec address.Codec,
-    enablesSignModes []apitxsigning.SignMode,
-    conn grpc.ClientConn,
-    msgs ...transaction.Msg,
-) error {
+func GenerateOrBroadcastTxCLI(
+    ctx context.Context,
+    flagSet *pflag.FlagSet,
+    txParams TxParams,
+    msgs ...transaction.Msg,
+) error {

Comment on lines +96 to +103
func newFactory(
keybase keyring.Keyring,
cdc codec.Codec,
addressCodec, validatorCodec address.Codec,
enablesSignModes []apitxsigning.SignMode,
conn grpc.ClientConn,
flagSet *pflag.FlagSet,
) (Factory, error) {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor newFactory function parameters for better clarity

The function newFactory currently accepts 8 parameters, which can hinder readability. Grouping related parameters into a struct can simplify the function signature and improve code maintainability.

Apply this refactor:

// Define a struct for factory parameters
type FactoryParams struct {
    Keybase           keyring.Keyring
    Codec             codec.Codec
    AddressCodec      address.Codec
    ValidatorCodec    address.Codec
    EnabledSignModes  []apitxsigning.SignMode
    Conn              grpc.ClientConn
}

// Update the function signature
-func newFactory(
-    keybase keyring.Keyring,
-    cdc codec.Codec,
-    addressCodec, validatorCodec address.Codec,
-    enablesSignModes []apitxsigning.SignMode,
-    conn grpc.ClientConn,
-    flagSet *pflag.FlagSet,
-) (Factory, error) {
+func newFactory(
+    params FactoryParams,
+    flagSet *pflag.FlagSet,
+) (Factory, error) {

keybase keyring.Keyring,
cdc codec.Codec,
addressCodec, validatorCodec address.Codec,
enablesSignModes []apitxsigning.SignMode,
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Rename enablesSignModes to enabledSignModes for grammatical accuracy

The parameter name enablesSignModes is grammatically incorrect. Renaming it to enabledSignModes improves clarity and maintains consistency across the codebase.

Apply this change:

- enablesSignModes []apitxsigning.SignMode,
+ enabledSignModes []apitxsigning.SignMode,

Ensure that all occurrences of enablesSignModes are updated to enabledSignModes throughout the code.

Also applies to: 74-74, 100-100, 171-171

Comment on lines +325 to +326
creds = credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12})
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Set explicit server name in TLS configuration

When creating TLS credentials with credentials.NewTLS, the ServerName field in tls.Config is not set, which might cause hostname verification to be skipped. This can reduce the security of the TLS connection.

Modify the TLS configuration to include the server name derived from the address:

 if !insecure {
-    creds = credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12})
+    tlsConfig := &tls.Config{
+        MinVersion: tls.VersionTLS12,
+        ServerName: extractHostname(addr),
+    }
+    creds = credentials.NewTLS(tlsConfig)
 }

Implement a helper function extractHostname to parse and return the hostname from the addr variable.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +309 to +347
// getQueryClientConn returns a function that creates a gRPC client connection based on command flags.
// It handles the creation of secure or insecure connections and falls back to a CometBFT broadcaster
// if no gRPC address is specified.
func getQueryClientConn(cdc codec.Codec, ir types.InterfaceRegistry) func(cmd *cobra.Command) (grpc.ClientConnInterface, error) {
return func(cmd *cobra.Command) (grpc.ClientConnInterface, error) {
var err error
creds := grpcinsecure.NewCredentials()

insecure := true
if cmd.Flags().Lookup("grpc-insecure") != nil {
insecure, err = cmd.Flags().GetBool("grpc-insecure")
if err != nil {
return nil, err
}
}
if !insecure {
creds = credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12})
}

var addr string
if cmd.Flags().Lookup("grpc-addr") != nil {
addr, err = cmd.Flags().GetString("grpc-addr")
if err != nil {
return nil, err
}
}
if addr == "" {
// if grpc-addr has not been set, use the default clientConn
// TODO: default is comet
node, err := cmd.Flags().GetString("node")
if err != nil {
return nil, err
}
return comet.NewCometBFTBroadcaster(node, comet.BroadcastSync, cdc, ir)
}

return grpc.NewClient(addr, []grpc.DialOption{grpc.WithTransportCredentials(creds)}...)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Defaulting to insecure gRPC connections may pose security risks

In the getQueryClientConn function, the insecure variable is initialized to true, which could default to establishing insecure gRPC connections if the grpc-insecure flag is not explicitly set by the user. This may inadvertently expose the connection to man-in-the-middle attacks or other vulnerabilities.

Recommend changing the default value of insecure to false to prioritize secure connections by default. Apply this diff to implement the change:

 func getQueryClientConn(cdc codec.Codec, ir types.InterfaceRegistry) func(cmd *cobra.Command) (grpc.ClientConnInterface, error) {
     return func(cmd *cobra.Command) (grpc.ClientConnInterface, error) {
         var err error
-        creds := grpcinsecure.NewCredentials()

-        insecure := true
+        insecure := false
+        creds := credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12})

         if cmd.Flags().Lookup("grpc-insecure") != nil {
             insecure, err = cmd.Flags().GetBool("grpc-insecure")
             if err != nil {
                 return nil, err
             }
         }
         if insecure {
             creds = grpcinsecure.NewCredentials()
         }

This ensures that the application defaults to secure gRPC connections, enhancing security. Users can still opt-in to insecure connections by explicitly setting the --grpc-insecure flag.

📝 Committable suggestion

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

Suggested change
// getQueryClientConn returns a function that creates a gRPC client connection based on command flags.
// It handles the creation of secure or insecure connections and falls back to a CometBFT broadcaster
// if no gRPC address is specified.
func getQueryClientConn(cdc codec.Codec, ir types.InterfaceRegistry) func(cmd *cobra.Command) (grpc.ClientConnInterface, error) {
return func(cmd *cobra.Command) (grpc.ClientConnInterface, error) {
var err error
creds := grpcinsecure.NewCredentials()
insecure := true
if cmd.Flags().Lookup("grpc-insecure") != nil {
insecure, err = cmd.Flags().GetBool("grpc-insecure")
if err != nil {
return nil, err
}
}
if !insecure {
creds = credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12})
}
var addr string
if cmd.Flags().Lookup("grpc-addr") != nil {
addr, err = cmd.Flags().GetString("grpc-addr")
if err != nil {
return nil, err
}
}
if addr == "" {
// if grpc-addr has not been set, use the default clientConn
// TODO: default is comet
node, err := cmd.Flags().GetString("node")
if err != nil {
return nil, err
}
return comet.NewCometBFTBroadcaster(node, comet.BroadcastSync, cdc, ir)
}
return grpc.NewClient(addr, []grpc.DialOption{grpc.WithTransportCredentials(creds)}...)
}
}
// getQueryClientConn returns a function that creates a gRPC client connection based on command flags.
// It handles the creation of secure or insecure connections and falls back to a CometBFT broadcaster
// if no gRPC address is specified.
func getQueryClientConn(cdc codec.Codec, ir types.InterfaceRegistry) func(cmd *cobra.Command) (grpc.ClientConnInterface, error) {
return func(cmd *cobra.Command) (grpc.ClientConnInterface, error) {
var err error
insecure := false
creds := credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12})
if cmd.Flags().Lookup("grpc-insecure") != nil {
insecure, err = cmd.Flags().GetBool("grpc-insecure")
if err != nil {
return nil, err
}
}
if insecure {
creds = grpcinsecure.NewCredentials()
}
var addr string
if cmd.Flags().Lookup("grpc-addr") != nil {
addr, err = cmd.Flags().GetString("grpc-addr")
if err != nil {
return nil, err
}
}
if addr == "" {
// if grpc-addr has not been set, use the default clientConn
// TODO: default is comet
node, err := cmd.Flags().GetString("node")
if err != nil {
return nil, err
}
return comet.NewCometBFTBroadcaster(node, comet.BroadcastSync, cdc, ir)
}
return grpc.NewClient(addr, []grpc.DialOption{grpc.WithTransportCredentials(creds)}...)
}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants