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(pkg/user): Implement gas estimation in TxClient. Fix issue #4282 #4305

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

Conversation

VolodymyrBg
Copy link

Closes #4282

This PR implements gas estimation functionality in the TxClient when building transactions. The changes include:

  1. Added a new estimateAndSetGas method to handle gas estimation and setting in the transaction builder
  2. Updated the BroadcastTx method to use gas estimation by default when no explicit gas limit is provided
  3. Added comprehensive tests for the new gas estimation functionality

Key changes:

  • Gas estimation is now performed automatically when no explicit gas limit is provided
  • Existing behavior is preserved when gas limit is explicitly set through options
  • Added unit tests to verify both automatic gas estimation and explicit gas setting scenarios

The implementation ensures that:

  • Gas estimation is performed efficiently using the existing estimateGas method
  • Transaction fees are calculated correctly based on the estimated gas
  • The process is thread-safe with proper mutex locking
  • Existing functionality for custom gas limits is maintained through TxOptions

Testing:

  • Added new test cases in tx_client_test.go
  • Verified both automatic gas estimation and explicit gas setting scenarios
  • Ensured backward compatibility with existing transaction building process

Added verification of the initial total supply in TestGetCmdQueryAnnualProvisions.
This ensures that the total supply is exactly 500,000,000 utia before calculating
annual provisions, which is a critical assumption for the test.

Resolves TODO comment in x/mint/client/testutil/suite_test.go
@VolodymyrBg VolodymyrBg requested a review from a team as a code owner February 6, 2025 19:13
@VolodymyrBg VolodymyrBg requested review from rootulp and ninabarbakadze and removed request for a team February 6, 2025 19:13
Copy link
Contributor

coderabbitai bot commented Feb 6, 2025

📝 Walkthrough

Walkthrough

This pull request refactors the transaction broadcasting process within the TxClient. The original BroadcastTx method has been restructured to use a new helper method, estimateAndSetGas, which conditionally estimates and sets the gas limit based on provided options. In addition, the transaction tracking and error handling mechanisms have been updated. The PR also extends test coverage by adding tests for gas estimation and broadcasting, and it enhances the mint module’s tests by verifying the initial total supply.

Changes

File Change Summary
pkg/user/tx_client.go Refactored BroadcastTx: removed old implementation; introduced estimateAndSetGas for gas estimation; updated transaction tracking and error handling.
pkg/user/tx_client_test.go Added TestEstimateAndSetGas and TestBroadcastTxWithGasEstimation to validate gas estimation and transaction broadcasting functionalities.
x/mint/client/.../suite_test.go Added context and bank/types imports; updated TestGetCmdQueryAnnualProvisions to verify the initial total supply of "utia".

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant T as TxClient
    participant B as TxBuilder
    participant E as estimateAndSetGas
    participant TT as TxTracker

    C->>T: BroadcastTx(ctx, msgs, opts)
    T->>B: Create Transaction Builder
    alt Gas not provided
        T->>E: Estimate gas and set in TxBuilder
    else Gas provided
        T->>B: Use provided gas limit
    end
    T->>T: Sign transaction
    T->>TT: Update transaction tracking (tx hash, sequence, signer info)
    T-->>C: Return TxResponse
Loading

Assessment against linked issues

Objective Addressed Explanation
Use gas estimation when building the transaction (#4282)

Possibly related issues

Possibly related PRs

Suggested labels

WS: BestTxs, backport:v3.x

Suggested reviewers

  • rach-id
  • ninabarbakadze
  • cmwaters
  • evan-forbes

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 4

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dff4322 and 6566344.

📒 Files selected for processing (3)
  • pkg/user/tx_client.go (1 hunks)
  • pkg/user/tx_client_test.go (1 hunks)
  • x/mint/client/testutil/suite_test.go (3 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
pkg/user/tx_client_test.go

387-387: undefined: sdk.NewTestMsg

(typecheck)


393-393: undefined: DefaultTxOptions

(typecheck)


403-403: undefined: DefaultTxOptions

(typecheck)


415-415: undefined: sdk.NewTestMsg

(typecheck)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Summary
🔇 Additional comments (3)
pkg/user/tx_client.go (1)

313-330: Looks solid!
The gas estimation logic is straightforward and aligns with best practices. By checking if gas is explicitly set, you avoid redundant estimation, and you handle errors clearly.

x/mint/client/testutil/suite_test.go (2)

4-4: Import additions look good.
Bringing in "context" and "github.com/cosmos/cosmos-sdk/x/bank/types" is valid for the subsequent usage.

Also applies to: 20-20


89-95: Initial total supply test is correct.
Verifying “500,000,000 utia” ensures a solid baseline for your mint module tests. This validation helps catch unexpected supply changes early.

Comment on lines +332 to 377
func (client *TxClient) BroadcastTx(ctx context.Context, msgs []sdktypes.Msg, opts ...TxOption) (*sdktypes.TxResponse, error) {
client.mtx.Lock()
defer client.mtx.Unlock()

txBuilder, err := client.signer.txBuilder(msgs, opts...)
if err != nil {
return nil, err
}

hasUserSetFee := false
for _, coin := range txBuilder.GetTx().GetFee() {
if coin.Denom == appconsts.BondDenom {
hasUserSetFee = true
break
}
// Get options for gas estimation
txOpts := DefaultTxOptions()
for _, opt := range opts {
opt(txOpts)
}

gasLimit := txBuilder.GetTx().GetGas()
if gasLimit == 0 {
if !hasUserSetFee {
// add at least 1utia as fee to builder as it affects gas calculation.
txBuilder.SetFeeAmount(sdktypes.NewCoins(sdktypes.NewCoin(appconsts.BondDenom, sdktypes.NewInt(1))))
}
gasLimit, err = client.estimateGas(ctx, txBuilder)
if err != nil {
return nil, err
}
txBuilder.SetGasLimit(gasLimit)
// Estimate and set gas if not explicitly provided
if err := client.estimateAndSetGas(ctx, txBuilder, txOpts); err != nil {
return nil, err
}

if !hasUserSetFee {
fee := int64(math.Ceil(appconsts.DefaultMinGasPrice * float64(gasLimit)))
txBuilder.SetFeeAmount(sdktypes.NewCoins(sdktypes.NewCoin(appconsts.BondDenom, sdktypes.NewInt(fee))))
// Sign the transaction
signer, sequence, err := client.signer.signTransaction(txBuilder)
if err != nil {
return nil, err
}

account, _, err = client.signer.signTransaction(txBuilder)
txBytes, err := client.signer.EncodeTx(txBuilder.GetTx())
if err != nil {
return nil, err
}

txBytes, err := client.signer.EncodeTx(txBuilder.GetTx())
resp, err := client.broadcastTx(ctx, txBytes, signer)
if err != nil {
return nil, err
}

return client.broadcastTx(ctx, txBytes, account)
if resp.TxHash != "" {
client.txTracker[resp.TxHash] = txInfo{
sequence: sequence,
signer: signer,
timestamp: time.Now(),
}
}

return resp, 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

Undefined function 'DefaultTxOptions()' breaks builds.
It appears that “DefaultTxOptions()” is referenced but not declared anywhere, which will cause a compilation error. Ensure that the function is defined or remove these calls.

Below is a possible fix if you do not need a dedicated “DefaultTxOptions” function. You can remove references and handle options inline:

-  txOpts := DefaultTxOptions()
-  for _, opt := range opts {
-    opt(txOpts)
-  }
-  if err := client.estimateAndSetGas(ctx, txBuilder, txOpts); err != nil {
+  txOpts := &TxOptions{}
+  for _, opt := range opts {
+    opt(txOpts)
+  }
+  if err := client.estimateAndSetGas(ctx, txBuilder, txOpts); err != nil {
     return nil, err
  }
📝 Committable suggestion

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

Suggested change
func (client *TxClient) BroadcastTx(ctx context.Context, msgs []sdktypes.Msg, opts ...TxOption) (*sdktypes.TxResponse, error) {
client.mtx.Lock()
defer client.mtx.Unlock()
txBuilder, err := client.signer.txBuilder(msgs, opts...)
if err != nil {
return nil, err
}
hasUserSetFee := false
for _, coin := range txBuilder.GetTx().GetFee() {
if coin.Denom == appconsts.BondDenom {
hasUserSetFee = true
break
}
// Get options for gas estimation
txOpts := DefaultTxOptions()
for _, opt := range opts {
opt(txOpts)
}
gasLimit := txBuilder.GetTx().GetGas()
if gasLimit == 0 {
if !hasUserSetFee {
// add at least 1utia as fee to builder as it affects gas calculation.
txBuilder.SetFeeAmount(sdktypes.NewCoins(sdktypes.NewCoin(appconsts.BondDenom, sdktypes.NewInt(1))))
}
gasLimit, err = client.estimateGas(ctx, txBuilder)
if err != nil {
return nil, err
}
txBuilder.SetGasLimit(gasLimit)
// Estimate and set gas if not explicitly provided
if err := client.estimateAndSetGas(ctx, txBuilder, txOpts); err != nil {
return nil, err
}
if !hasUserSetFee {
fee := int64(math.Ceil(appconsts.DefaultMinGasPrice * float64(gasLimit)))
txBuilder.SetFeeAmount(sdktypes.NewCoins(sdktypes.NewCoin(appconsts.BondDenom, sdktypes.NewInt(fee))))
// Sign the transaction
signer, sequence, err := client.signer.signTransaction(txBuilder)
if err != nil {
return nil, err
}
account, _, err = client.signer.signTransaction(txBuilder)
txBytes, err := client.signer.EncodeTx(txBuilder.GetTx())
if err != nil {
return nil, err
}
txBytes, err := client.signer.EncodeTx(txBuilder.GetTx())
resp, err := client.broadcastTx(ctx, txBytes, signer)
if err != nil {
return nil, err
}
return client.broadcastTx(ctx, txBytes, account)
if resp.TxHash != "" {
client.txTracker[resp.TxHash] = txInfo{
sequence: sequence,
signer: signer,
timestamp: time.Now(),
}
}
return resp, nil
}
func (client *TxClient) BroadcastTx(ctx context.Context, msgs []sdktypes.Msg, opts ...TxOption) (*sdktypes.TxResponse, error) {
client.mtx.Lock()
defer client.mtx.Unlock()
txBuilder, err := client.signer.txBuilder(msgs, opts...)
if err != nil {
return nil, err
}
// Get options for gas estimation
txOpts := &TxOptions{}
for _, opt := range opts {
opt(txOpts)
}
// Estimate and set gas if not explicitly provided
if err := client.estimateAndSetGas(ctx, txBuilder, txOpts); err != nil {
return nil, err
}
// Sign the transaction
signer, sequence, err := client.signer.signTransaction(txBuilder)
if err != nil {
return nil, err
}
txBytes, err := client.signer.EncodeTx(txBuilder.GetTx())
if err != nil {
return nil, err
}
resp, err := client.broadcastTx(ctx, txBytes, signer)
if err != nil {
return nil, err
}
if resp.TxHash != "" {
client.txTracker[resp.TxHash] = txInfo{
sequence: sequence,
signer: signer,
timestamp: time.Now(),
}
}
return resp, nil
}

ctx := context.Background()

// Create a test message
msg := sdk.NewTestMsg()
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

Calls to 'sdk.NewTestMsg()' are undefined.
The static analysis flags that “sdk.NewTestMsg()” does not exist, causing a build error. Consider defining it or removing these references.

If you intend to create a minimal test message, define it in your tests or switch to a known cosmos type. For instance:

- msg := sdk.NewTestMsg()
+ msg := bank.NewMsgSend(
+   s.txClient.DefaultAddress(),
+   s.txClient.DefaultAddress(),
+   sdk.NewCoins(sdk.NewInt64Coin("utia", 1)),
+ )

Also applies to: 415-415

🧰 Tools
🪛 golangci-lint (1.62.2)

387-387: undefined: sdk.NewTestMsg

(typecheck)

txBuilder, err := s.txClient.signer.txBuilder([]sdk.Msg{msg})
s.Require().NoError(err)

opts := DefaultTxOptions()
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

'DefaultTxOptions()' is not defined.
Similar to the main code, these calls to “DefaultTxOptions()” will result in a compile error.

You can remove them or properly define a helper function. For example:

-func DefaultTxOptions() *TxOptions {
-   return &TxOptions{}
-}

Also applies to: 403-403

🧰 Tools
🪛 golangci-lint (1.62.2)

393-393: undefined: DefaultTxOptions

(typecheck)


// Test broadcasting with explicit gas setting
predefinedGas := uint64(100000)
resp, err = s.txClient.BroadcastTx(ctx, []sdk.Msg{msg}, WithGas(predefinedGas))
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

'WithGas' function is not defined.
The call “WithGas(predefinedGas)” does not match any known function, resulting in a compile error. If you intended to set gas, consider using “SetGasLimit()” or define “WithGas()” appropriately.

Example replacement:

- resp, err = s.txClient.BroadcastTx(ctx, []sdk.Msg{msg}, WithGas(predefinedGas))
+ resp, err = s.txClient.BroadcastTx(ctx, []sdk.Msg{msg}, user.SetGasLimit(predefinedGas))
📝 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
resp, err = s.txClient.BroadcastTx(ctx, []sdk.Msg{msg}, WithGas(predefinedGas))
resp, err = s.txClient.BroadcastTx(ctx, []sdk.Msg{msg}, user.SetGasLimit(predefinedGas))

Copy link
Member

@ninabarbakadze ninabarbakadze left a comment

Choose a reason for hiding this comment

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

Thanks! Let's fix CI and I'll take a look

@vgonkivs
Copy link
Member

vgonkivs commented Feb 7, 2025

Thanks for your contribution, @VolodymyrBg. Unfortunately, this is not exactly what I meant in my comment. Let me clarify.

The current estimation process is inefficient because it relies on SimulateTx, which includes a round trip. To improve efficiency, the app team has implemented the GasEstimator service. This service connects to a third-party estimator that provides GasPrice and Gas.

By default, every consensus node runs this service. However, if the user wants to query another node, they should be able to provide a gRPC connection. Only if the GasEstimator fails should we fall back to SimulateTx as the default solution.

Additionally, the user should have the option to specify a maximum gas price (by default, minGasPrice * 100). If the calculated gas price exceeds this limit, the transaction should not be executed.

Question: What is TxOptions? I couldn't find any references to it in your code.

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.

use the gas estimation when building the transaction
3 participants