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

refactor(crosschain): simplify interface references for the erc20 module #731

Merged
merged 1 commit into from
Oct 11, 2024

Conversation

zakir-code
Copy link
Contributor

@zakir-code zakir-code commented Oct 11, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for bridge call processes, improving reliability during refunds.
    • Updated method for retrieving bridge denominations to support flexible chain name queries.
  • Bug Fixes

    • Streamlined error propagation in key methods, ensuring better feedback on operation outcomes.
  • Refactor

    • Removed redundant functions and restructured method signatures for clarity and efficiency.
  • Tests

    • Updated test cases to align with modified method signatures and removed functions, maintaining test relevance.

Copy link

coderabbitai bot commented Oct 11, 2024

Walkthrough

The changes in this pull request primarily focus on enhancing error handling, restructuring method signatures, and removing redundant functions within the x/crosschain/keeper package. Key updates include improved error propagation in several methods, modifications to method signatures to return errors where applicable, and the removal of outdated functions related to bridge calls and refunds. Additionally, tests have been adjusted to align with these changes, ensuring their relevance and functionality.

Changes

File Path Change Summary
x/crosschain/keeper/abci.go Improved error handling in cleanupTimeOutBridgeCall.
x/crosschain/keeper/attestation_handler.go Enhanced error handling in ExecuteClaim method.
x/crosschain/keeper/bridge_call_in.go Streamlined error handling in BridgeCallHandler, integrated refund logic.
x/crosschain/keeper/bridge_call_out.go Updated BridgeCallResultHandler to return an error.
x/crosschain/keeper/many_to_one.go Changed IBCCoinRefund method context parameter from context.Context to sdk.Context.
x/crosschain/keeper/bridge_token.go Renamed GetBridgeDenom to GetBridgeDenoms and added a new method for flexible retrieval.
x/crosschain/keeper/bridge_call_refund.go Removed related functions and deleted the file.
x/crosschain/keeper/bridge_call_refund_test.go Deleted test file corresponding to removed functionality.
x/crosschain/keeper/bridge_call_in_test.go Updated tests to reflect changes in method signatures and removed functions.
x/crosschain/keeper/grpc_query.go Removed unused variable bridgeCoinMetaData.
x/crosschain/mock/expected_keepers_mocks.go Updated mock interfaces to reflect changes in underlying types and method parameters.
x/crosschain/types/expected_keepers.go Adjusted as necessary to accommodate the changes in keeper methods.
x/ibc/middleware/types/expected_keepers.go Adjusted as necessary to accommodate the changes in keeper methods.

Possibly related PRs

🐰 "In the fields where bunnies play,
Changes hop in bright array.
Error handling, signatures new,
Redundant paths we bid adieu.
With tests refined, our code takes flight,
Cross-chain dreams are now in sight!" 🐇


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

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

🧹 Outside diff range and nitpick comments (9)
x/crosschain/keeper/attestation_handler.go (1)

Line range hint 9-26: Consider consistent error handling in AttestationHandler

While the AttestationHandler function is well-structured, it could benefit from consistent error handling across all cases. Currently, only some cases return errors, while others don't.

Consider modifying the function to return errors for all cases, similar to the ExecuteClaim function. This would provide more consistent behavior and potentially improve error tracking. Here's a suggested modification:

 func (k Keeper) AttestationHandler(ctx sdk.Context, externalClaim types.ExternalClaim) error {
 	switch claim := externalClaim.(type) {
 	case *types.MsgSendToFxClaim, *types.MsgBridgeCallClaim, *types.MsgBridgeCallResultClaim:
-		k.SavePendingExecuteClaim(ctx, externalClaim)
+		return k.SavePendingExecuteClaim(ctx, externalClaim)
 
 	case *types.MsgSendToExternalClaim:
-		k.OutgoingTxBatchExecuted(ctx, claim.TokenContract, claim.BatchNonce)
+		return k.OutgoingTxBatchExecuted(ctx, claim.TokenContract, claim.BatchNonce)
 
 	case *types.MsgBridgeTokenClaim:
 		return k.AddBridgeTokenExecuted(ctx, claim)
 
 	case *types.MsgOracleSetUpdatedClaim:
 		return k.UpdateOracleSetExecuted(ctx, claim)
 
 	default:
 		return types.ErrInvalid.Wrapf("event type: %s", claim.GetType())
 	}
-	return nil
 }

This change would require updating the SavePendingExecuteClaim and OutgoingTxBatchExecuted methods to return an error if they don't already do so.

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

Line range hint 1-80: Consider expanding test coverage and maintaining consistency.

While the changes improve error handling, there are a couple of suggestions to enhance the overall test suite:

  1. The TestKeeper_BridgeCallResultHandler function has a tests slice with only one test case. Consider adding more test cases to cover different scenarios, such as failure cases or edge cases.

  2. For consistency, you might want to apply similar error handling improvements to other test functions in this suite, like TestKeeper_DeleteOutgoingBridgeCall.

Would you like assistance in generating additional test cases or applying consistent error handling across the test suite?

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

Line range hint 105-119: LGTM with a minor suggestion for error handling.

The GetBridgeDenoms function is well-implemented and handles various error cases appropriately. It correctly retrieves the metadata for a given denomination and checks for the presence of aliases.

Consider using a custom error type or wrapping errors to provide more context. For example:

if !ok {
    return nil, fmt.Errorf("%w: denom %s not found", types.ErrInvalidDenom, denom)
}

This approach would allow callers to easily check for specific error types and provide more context about where the error occurred.


120-131: LGTM with suggestions for improvements.

The GetBridgeDenom function is implemented correctly and achieves its purpose of finding a bridge denomination that matches a given chain name. However, there are a few areas where it could be improved:

  1. Error handling: Consider wrapping the error returned by GetBridgeDenoms to provide more context.

  2. Matching logic: The current implementation assumes that the chainName is always a prefix of the bridge denomination. This might not always be the case, depending on your naming conventions. Consider if a more flexible matching strategy is needed.

  3. Multiple matches: The function doesn't handle the case where multiple bridge denominations might start with the same chainName. Depending on your requirements, you might want to handle this case explicitly.

Here's a suggested refactoring that addresses these points:

func (k Keeper) GetBridgeDenom(ctx context.Context, denom, chainName string) (string, error) {
    bridgeDenoms, err := k.GetBridgeDenoms(ctx, denom)
    if err != nil {
        return "", fmt.Errorf("failed to get bridge denoms: %w", err)
    }
    
    var matches []string
    for _, bridgeDenom := range bridgeDenoms {
        if strings.Contains(bridgeDenom, chainName) {
            matches = append(matches, bridgeDenom)
        }
    }
    
    switch len(matches) {
    case 0:
        return "", fmt.Errorf("no bridge denom found for chain %s and denom %s", chainName, denom)
    case 1:
        return matches[0], nil
    default:
        return "", fmt.Errorf("multiple bridge denoms found for chain %s and denom %s: %v", chainName, denom, matches)
    }
}

This refactored version provides more detailed error messages, uses a more flexible matching strategy (Contains instead of HasPrefix), and explicitly handles the case of multiple matches.

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

185-187: Improved error handling for bridge call refunds.

The changes enhance the error handling for the RefundOutgoingBridgeCall operation, which aligns with the PR objective of simplifying interface references. The explicit error check and panic with a detailed message improve the debugging process in case of failures.

However, consider logging the error before panicking to ensure the error details are captured in the application logs.

Consider adding a log statement before the panic:

 if err := k.RefundOutgoingBridgeCall(ctx, data); err != nil {
+    k.Logger(ctx).Error("failed to refund outgoing bridge call", "nonce", data.Nonce, "error", err)
     panic(fmt.Sprintf("failed cancel out bridge call %d while trying to execute failed: %s", data.Nonce, err))
 }
x/crosschain/types/expected_keepers.go (2)

59-59: Add missing documentation for DeleteIBCTransferRelation

The method DeleteIBCTransferRelation lacks a documentation comment. Adding a comment explaining its purpose and return value will enhance maintainability and readability.


84-85: Add documentation for GetBridgeDenoms and GetBridgeDenom

The new methods lack documentation comments. Providing clear descriptions of their functionality, parameters, and return values will aid other developers in understanding and using these methods correctly.

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

124-127: Include missing attribute in refund event

The refund event does not include the BridgeCallNonce, which might be useful for tracking and logging purposes. Consider adding it to the emitted event.

Apply this diff to include the BridgeCallNonce attribute:

     ctx.EventManager().EmitEvent(sdk.NewEvent(
         types.EventTypeBridgeCallRefund,
         sdk.NewAttribute(types.AttributeKeyRefund, refund.String()),
+        sdk.NewAttribute(types.AttributeKeyBridgeCallNonce, fmt.Sprint(data.Nonce)),
     ))
x/crosschain/keeper/many_to_one.go (1)

Line range hint 170-186: Inconsistent use of context types in function signature

The function BaseDenomToBridgeDenom uses context.Context as its context parameter, while other functions have been updated to use sdk.Context. For consistency and to reduce unnecessary unwrapping of the context, consider changing the parameter type to sdk.Context.

Apply the following diff to update the function signature and adjust the context usage:

-func (k Keeper) BaseDenomToBridgeDenom(ctx context.Context, baseDenom, target string) (string, error) {
+func (k Keeper) BaseDenomToBridgeDenom(ctx sdk.Context, baseDenom, target string) (string, error) {

...

-            denomTrace, found := k.ibcTransferKeeper.GetDenomTrace(sdk.UnwrapSDKContext(ctx), hash)
+            denomTrace, found := k.ibcTransferKeeper.GetDenomTrace(ctx, hash)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1f0b77f and 8cd1e49.

📒 Files selected for processing (17)
  • x/crosschain/keeper/abci.go (1 hunks)
  • x/crosschain/keeper/attestation_handler.go (1 hunks)
  • x/crosschain/keeper/bridge_call_in.go (2 hunks)
  • x/crosschain/keeper/bridge_call_in_test.go (0 hunks)
  • x/crosschain/keeper/bridge_call_out.go (2 hunks)
  • x/crosschain/keeper/bridge_call_out_test.go (1 hunks)
  • x/crosschain/keeper/bridge_call_refund.go (0 hunks)
  • x/crosschain/keeper/bridge_call_refund_test.go (0 hunks)
  • x/crosschain/keeper/bridge_token.go (2 hunks)
  • x/crosschain/keeper/grpc_query.go (1 hunks)
  • x/crosschain/keeper/grpc_query_v1_test.go (0 hunks)
  • x/crosschain/keeper/keeper_test.go (0 hunks)
  • x/crosschain/keeper/keeper_v1_test.go (0 hunks)
  • x/crosschain/keeper/many_to_one.go (2 hunks)
  • x/crosschain/mock/expected_keepers_mocks.go (5 hunks)
  • x/crosschain/types/expected_keepers.go (2 hunks)
  • x/ibc/middleware/types/expected_keepers.go (1 hunks)
💤 Files with no reviewable changes (6)
  • x/crosschain/keeper/bridge_call_in_test.go
  • x/crosschain/keeper/bridge_call_refund.go
  • x/crosschain/keeper/bridge_call_refund_test.go
  • x/crosschain/keeper/grpc_query_v1_test.go
  • x/crosschain/keeper/keeper_test.go
  • x/crosschain/keeper/keeper_v1_test.go
🧰 Additional context used
🔇 Additional comments (19)
x/ibc/middleware/types/expected_keepers.go (1)

18-18: Approve the context type change and verify its impact.

The change from context.Context to sdk.Context in the IBCCoinRefund method signature is appropriate and aligns with the Cosmos SDK conventions. This change provides access to additional SDK-specific functionality and maintains consistency with other SDK methods.

To ensure this change doesn't introduce any issues, please run the following verification script:

This script will help identify any inconsistencies or potential issues related to the context type change. Please review the results and make any necessary adjustments to ensure all implementations and calls are updated correctly.

✅ Verification successful

Context type change verified successfully.

The change from context.Context to sdk.Context in the IBCCoinRefund method signature has been verified. No instances of context.Context usage remain in IBCCoinRefund implementations, and all calls correctly utilize sdk.Context. Additionally, there are no detected issues related to context cancellation or timeouts within the scope of this change.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the impact of changing context.Context to sdk.Context in IBCCoinRefund

# Test 1: Check for any remaining uses of context.Context in IBCCoinRefund implementations
echo "Checking for context.Context usage in IBCCoinRefund implementations:"
rg --type go "func.*IBCCoinRefund.*context\.Context"

# Test 2: Verify that all calls to IBCCoinRefund now use sdk.Context
echo "Verifying IBCCoinRefund calls use sdk.Context:"
rg --type go "IBCCoinRefund\s*\(\s*\w+\s*sdk\.Context"

# Test 3: Check for any potential issues with context cancellation or timeouts
echo "Checking for potential context cancellation or timeout issues:"
rg --type go "WithCancel|WithTimeout|WithDeadline" -C 5

Length of output: 97278

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

43-43: Approve change and verify error handling

The modification to return the result of k.BridgeCallResultHandler(ctx, claim) is a good improvement. It ensures proper error propagation and makes the handling of MsgBridgeCallResultClaim consistent with other claim types in the switch statement.

To ensure this change doesn't introduce any unexpected behavior, please verify the error handling in functions that call ExecuteClaim. Run the following script to find these caller functions:

Review the output to ensure that these calling functions properly handle any errors that may now be returned from ExecuteClaim.

✅ Verification successful

Error handling verified

No additional callers to ExecuteClaim were found. The modification ensures that errors from BridgeCallResultHandler are properly propagated.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find functions that call ExecuteClaim and check their error handling

# Search for ExecuteClaim function calls
ast-grep --lang go --pattern 'k.ExecuteClaim($$$)' | rg -A 10 'ExecuteClaim'

Length of output: 76


Script:

#!/bin/bash
# Description: Find all invocations of ExecuteClaim in the codebase

# Use ast-grep to find all calls to ExecuteClaim with any receiver
ast-grep --lang go --pattern '$_.ExecuteClaim($$$)'

# Additionally, use ripgrep to search for ExecuteClaim calls
rg 'ExecuteClaim\s*\('

Length of output: 5054

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

51-52: Improved error handling in the test case.

The addition of error checking for the BridgeCallResultHandler method call enhances the robustness of the test. This change ensures that the method executes without errors, which is a good practice in unit testing.

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

Line range hint 105-131: Summary of changes in bridge_token.go

The additions to this file, namely GetBridgeDenoms and GetBridgeDenom, contribute to the PR's objective of simplifying interface references for the erc20 module. These functions provide a more flexible and robust way of handling bridge denominations, which aligns with the refactoring goals.

The new implementation allows for:

  1. Retrieval of multiple bridge denominations for a given denom.
  2. Filtering of bridge denominations based on chain name.

These changes should make it easier to work with bridge tokens across different chains, potentially simplifying cross-chain operations in the erc20 module.

To fully achieve the PR's objectives, ensure that these new functions are utilized consistently throughout the codebase, replacing any older, less flexible methods of handling bridge denominations.

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

185-187: Summary: Focused improvement in error handling

The changes in this file are minimal and well-focused, improving the error handling in the cleanupTimeOutBridgeCall function without altering its core logic. This enhancement aligns with the PR objective of simplifying interface references for the erc20 module by making the error handling more explicit and informative.

The localized nature of these changes minimizes the risk of unintended side effects while improving the overall robustness of the code.

x/crosschain/types/expected_keepers.go (2)

59-59: ⚠️ Potential issue

Clarify the necessity of the boolean return value

DeleteIBCTransferRelation returns a bool, but it's unclear what the return value signifies. Ensure that the boolean indicates something meaningful (e.g., success status) and consider documenting it for clarity.


84-85: ⚠️ Potential issue

Ensure consistent error handling in GetBridgeDenoms and GetBridgeDenom

Verify that both methods handle errors consistently, especially in cases where the provided denom or chainName does not exist. This will prevent unexpected behavior and make debugging easier.

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

Line range hint 90-111: Improved error handling in BridgeCallResultHandler

The updates to BridgeCallResultHandler enhance its robustness by replacing the panic mechanism with proper error returns. This allows for graceful error handling and better control flow management throughout the application.


113-136: Correct implementation of RefundOutgoingBridgeCall

The new RefundOutgoingBridgeCall function appropriately handles the refund process, including token conversion and event emission. Error handling is correctly implemented, ensuring that issues are propagated upstream.


138-143: Effective encapsulation in DeleteOutgoingBridgeCallRecord

The new DeleteOutgoingBridgeCallRecord function neatly encapsulates the deletion logic for bridge calls and their confirmations, improving code readability and maintainability.


130-134: Handle potential issues with address conversion

When converting the refund address to an EVM-compatible address, ensure that the address conversion is valid and consider handling any potential edge cases.

Run the following script to verify the address conversions:

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

289-298: Verify all calls to IBCCoinRefund are updated to use sdk.Context

The IBCCoinRefund function's context parameter type has been changed from context.Context to sdk.Context. Ensure that all calls to this function across the codebase are updated accordingly to prevent potential type mismatches.

Run the following script to identify any calls still using the old context type:

✅ Verification successful

All calls to IBCCoinRefund are updated to use sdk.Context.

  • Verified that all instances of IBCCoinRefund pass sdk.Context as the context parameter.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all calls to `IBCCoinRefund` that may still use `context.Context`.

# Test: Search for usages of `IBCCoinRefund` with `context.Context`.
rg --type go 'IBCCoinRefund\s*\(\s*context\.Context' -A 2

Length of output: 59


Script:

#!/bin/bash
# Description: Find all calls to `IBCCoinRefund` and display the context parameter type.

rg --type go 'IBCCoinRefund\s*\(' -A 2

Length of output: 847

x/crosschain/mock/expected_keepers_mocks.go (5)

25-25: Import path update aligns with package restructuring

The import path for types5 has been updated to github.com/functionx/fx-core/v8/x/erc20/types, reflecting the new package organization.


401-404: Method ConvertCoin updated correctly

The method ConvertCoin now uses types5.MsgConvertCoin and types5.MsgConvertCoinResponse, which aligns with the updated types package.


416-419: Method ConvertERC20 updated correctly

The method ConvertERC20 has been updated to use types5.MsgConvertERC20 and types5.MsgConvertERC20Response, reflecting the changes in the types package.


457-460: Return type for GetTokenPair updated appropriately

The GetTokenPair method now returns types5.TokenPair, consistent with the package updates.


745-757: Updated GetBridgeDenom method signature

The signature of GetBridgeDenom has been modified to include an additional parameter chainName string, and this change is correctly reflected in both the method and its mock recorder.

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

40-41: Improved error handling enhances code clarity

Assigning the result of k.BridgeCallEvm directly to err and checking it immediately improves the readability and clarity of the error handling logic. This ensures that any errors from the EVM call are properly captured and handled.


52-69: Consolidated refund logic simplifies the codebase

Integrating the refund logic directly into the BridgeCallHandler function eliminates the need for the separate BridgeCallFailedRefund function. This consolidation reduces complexity and enhances maintainability by keeping related logic within a single function.

x/crosschain/types/expected_keepers.go Show resolved Hide resolved
x/crosschain/keeper/bridge_call_out.go Show resolved Hide resolved
x/crosschain/keeper/bridge_call_out.go Show resolved Hide resolved
x/crosschain/keeper/grpc_query.go Show resolved Hide resolved
x/crosschain/keeper/grpc_query.go Show resolved Hide resolved
x/crosschain/mock/expected_keepers_mocks.go Show resolved Hide resolved
x/crosschain/keeper/bridge_call_in.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