-
Notifications
You must be signed in to change notification settings - Fork 363
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
base: main
Are you sure you want to change the base?
Conversation
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
📝 WalkthroughWalkthroughThis 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
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
Assessment against linked issues
Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Tip 🌐 Web search-backed reviews and chat
✨ Finishing Touches
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
Documentation and Community
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
📜 Review details
Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 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.
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 | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
'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)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
'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.
resp, err = s.txClient.BroadcastTx(ctx, []sdk.Msg{msg}, WithGas(predefinedGas)) | |
resp, err = s.txClient.BroadcastTx(ctx, []sdk.Msg{msg}, user.SetGasLimit(predefinedGas)) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks! Let's fix CI and I'll take a look
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. |
Closes #4282
This PR implements gas estimation functionality in the TxClient when building transactions. The changes include:
estimateAndSetGas
method to handle gas estimation and setting in the transaction builderBroadcastTx
method to use gas estimation by default when no explicit gas limit is providedKey changes:
The implementation ensures that:
estimateGas
methodTesting:
tx_client_test.go