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

automate gas #25

Draft
wants to merge 6 commits into
base: main
Choose a base branch
from
Draft

automate gas #25

wants to merge 6 commits into from

Conversation

faddat
Copy link
Collaborator

@faddat faddat commented Oct 29, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced gas estimation logic with a 20% buffer for transactions.
    • New functions for handling balance adjustments and compliance checks.
  • Bug Fixes

    • Improved error handling for transaction failures, including specific conditions for gas limit adjustments.
  • Configuration Changes

    • Updated message type from "bank_send" to "store_code" in configuration.
    • Introduced a new gas limit parameter set to 75,000,000.
  • Documentation

    • Added a new field Limit to the GasConfig struct for better configuration management.

Copy link
Contributor

coderabbitai bot commented Oct 29, 2024

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The changes in this pull request primarily enhance transaction processing and gas estimation within the application. Modifications include updates to the BuildAndSignTransaction function to incorporate a 20% buffer in gas limit calculations, the introduction of new functions for handling balance adjustments and transaction validations in main.go, and updates to configuration parameters in nodes.toml. Additionally, a new field for gas limits is added to the GasConfig struct in types/types.go, refining how transaction parameters are managed.

Changes

File Change Summary
broadcast/transaction.go Modified BuildAndSignTransaction to include a 20% buffer on gas limit calculations and added conditional gas limit checks.
main.go Added handleBalanceAdjustment and shouldProceedWithBalances functions; enhanced error handling in TransferFunds for transaction failures.
nodes.toml Updated msg_type from "bank_send" to "store_code" and added limit parameter set to 75000000 in the [gas] section.
types/types.go Added new field Limit int64 \toml:"limit"`toGasConfig` struct.

Possibly related PRs

  • add more code for grpc broadcast #23: Significant modifications to the broadcast package, including the removal of the SendTransactionViaRPC function, which relates to transaction handling and gas estimation.
  • use 10 positions #24: Introduction of new parameters for managing multiple account positions and enhancements to transaction broadcasting with gRPC support, relevant to transaction handling improvements.

🐇 In the meadow where bunnies play,
New gas limits brighten the day!
With balance checks and flows refined,
Our transactions now are well-aligned.
Hops of joy, we celebrate,
For smoother paths, we elevate! 🎉


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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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: 3

🧹 Outside diff range and nitpick comments (2)
broadcast/transaction.go (1)

77-93: The gas estimation logic needs additional safeguards and documentation.

While the addition of a gas buffer is a good practice to prevent transaction failures, consider the following improvements:

  1. Add validation for minimum and maximum gas limits
  2. Document the rationale for the 20% buffer choice
  3. Consider making the buffer percentage configurable

Here's a suggested improvement:

 	// Estimate gas limit with a buffer
 	txSize := len(msg.String())
 	baseGas := txParams.Config.BaseGas
 	gasPerByte := txParams.Config.GasPerByte
 
-	// Calculate estimated gas
+	// Calculate estimated gas based on transaction size and base requirements
 	estimatedGas := uint64(int64(txSize)*gasPerByte + baseGas)
 
-	// Add a buffer (e.g., 20%)
-	buffer := uint64(float64(estimatedGas) * 0.2)
+	// Add 20% buffer to account for potential variations in execution cost
+	buffer := uint64(float64(estimatedGas) * txParams.Config.Gas.BufferPercent) // TODO: Add BufferPercent to GasConfig
 	gasLimit := estimatedGas + buffer
 
+	// Ensure gas limit stays within safe bounds
+	minGasLimit := uint64(50_000)    // Adjust based on your chain's requirements
+	maxGasLimit := uint64(2_000_000) // Adjust based on your chain's block gas limit
+
 	if txParams.Config.Gas.Limit > 0 {
-		txBuilder.SetGasLimit(uint64(txParams.Config.Gas.Limit))
+		gasLimit = uint64(txParams.Config.Gas.Limit)
 	}
