Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat: handle fallback address with memo execution and adjust message coins #2443

Merged
merged 7 commits into from
Mar 1, 2024

Conversation

robert-zaremba
Copy link
Member

@robert-zaremba robert-zaremba commented Mar 1, 2024

Description

  1. The amount of IBC tokens we sent might be different than the amount we receive (eg operator can take fees). So, if a user will set a maximum amount (eg in MsgSupply) then we may get an error when executing the message. In that case we need to adjust the amount in the message.
  2. chore: refactore ibc memo handling to unify GMP and standard hooks
  3. support receiver fallback address in case hook execution fails.

Summary by CodeRabbit

  • Refactor
    • Renamed and updated methods in MemoHandler for improved memo parsing and preparation.
    • Refactored ICS20Module to handle memo validation errors and manage fallback receivers efficiently.
    • Improved test coverage in memo_handler_test.go for enhanced functionality testing.
  • New Features
    • Added new fields and methods to MemoHandler for advanced memo handling capabilities.
  • Bug Fixes
    • Addressed issues related to memo message validation and handling.

@robert-zaremba robert-zaremba requested a review from a team as a code owner March 1, 2024 01:31
Copy link
Contributor

coderabbitai bot commented Mar 1, 2024

Walkthrough

The update introduces significant enhancements to memo handling within the MemoHandler and related components. It includes the addition of new fields, methods, and test scenarios for improved memo processing and validation. Existing methods have been restructured to elevate memo management functionalities.

Changes

Files Change Summary
x/uibc/uics20/memo_handler.go Imported strings. Added fields, methods to MemoHandler. Renamed and updated methods.
x/uibc/uics20/ibc_module.go, x/uibc/uics20/memo_handler_test.go Refactored ICS20Module's onRecvPacket. Enhanced memo validation, cache handling, and message execution.

🐇📝
In the realm of memos, a rabbit's decree,
New fields and tests, under the moon's glee.
Strings entwined, methods refined,
Memo magic unfolds, a tale designed.
Test cases prance in a merry whirl,
Progress whispers, a promising swirl.
🌙🐾

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>.
    • Generate unit-tests for this file.
  • 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 tests 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 generate interesting stats about this repository from git and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit tests.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

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 as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • The JSON schema for the configuration file is available here.
  • 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/coderabbit-overrides.v2.json

CodeRabbit Discord Community

Join our Discord Community to get help, request features, and share feedback.

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.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 01bbb48 and 0990ff3.
Files selected for processing (5)
  • x/uibc/gmp/gmp_middleware.go (1 hunks)
  • x/uibc/gmp/types.go (1 hunks)
  • x/uibc/uics20/ibc_module.go (1 hunks)
  • x/uibc/uics20/memo_handler.go (5 hunks)
  • x/uibc/uics20/memo_handler_test.go (2 hunks)
Additional comments: 12
x/uibc/gmp/types.go (2)
  • 1-1: The removal of the import statement for sdk "github.com/cosmos/cosmos-sdk/types" indicates that it's no longer needed in this file. Verify that this change does not affect other parts of the code where sdk types might be used indirectly through this file.
  • 3-3: The introduction of the DefaultGMPAddress constant is a good practice for managing hardcoded values. Ensure that this address is correctly used wherever a default GMP address is needed in the codebase.
x/uibc/gmp/gmp_middleware.go (3)
  • 16-52: Refactoring the OnRecvPacket method to accept sdk.Coin instead of ics20types.FungibleTokenPacketData and updating the method signatures accordingly is a significant change. This adjustment allows for more precise handling of received coins and memo processing. Ensure that all calls to OnRecvPacket throughout the codebase have been updated to match the new signature and that the handling of sdk.Coin is correctly implemented.
  • 46-67: The implementation of HandleGeneralMessage and HandleGeneralMessageWithToken methods within the Handler struct is crucial for processing general messages and those with tokens. Ensure that these methods are correctly called with the appropriate parameters and that their error handling is robust to prevent unintended behavior.
  • 22-23: Adjustments made to error handling and logging within the Handler methods improve the clarity and traceability of operations. It's important to ensure that all error paths are correctly logged and that errors are handled appropriately to maintain the reliability of the message processing.

Also applies to: 34-35, 40-40

x/uibc/uics20/memo_handler_test.go (2)
  • 96-99: Setting mh.receiver, mh.received, and mh.msgs before calling validateMemoMsg in the test setup is a good practice for ensuring that the MemoHandler is in the correct state for testing. This approach helps in accurately testing the behavior of validateMemoMsg under different conditions.
  • 144-161: The addition of the TestAdjustOperatedCoin function is an excellent way to ensure the adjustOperatedCoin method behaves as expected under various scenarios. This test function covers different cases, including when the operated coin is of a different denom, when the operated amount is less than, equal to, or greater than the received amount. Ensure that all edge cases are covered and that the tests accurately reflect the intended behavior of adjustOperatedCoin.
x/uibc/uics20/memo_handler.go (4)
  • 6-6: The addition of the strings import is necessary for the new logic introduced in this file, particularly for string operations such as strings.EqualFold used in memo processing. Ensure that this import is used appropriately and does not introduce any unnecessary dependencies.
  • 25-31: The addition of new fields (isGMP, msgs, memo, received, receiver, fallbackReceiver) to the MemoHandler struct enhances its functionality and allows for more comprehensive handling of memos and messages. Ensure that these fields are correctly initialized and used throughout the MemoHandler methods to maintain the integrity of memo processing.
  • 36-83: Renaming the method onRecvPacketPre to onRecvPacketPrepare and updating its signature, along with the changes made to handle memo parsing and preparation, improves the clarity and functionality of the memo handling process. Ensure that all references to this method are updated accordingly and that the memo parsing logic is robust and handles all expected cases correctly.
Verification successful

The method renaming from onRecvPacketPre to onRecvPacketPrepare has been correctly implemented in the codebase, as evidenced by its usage in ibc_module.go. However, there is an outdated comment in memo_handler.go that still references the old method name. While this does not impact functionality, updating the comment would help maintain consistency and clarity in the documentation. All references to the method in the code have been updated accordingly, and the memo parsing logic's improvements are noted.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Search for references to onRecvPacketPre to ensure they've been updated to onRecvPacketPrepare.
rg --type go 'onRecvPacketPre'

Length of output: 317

* 195-203: The introduction of the `adjustOperatedCoin` method is a critical addition for handling discrepancies between sent and received coin amounts. This method ensures that the operated coin amount is adjusted to not exceed the received amount, which is essential for maintaining consistency in transactions. Review the logic to ensure it correctly handles all scenarios, especially the denomination check and the adjustment of the operated amount.
x/uibc/uics20/ibc_module.go (1)
  • 70-113: The refactoring of the onRecvPacket method includes significant changes to handle different scenarios during packet reception, such as memo validation errors and managing fallback receivers. The introduction of cache contexts to manage state changes conditionally is a sophisticated approach. Ensure that the control flow is clear and that all edge cases are handled correctly, especially regarding the use of fallback receivers and the execution of memo messages.

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.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 0990ff3 and eb45518.
Files selected for processing (1)
  • x/uibc/uics20/memo_handler.go (5 hunks)
Additional comments: 8
x/uibc/uics20/memo_handler.go (8)
  • 6-6: The addition of the strings import is appropriate for the new string operations introduced in this file, such as checking if the ftData.Sender is the default GMP address using strings.EqualFold.
  • 19-19: The introduction of the memoValidationErr variable is a good practice for error handling, ensuring consistency and reusability of the error message across the codebase.
  • 25-31: Adding new fields to the MemoHandler struct enhances its functionality to support the new features introduced in this PR, such as handling GMP transactions, storing parsed messages, and managing fallback receivers. This aligns well with the objectives of refactoring IBC memo handling and supporting a receiver fallback address.
  • 36-38: Renaming the method onRecvPacketPre to onRecvPacketPrepare and updating its signature improves clarity and better reflects the method's purpose of preparing the MemoHandler based on the received packet. This change enhances code readability and maintainability.
  • 52-56: The check for the default GMP address using strings.EqualFold is a good practice for case-insensitive comparison. However, it's important to ensure that gmp.DefaultGMPAddress is correctly defined and used consistently throughout the codebase.
Verification successful

Based on the provided script output, gmp.DefaultGMPAddress is defined in gmp/types.go and used in memo_handler.go. This suggests that it is correctly defined and used consistently in the shown context. The search did not reveal any inconsistencies or incorrect usage within the scope of the provided information.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that gmp.DefaultGMPAddress is defined and used consistently
rg 'DefaultGMPAddress' --type go

Length of output: 233

* 66-71: The logic to handle a fallback receiver address when the memo's fallback address is not formatted correctly is well-implemented. However, setting `fallbackReceiver` to `nil` if it equals `mh.receiver` (lines 69-71) is a critical step for avoiding redundant transactions to the same address. This logic enhances the robustness of the transaction process, aligning with the PR's objective to support a receiver fallback address. * 92-97: The `execute` method's implementation to handle GMP transactions by delegating to a `gmp.Handler` is a good example of modularity and separation of concerns. This change aligns with the PR's objective to refactor IBC memo handling. However, ensure that the `gmp.NewHandler()` method is correctly implemented and that it handles the provided arguments appropriately.
Verification successful

The implementation of gmp.NewHandler and its OnRecvPacket method aligns with the expectations set in the review comment, focusing on modularity and separation of concerns. The NewHandler function is correctly implemented to return a Handler object, and the OnRecvPacket method accepts the appropriate arguments (sdk.Context, sdk.Coin, string, sdk.AccAddress) for handling GMP transactions. This confirms the PR's objective to refactor IBC memo handling effectively.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify the implementation of gmp.NewHandler and its OnRecvPacket method
rg 'func NewHandler' --type go
rg 'func \(.*Handler\) OnRecvPacket' --type go

Length of output: 276

* 198-206: The `adjustOperatedCoin` method ensures that the operated coin amount does not exceed the received amount, which is crucial for addressing the discrepancy issue mentioned in the PR objectives. This method enhances the robustness of message coin adjustments. However, it's important to ensure that this method is called appropriately in the context where coin amounts are adjusted.

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.

Review Status

Actionable comments generated: 2

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between eb45518 and c50f6c9.
Files selected for processing (2)
  • x/uibc/uics20/memo_handler.go (5 hunks)
  • x/uibc/uics20/memo_handler_test.go (3 hunks)
Files skipped from review as they are similar to previous changes (1)
  • x/uibc/uics20/memo_handler_test.go
Additional comments: 14
x/uibc/uics20/memo_handler.go (14)
  • 6-6: The addition of the strings import is appropriate for the string operations performed in the updated code, such as checking if the ftData.Sender is the GMP address.
  • 19-19: The introduction of the memoValidationErr variable is a good practice for standardizing error responses related to memo validation. This makes error handling more consistent across the codebase.
  • 25-31: Adding new fields to the MemoHandler struct (isGMP, msgs, memo, received, receiver, and fallbackReceiver) enhances the handler's capability to process and manage memo-related data effectively. This aligns with the PR's objectives to improve memo execution and handling.
  • 36-37: Renaming onRecvPacketPre to onRecvPacketPrepare and updating its signature improves code readability and better reflects the method's purpose, which is to prepare the memo handler based on the received packet data.
  • 53-57: The check for the GMP address using strings.EqualFold and setting the isGMP flag based on this check is a clear and efficient way to handle GMP transactions. This aligns with the PR's objective to refactor IBC memo handling.
  • 62-62: Logging the error when the ICS20 memo is not recognized and ignoring hook execution is a reasonable approach. However, ensure that this behavior is documented and understood by users, as it could impact the execution of transactions with unrecognized memos.
  • 67-67: Validating the format of the fallbackReceiver address when defined in the memo is crucial for ensuring that transactions can be redirected correctly in case of hook execution failure. This adds robustness to the transaction process.
  • 70-72: Setting the fallbackReceiver to nil if it equals the receiver is a logical safeguard to prevent unnecessary redirections. This ensures that the fallback mechanism is used appropriately.
  • 75-79: Handling errors when unpacking memo messages and appending the error to the events list is a good practice. It provides feedback on the memo processing outcome, which is valuable for debugging and monitoring.
  • 82-84: Validating memo messages and returning a standardized memoValidationErr if they are not valid is consistent with the approach of using predefined error variables. This enhances error handling consistency.
  • 93-98: The execute method's approach to handling GMP transactions by delegating to a gmp.NewHandler() is a clean separation of concerns. This modularizes the handling of different types of transactions and aligns with the PR's refactoring objectives.
  • 100-105: The early return when there are no messages to handle in the execute method is an efficient way to avoid unnecessary processing. This is a good practice for performance optimization.
  • 135-156: > 📝 NOTE

This review was outside the diff hunks and was mapped to the diff hunk with the greatest overlap. Original lines [126-153]

The validateMemoMsg method's implementation to support specific message combinations and validate the operated coin against the received coin is crucial for ensuring transaction integrity. However, consider documenting the supported message types and combinations more explicitly for clarity.

  • 199-207: The adjustOperatedCoin method ensures that the operated coin is of the same denom as the received coin and adjusts the operated amount if necessary. This is an important check for maintaining transaction integrity and aligns with the PR's objective to adjust message coins.

Copy link

codecov bot commented Mar 1, 2024

Codecov Report

Attention: Patch coverage is 16.43836% with 61 lines in your changes are missing coverage. Please review.

Project coverage is 68.90%. Comparing base (7f05ad4) to head (e829eff).
Report is 391 commits behind head on main.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #2443      +/-   ##
==========================================
- Coverage   75.38%   68.90%   -6.49%     
==========================================
  Files         100      183      +83     
  Lines        8025    10821    +2796     
==========================================
+ Hits         6050     7456    +1406     
- Misses       1589     2755    +1166     
- Partials      386      610     +224     
Files Coverage Δ
x/uibc/uics20/ibc_module.go 0.00% <0.00%> (ø)
x/uibc/uics20/memo_handler.go 28.73% <26.66%> (ø)

... and 172 files with indirect coverage changes

@robert-zaremba robert-zaremba enabled auto-merge March 1, 2024 06:44
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.

Review Status

Actionable comments generated: 0

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between c50f6c9 and e44fa5c.
Files selected for processing (2)
  • x/uibc/uics20/ibc_module.go (1 hunks)
  • x/uibc/uics20/memo_handler.go (5 hunks)
Files skipped from review as they are similar to previous changes (2)
  • x/uibc/uics20/ibc_module.go
  • x/uibc/uics20/memo_handler.go

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.

Review Status

Actionable comments generated: 1

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between e44fa5c and e829eff.
Files selected for processing (2)
  • x/uibc/uics20/ibc_module.go (1 hunks)
  • x/uibc/uics20/memo_handler.go (5 hunks)
Files skipped from review as they are similar to previous changes (1)
  • x/uibc/uics20/ibc_module.go
Additional comments: 8
x/uibc/uics20/memo_handler.go (8)
  • 6-6: The addition of the strings import is appropriate for the usage of strings.EqualFold in the onRecvPacketPrepare method. This is a good practice for case-insensitive string comparison.
  • 19-19: The introduction of the errMemoValidation variable is a good practice for defining custom errors. It enhances the readability and maintainability of error handling.
  • 25-31: Adding new fields to the MemoHandler struct (isGMP, msgs, memo, received, receiver, and fallbackReceiver) is crucial for supporting the new functionalities described in the PR objectives. These additions allow for more flexible and robust memo handling.
  • 36-38: Renaming onRecvPacketPre to onRecvPacketPrepare and updating its signature improves clarity and better reflects the method's purpose. This change aligns with best practices for naming and method design.
  • 53-56: The check for strings.EqualFold(ftData.Sender, gmp.DefaultGMPAddress) and setting mh.isGMP accordingly is a smart way to handle GMP transactions. However, ensure that gmp.DefaultGMPAddress is correctly defined and accessible.
Verification successful

The verification confirms that gmp.DefaultGMPAddress is correctly defined in x/uibc/gmp/types.go and is accessible for use in x/uibc/uics20/memo_handler.go, as intended. This addresses the concern raised in the review comment.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Verify that gmp.DefaultGMPAddress is defined and accessible
rg 'DefaultGMPAddress' --type go

Length of output: 233

* 64-71: The logic to set `mh.fallbackReceiver` based on `memo.FallbackAddr` and to clear it if it equals `mh.receiver` is a thoughtful addition for handling fallback scenarios. This enhances the robustness of the transaction process. * 92-97: The `execute` method's handling of GMP transactions by checking `mh.isGMP` and delegating to a `gmp.NewHandler().OnRecvPacket` is a clean separation of concerns. This modular approach facilitates easier maintenance and future enhancements. * 198-206: The `adjustOperatedCoin` function's logic to ensure that the received and operated coins are of the same denom and to adjust the operated amount if necessary is a critical check for transaction integrity. This is a well-thought-out addition to the codebase.

Copy link
Collaborator

@gsk967 gsk967 left a comment

Choose a reason for hiding this comment

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

utACK

@robert-zaremba robert-zaremba added this pull request to the merge queue Mar 1, 2024
Merged via the queue into main with commit ea3b304 Mar 1, 2024
24 of 26 checks passed
@robert-zaremba robert-zaremba deleted the robert/update-memo-handler branch March 1, 2024 16:41
# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants