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(ibctransfer): convert FX to apundiai on OnAck error or Timeout #924

Merged
merged 1 commit into from
Jan 20, 2025

Conversation

zakir-code
Copy link
Contributor

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

Summary by CodeRabbit

  • New Features

    • Enhanced IBC transfer module testing with new validation function
    • Added token migration logic for escrow denominations during upgrades
    • Improved packet data handling in IBC middleware
  • Tests

    • Added comprehensive test cases for packet data unmarshalling
    • Updated test error handling for IBC acknowledgment scenarios
  • Refactor

    • Centralized packet data processing logic
    • Streamlined IBC transfer module upgrade procedures

Copy link

coderabbitai bot commented Jan 20, 2025

Walkthrough

This pull request introduces enhancements to the upgrade process and testing framework for the IBC transfer module. The changes focus on improving token migration logic, specifically for handling escrow denominations during upgrades. New functions are added to validate the state of IBC transfer tokens, manage denomination changes, and centralize packet data unmarshalling. The modifications aim to provide more robust testing and migration capabilities for cross-chain token transfers.

Changes

File Change Summary
app/upgrade_test.go Added checkIBCTransferModule function to validate IBC transfer module state after upgrade
app/upgrades/v8/upgrade.go - Added migrateTransferTokenInEscrow function for token escrow migration
- Added GetMigrateEscrowDenoms to generate denomination mapping
x/ibc/middleware/keeper/relay.go - Introduced UnmarshalAckPacketData function for centralized packet data handling
- Refactored OnAcknowledgementPacket and OnTimeoutPacket methods
x/ibc/middleware/keeper/relay_test.go - Added TestUnmarshalAckPacketData test function
- Added mustProtoMarshalJSON utility function
- Modified error handling in existing tests

Sequence Diagram

sequenceDiagram
    participant Upgrade as Upgrade Process
    participant TransferModule as IBC Transfer Module
    participant EscrowKeeper as Escrow Keeper

    Upgrade->>TransferModule: Initiate Migration
    TransferModule->>EscrowKeeper: Get Old Denominations
    EscrowKeeper-->>TransferModule: Return Escrow Denominations
    TransferModule->>TransferModule: Migrate Token Escrow
    TransferModule->>EscrowKeeper: Update Escrow Amounts
    TransferModule-->>Upgrade: Migration Complete
Loading

Possibly related PRs

Poem

🐰 Hopping through tokens, upgrade in sight,
Escrow migrations, everything's right!
Denominations dance, old to new,
IBC transfers leap with a breakthrough
Rabbit's code hops, migration complete! 🌈

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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.

Comment on lines +224 to +234
for oldDenom, newDenom := range escrowDenoms {
totalEscrow := transferKeeper.GetTotalEscrowForDenom(ctx, oldDenom)
newAmount := totalEscrow.Amount
if oldDenom == fxtypes.IBCFXDenom {
newAmount = fxtypes.SwapAmount(newAmount)
}
// first remove old denom
transferKeeper.SetTotalEscrowForDenom(ctx, sdk.NewCoin(oldDenom, sdkmath.ZeroInt()))
// then add new denom
transferKeeper.SetTotalEscrowForDenom(ctx, sdk.NewCoin(newDenom, newAmount))
}

Check warning

Code scanning / CodeQL

Iteration over map Warning

Iteration over map may be a possible source of non-determinism
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 (2)
x/ibc/middleware/keeper/relay_test.go (1)

228-250: Consider handling errors explicitly in mustProtoMarshalJSON

The mustProtoMarshalJSON helper function currently panics on errors, which can obscure test failures. Refactoring it to return an error allows tests to handle failures gracefully and provides clearer error messages.

Apply this refactoring to handle errors without panicking:

-func mustProtoMarshalJSON(msg proto.Message) []byte {
+func mustProtoMarshalJSON(msg proto.Message) ([]byte, error) {
     anyResolver := codectypes.NewInterfaceRegistry()

     jm := &jsonpb.Marshaler{OrigName: true, EmitDefaults: false, AnyResolver: anyResolver}

     err := codectypes.UnpackInterfaces(msg, codectypes.ProtoJSONPacker{JSONPBMarshaler: jm})
     if err != nil {
-        panic(err)
+        return nil, err
     }

     buf := new(bytes.Buffer)
     if err := jm.Marshal(buf, msg); err != nil {
-        panic(err)
+        return nil, err
     }

-    return buf.Bytes()
+    return buf.Bytes(), nil
 }

Update the calling code to handle the returned error:

-packetDateByte, err := sdk.SortJSON(mustProtoMarshalJSON(&tcData))
+dataBytes, err := mustProtoMarshalJSON(&tcData)
+require.NoError(t, err)
+packetDateByte, err := sdk.SortJSON(dataBytes)
 require.NoError(t, err)
app/upgrades/v8/upgrade.go (1)

752-762: Improve documentation and maintainability.

The function would benefit from better documentation and use of constants.

+// escrowDenomsMapSize represents the number of denomination mappings
+const escrowDenomsMapSize = 2
+
+// GetMigrateEscrowDenoms returns a mapping of old denominations to new denominations
+// for escrow migration. It handles both:
+// 1. FX to PUNDIAI conversion
+// 2. PUNDIX unwrapped to wrapped conversion
 func GetMigrateEscrowDenoms(chainID string) map[string]string {
-    result := make(map[string]string, 2)
+    result := make(map[string]string, escrowDenomsMapSize)
     result[fxtypes.IBCFXDenom] = fxtypes.DefaultDenom

     pundixDenom := fxtypes.MainnetPundixUnWrapDenom
     if chainID == fxtypes.TestnetChainId {
         pundixDenom = fxtypes.TestnetPundixUnWrapDenom
     }
     result[pundixDenom] = fxtypes.PundixWrapDenom
     return result
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 73af7fa and 2920664.

📒 Files selected for processing (4)
  • app/upgrade_test.go (2 hunks)
  • app/upgrades/v8/upgrade.go (3 hunks)
  • x/ibc/middleware/keeper/relay.go (2 hunks)
  • x/ibc/middleware/keeper/relay_test.go (3 hunks)
🧰 Additional context used
🪛 GitHub Check: CodeQL
app/upgrades/v8/upgrade.go

[warning] 224-234: Iteration over map
Iteration over map may be a possible source of non-determinism

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Mergify Merge Protections
  • GitHub Check: Summary
🔇 Additional comments (5)
x/ibc/middleware/keeper/relay.go (3)

90-96: Verify the handling of zero amounts in OnAcknowledgementPacket

The updated OnAcknowledgementPacket method introduces logic to handle packets with zero amounts. Ensure that invoking AfterIBCAckSuccess when isZeroAmount is true aligns with the intended protocol behavior and doesn't introduce any unintended side effects.


112-118: Confirm consistent handling of zero amounts in OnTimeoutPacket

Similar to OnAcknowledgementPacket, the OnTimeoutPacket method checks for isZeroAmount and calls AfterIBCAckSuccess. Verify that this logic is appropriate for timeout scenarios and that it maintains consistency across different packet handling pathways.


126-148: Ensure robust error handling and correct amount calculations in UnmarshalAckPacketData

The new UnmarshalAckPacketData function adds clarity by centralizing the unmarshalling and processing of packet data. Please verify the following:

  • Unmarshalling Safety: Confirm that transfertypes.ModuleCdc.UnmarshalJSON correctly handles all possible packet data inputs without risking panics due to malformed data.
  • Amount and Fee Parsing: Ensure that parseAmountAndFeeByPacket properly validates and handles edge cases, such as negative amounts or fees, which could lead to incorrect calculations.
  • Denomination Swap Logic: Validate that the denomination swap from fxtypes.IBCFXDenom to fxtypes.DefaultDenom and the application of fxtypes.SwapAmount correctly reflect the intended token transformation.
  • Zero Amount Check: The condition !totalAmount.IsPositive() determines if the total amount is zero or negative. Confirm that this logic aligns with protocol specifications and that downstream processes handle zero or negative amounts appropriately.
x/ibc/middleware/keeper/relay_test.go (1)

148-250: Excellent addition of comprehensive tests for UnmarshalAckPacketData

The TestUnmarshalAckPacketData function thoroughly tests various scenarios, including normal cases, zero amounts, and packets with fees. This enhances the reliability of the UnmarshalAckPacketData function by ensuring it behaves correctly under different conditions.

app/upgrade_test.go (1)

194-206: Good addition of IBC transfer module validation in tests

The new checkIBCTransferModule function effectively validates the migration of escrowed tokens during the upgrade. By asserting that old denominations have zero total escrow and new denominations have non-zero total escrow, it ensures that the migration logic works as intended.

Comment on lines +216 to +218

migrateTransferTokenInEscrow(ctx, app.IBCTransferKeeper)

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for transfer token migration.

The migrateTransferTokenInEscrow call should return and handle potential errors like other migrations in this function to maintain consistency and prevent partial migrations.

-  migrateTransferTokenInEscrow(ctx, app.IBCTransferKeeper)
+  if err := migrateTransferTokenInEscrow(ctx, app.IBCTransferKeeper); err != nil {
+    return 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.

Suggested change
migrateTransferTokenInEscrow(ctx, app.IBCTransferKeeper)
if err := migrateTransferTokenInEscrow(ctx, app.IBCTransferKeeper); err != nil {
return err
}

Comment on lines +222 to +235
func migrateTransferTokenInEscrow(ctx sdk.Context, transferKeeper ibctransferkeeper.Keeper) {
escrowDenoms := GetMigrateEscrowDenoms(ctx.ChainID())
for oldDenom, newDenom := range escrowDenoms {
totalEscrow := transferKeeper.GetTotalEscrowForDenom(ctx, oldDenom)
newAmount := totalEscrow.Amount
if oldDenom == fxtypes.IBCFXDenom {
newAmount = fxtypes.SwapAmount(newAmount)
}
// first remove old denom
transferKeeper.SetTotalEscrowForDenom(ctx, sdk.NewCoin(oldDenom, sdkmath.ZeroInt()))
// then add new denom
transferKeeper.SetTotalEscrowForDenom(ctx, sdk.NewCoin(newDenom, newAmount))
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ensure deterministic processing of escrow denominations.

The current implementation uses map iteration which could be non-deterministic. For consensus-critical operations, we should ensure deterministic processing order.

 func migrateTransferTokenInEscrow(ctx sdk.Context, transferKeeper ibctransferkeeper.Keeper) {
     escrowDenoms := GetMigrateEscrowDenoms(ctx.ChainID())
-    for oldDenom, newDenom := range escrowDenoms {
+    // Get sorted keys for deterministic iteration
+    oldDenoms := make([]string, 0, len(escrowDenoms))
+    for oldDenom := range escrowDenoms {
+        oldDenoms = append(oldDenoms, oldDenom)
+    }
+    sort.Strings(oldDenoms)
+
+    for _, oldDenom := range oldDenoms {
+        newDenom := escrowDenoms[oldDenom]
         totalEscrow := transferKeeper.GetTotalEscrowForDenom(ctx, oldDenom)
         newAmount := totalEscrow.Amount
         if oldDenom == fxtypes.IBCFXDenom {
             newAmount = fxtypes.SwapAmount(newAmount)
         }
+        // Log migration details
+        ctx.Logger().Info("migrating escrow token",
+            "old_denom", oldDenom,
+            "new_denom", newDenom,
+            "old_amount", totalEscrow.Amount,
+            "new_amount", newAmount)
+
+        if !newAmount.IsPositive() {
+            ctx.Logger().Info("skipping zero amount escrow", "denom", oldDenom)
+            continue
+        }
+
         // first remove old denom
         transferKeeper.SetTotalEscrowForDenom(ctx, sdk.NewCoin(oldDenom, sdkmath.ZeroInt()))
         // then add new denom
         transferKeeper.SetTotalEscrowForDenom(ctx, sdk.NewCoin(newDenom, newAmount))
     }
 }
📝 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.

Suggested change
func migrateTransferTokenInEscrow(ctx sdk.Context, transferKeeper ibctransferkeeper.Keeper) {
escrowDenoms := GetMigrateEscrowDenoms(ctx.ChainID())
for oldDenom, newDenom := range escrowDenoms {
totalEscrow := transferKeeper.GetTotalEscrowForDenom(ctx, oldDenom)
newAmount := totalEscrow.Amount
if oldDenom == fxtypes.IBCFXDenom {
newAmount = fxtypes.SwapAmount(newAmount)
}
// first remove old denom
transferKeeper.SetTotalEscrowForDenom(ctx, sdk.NewCoin(oldDenom, sdkmath.ZeroInt()))
// then add new denom
transferKeeper.SetTotalEscrowForDenom(ctx, sdk.NewCoin(newDenom, newAmount))
}
}
func migrateTransferTokenInEscrow(ctx sdk.Context, transferKeeper ibctransferkeeper.Keeper) {
escrowDenoms := GetMigrateEscrowDenoms(ctx.ChainID())
// Get sorted keys for deterministic iteration
oldDenoms := make([]string, 0, len(escrowDenoms))
for oldDenom := range escrowDenoms {
oldDenoms = append(oldDenoms, oldDenom)
}
sort.Strings(oldDenoms)
for _, oldDenom := range oldDenoms {
newDenom := escrowDenoms[oldDenom]
totalEscrow := transferKeeper.GetTotalEscrowForDenom(ctx, oldDenom)
newAmount := totalEscrow.Amount
if oldDenom == fxtypes.IBCFXDenom {
newAmount = fxtypes.SwapAmount(newAmount)
}
// Log migration details
ctx.Logger().Info("migrating escrow token",
"old_denom", oldDenom,
"new_denom", newDenom,
"old_amount", totalEscrow.Amount,
"new_amount", newAmount)
if !newAmount.IsPositive() {
ctx.Logger().Info("skipping zero amount escrow", "denom", oldDenom)
continue
}
// first remove old denom
transferKeeper.SetTotalEscrowForDenom(ctx, sdk.NewCoin(oldDenom, sdkmath.ZeroInt()))
// then add new denom
transferKeeper.SetTotalEscrowForDenom(ctx, sdk.NewCoin(newDenom, newAmount))
}
}
🧰 Tools
🪛 GitHub Check: CodeQL

[warning] 224-234: Iteration over map
Iteration over map may be a possible source of non-determinism

@fx0x55 fx0x55 merged commit 7268f86 into main Jan 20, 2025
13 checks passed
@fx0x55 fx0x55 deleted the fx0x55/ibc-transfer branch January 20, 2025 05:57
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.

2 participants