-	else {
-		txBuilder.SetGasLimit(gasLimit)
+
+	// Validate final gas limit
+	if gasLimit < minGasLimit {
+		gasLimit = minGasLimit
+	} else if gasLimit > maxGasLimit {
+		gasLimit = maxGasLimit
 	}
+	txBuilder.SetGasLimit(gasLimit)
main.go (1)

Line range hint 392-415: Consider adding unit tests for handleBalanceAdjustment and shouldProceedWithBalances

Adding unit tests for these new functions will help ensure they behave correctly under various conditions and improve code reliability.

🧰 Tools
🪛 GitHub Check: lint

[failure] 384-384:
SA4006: this value of resp is never used (staticcheck)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6b838dc and e66822b.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • broadcast/transaction.go (1 hunks)
  • main.go (1 hunks)
  • nodes.toml (2 hunks)
  • types/types.go (1 hunks)
🧰 Additional context used
🪛 GitHub Check: lint
main.go

[failure] 384-384:
SA4006: this value of resp is never used (staticcheck)

🔇 Additional comments (4)
nodes.toml (2)

22-22: Verify gas settings for contract deployment

Changing msg_type from "bank_send" to "store_code" significantly increases gas consumption. Contract deployment typically requires much more gas than token transfers.

Consider reviewing and adjusting the following gas-related parameters for contract deployment:

  • base_gas (currently 200000)
  • gas_per_byte (currently 100)

17-17: Review positions count for contract deployment

With the change to contract deployment transactions, verify if using 50 positions is intentional and won't cause excessive resource consumption or network congestion.

Run this script to check for any existing contract deployment patterns or limits:

✅ Verification successful

Let me gather more information about the positions limit and its usage.


Let me check how the positions value is used in the context of contract deployment.


Based on the gathered information, I can now provide the final response:

50 positions is within safe limits for contract deployment

The current setting of 50 positions is well within the codebase's defined maximum limit of 100 positions. The value is used for deriving accounts from the seed phrase and not directly related to contract deployment resource consumption. The store_code transaction itself follows standard CosmWasm patterns without any position-specific amplification.

  • Maximum allowed positions: 100 (defined in main.go)
  • Current setting: 50 positions (nodes.toml)
  • Usage: Account derivation from seed phrase
  • Impact: No direct correlation with contract deployment resource usage
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for contract deployment configurations and limits
rg -A 5 "store_code|positions.*=.*[0-9]+" 

Length of output: 1541


Script:

#!/bin/bash
# Check for MaxPositions constant and related code
rg -A 2 "MaxPositions.*=|const.*MaxPositions"

# Look for any documentation about positions usage
fd README.md --exec cat {}

Length of output: 4281


Script:

#!/bin/bash
# Check how positions are used in relation to contract deployment
rg -B 3 -A 3 "positions.*=|positions.*:=|positions.*<-"

# Look for store_code message construction
ast-grep --pattern 'CreateStoreCodeMsg($$$)'

Length of output: 846

broadcast/transaction.go (1)

77-93: Verify gas configuration usage across the codebase.

Let's ensure the gas configuration changes are consistently applied across the codebase.

✅ Verification successful

Let me try a different search strategy to gather more information about gas-related code.


Gas calculation changes are properly isolated and consistent

The verification shows that the gas calculation logic is centralized in broadcast/transaction.go and properly integrated with the configuration system:

  • The gas estimation logic is only implemented in broadcast/transaction.go
  • The gas configuration is properly structured in types/types.go
  • Gas limit adjustments in main.go work with the same configuration system
  • No test files are impacted as they don't contain gas-specific test cases

The changes are well-contained and maintain consistency with the existing gas handling across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for gas-related configurations and usages

# Check for gas limit configurations
echo "Checking for gas limit configurations..."
rg -l "Gas.*Limit|gas.*limit" --type toml

# Check for other gas estimation implementations
echo "Checking for other gas estimation code..."
ast-grep --pattern 'SetGasLimit($$$)'

# Check for potential test files that might need updating
echo "Checking for related test files..."
fd -e go -e toml test.*gas

Length of output: 377


Script:

#!/bin/bash
# Search for gas-related code with more context
echo "Searching for gas configuration structs and types..."
rg -A 5 "type.*Gas" --type go

echo "Searching for gas calculation and estimation logic..."
rg -A 5 "gas.*estimate|estimate.*gas" --type go -i

echo "Searching for gas limit setter usage..."
rg -A 2 "SetGasLimit|GasLimit" --type go

echo "Looking for gas-related test files..."
rg -l "TestGas|test.*gas" --type go

Length of output: 2363

types/types.go (1)

165-165: Consider enhancing documentation and validation for the new Limit field.

While the comment indicates this field is "to be set entirely by software", it would be helpful to:

  1. Document the relationship between this field and the other gas thresholds (Zero, Low, Medium, High)
  2. Clarify when and how this limit is set by the software
  3. Consider adding validation to ensure the limit is positive and within reasonable bounds

Consider updating the comment to be more descriptive:

-	Limit     int64 `toml:"limit"` // to be set entirely by software
+	Limit     int64 `toml:"limit"` // Dynamic gas limit calculated by software based on transaction complexity. Must be positive and typically ranges between Low and High gas values.

Let's verify how this limit is being used:

✅ Verification successful

Let me gather more context about the gas limit usage with a different search strategy.


Based on the search results, I can now provide a final response as we have sufficient context about how the Limit field is being used in the codebase.

The Limit field implementation is well-justified and properly used

The code shows that the Limit field serves as a dynamic gas limit with proper handling:

  • It's used in transaction broadcasting logic with fallback to calculated values
  • Has proper validation in broadcast/transaction.go where if txParams.Config.Gas.Limit > 0 ensures positive values
  • Integrates with automatic gas estimation that includes a 20% safety buffer
  • Can be adjusted dynamically as shown in main.go for transaction retry scenarios

The current implementation and documentation are sufficient given that:

  1. The field is only set programmatically in well-defined scenarios
  2. Has implicit bounds through the retry mechanism (maxBlockGas - buffer)
  3. Integrates cleanly with the existing gas estimation logic
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of GasConfig.Limit to understand its context
rg -l "GasConfig" | xargs rg "Limit" -B 2 -A 2

# Look for any validation of this field
ast-grep --pattern 'if $_.Limit $_ {
  $$$
}'

