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

chore: move generic txdecoder #22653

Merged
merged 2 commits into from
Nov 26, 2024
Merged

chore: move generic txdecoder #22653

merged 2 commits into from
Nov 26, 2024

Conversation

tac0turtle
Copy link
Member

@tac0turtle tac0turtle commented Nov 26, 2024

Description

Closes: #XXXX

move default tx decoder to client/tx_config.go


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

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

Reviewers Checklist

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

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

I have...

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

Summary by CodeRabbit

  • New Features
    • Introduced a new generic transaction decoder for enhanced type safety during transaction decoding.
  • Bug Fixes
    • Streamlined transaction decoding by removing outdated structures, ensuring more reliable functionality.
  • Refactor
    • Simplified command initialization by leveraging the new default transaction decoder, enhancing code maintainability.

Copy link
Contributor

coderabbitai bot commented Nov 26, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve significant modifications to transaction decoding mechanisms within the codebase. A new generic transaction decoder type, DefaultTxDecoder[T], is introduced in client/tx_config.go, which implements the transaction.Codec interface. This replaces the previous genericTxDecoder in simapp/v2/simdv2/cmd/commands.go, streamlining transaction decoding by utilizing the new decoder. The changes enhance type safety and simplify the overall structure of transaction handling in the application.

Changes

File Change Summary
client/tx_config.go Added DefaultTxDecoder[T] type, methods Decode and DecodeJSON, and variable for type assertion.
simapp/v2/simdv2/cmd/commands.go Removed genericTxDecoder type and its methods, updated imports, and streamlined transaction decoding logic.

Possibly related PRs

Suggested reviewers

  • 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: 2

🧹 Outside diff range and nitpick comments (3)
client/tx_config.go (3)

74-74: Use a nil pointer in interface assertion for clarity

In line 74, when asserting that DefaultTxDecoder[transaction.Tx] implements the transaction.Codec[transaction.Tx] interface, it's conventional to use a nil pointer for the implementation side. This improves readability and avoids unnecessary allocations.

Apply this change:

-var _ transaction.Codec[transaction.Tx] = &DefaultTxDecoder[transaction.Tx]{}
+var _ transaction.Codec[transaction.Tx] = (*DefaultTxDecoder[transaction.Tx])(nil)

81-95: Simplify type assertion and error handling in Decode method

The type assertion logic in the Decode method can be streamlined for clarity. Additionally, ensure consistent handling of zero values for the generic type T when returning errors.

Refactor the method as follows:

func (t *DefaultTxDecoder[T]) Decode(bz []byte) (T, error) {
-	var out T
	tx, err := t.TxConfig.TxDecoder()(bz)
	if err != nil {
-		return out, err
+		var zero T
+		return zero, err
	}

-	var ok bool
-	out, ok = tx.(T)
+	out, ok := tx.(T)
	if !ok {
-		return out, errors.New("unexpected Tx type")
+		var zero T
+		return zero, errors.New("unexpected Tx type")
	}

	return out, nil
}

97-112: Eliminate code duplication between Decode and DecodeJSON methods

The Decode and DecodeJSON methods contain duplicated logic. Refactoring to use a shared helper function promotes the DRY (Don't Repeat Yourself) principle.

Introduce a helper function:

func (t *DefaultTxDecoder[T]) decode(bz []byte, decoder sdk.TxDecoder) (T, error) {
	var zero T
	tx, err := decoder(bz)
	if err != nil {
		return zero, err
	}

	out, ok := tx.(T)
	if !ok {
		return zero, errors.New("unexpected Tx type")
	}

	return out, nil
}

func (t *DefaultTxDecoder[T]) Decode(bz []byte) (T, error) {
	return t.decode(bz, t.TxConfig.TxDecoder())
}

func (t *DefaultTxDecoder[T]) DecodeJSON(bz []byte) (T, error) {
	return t.decode(bz, t.TxConfig.TxJSONDecoder())
}
📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a60dfda and 56b20e8.

📒 Files selected for processing (2)
  • client/tx_config.go (2 hunks)
  • simapp/v2/simdv2/cmd/commands.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
client/tx_config.go (1)

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

simapp/v2/simdv2/cmd/commands.go (1)

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

🔇 Additional comments (1)
simapp/v2/simdv2/cmd/commands.go (1)

110-110: LGTM: Successfully migrated to DefaultTxDecoder

The change aligns with the PR objective of moving the generic transaction decoder. Using DefaultTxDecoder[T] simplifies the codebase by leveraging a standard implementation.

Let's verify that the old decoder is completely removed and no references remain:

✅ Verification successful

Successfully verified DefaultTxDecoder migration

The search results confirm that:

  • No references to genericTxDecoder remain in the codebase
  • DefaultTxDecoder is properly implemented in client/tx_config.go and correctly used in simapp/v2/simdv2/cmd/commands.go
  • The implementation follows a consistent pattern across the codebase with proper interface compliance (var _ transaction.Codec[transaction.Tx] = &DefaultTxDecoder[transaction.Tx]{}).
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify complete removal of genericTxDecoder
# and consistent usage of DefaultTxDecoder

# Check for any remaining references to genericTxDecoder
rg "genericTxDecoder"

# Verify DefaultTxDecoder usage pattern
ast-grep --pattern 'DefaultTxDecoder[T]{TxConfig: $_}'

Length of output: 78


Script:

#!/bin/bash
# Let's try a more comprehensive search strategy

# Search for any references to genericTxDecoder with case insensitivity
rg -i "generictxdecoder"

# Search for DefaultTxDecoder usage with surrounding context
rg -A 2 "DefaultTxDecoder"

# Look for any decoder-related type definitions or interfaces
ast-grep --pattern 'type $_ struct {
  $$$
  TxConfig $_
  $$$
}'

# Check for any decoder-related imports
rg "\"github.com/.*client.*decoder\""

Length of output: 11103

Comment on lines +76 to +78
type DefaultTxDecoder[T transaction.Tx] struct {
TxConfig TxConfig
}
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 26, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add documentation for exported type DefaultTxDecoder

The exported type DefaultTxDecoder lacks a comment. According to the Uber Go Style Guide, all exported types should have a comment explaining their purpose.

Add a comment like:

+// DefaultTxDecoder is a generic transaction decoder that implements the transaction.Codec interface.
type DefaultTxDecoder[T transaction.Tx] struct {
	TxConfig TxConfig
}
📝 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
type DefaultTxDecoder[T transaction.Tx] struct {
TxConfig TxConfig
}
// DefaultTxDecoder is a generic transaction decoder that implements the transaction.Codec interface.
type DefaultTxDecoder[T transaction.Tx] struct {
TxConfig TxConfig
}

Copy link
Member

Choose a reason for hiding this comment

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

Yes, let's add this please @tac0turtle

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Comment on lines 97 to 112
// DecodeJSON implements transaction.Codec.
func (t *DefaultTxDecoder[T]) DecodeJSON(bz []byte) (T, error) {
var out T
tx, err := t.TxConfig.TxJSONDecoder()(bz)
if err != nil {
return out, err
}

var ok bool
out, ok = tx.(T)
if !ok {
return out, errors.New("unexpected Tx type")
}

return out, nil
}
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 26, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add comments for exported methods Decode and DecodeJSON

The exported methods Decode and DecodeJSON lack documentation. Per the Uber Go Style Guide, all exported functions and methods should have comments.

Add comments like:

+// Decode decodes a binary transaction into type T using the TxConfig's TxDecoder.
func (t *DefaultTxDecoder[T]) Decode(bz []byte) (T, error) {
	// existing code
}

+// DecodeJSON decodes a JSON transaction into type T using the TxConfig's TxJSONDecoder.
func (t *DefaultTxDecoder[T]) DecodeJSON(bz []byte) (T, error) {
	// existing code
}

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

Copy link
Member

Choose a reason for hiding this comment

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

ditto

Copy link
Contributor

Choose a reason for hiding this comment

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

@julienrbrt, understood. In addition to Decode and DecodeJSON, I noticed that the exported interface methods in TxEncodingConfig and TxConfig also lack documentation comments. Per the Uber Go Style Guide, all exported functions and methods should have comments.

I recommend adding comments like:

// TxEncoder returns the transaction encoder.
TxEncoder() sdk.TxEncoder

// TxDecoder returns the transaction decoder.
TxDecoder() sdk.TxDecoder

// TxJSONEncoder returns the JSON transaction encoder.
TxJSONEncoder() sdk.TxEncoder

// TxJSONDecoder returns the JSON transaction decoder.
TxJSONDecoder() sdk.TxDecoder

// MarshalSignatureJSON marshals the signatures to JSON.
MarshalSignatureJSON([]signingtypes.SignatureV2) ([]byte, error)

// UnmarshalSignatureJSON unmarshals the signatures from JSON.
UnmarshalSignatureJSON([]byte) ([]signingtypes.SignatureV2, error)

This will help maintain consistency and improve code readability.

Copy link
Member

@julienrbrt julienrbrt left a comment

Choose a reason for hiding this comment

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

ACK

@julienrbrt julienrbrt added the backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release label Nov 26, 2024
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: 0

🧹 Outside diff range and nitpick comments (1)
client/tx_config.go (1)

81-96: Enhance error messages for better debugging

The error messages in type assertions could be more descriptive by including the actual type information.

Consider updating the error messages:

-		return out, errors.New("unexpected Tx type")
+		return out, fmt.Errorf("unexpected Tx type: got %T, want %T", tx, out)

This change would require adding "fmt" to the imports.

Also applies to: 98-113

📜 Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 56b20e8 and 9c47177.

📒 Files selected for processing (1)
  • client/tx_config.go (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
client/tx_config.go (1)

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

🔇 Additional comments (3)
client/tx_config.go (3)

4-4: LGTM: Import statements are properly used

The new imports are correctly added and utilized in the implementation.

Also applies to: 7-7


74-74: LGTM: Proper interface compliance check

The compile-time interface assertion ensures that DefaultTxDecoder implements the transaction.Codec interface.


76-79: LGTM: Well-documented type definition

The type definition is properly documented and follows Go conventions.

@julienrbrt julienrbrt added this pull request to the merge queue Nov 26, 2024
Merged via the queue into main with commit f153426 Nov 26, 2024
74 of 75 checks passed
@julienrbrt julienrbrt deleted the marko/move_defaultDecoder branch November 26, 2024 14:31
mergify bot pushed a commit that referenced this pull request Nov 26, 2024
julienrbrt pushed a commit that referenced this pull request Nov 26, 2024
Co-authored-by: Marko <marko@baricevic.me>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport/v0.52.x PR scheduled for inclusion in the v0.52's next stable release C:CLI
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants