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

fix: transfer bridge fee #878

Merged
merged 1 commit into from
Jan 8, 2025
Merged

fix: transfer bridge fee #878

merged 1 commit into from
Jan 8, 2025

Conversation

zakir-code
Copy link
Contributor

@zakir-code zakir-code commented Jan 8, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced enhanced bridge fee management with new validation and transfer mechanisms
    • Added a dedicated bridge fee collector address
  • Improvements

    • Streamlined bridge call fee handling logic
    • Simplified quote validation and fee transfer processes
    • Improved naming conventions for bridge-related functionalities
  • Changes

    • Renamed several methods related to bridge call fee handling
    • Updated bridge call sender and fee collector identifiers

Copy link

coderabbitai bot commented Jan 8, 2025

Walkthrough

This pull request introduces significant changes to the crosschain module's bridge call and fee handling mechanisms. The modifications focus on renaming methods, simplifying fee transfer logic, and adding new functions for quote validation and fee management. The changes streamline the process of handling bridge call fees, introducing a more consolidated approach to managing quote validation, fee transfers, and module-level fee collection.

Changes

File Changes
x/crosschain/keeper/bridge_call_in.go - Renamed handleBridgeCallInQuote to handlerBridgeCallInFee
- Simplified quote validation logic
- Removed detailed gas limit checks
x/crosschain/keeper/bridge_call_out.go - Renamed handleBridgeCallOutQuote to handlerBridgeCallOutFee
- Renamed TransferQuoteFeeToRelayer to TransferBridgeFeeToRelayer
- Streamlined fee handling process
x/crosschain/keeper/bridge_fee.go - Added new ValidateQuote method
- Added new TransferBridgeFee method for fee transfers
x/crosschain/keeper/keeper.go - Added bridgeFeeCollector field
- Removed GetModuleEvmAddress method
x/crosschain/types/key.go - Updated BridgeCallSender constant
- Added BridgeFeeCollectorName constant

Sequence Diagram

sequenceDiagram
    participant Caller
    participant BridgeModule
    participant QuoteValidator
    participant FeeTransfer

    Caller->>BridgeModule: Initiate Bridge Call
    BridgeModule->>QuoteValidator: Validate Quote
    QuoteValidator-->>BridgeModule: Return Validated Quote
    BridgeModule->>FeeTransfer: Transfer Bridge Fee
    FeeTransfer-->>BridgeModule: Confirm Fee Transfer
    BridgeModule-->>Caller: Complete Bridge Call
Loading

Possibly related PRs

Poem

🐰 Hopping through code with glee,
Bridge fees now flow more free!
Quotes validated, transfers neat,
Our crosschain dance is now complete.
Simplicity wins the day! 🌉


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 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.

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

@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

🧹 Nitpick comments (5)
x/crosschain/keeper/bridge_call_in.go (1)

140-152: Add validation for gasLimit in handlerBridgeCallInFee.

Currently, gasLimit is accepted without validation. It's important to ensure that gasLimit is not nil and has a positive value to prevent issues during comparison in downstream logic.

Apply this diff to validate gasLimit:

 func (k Keeper) handlerBridgeCallInFee(ctx sdk.Context, from common.Address, quoteId, gasLimit *big.Int) error {
+    if gasLimit == nil || gasLimit.Sign() <= 0 {
+        return types.ErrInvalid.Wrap("invalid gasLimit: must be positive")
+    }
     if quoteId == nil || quoteId.Sign() <= 0 {
         // Allow free bridgeCall
         return nil
     }
     quote, err := k.ValidateQuote(ctx, quoteId, gasLimit)
     if err != nil {
         return err
     }
     return k.TransferBridgeFee(ctx, from, quote.Oracle, quote.Fee, quote.TokenName)
 }
x/crosschain/keeper/bridge_fee.go (2)

16-28: Validate gasLimit parameter in ValidateQuote function.

The function assumes that gasLimit is not nil. To prevent potential nil pointer dereferences, add a check to ensure gasLimit is not nil and has a non-negative value before proceeding.

Apply this diff to add validation:

 func (k Keeper) ValidateQuote(ctx sdk.Context, quoteId, gasLimit *big.Int) (contract.IBridgeFeeQuoteQuoteInfo, error) {
+    if gasLimit == nil || gasLimit.Sign() < 0 {
+        return contract.IBridgeFeeQuoteQuoteInfo{}, types.ErrInvalid.Wrap("invalid gasLimit: must be non-negative")
+    }
     quote, err := k.bridgeFeeQuoteKeeper.GetQuoteById(ctx, quoteId)
     if err != nil {
         return contract.IBridgeFeeQuoteQuoteInfo{}, err
     }
     if quote.IsTimeout(ctx.BlockTime()) {
         return contract.IBridgeFeeQuoteQuoteInfo{}, types.ErrInvalid.Wrap("quote has timed out")
     }
     if quote.GasLimit.Cmp(gasLimit) < 0 {
         return contract.IBridgeFeeQuoteQuoteInfo{}, types.ErrInvalid.Wrap("quote gas limit is less than requested gas limit")
     }
     return quote, nil
 }

31-34: Ensure consistent denomination comparison for bridgeTokenName.

Comparing bridgeTokenName using strings.ToUpper might lead to incorrect matches if fxtypes.DefaultDenom is not also converted to uppercase. Ensure that both are compared in a case-insensitive manner.

Apply this diff to standardize the comparison:

 if strings.EqualFold(bridgeTokenName, fxtypes.DefaultDenom) {
     fees := sdk.NewCoins(sdk.NewCoin(fxtypes.DefaultDenom, sdkmath.NewIntFromBigInt(bridgeFee)))
     return k.bankKeeper.SendCoins(ctx, from.Bytes(), to.Bytes(), fees)
 }
x/crosschain/keeper/keeper.go (1)

34-36: Maintain field ordering and grouping in the Keeper struct.

For better readability and maintainability, consider grouping related fields together. Place the bridgeFeeCollector field next to other address-related fields.

Apply this diff to adjust field ordering:

 type Keeper struct {
     // ... other fields ...
     bankKeeper           types.BankKeeper
     ak                   types.AccountKeeper
     ibcTransferKeeper    types.IBCTransferKeeper
     erc20Keeper          types.Erc20Keeper
     evmKeeper            types.EVMKeeper
     bridgeFeeQuoteKeeper types.BridgeFeeQuoteKeeper
     erc20TokenKeeper     types.ERC20TokenKeeper

-    authority          string
-    callbackFrom       common.Address
+    authority          string
+    callbackFrom       common.Address
+    bridgeFeeCollector sdk.AccAddress
 }
x/crosschain/keeper/bridge_call_out.go (1)

406-415: Consider extracting bridgeFeeAddr initialization.

The bridgeFeeAddr initialization appears in multiple places in the code. Consider extracting it to a method or initializing it once in the Keeper struct for better maintainability.

 type Keeper struct {
     // existing fields
+    bridgeFeeAddress common.Address
 }

 func NewKeeper(...) Keeper {
     // existing initialization
+    k.bridgeFeeAddress = common.BytesToAddress(k.bridgeFeeCollector)
     return k
 }

 func (k Keeper) TransferBridgeFeeToRelayer(ctx sdk.Context, bridgeCallNonce uint64) error {
     quote, found := k.GetOutgoingBridgeCallQuoteInfo(ctx, bridgeCallNonce)
     if !found {
         return nil
     }
     k.DeleteOutgoingBridgeCallQuoteInfo(ctx, bridgeCallNonce)
-    bridgeFeeAddr := common.BytesToAddress(k.bridgeFeeCollector)
-    return k.TransferBridgeFee(ctx, bridgeFeeAddr, quote.OracleAddress(), quote.Fee.BigInt(), quote.Token)
+    return k.TransferBridgeFee(ctx, k.bridgeFeeAddress, quote.OracleAddress(), quote.Fee.BigInt(), quote.Token)
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fdf7355 and b08a784.

📒 Files selected for processing (5)
  • x/crosschain/keeper/bridge_call_in.go (2 hunks)
  • x/crosschain/keeper/bridge_call_out.go (3 hunks)
  • x/crosschain/keeper/bridge_fee.go (1 hunks)
  • x/crosschain/keeper/keeper.go (2 hunks)
  • x/crosschain/types/key.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary
🔇 Additional comments (6)
x/crosschain/keeper/bridge_call_in.go (1)

151-151: Confirm that TransferBridgeFee handles all possible error scenarios.

Ensure that TransferBridgeFee properly handles errors, especially in cases where the fee transfer might fail due to insufficient funds or incorrect addresses. Consider adding context to the error messages for better traceability.

x/crosschain/keeper/bridge_fee.go (1)

35-40: Handle potential nil values and errors in ERC20 token operations.

  • Confirm that erc20Token is not nil after retrieval.
  • Ensure Transfer errors are properly handled, and consider adding more descriptive error messages if needed.
x/crosschain/keeper/keeper.go (1)

66-67: Verify correct initialization of callbackFrom and bridgeFeeCollector addresses.

Ensure that the module addresses are correctly derived from the module names and that they correspond to valid and expected addresses within the system.

Run the following script to confirm the addresses:

✅ Verification successful

Module addresses are correctly initialized and used consistently

  • Constants are properly defined in x/crosschain/types/key.go
  • BridgeCallSender account is properly initialized during genesis in genesis.go
  • Address format conversions are appropriate for cross-chain functionality
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify module addresses for 'BridgeCallSender' and 'BridgeFeeCollectorName'

# Expected variables (replace with actual values if known)
MODULE_NAME="crosschain"
BRIDGE_CALL_SENDER="bridge_call_sender"
BRIDGE_FEE_COLLECTOR_NAME="bridge_fee_collector"

# Check module addresses
echo "Module address for BridgeCallSender:"
fx-core query auth module-account $BRIDGE_CALL_SENDER

echo "Module address for BridgeFeeCollectorName:"
fx-core query auth module-account $BRIDGE_FEE_COLLECTOR_NAME

Length of output: 601


Script:

#!/bin/bash
# Find constant definitions and their usage
echo "=== Searching for BridgeCallSender and BridgeFeeCollectorName constants ==="
rg "BridgeCallSender|BridgeFeeCollectorName" -A 2 -B 2

echo -e "\n=== Looking for NewModuleAddress implementation ==="
ast-grep --pattern 'func NewModuleAddress($$$) {$$$}'

echo -e "\n=== Checking other usages of these module addresses ==="
rg "NewModuleAddress.*BridgeCallSender|NewModuleAddress.*BridgeFeeCollector" -A 2 -B 2

Length of output: 2591

x/crosschain/types/key.go (1)

16-18: LGTM! Improved naming conventions.

The updated constant names with underscores improve readability and maintain consistency across the codebase.

x/crosschain/keeper/bridge_call_out.go (2)

124-124: LGTM! Method name better reflects its purpose.

The rename from TransferQuoteFeeToRelayer to TransferBridgeFeeToRelayer better describes the function's purpose.


321-324: LGTM! Proper error handling maintained.

The integration of handlerBridgeCallOutFee maintains proper error handling and control flow.

x/crosschain/keeper/bridge_call_in.go Show resolved Hide resolved
x/crosschain/keeper/bridge_call_out.go Show resolved Hide resolved
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