Length of output: 388


Script:

#!/bin/bash
# Search for any references to gas limit in the codebase
rg -B 3 -A 3 "gas.*limit" -i

# Look for functions that might be setting this limit
ast-grep --pattern 'func $_($_) {
  $$$
  $_.Limit = $_
  $$$
}'

# Check for any gas-related calculations
rg -B 3 -A 3 "gas.*calc" -i

Length of output: 2280

main.go Outdated
Comment on lines 375 to 390
// Assuming you are inside the loop where you handle the transaction response
if resp.Code == 41 {
fmt.Printf("Transaction failed with code %d: %s\n", resp.Code, resp.RawLog)
maxBlockGas := 75000000
newGasLimit := maxBlockGas - 1000000
txParams.Config.Gas.Limit = int64(newGasLimit)
fmt.Printf("Reducing gas limit to %d and retrying...\n", newGasLimit)

// Retry sending the transaction
resp, _, err = broadcast.SendTransactionViaGRPC(ctx, txParams, sequence, grpcClient)
if err != nil {
return fmt.Errorf("failed to send transaction: %v", err)
}
continue
}

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

Ensure thread safety when modifying shared configuration

The modification of txParams.Config.Gas.Limit within a goroutine could lead to race conditions if txParams.Config is shared across multiple goroutines.

Consider copying the txParams or ensuring that each goroutine has its own instance to prevent concurrent access issues.

🧰 Tools
🪛 GitHub Check: lint

[failure] 384-384:
SA4006: this value of resp is never used (staticcheck)


🛠️ Refactor suggestion

Optimize gas limit adjustment logic

The current logic reduces the gas limit to maxBlockGas - 1,000,000 upon encountering an error with code 41. Consider making the decrement value configurable or proportional to the previous gas limit to enhance adaptability across different network conditions.

Apply this diff to adjust the gas limit dynamically:

 maxBlockGas := 75000000
-newGasLimit := maxBlockGas - 1000000
+decrement := int64(1000000) // Make this value configurable if needed
+newGasLimit := txParams.Config.Gas.Limit - decrement
 if newGasLimit <= 0 {
     return fmt.Errorf("gas limit cannot be reduced further")
 }
 txParams.Config.Gas.Limit = newGasLimit

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 GitHub Check: lint

[failure] 384-384:
SA4006: this value of resp is never used (staticcheck)

main.go Outdated
Comment on lines 384 to 388
resp, _, err = broadcast.SendTransactionViaGRPC(ctx, txParams, sequence, grpcClient)
if err != nil {
return fmt.Errorf("failed to send transaction: %v", err)
}
continue
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

Handle the response after retrying the transaction

After retrying the transaction on line 384, the code reassigns resp but does not check the new response's Code. This can lead to unhandled transaction failures or missed errors.

Apply this diff to handle the response properly:

 resp, _, err = broadcast.SendTransactionViaGRPC(ctx, txParams, sequence, grpcClient)
-if err != nil {
+if err != nil || resp.Code != 0 {
     return fmt.Errorf("failed to send transaction: %v", err)
 }
+if resp.Code != 0 {
+    fmt.Printf("Transaction failed with code %d: %s\n", resp.Code, resp.RawLog)
+    continue
+}

Committable suggestion was skipped due to low confidence.

🧰 Tools
🪛 GitHub Check: lint

[failure] 384-384:
SA4006: this value of resp is never used (staticcheck)

@faddat faddat marked this pull request as draft October 29, 2024 08:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant