Skip to content

Enhance transaction broadcasting with advanced node and account management strategies#48

Open
faddat wants to merge 1 commit intomainfrom
faddat/dirty2
Open

Enhance transaction broadcasting with advanced node and account management strategies#48
faddat wants to merge 1 commit intomainfrom
faddat/dirty2

Conversation

@faddat
Copy link
Collaborator

@faddat faddat commented Mar 5, 2025

  • Implement per-account node assignment and locking mechanism
  • Add sophisticated gas strategy tracking with node-specific minimum gas price detection
  • Improve transaction signing and encoding for Cosmos SDK v0.50.x compatibility
  • Optimize gas limit and fee calculation with adaptive strategies
  • Add configuration for AtomOne chain with comprehensive node registry

Summary by CodeRabbit

  • New Features

    • Added support for the AtomOne network with customizable configuration, enhancing connectivity and gas settings.
    • Introduced dynamic gas fee tracking for more precise fee calculation during transactions.
  • Refactor

    • Streamlined transaction construction, signing, and broadcasting to improve processing reliability.
    • Enhanced logging for clearer transaction insights and improved synchronization across operations.

…ement strategies

- Implement per-account node assignment and locking mechanism
- Add sophisticated gas strategy tracking with node-specific minimum gas price detection
- Improve transaction signing and encoding for Cosmos SDK v0.50.x compatibility
- Optimize gas limit and fee calculation with adaptive strategies
- Add configuration for AtomOne chain with comprehensive node registry
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 5, 2025

Walkthrough

This pull request enhances the transaction broadcasting workflow and gas management in the system. It introduces global synchronization constructs and a node-assignment function to manage account-node relationships, refines the transaction building and signing process by using a more specific TxConfig, and improves gas strategy tracking with updates to gas-related structures and methods. A new configuration file for the AtomOne network has been added, and error handling in chain tests has been simplified by removing balance adjustment checks.

Changes

File(s) Change Summary
broadcast/broadcast.go Added global variables for account locking and node mapping; implemented assignNodeToAccount and updated the Loop function for synchronized node assignment and logging enhancements.
broadcast/gas_strategy.go Updated NodeGasCapabilities to include MinGasPrice; modified RecordTransactionResult to accept additional parameters for fee calculations; added GetMinGasPrice method to track gas price adjustments.
broadcast/grpc.go, broadcast/rpc.go, broadcast/transaction.go Updated transaction building: switched to using encodingConfig.TxConfig for the BuildAndSignTransaction function, restructured transaction builder initialization, refined gas limit and fee calculations, and streamlined message and signature handling.
configurations/atomone/nodes.toml Introduced a new configuration file detailing AtomOne network parameters, including chain ID, gas settings, node endpoints, and message defaults.
modes/registry/registry.go Removed error handling for balance adjustments in runChainTest, eliminating the call to checkAndAdjustBalances.

Sequence Diagram(s)

sequenceDiagram
    participant L as Broadcast Loop
    participant A as assignNodeToAccount
    participant T as BuildAndSignTransaction
    participant G as GasStrategyManager
    participant N as Node
    L->>A: Request node assignment (account address, node URL)
    A-->>L: Return node assignment (if not previously assigned)
    L->>T: Build and sign transaction using TxConfig
    T-->>L: Return signed transaction along with gas/fee data
    L->>G: Record transaction result (gas used, txGasLimit, requiredFee)
    G-->>L: Update MinGasPrice if necessary
    L->>N: Broadcast transaction to node
Loading

Possibly related PRs

  • faddat/seqnum price #44: Both this PR and the retrieved one modify the BuildAndSignTransaction function in broadcast/transaction.go, linking concurrency control improvements with node-specific fee calculation adjustments.

Poem

I'm a rabbit hopping with glee,
Through changes in concurrency and fee,
Assigning nodes with a gentle tap,
Transactions built with a streamlined map,
Gas prices updated, smooth and free,
A blockchain dance for you and me!
🐰🚀

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

Error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)
Failed executing command with error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24)

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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 generate docstrings to generate docstrings for this 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: 1

🧹 Nitpick comments (8)
broadcast/broadcast.go (3)

19-24: Consider verifying the usage pattern of global concurrency maps and locks.
A sync.Map is concurrency-safe for loads/stores, but locking it externally can restrict parallel reads/writes. If atomic check-then-set logic is needed, ensure it won’t introduce performance bottlenecks or memory growth over time.


71-82: Evaluate consolidating concurrency control with atomic operations.
Although locking around a sync.Map ensures atomic assignment, you could simplify this with LoadOrStore, removing the extra mutex to handle the check-then-set pattern.


151-155: Ensure fallback for missing or invalid calculated_gas_amount.
The same concern applies here in the failure path. If the key is not present, it will default to 0 without warning.

broadcast/gas_strategy.go (4)

15-15: Doc comment clarity.
Consider briefly mentioning MinGasPrice in the comment for quicker reference.


20-20: Consider using decimal-based data type.
Storing gas price as float64 can introduce rounding issues. Using an SDK Dec-like type or an integer in micro-units might be more reliable.

-type NodeGasCapabilities struct {
-  ...
-  MinGasPrice       float64
-  ...
+type NodeGasCapabilities struct {
+  ...
+  MinGasPrice       sdk.Dec // or a similar fixed-point representation
+  ...
}

32-32: Optional: add back a brief comment.
Retaining a short description of the purpose of RecentGasValues may aid newcomers.


139-150: Logic for updating MinGasPrice.
This logic correctly updates the node’s min gas price on detecting “insufficient fee”. If multi-denom support is ever needed, consider capturing different denoms instead of filtering only uatone.

broadcast/transaction.go (1)

629-637: Fee calculation uses floating point.
Multiplying gasPrice * float64(gasLimit) could be risky for large values or high precision. Consider using sdk.Dec or integer-based micro-denoms to avoid floating inaccuracies.

- feeAmount := int64(gasPrice * float64(gasLimit))
+ decGasPrice := sdk.NewDecFromInt(sdk.NewInt(int64(gasPrice * 1_000_000))).Quo(sdk.NewDec(1_000_000))
+ decGasLimit := sdk.NewDec(int64(gasLimit))
+ feeAmountDec := decGasPrice.Mul(decGasLimit)
+ feeAmount := feeAmountDec.RoundInt64()
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b5a3f34 and 8cf5ac3.

⛔ Files ignored due to path filters (1)
  • configurations/atomone/peerdiscovery.log is excluded by !**/*.log
📒 Files selected for processing (7)
  • broadcast/broadcast.go (7 hunks)
  • broadcast/gas_strategy.go (8 hunks)
  • broadcast/grpc.go (1 hunks)
  • broadcast/rpc.go (1 hunks)
  • broadcast/transaction.go (4 hunks)
  • configurations/atomone/nodes.toml (1 hunks)
  • modes/registry/registry.go (1 hunks)
✅ Files skipped from review due to trivial changes (2)
  • configurations/atomone/nodes.toml
  • modes/registry/registry.go
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (go)
🔇 Additional comments (20)
broadcast/rpc.go (1)

41-41: Switching to TxConfig is appropriate and consistent.
This ensures that the builder and signer use the correct transaction configuration, aligning with other changes in this PR.

broadcast/grpc.go (1)

39-39: Consistent usage of TxConfig
Similar to the RPC approach, passing encodingConfig.TxConfig clarifies which configuration is being used for building and signing the transaction.

broadcast/broadcast.go (5)

6-6: Import of sync is appropriate.
This is required for the concurrency primitives introduced below.


95-108: Lock-based serialization for per-account operations is valid.
This ensures that only one goroutine at a time broadcasts transactions for a specific account, preventing sequence collisions. The approach using LoadOrStore(txParams.AcctAddress, &sync.Mutex{}) is a straightforward solution.


110-111: Logging improvements look good.
Providing node information is helpful for debugging.


135-137: Confirm error code usage for sequence mismatch.
Ensure that resp.Code == 32 actually corresponds to sequence mismatch on all target chains. If it differs, this check could lead to misleading error handling.

Would you like a script to search for references to code 32 in the codebase or relevant docs to confirm its usage?


163-167: Check for missing gas parameter on success path.
Just like the failure path, confirm that calculated_gas_amount is reliably set to avoid unexpected zero values in your gas strategy methods.

broadcast/gas_strategy.go (4)

6-6: Import usage looks fine.
This import is necessary for checking substrings (e.g., “insufficient fee”) in the failure message.


11-11: Import usage validated.
This import is required to call lib.ExtractRequiredFee(). No concerns.


79-90: Extended transaction result tracking.
The added parameters txGasLimit and requiredFee expand how transaction data is tracked. Ensure you handle empty or non-fee-related errors gracefully, since requiredFee might not always have "insufficient fee" content.


277-281: Method correctness.
This conveniently exposes the node’s minimum gas price. If adopting an sdk.Dec type, ensure the return type stays consistent.

broadcast/transaction.go (9)

14-24: New imports usage.
These references to bankmodule, client, and authsigning align well with the updated transaction-building flow.


278-278: SignerData usage.
Using authsigning.SignerData with SIGN_MODE_DIRECT is correct for SDK v0.50.x signing.


597-600: Function doc improvement.
The revised doc comment clearly reflects the new behavior of building and signing a transaction with custom encoding.


603-610: Gas limit fallback for multisend.
Fetching a pre-calculated gas in MsgParams is useful for large multisends. The fallback of 200000 may still be too low for heavier scenarios; just verify or incorporate higher defaults if needed.


615-627: Minimum gas price adjustment logic.
Overriding the local gasPrice with GetMinGasPrice is sensible. Double-check you’re not missing scenarios where the config’s Gas.Price is higher than the node’s minimum.


639-677: Switch block for message creation.
Leveraging bankmodule.CreateBankSendMsg and a distributor for bank_multisend is consistent. Validate the type assertion for the distributor in tests.


679-683: Memo and timeout height.
This is straightforward and matches typical Cosmos SDK usage.


686-720: Simplified signing approach.
Creating an empty signature first, then encoding & signing the full tx is a known pattern for v0.50.x. Double-check that you’re signing the canonical bytes matching SIGN_MODE_DIRECT.


723-723: Final transaction encoding.
Re-encoding the builder’s final transaction is the standard approach. No issues spotted.

Comment on lines +146 to 148
GetGasStrategyManager().RecordTransactionResult(
txParams.NodeURL, success, 0, txParams.MsgType, txParams.MsgParams["calculated_gas_amount"].(uint64), err.Error())
continue
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Validate key existence before casting to uint64.
Casting txParams.MsgParams["calculated_gas_amount"] to uint64 without checking might cause a panic if the key is missing or if the type is different.


🏁 Script executed:

#!/bin/bash
# This script searches for potential calls to `RecordTransactionResult` where
# "calculated_gas_amount" may not be set in `txParams.MsgParams`.

rg -A 5 "RecordTransactionResult" 

Length of output: 1886


Action: Validate key existence of "calculated_gas_amount" before type casting

Before calling RecordTransactionResult, please ensure that the txParams.MsgParams map actually contains the calculated_gas_amount key and that its value is of type uint64. Directly casting without this check can lead to a panic if the key is missing or holds an unexpected type.

For example, update:

GetGasStrategyManager().RecordTransactionResult(
	txParams.NodeURL, success, 0, txParams.MsgType, txParams.MsgParams["calculated_gas_amount"].(uint64), err.Error())
continue

to something like:

gasAmount, ok := txParams.MsgParams["calculated_gas_amount"].(uint64)
if !ok {
	// Handle the error case - either assign a default value or log the error
	// For example:
	errMsg := "calculated_gas_amount missing or not a uint64"
	GetGasStrategyManager().RecordTransactionResult(
		txParams.NodeURL, success, 0, txParams.MsgType, 0, errMsg)
	continue
}
GetGasStrategyManager().RecordTransactionResult(
	txParams.NodeURL, success, 0, txParams.MsgType, gasAmount, err.Error())
continue

This change will make the code more resilient against potential panics due to unexpected input.

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