Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat(client/v2): factory and txBuilder #20623

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

Conversation

JulianToledano
Copy link
Contributor

@JulianToledano JulianToledano commented Jun 11, 2024

Description

Ref:
#18580
#19738

Closes:
#19433


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 new methods KeyType and KeyInfo to the keyring interface for retrieving key type and key information.
    • Added functionality for retrieving account details necessary for transaction signing.
    • Implemented a comprehensive transaction handling system, including tools for generating, signing, and broadcasting transactions.
    • Added functions for managing transaction parameters, including gas and fee configurations.
  • Improvements

    • Enhanced keyring initialization by accepting an address codec parameter.
    • Introduced utility functions for handling coin-related operations, including parsing and normalization.
    • Improved transaction flag management with flexible gas settings.
  • Bug Fixes

    • Addressed keyring initialization issues by modifying the sign function.
  • Tests

    • Added various test functions related to transaction preparation, building unsigned transactions, gas calculations, and transaction simulations.

Copy link
Contributor

coderabbitai bot commented Jun 11, 2024

Note

Reviews paused

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.
Walkthrough

Walkthrough

The recent changes enhance the client functionality of a Cosmos SDK-based application. Key modifications include the integration of address codecs into keyring management, the addition of methods for retrieving key type and information, and improvements in transaction handling with new utilities for account and coin operations. The changes also introduce tests to validate these functionalities, and the go.mod file has been updated to streamline dependencies.

Changes

File(s) Change Summary
client/v2/autocli/flag/address.go Modified getKeyringFromCtx to accept an additional address.Codec parameter.
client/v2/autocli/keyring/interface.go, client/v2/autocli/keyring/keyring.go, client/v2/autocli/keyring/no_keyring.go Added KeyType and KeyInfo methods to the Keyring interface and its implementations.
client/v2/go.mod Removed the // indirect directive from github.com/cosmos/go-bip39 dependency.
client/v2/internal/account/retriever.go Introduced account retrieval functionality for transaction signing.
client/v2/internal/coins/util.go, client/v2/internal/coins/util_test.go Added functions for coin operations and corresponding tests for IsZero.
client/v2/internal/grpc/client.go Introduced ClientConn struct implementing gogogrpc.ClientConn interface.
client/v2/offchain/sign.go Updated sign function to include address.Codec in keyring initialization.
client/v2/tx/README.md, client/v2/tx/builder.go, client/v2/tx/flags.go, client/v2/tx/tx.go, client/v2/tx/types.go Documented transaction architecture, enhanced transaction management, and introduced comprehensive transaction handling functionalities.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CLI
    participant Keyring
    participant TxFactory
    participant Network

    User->>CLI: Request to build transaction
    CLI->>Keyring: Initialize keyring with address codec
    Keyring-->>CLI: Keyring instance
    CLI->>TxFactory: Prepare transaction
    TxFactory->>Network: Retrieve account info
    Network-->>TxFactory: Account details
    TxFactory->>CLI: Unsigned transaction
    CLI->>Keyring: Sign transaction
    Keyring-->>CLI: Signed transaction
    CLI->>Network: Broadcast transaction
    Network-->>CLI: Transaction response
    CLI-->>User: Response details
Loading

Possibly related PRs

  • refactor: decouple comet from modules #21382: The changes in the main PR involve modifications to the getKeyringFromCtx function, which may relate to the overall structure and handling of keyring functionalities, similar to the refactoring efforts in this PR that aim to enhance modularity within the Cosmos SDK.
  • fix(unorderedtx): issues reported in audit #21467: This PR addresses issues related to unordered transactions, which may connect to the changes in the main PR that involve keyring functionalities, as both are part of the broader transaction management system within the SDK.
  • refactor(x/bank/v2): migrate to handlers #21659: The migration to a handler-based architecture in this PR could relate to the changes in the main PR, as both involve enhancing the modularity and maintainability of the codebase, particularly in how transactions and keyring functionalities are managed.
  • feat(auth): support accounts from auth #21688: The introduction of querying accounts from the auth module in this PR may connect to the changes in the main PR, as both involve enhancements to account management and keyring functionalities within the Cosmos SDK.
  • refactor(mempool)!: match server/v2/cometbft and sdk mempool interface #21744: The refactoring of the mempool interface in this PR may relate to the changes in the main PR, as both involve improving transaction handling and management within the SDK.
  • fix(sims): TestAppSimulationAfterImport and legacy proposal handling #21800: The fixes related to simulation and legacy proposal handling in this PR may connect to the changes in the main PR, as both involve ensuring the integrity and functionality of transaction management systems within the Cosmos SDK.

Suggested labels

C:x/accounts, C:x/auth, C:x/bank, C:x/genutil, C:x/feegrant, C:x/staking, C:x/gov, C:x/group, C:x/authz

Suggested reviewers

  • julienrbrt
  • sontrinh16
  • akhilkumarpilli
  • kocubinski
  • facundomedica
  • testinginprod

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.

@github-actions github-actions bot added the C:CLI label Jun 11, 2024
client/v2/tx/types.go Fixed Show fixed Hide fixed
Copy link
Contributor

@raynaudoe raynaudoe left a comment

Choose a reason for hiding this comment

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

Left a few comments, looks very good 🚀

client/v2/tx/builder.go Show resolved Hide resolved
client/v2/tx/builder.go Outdated Show resolved Hide resolved
client/v2/tx/config.go Outdated Show resolved Hide resolved
client/v2/tx/config.go Outdated Show resolved Hide resolved
client/v2/tx/config.go Show resolved Hide resolved
client/v2/tx/factory.go Outdated Show resolved Hide resolved
client/v2/tx/factory.go Outdated Show resolved Hide resolved
client/v2/tx/factory.go Outdated Show resolved Hide resolved
client/v2/tx/factory.go Fixed Show fixed Hide fixed
client/v2/tx/types.go Fixed Show fixed Hide fixed
@JulianToledano JulianToledano changed the title [WIP] client/v2: factory and txBuilder feat(client/v2): factory and txBuilder Jun 21, 2024
@JulianToledano JulianToledano marked this pull request as ready for review June 21, 2024 12:59
@JulianToledano JulianToledano requested a review from a team as a code owner June 21, 2024 12:59
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: 11

Outside diff range and nitpick comments (2)
client/v2/tx/aux_builder_test.go (1)

34-226: Comprehensive testing of AuxTxBuilder functionalities.

The test cases in TestAuxTxBuilder are comprehensive, covering various error scenarios and successful setups. The use of table-driven tests enhances the maintainability and readability of the tests. However, consider adding a few more comments within the test cases to explain the rationale behind specific checks, especially for complex scenarios.

+ // Test case: "cannot set SIGN_MODE_DIRECT" checks that only specific signing modes are allowed
+ // Test case: "GetSignBytes body should not be nil" ensures that the builder is properly initialized before use
client/v2/tx/tx.go (1)

102-123: Ensure consistency in error messages.

The validate function uses different styles for error messages. Consistency in error messages improves readability and maintainability. Consider using a consistent format for all error messages within this function.

- return errors.New("account-number and sequence must be set in offline mode")
+ return errors.New("account-number and sequence must be set in offline mode.")
- return errors.New("chain ID cannot be used when offline and generate-only flags are set")
+ return errors.New("chain ID cannot be used when offline and generate-only flags are set.")
- return errors.New("chain ID required but not specified")
+ return errors.New("chain ID is required but not specified.")
Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9ee9940 and d360670.

Files selected for processing (11)
  • client/v2/tx/README.md (1 hunks)
  • client/v2/tx/aux_builder_test.go (1 hunks)
  • client/v2/tx/builder.go (1 hunks)
  • client/v2/tx/builder_test.go (1 hunks)
  • client/v2/tx/config.go (1 hunks)
  • client/v2/tx/encoder.go (1 hunks)
  • client/v2/tx/encoder_test.go (1 hunks)
  • client/v2/tx/factory.go (1 hunks)
  • client/v2/tx/tx.go (1 hunks)
  • client/v2/tx/types.go (1 hunks)
  • client/v2/tx/wrapper.go (1 hunks)
Additional context used
Path-based instructions (11)
client/v2/tx/encoder_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/wrapper.go (1)

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

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/types.go (1)

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

client/v2/tx/aux_builder_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/builder.go (1)

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

client/v2/tx/config.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/builder_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/factory.go (1)

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

client/v2/tx/README.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

LanguageTool
client/v2/tx/README.md

[grammar] ~512-~512: The verb ‘Prepare’ does not usually follow articles like ‘a’. Check that ‘Prepare’ is spelled correctly; using ‘Prepare’ as a noun may be non-standard.
Context: ...ackage, typically you would: 1. Create a Factory 2. Prepare the account 3. Build an unsigned transa...

(A_INFINITIVE)

Additional comments not posted (51)
client/v2/tx/encoder_test.go (3)

16-49: Helper function getWrappedTx looks good.

The helper function correctly sets up a wrapped transaction for testing.


51-74: Test function Test_txEncoder_txDecoder looks good.

The test function correctly verifies the encoding and decoding process, including checks for determinism and equality.


76-104: Test function Test_txJsonEncoder_txJsonDecoder looks good.

The test function correctly verifies the JSON encoding and decoding process, including checks for equality.

client/v2/tx/wrapper.go (5)

30-35: Initialization method newWrapperTx looks good.

The method correctly initializes the wrappedTx struct with the provided codec and decoded transaction.


37-40: Method GetSigners looks good.

The method correctly returns the signers from the decoded transaction.


42-65: Method GetPubKeys looks good.

The method correctly retrieves and decodes the public keys from the transaction's SignerInfos, including error handling for invalid public key types.


67-97: Method GetSignatures looks good.

The method correctly retrieves the signatures and constructs the Signature structs, including error handling for invalid signature data.


99-115: Method decodeAny looks good.

The method correctly decodes the Any message using reflection and the provided codec, including error handling for unknown types and unmarshalling errors.

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

38-58: Function decodeTx looks good.

The function correctly decodes transaction bytes into an apitx.Tx structure, including error handling for unmarshalling and decoding errors.


60-67: Function encodeTx looks good.

The function correctly encodes an apitx.Tx into bytes using protobuf marshaling options, including error handling for unexpected transaction types.


69-91: Function decodeJsonTx looks good.

The function correctly decodes transaction bytes into an apitx.Tx structure using JSON format, including error handling for unmarshalling and decoding errors.


94-101: Function encodeJsonTx looks good.

The function correctly encodes an apitx.Tx into bytes using JSON marshaling options, including error handling for unexpected transaction types.


103-119: Function protoTxBytes looks good.

The function correctly marshals a transaction into bytes using protobuf marshaling options, including error handling for marshaling errors.

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

28-40: Type TxParameters looks good.

The type correctly defines the parameters required for constructing a transaction, with appropriate comments explaining each field.


42-54: Type AccountConfig looks good.

The type correctly defines the account-related fields in a transaction, with appropriate comments explaining each field.


56-62: Type GasConfig looks good.

The type correctly defines the gas-related settings for a transaction, with appropriate comments explaining each field.


84-89: Type FeeConfig looks good.

The type correctly defines the fee details for a transaction, with appropriate comments explaining each field.


106-115: Type ExecutionOptions looks good.

The type correctly defines the settings for transaction execution, with appropriate comments explaining each field.


132-142: Type Tx looks good.

The type correctly defines the interface for transaction operations, with appropriate methods for transaction operations.

client/v2/tx/builder.go (5)

27-44: LGTM! Interface methods are well-defined.

The TxBuilder interface methods cover all necessary transaction functionalities and are well-defined.


52-81: LGTM! Struct implementation is correct.

The BuilderProvider struct correctly implements TxBuilderProvider and provides methods for creating and wrapping transaction builders.


116-166: LGTM! Method implementation is correct.

The getTx method correctly converts txBuilder messages to V2 and handles errors appropriately.


240-252: LGTM! Method implementation is correct.

The SetFeePayer method correctly sets the fee payer for the transaction and handles errors appropriately.


277-316: LGTM! Method implementation is correct.

The SetSignatures method correctly sets the signatures for the transaction builder and handles errors appropriately.

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

36-42: LGTM! Interface methods are well-defined.

The TxConfig interface methods cover all necessary functionalities and are well-defined.


69-84: LGTM! Struct implementation is correct.

The ConfigOptions struct correctly defines the configuration options for transaction processing.

client/v2/tx/builder_test.go (12)

23-48: Ensure initialization of test variables in TestNewBuilderProvider.

The test function TestNewBuilderProvider uses variables ac, decoder, and cdc which are not initialized within the test or in a setup function. This could lead to a runtime panic if these are nil.

func TestNewBuilderProvider(t *testing.T) {
+	var ac address.Codec
+	var decoder *txdecode.Decoder
+	var cdc codec.BinaryCodec
	type args struct {
		addressCodec address.Codec
		decoder      *txdecode.Decoder
		codec        codec.BinaryCodec
	}
	// Existing code...
}

112-196: Confirm test cases cover both empty and full transaction scenarios in Test_txBuilder_GetTx.

The test function Test_txBuilder_GetTx includes test cases for both empty and full transactions, which is essential for comprehensive coverage. Ensure these test cases are maintained and updated as necessary.


198-220: Test function for message conversion lacks assertions.

The test Test_msgsV1toAnyV2 converts transaction messages but does not assert the expected properties of the resulting anypb.Any objects. This makes the test less effective as it does not verify the correctness of the conversion.

func Test_msgsV1toAnyV2(t *testing.T) {
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			got, err := msgsV1toAnyV2(tt.msgs)
			require.NoError(t, err)
			require.NotNil(t, got)
+			// Example assertion
+			require.Equal(t, "/cosmos.tx.v1beta1.MsgIncreaseCounter", got[0].TypeUrl)
		})
	}
}

222-248: Confirm test cases cover the conversion of codectypes.Any to anypb.Any in Test_intoAnyV2.

The test function Test_intoAnyV2 includes assertions that verify the correctness of the conversion, which is essential for comprehensive coverage. Ensure these test cases are maintained and updated as necessary.


250-309: Confirm test cases cover different fee scenarios in Test_txBuilder_getFee.

The test function Test_txBuilder_getFee includes test cases for different fee scenarios, which is essential for comprehensive coverage. Ensure these test cases are maintained and updated as necessary.


311-365: Confirm test cases cover both empty and full transaction scenarios in Test_txBuilder_GetSigningTxData.

The test function Test_txBuilder_GetSigningTxData includes test cases for both empty and full transactions, which is essential for comprehensive coverage. Ensure these test cases are maintained and updated as necessary.


367-399: Confirm test cases cover the message setting in Test_txBuilder_SetMsgs.

The test function Test_txBuilder_SetMsgs includes assertions that verify the messages are set correctly, which is essential for comprehensive coverage. Ensure these test cases are maintained and updated as necessary.


401-418: Confirm test cases cover the memo setting in Test_txBuilder_SetMemo.

The test function Test_txBuilder_SetMemo includes assertions that verify the memo is set correctly, which is essential for comprehensive coverage. Ensure these test cases are maintained and updated as necessary.


420-446: Confirm test cases cover the fee amount setting in Test_txBuilder_SetFeeAmount.

The test function Test_txBuilder_SetFeeAmount includes assertions that verify the fee amount is set correctly, which is essential for comprehensive coverage. Ensure these test cases are maintained and updated as necessary.


448-464: Confirm test cases cover the gas limit setting in Test_txBuilder_SetGasLimit.

The test function Test_txBuilder_SetGasLimit includes assertions that verify the gas limit is set correctly, which is essential for comprehensive coverage. Ensure these test cases are maintained and updated as necessary.


467-487: Confirm test cases cover the unordered flag setting in Test_txBuilder_SetUnordered.

The test function Test_txBuilder_SetUnordered includes assertions that verify the unordered flag is set correctly, which is essential for comprehensive coverage. Ensure these test cases are maintained and updated as necessary.


490-572: Ensure correct handling of multiple and single signatures in Test_txBuilder_SetSignatures.

The test cases for setting signatures should include assertions to verify that the signatures are correctly set on the transaction. Currently, the test only checks for errors but does not validate the state of the transaction after setting signatures.

func Test_txBuilder_SetSignatures(t *testing.T) {
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			b := newTxBuilder(ac, decoder, cdc)
			sigs := tt.signatures()
			err := b.SetSignatures(sigs...)
			require.NoError(t, err)
+			// Verify the state of the transaction
+			tx, _ := b.GetTx()
+			require.Equal(t, len(sigs), len(tx.Signatures))
		})
	}
}
client/v2/tx/factory.go (5)

45-58: LGTM! Factory initialization looks correct.

The NewFactory function correctly initializes a new Factory instance with the provided parameters.


487-506: LGTM! Signature data handling looks correct.

The getSimSignatureData function correctly handles the signature data based on the public key type.


271-395: Consider using propagated context.

The function uses context.Background() which might not respect cancellation or timeouts from an upstream context. Consider modifying the function signature to include a context.Context parameter and use it instead.

- func (f *Factory) Sign(ctx context.Context, txBuilder TxBuilder, overwriteSig bool) error {
+ func (f *Factory) Sign(ctx context.Context, txBuilder TxBuilder, overwriteSig bool, ctx context.Context) error {

Likely invalid or redundant comment.


199-232: Consider using propagated context.

The function uses context.Background() which might not respect cancellation or timeouts from an upstream context. Consider modifying the function signature to include a context.Context parameter and use it instead.

- func (f *Factory) UnsignedTxString(msgs ...transaction.Msg) (string, error) {
+ func (f *Factory) UnsignedTxString(ctx context.Context, msgs ...transaction.Msg) (string, error) {
- encoder := f.txConfig.TxJSONEncoder()
+ encoder := f.txConfig.TxJSONEncoder(ctx)

Likely invalid or redundant comment.


397-406: Consider using propagated context.

The function uses context.Background() which might not respect cancellation or timeouts from an upstream context. Consider modifying the function signature to include a context.Context parameter and use it instead.

- func (f *Factory) getSignBytesAdapter(ctx context.Context, signerData signing.SignerData, builder TxBuilder) ([]byte, error) {
+ func (f *Factory) getSignBytesAdapter(ctx context.Context, signerData signing.SignerData, builder TxBuilder, ctx context.Context) ([]byte, error) {

Likely invalid or redundant comment.

client/v2/tx/README.md (8)

1-12: LGTM! Overview section looks correct.

The Overview section correctly lists the key components in the tx package.


13-27: LGTM! Architecture section looks correct.

The Architecture section correctly provides a mermaid diagram and descriptions of the architecture.


29-99: LGTM! Key Components section looks correct.

The Key Components section correctly provides detailed descriptions and mermaid diagrams for the key components in the tx package.


101-176: LGTM! TxBuilder section looks correct.

The TxBuilder section correctly provides a mermaid diagram and descriptions for the TxBuilder.


178-236: LGTM! Factory section looks correct.

The Factory section correctly provides a mermaid diagram and descriptions for the Factory.


238-285: LGTM! Encoder/Decoder section looks correct.

The Encoder/Decoder section correctly provides a mermaid diagram and descriptions for the encoder and decoder functionalities.


287-506: LGTM! Sequence Diagrams section looks correct.

The Sequence Diagrams section correctly provides mermaid sequence diagrams for various processes.


508-528: **Fix the grammatical

Tools
LanguageTool

[grammar] ~512-~512: The verb ‘Prepare’ does not usually follow articles like ‘a’. Check that ‘Prepare’ is spelled correctly; using ‘Prepare’ as a noun may be non-standard.
Context: ...ackage, typically you would: 1. Create a Factory 2. Prepare the account 3. Build an unsigned transa...

(A_INFINITIVE)

client/v2/tx/config.go Show resolved Hide resolved
client/v2/tx/builder_test.go Show resolved Hide resolved
client/v2/tx/builder_test.go Show resolved Hide resolved
client/v2/tx/factory.go Outdated Show resolved Hide resolved
client/v2/tx/factory.go Outdated Show resolved Hide resolved
client/v2/tx/factory.go Show resolved Hide resolved
client/v2/tx/factory.go Outdated Show resolved Hide resolved
client/v2/tx/factory.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 12

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d360670 and 5a8aba9.

Files selected for processing (4)
  • client/v2/tx/README.md (1 hunks)
  • client/v2/tx/factory.go (1 hunks)
  • client/v2/tx/factory_test.go (1 hunks)
  • client/v2/tx/tx.go (1 hunks)
Files not reviewed due to server errors (1)
  • client/v2/tx/factory.go
Additional context used
Path-based instructions (4)
client/v2/tx/factory_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/tx.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/README.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

LanguageTool
client/v2/tx/README.md

[grammar] ~513-~513: The verb ‘Prepare’ does not usually follow articles like ‘a’. Check that ‘Prepare’ is spelled correctly; using ‘Prepare’ as a noun may be non-standard.
Context: ...ackage, typically you would: 1. Create a Factory 2. Prepare the account 3. Build an unsigned transa...

(A_INFINITIVE)

Markdownlint
client/v2/tx/README.md

35-35: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


36-36: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


37-37: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


182-182: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


183-183: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


184-184: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


185-185: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


290-290: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


337-337: Expected: 1; Actual: 0; Above
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


337-337: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


386-386: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


439-439: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


291-291: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


336-336: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


338-338: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


387-387: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


440-440: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


1-1: null
First line in a file should be a top-level heading

(MD041, first-line-heading, first-line-h1)


529-529: null
Files should end with a single newline character

(MD047, single-trailing-newline)

Additional comments not posted (1)
client/v2/tx/README.md (1)

1-529: Comprehensive Review of client/v2/tx/README.md

This documentation provides a detailed and structured overview of the tx package functionalities, including transaction building, signing, and management. The use of class diagrams and sequence diagrams enhances the clarity of the architectural and operational details.

Suggestions and Corrections:

  1. Grammar and Style Consistency:

    • Consider using consistent list markers. The document mixes dashes and asterisks. For consistency, choose one style. (MD004)
    • Ensure that headings are surrounded by blank lines to improve readability and adhere to Markdown standards. (MD022)
    • Fenced code blocks should also be surrounded by blank lines. (MD031)
    • The document should start with a top-level heading and end with a newline. (MD041, MD047)
  2. Technical Accuracy and Completeness:

    • The sections cover key components and their interactions comprehensively. However, ensure all newly introduced terms or concepts are defined or linked to further resources for new users.
  3. LanguageTool Feedback:

    • The phrase "Prepare the account" might be misleading as 'Prepare' is typically not used as a noun. Consider rephrasing to "Prepare for account setup" or similar to clarify the action. (A_INFINITIVE)

Overall, the document is well-organized and informative, providing essential insights into the transaction management system of the Cosmos SDK. Minor adjustments to markdown syntax and some clarifications in language use will enhance its quality.

Tools
LanguageTool

[grammar] ~513-~513: The verb ‘Prepare’ does not usually follow articles like ‘a’. Check that ‘Prepare’ is spelled correctly; using ‘Prepare’ as a noun may be non-standard.
Context: ...ackage, typically you would: 1. Create a Factory 2. Prepare the account 3. Build an unsigned transa...

(A_INFINITIVE)

Markdownlint

35-35: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


36-36: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


37-37: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


182-182: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


183-183: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


184-184: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


185-185: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


290-290: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


337-337: Expected: 1; Actual: 0; Above
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


337-337: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


386-386: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


439-439: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


291-291: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


336-336: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


338-338: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


387-387: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


440-440: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


1-1: null
First line in a file should be a top-level heading

(MD041, first-line-heading, first-line-h1)


529-529: null
Files should end with a single newline character

(MD047, single-trailing-newline)

client/v2/tx/factory_test.go Outdated Show resolved Hide resolved
client/v2/tx/factory_test.go Outdated Show resolved Hide resolved
client/v2/tx/factory_test.go Outdated Show resolved Hide resolved
client/v2/tx/factory_test.go Outdated Show resolved Hide resolved
client/v2/tx/factory_test.go Outdated Show resolved Hide resolved
client/v2/tx/factory_test.go Show resolved Hide resolved
client/v2/tx/factory_test.go Outdated Show resolved Hide resolved
client/v2/tx/tx.go Outdated Show resolved Hide resolved
client/v2/tx/tx.go Outdated Show resolved Hide resolved
client/v2/tx/tx.go Outdated Show resolved Hide resolved
@JulianToledano
Copy link
Contributor Author

@coderabbitai stop

Copy link
Contributor

coderabbitai bot commented Jul 17, 2024

Tip

For best results, initiate chat on the files or code changes.

@JulianToledano, I've stopped as requested. If there's anything else you need, just let me know!

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.

I like how the new tx factory is, however it seems that the complexity moved to TxParameters. I don't think we need api parity for a v2. Less is more. Can we simplify the API?

@@ -0,0 +1,307 @@
package tx
Copy link
Member

Choose a reason for hiding this comment

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

Can we just drop the aux builder for v2? cc @tac0turtle. Can textual replace it?

Copy link
Member

Choose a reason for hiding this comment

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

client/v2/tx/builder.go Outdated Show resolved Hide resolved
client/v2/tx/tx.go Outdated Show resolved Hide resolved
client/v2/tx/types.go Outdated Show resolved Hide resolved
client/v2/tx/types.go Outdated Show resolved Hide resolved
client/v2/tx/encoder.go Outdated Show resolved Hide resolved
client/v2/tx/types.go Outdated Show resolved Hide resolved
client/v2/tx/types.go Outdated Show resolved Hide resolved
client/v2/tx/factory.go Outdated Show resolved Hide resolved
return nil, 0, err
}

return simRes, uint64(f.gasAdjustment() * float64(simRes.GasInfo.GasUsed)), nil

Check notice

Code scanning / CodeQL

Floating point arithmetic Note

Floating point arithmetic operations are not associative and a possible source of non-determinism

import (
"fmt"
"reflect"

Check notice

Code scanning / CodeQL

Sensitive package import Note

Certain system packages contain functions which may be a possible source of non-determinism
@julienrbrt
Copy link
Member

Forgot about, this I'll try to review tomorrow.

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.

I still see some comments of mine left unanswered or unimplemented. Could you have a look @JulianToledano ?

@@ -0,0 +1,307 @@
package tx
Copy link
Member

Choose a reason for hiding this comment

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

client/v2/tx/builder.go Outdated Show resolved Hide resolved
client/v2/tx/tx.go Outdated Show resolved Hide resolved
Copy link
Contributor

@raynaudoe raynaudoe left a comment

Choose a reason for hiding this comment

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

LGTM. Left a few comments only

@@ -147,11 +147,11 @@ func (a *consensusAddressValue) Set(s string) error {
return nil
}

func getKeyringFromCtx(ctx *context.Context) keyring.Keyring {
func getKeyringFromCtx(ctx *context.Context, ac address.Codec) keyring.Keyring {
Copy link
Contributor

Choose a reason for hiding this comment

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

Not sure but isn't address.Codec available inside Context ?

client/v2/internal/grpc/client.go Outdated Show resolved Hide resolved
client/v2/internal/grpc/client.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Outside diff range and nitpick comments (2)
client/v2/tx/types.go (1)

128-196: Consider refactoring the txParamsFromFlagSet function.

The txParamsFromFlagSet function is quite large and complex, handling the extraction and parsing of various transaction parameters from flags. While the function is well-documented and handles errors properly, it could benefit from refactoring.

Consider breaking down the function into smaller, more focused functions that handle specific parameter extractions. This will improve readability, maintainability, and testability of the code.

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

71-78: Evaluate the necessity of the WrapTxBuilder method.

The WrapTxBuilder method wraps an existing transaction into a txBuilder object. However, the TODO comment raises a valid concern about the necessity of this method.

Consider the following:

  • If this functionality is rarely used or can be integrated into the NewTxBuilder method, it may introduce unnecessary complexity to the interface.
  • If it remains necessary, ensure that its usage is justified and well-documented to avoid confusion about when to use NewTxBuilder versus WrapTxBuilder.
Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5a8aba9 and 738605d.

Files selected for processing (7)
  • client/v2/autocli/keyring/keyring.go (1 hunks)
  • client/v2/tx/builder.go (1 hunks)
  • client/v2/tx/encoder.go (1 hunks)
  • client/v2/tx/factory.go (1 hunks)
  • client/v2/tx/factory_test.go (1 hunks)
  • client/v2/tx/tx.go (1 hunks)
  • client/v2/tx/types.go (1 hunks)
Additional context used
Path-based instructions (7)
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/tx/encoder.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.

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/builder.go (1)

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

client/v2/tx/factory_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/factory.go (1)

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

Additional comments not posted (60)
client/v2/autocli/keyring/keyring.go (2)

52-55: LGTM!

The KeyType function correctly delegates the call to the underlying Keyring implementation to retrieve the key type based on the provided name. The function signature and implementation adhere to the Uber Golang style guide.


57-60: LGTM!

The KeyInfo function correctly delegates the call to the underlying Keyring implementation to retrieve comprehensive information about a key based on the provided name or address. The function signature and implementation adhere to the Uber Golang style guide.

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

39-58: LGTM!

The decodeTx function correctly decodes transaction bytes into an apitx.Tx structure using the provided binary codec and decoder. It handles errors appropriately and follows the expected logic.


61-67: LGTM!

The encodeTx function correctly encodes an apitx.Tx into bytes using the protobuf marshaling options. It performs type assertion to ensure the provided Tx is of the expected *wrappedTx type and handles the error case appropriately.


70-92: LGTM!

The decodeJsonTx function correctly decodes JSON transaction bytes into an apitx.Tx structure using the provided binary codec and decoder. It handles errors appropriately and follows the expected logic.


95-101: LGTM!

The encodeJsonTx function correctly encodes an apitx.Tx into bytes using the JSON marshaling options. It performs type assertion to ensure the provided Tx is of the expected *wrappedTx type and handles the error case appropriately.


103-119: LGTM!

The protoTxBytes function correctly marshals the components of a txv1beta1.Tx structure into a raw transaction format. It handles errors appropriately and follows the expected logic.


1-119: Code conforms to the Uber Golang style guide.

The file follows the recommended conventions and best practices outlined in the Uber Golang style guide, including:

  • Appropriate package naming
  • Grouping and separation of import statements
  • Consistent use of camelCase for variable and function names
  • Proper function signatures and variable declarations
  • Recommended error handling style
  • Avoidance of global variables and init functions

No deviations from the style guide were found.

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

20-25: LGTM!

The HasValidateBasic interface is a clean copy from the SDK to avoid an import cycle. The naming follows Go conventions and the comment justifies the duplication.


27-38: Excellent struct design!

The TxParameters struct is well-designed with clear field names and comments. The use of struct composition to group related fields into sub-configs enhances readability and maintainability. Great job!


40-52: LGTM!

The AccountConfig struct is well-defined with clear field names and comments. The fields cover all the necessary account-related information for a transaction.


54-60: LGTM!

The GasConfig struct is well-defined with clear field names and comments. It captures all the necessary gas-related settings for a transaction.


78-83: LGTM!

The FeeConfig struct is well-defined with clear field names and comments. It captures all the necessary fee-related details for a transaction.


85-98: LGTM!

The NewFeeConfig function is well-implemented. It properly parses and normalizes the fees and returns an error if parsing fails. The function is well-documented and follows Go conventions.


100-105: LGTM!

The ExecutionOptions struct is well-defined with clear field names and comments. It captures the necessary settings for transaction execution.


107-114: LGTM!

The GasEstimateResponse struct is well-defined with a clear field name and comment. The String method provides a readable string representation of the response.


116-126: LGTM!

The Tx interface is well-defined and extends the transaction.Tx interface with additional transaction-related methods. It provides a clear contract for transaction operations.

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

26-53: LGTM!

The GenerateOrBroadcastTxCLI function is well-structured and handles the transaction lifecycle effectively based on the provided user flags. It validates messages, creates a transaction factory, and determines the appropriate action to take. The error handling is also properly implemented.


58-82: LGTM!

The newFactory function properly initializes a new transaction factory by setting up the necessary components such as the keyring, transaction config, and account retriever. The error handling is also properly implemented.


88-101: LGTM!

The validateMessages function properly validates all messages before generating or broadcasting the transaction. It checks if each message implements the HasValidateBasic interface and calls the ValidateBasic method if available. The error handling is also properly implemented.


104-111: LGTM!

The generateAuxSignerData function properly generates and prints the auxiliary signer data. It calls the makeAuxSignerData function to generate the data and handles any errors returned by it. The function also uses the provided context to print the generated data.


116-123: LGTM!

The generateOnly function properly prepares the transaction and prints the unsigned transaction string. It calls the UnsignedTxString method of the transaction factory to generate the string and handles any errors returned by it. The function also uses the provided context to print the generated string.


127-135: LGTM!

The dryRun function properly performs a dry run of the transaction to estimate the gas required. It calls the Simulate method of the transaction factory to simulate the transaction and handles any errors returned by it. The function also prints the estimated gas to the standard error using the fmt.Fprintf function.


138-146: LGTM!

The SimulateTx function properly simulates a transaction and returns the simulation response. It creates a new transaction factory using the newFactory function and handles any errors returned by it. The function then calls the Simulate method of the factory to simulate the transaction and returns the simulation response along with any error.


151-212: LGTM!

The BroadcastTx function properly generates, signs, and broadcasts a transaction with the given set of messages. It handles gas simulation, builds an unsigned transaction, prompts for user confirmation, signs the transaction, and broadcasts it to a CometBFT node. The function also handles errors and returns them to the caller.


215-264: LGTM!

The makeAuxSignerData function properly generates an AuxSignerData from the client inputs. It sets various fields of the AuxSignerData such as address, account number, sequence, messages, sign mode, public key, chain ID, and signature using the appropriate methods of the AuxTxBuilder. The function also handles errors and returns them to the caller.


267-300: LGTM!

The countDirectSigners function properly counts the number of DIRECT signers in a signature data. It uses a switch statement to handle different types of signature data and recursively counts the number of DIRECT signers. The function also panics with an "unreachable case" message for any unsupported signature data type.

The getSignMode function properly returns the corresponding apitxsigning.SignMode based on the provided mode string. It uses a switch statement to map the mode string to the corresponding apitxsigning.SignMode and returns apitxsigning.SignMode_SIGN_MODE_UNSPECIFIED if no match is found.

client/v2/tx/builder.go (11)

57-63: LGTM!

The NewBuilderProvider constructor function is implemented correctly, initializing a new BuilderProvider instance with the provided parameters.


66-68: LGTM!

The NewTxBuilder method is implemented correctly, creating a new TxBuilder instance by calling the newTxBuilder function with the appropriate parameters from the BuilderProvider instance.


101-107: LGTM!

The newTxBuilder function is implemented correctly, initializing a new txBuilder instance with the provided parameters.


110-112: LGTM!

The GetTx method is implemented correctly, converting txBuilder messages to V2 by calling the getTx method and returning the result.


114-165: LGTM!

The getTx method is implemented correctly, converting txBuilder messages to V2 and creating a wrappedTx. It follows the necessary steps, such as converting messages, creating a TxBody and AuthInfo, marshaling the data, and decoding the TxRaw bytes. The error handling is appropriate, returning any errors encountered during the process.


170-195: LGTM!

The getFee method is implemented correctly, computing the transaction fee information based on the txBuilder fields. It properly handles the conversion of granter and payer addresses from bytes to string using the addressCodec. The logic follows the necessary steps to create a valid apitx.Fee struct.


198-211: LGTM!

The GetSigningTxData method is implemented correctly, returning a TxData with the txBuilder info. It calls the getTx method to get the wrappedTx and creates a signing.TxData struct with the relevant fields from the wrappedTx. The logic follows the necessary steps to create a valid signing.TxData struct.


219-222: LGTM!

The SetMemo method is implemented correctly, setting the memo field of txBuilder with the provided memo string.


224-227: LGTM!

The SetFeeAmount method is implemented correctly, setting the fees field of txBuilder with the provided coins.


229-232: LGTM!

The SetGasLimit method is implemented correctly, setting the gasLimit field of txBuilder with the provided gas limit.


234-237: LGTM!

The SetTimeoutTimestamp method is implemented correctly, setting the timeoutTimestamp field of txBuilder with the provided timeout timestamp.

client/v2/tx/factory_test.go (9)

24-53: LGTM!

The TestFactory_prepareTxParams function is well-structured and covers the important scenarios. The assertions correctly check the error conditions.


55-123: LGTM!

The TestFactory_BuildUnsignedTx function is well-structured and covers the important scenarios, including providing fees and gas prices. The assertions correctly check the error conditions and the returned unsigned transaction.


125-165: LGTM!

The TestFactory_calculateGas function is well-structured and covers the successful scenario. The assertions correctly check the error condition and the updated gas configuration.


167-208: LGTM!

The TestFactory_Simulate function is well-structured and covers the successful scenario. The assertions correctly check the error condition and the simulation results.


210-242: LGTM!

The TestFactory_BuildSimTx function is well-structured and covers the successful scenario. The assertions correctly check the error condition and the returned simulated transaction.


244-293: LGTM!

The TestFactory_Sign function is well-structured and covers the successful scenario. The assertions correctly check the error condition, the signatures, and the signer infos.


295-364: LGTM!

The TestFactory_getSignBytesAdapter function is well-structured and covers the important scenarios, including when the sign mode is not specified. The assertions correctly check the error conditions and the returned sign bytes adapter.


366-393: LGTM!

The Test_validateMemo function is well-structured and covers the important scenarios, including empty memo, valid memo, and invalid memo. The assertions correctly check the error conditions.


395-455: LGTM!

The TestFactory_WithFunctions function is well-structured and covers the important With* methods, including WithGas, WithSequence, and WithAccountNumber. The assertions correctly check the updated factory parameters.

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

37-47: LGTM!

The Factory struct encapsulates the necessary dependencies and configurations for building and signing transactions. The fields are appropriately named and typed.


49-68: LGTM!

The NewFactoryFromFlagSet function follows a clear flow to initialize a Factory instance based on command-line flags. It validates the flag set, retrieves transaction parameters, prepares them, and returns a new Factory instance. The error handling is appropriate.


70-83: LGTM!

The NewFactory function is a simple constructor that initializes a Factory instance with the provided parameters and returns it along with a nil error.


85-114: LGTM!

The validateFlagSet function performs necessary validations on the provided flag set based on the operation mode. It checks for required flags, conflicts between flags, and the presence of the chain ID. The error messages are clear and informative.


116-144: LGTM!

The prepareTxParams function ensures the account exists and sets the account number and sequence if they are zero. It follows a clear flow, handles errors appropriately, and returns the updated transaction parameters.


146-205: LGTM!

The BuildUnsignedTx function builds an unsigned transaction given a set of messages. It calculates fees based on gas prices and gas limit, validates the memo field, creates a new transaction builder, sets the necessary fields, and returns the builder. The function follows a clear flow and handles errors appropriately.


207-214: LGTM!

The BuildsSignedTx function is a simple wrapper that builds an unsigned transaction using BuildUnsignedTx and signs it using the sign method. It handles errors appropriately.


216-226: LGTM!

The calculateGas function is a simple wrapper that simulates the transaction execution to obtain the adjusted gas amount and updates the factory's gas value. It handles errors appropriately.


228-245: LGTM!

The Simulate function simulates the execution of a transaction and returns the simulation response and the adjusted gas amount. It follows a clear flow, building a simulation transaction, sending a simulation request, retrieving the response, calculating the adjusted gas amount, and returning the results. The error handling is appropriate.


247-280: LGTM!

The UnsignedTxString function generates an unsigned transaction and returns it as a JSON string. It follows a clear flow, calculating gas if requested, building an unsigned transaction, retrieving the JSON encoder, encoding the transaction, and returning the JSON string. The error handling is appropriate.


282-317: LGTM!

The BuildSimTx function creates an unsigned transaction with an empty single signature for simulation purposes. It follows a clear flow, building an unsigned transaction, retrieving the simulation public key, creating an empty signature, setting the signature on the builder, retrieving the encoder, encoding the transaction, and returning the encoded transaction. The error handling is appropriate.


319-441: LGTM!

The sign function signs a given transaction with a named key. It follows a complex flow with multiple steps, including checking the keybase, retrieving the sign mode, public key, and address, creating the signer data and signature, setting the signature on the builder, retrieving the signed transaction, checking for multiple signers, retrieving the sign bytes, signing the bytes, creating a new signature, setting the new signature on the builder, and returning the signed transaction. The error handling is appropriate, covering various failure scenarios.


443-452: LGTM!

The getSignBytesAdapter function is a simple adapter that retrieves the signing transaction data from the transaction builder and generates the sign bytes using the sign mode handler. It handles errors appropriately.

client/v2/tx/types.go Show resolved Hide resolved
client/v2/tx/builder.go Show resolved Hide resolved
@JulianToledano
Copy link
Contributor Author

@coderabbitai stop

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Outside diff range and nitpick comments (4)
client/v2/tx/README.md (4)

35-37: Use consistent unordered list markers

In lines 35-37, the list items use dashes - instead of asterisks *. For consistency and adherence to Markdown style guidelines, consider changing the list markers to asterisks.

Apply this diff to correct the list markers:

- - Encoding and decoding
- - Sign mode handling
- - Signature JSON marshaling/unmarshaling
+ * Encoding and decoding
+ * Sign mode handling
+ * Signature JSON marshaling/unmarshaling
Tools
Markdownlint

35-35: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


36-36: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


37-37: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


180-183: Use consistent unordered list markers

In lines 180-183, the list items use dashes - instead of asterisks *. For consistency and adherence to Markdown style guidelines, consider changing the list markers to asterisks.

Apply this diff to correct the list markers:

- - Account preparation
- - Gas calculation
- - Transaction simulation
- - Unsigned transaction building
+ * Account preparation
+ * Gas calculation
+ * Transaction simulation
+ * Unsigned transaction building
Tools
Markdownlint

180-180: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


181-181: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


182-182: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


183-183: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


288-288: Add blank lines around headings

Headings on lines 288, 335, 384, and 437 are not surrounded by blank lines. To improve readability and adhere to Markdown conventions, add a blank line before and after each heading.

Apply these diffs:

At line 288:

-#### Generate Aux Signer Data
+ 
+#### Generate Aux Signer Data
+

At line 335:

-#### Generate Only
+ 
+#### Generate Only
+

At line 384:

-#### DryRun
+ 
+#### DryRun
+

At line 437:

-#### Generate and Broadcast Tx
+ 
+#### Generate and Broadcast Tx
+

Also applies to: 335-335, 384-384, 437-437

Tools
Markdownlint

288-288: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


527-527: Ensure the file ends with a single newline character

The file should end with a single trailing newline character to adhere to POSIX standards and improve compatibility with various tools.

Tools
Markdownlint

527-527: null
Files should end with a single newline character

(MD047, single-trailing-newline)

Review details

Configuration used: .coderabbit.yml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 738605d and 4a51df0.

Files selected for processing (6)
  • client/v2/internal/account/retriever.go (1 hunks)
  • client/v2/tx/README.md (1 hunks)
  • client/v2/tx/builder.go (1 hunks)
  • client/v2/tx/flags.go (1 hunks)
  • client/v2/tx/tx.go (1 hunks)
  • client/v2/tx/types.go (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • client/v2/tx/tx.go
  • client/v2/tx/types.go
Additional context used
Path-based instructions (4)
client/v2/internal/account/retriever.go (1)

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

client/v2/tx/README.md (1)

Pattern **/*.md: "Assess the documentation for misspellings, grammatical errors, missing documentation and correctness"

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

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

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

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

LanguageTool
client/v2/tx/README.md

[grammar] ~511-~511: The verb ‘Prepare’ does not usually follow articles like ‘a’. Check that ‘Prepare’ is spelled correctly; using ‘Prepare’ as a noun may be non-standard.
Context: ...ackage, typically you would: 1. Create a Factory 2. Prepare the account 3. Build an unsigned transa...

(A_INFINITIVE)

Markdownlint
client/v2/tx/README.md

35-35: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


36-36: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


37-37: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


180-180: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


181-181: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


182-182: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


183-183: Expected: asterisk; Actual: dash
Unordered list style

(MD004, ul-style)


288-288: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


335-335: Expected: 1; Actual: 0; Above
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


335-335: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


384-384: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


437-437: Expected: 1; Actual: 0; Below
Headings should be surrounded by blank lines

(MD022, blanks-around-headings)


289-289: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


334-334: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


336-336: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


385-385: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


438-438: null
Fenced code blocks should be surrounded by blank lines

(MD031, blanks-around-fences)


1-1: null
First line in a file should be a top-level heading

(MD041, first-line-heading, first-line-h1)


527-527: null
Files should end with a single newline character

(MD047, single-trailing-newline)

Additional comments not posted (20)
client/v2/tx/flags.go (1)

37-53: LGTM!

The parseGasSetting function is well-implemented and adheres to the Uber Golang style guide. It provides a flexible way to manage gas settings in transaction processing by allowing both automatic and manual gas settings. The function correctly handles the three scenarios using a switch statement and returns appropriate values for each scenario. It also returns a clear error message if parsing fails.

The function enhances the transaction handling capabilities of the package and is a valuable addition to the codebase.

client/v2/internal/account/retriever.go (6)

1-24: LGTM!

The package declaration, imports, and constant declaration are all in order. The constant GRPCBlockHeightHeader is clearly named and follows the naming convention.


25-41: LGTM!

The interface declarations for Account and AccountRetriever are well-defined and provide a clear abstraction for account-related functionality. The methods have appropriate signatures and return types.


43-56: LGTM!

The accountRetriever struct and its constructor function NewAccountRetriever are well-implemented. The struct has appropriate fields, and the constructor function takes the necessary dependencies as parameters and returns a pointer to the accountRetriever instance.


58-62: LGTM!

The GetAccount method correctly implements the AccountRetriever interface by delegating the account retrieval to the GetAccountWithHeight method and discarding the block height.


97-103: LGTM!

The EnsureExists method correctly implements the AccountRetriever interface by using the GetAccount method to check if an account exists and returning an error if it does not.


105-116: LGTM!

The GetAccountNumberSequence method correctly implements the AccountRetriever interface by using the GetAccount method to retrieve the account and handling the case when the account is not found. The method returns the account number and sequence if the account is found, and zero values if it is not.

client/v2/tx/builder.go (13)

56-62: LGTM!

The NewBuilderProvider constructor function is implemented correctly, taking the necessary parameters and returning a new BuilderProvider instance.


65-67: LGTM!

The NewTxBuilder method is implemented correctly, utilizing the newTxBuilder function to create a new TxBuilder instance with the necessary fields from the BuilderProvider.


90-96: LGTM!

The newTxBuilder function is implemented correctly, taking the necessary parameters and returning a new txBuilder instance.


99-101: LGTM!

The GetTx method is implemented correctly, delegating the conversion of txBuilder messages to V2 and returning the resulting Tx by calling the getTx method.


103-154: LGTM!

The getTx method is implemented correctly, following these steps:

  1. Convert messages from V1 to V2.
  2. Create a new TxBody with the converted messages and other fields.
  3. Get the fee information using the getFee method.
  4. Create a new AuthInfo with the signer infos and fee.
  5. Marshal the TxBody and AuthInfo.
  6. Create a new TxRaw with the marshaled body, auth info, and signatures.
  7. Marshal the TxRaw.
  8. Decode the marshaled TxRaw using the decoder.
  9. Return a new wrappedTx with the decoded Tx and codec.

The error handling is in place, and the logic is sound.


159-184: LGTM!

The getFee method is implemented correctly, following these steps:

  1. Check if the granter field is set and convert it from bytes to string using the addressCodec.
  2. Check if the payer field is set and convert it from bytes to string using the addressCodec.
  3. Create a new apitx.Fee instance with the fees, gasLimit, payer, and granter fields.
  4. Return the apitx.Fee instance and any error that occurred during the conversion.

The error handling is in place, and the logic is sound.


187-200: LGTM!

The GetSigningTxData method is implemented correctly, following these steps:

  1. Call the getTx method to get the wrappedTx instance.
  2. Create a new signing.TxData instance with the necessary fields from the wrappedTx.
  3. Return the signing.TxData instance and any error that occurred during the getTx call.

The error handling is in place, and the logic is sound.


202-206: LGTM!

The SetMsgs method is implemented correctly, taking a variadic parameter of type transaction.Msg and assigning it to the msgs field of txBuilder. It returns nil as the error, indicating that the operation was successful.


209-211: LGTM!

The SetMemo method is implemented correctly, taking a string parameter memo and assigning it to the memo field of txBuilder.


214-216: LGTM!

The SetFeeAmount method is implemented correctly, taking a slice of base.Coin as a parameter and assigning it to the fees field of txBuilder.


219-221: LGTM!

The SetGasLimit method is implemented correctly, taking a uint64 parameter gasLimit and assigning it to the gasLimit field of txBuilder.


224-226: LGTM!

The SetTimeoutTimestamp method is implemented correctly, taking a time.Time parameter timeoutHeight and assigning it to the timeoutTimestamp field of txBuilder.


228-240: LGTM!

The SetFeePayer method is implemented correctly, following these steps:

  1. Check if the feePayer is an empty string and return nil if true.
  2. Convert the feePayer string to bytes using the addressCodec.
  3. Assign the converted bytes to the payer field of txBuilder.
  4. Return any error that occurred during the conversion.

The error handling is in place, and the logic is sound.

client/v2/tx/README.md Show resolved Hide resolved
Copy link
Contributor

coderabbitai bot commented Sep 19, 2024

@JulianToledano, I've paused the automatic reviews as requested.

Actions performed

Reviews paused.

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

Successfully merging this pull request may close these issues.

6 participants