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

feat: add submsg impl #277

Merged
merged 6 commits into from
Oct 7, 2024
Merged

feat: add submsg impl #277

merged 6 commits into from
Oct 7, 2024

Conversation

beer-1
Copy link
Contributor

@beer-1 beer-1 commented Oct 4, 2024

Description

Allow executing Stargate message with options to allow callback and failure.

Closes: #XXXX


Author Checklist

All items are required. Please add a note to the item if the item is not applicable and
please add links to any relevant follow up issues.

I have...

  • included the correct type prefix in the PR title, you can find examples of the prefixes below:
  • confirmed ! in the type prefix if API or client breaking change
  • targeted the correct branch
  • provided a link to the relevant issue or specification
  • reviewed "Files changed" and left comments if necessary
  • included the necessary unit and integration tests
  • updated the relevant documentation or specification, including comments for documenting Go code
  • confirmed all CI checks have passed

Reviewers Checklist

All items are required. Please add a note if the item is not applicable and please add
your handle next to the items reviewed if you only reviewed selected items.

I have...

  • confirmed the correct type prefix in the PR title
  • confirmed all author checklist items have been addressed
  • reviewed state machine logic, API design and naming, documentation is accurate, tests and test coverage

@beer-1 beer-1 self-assigned this Oct 4, 2024
@beer-1 beer-1 requested a review from a team as a code owner October 4, 2024 07:43
Copy link

coderabbitai bot commented Oct 4, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces several updates across multiple files, primarily focusing on version upgrades, command modifications, and enhancements to message handling within the application. Key changes include updating the LIBMOVEVM library version in the Dockerfile, modifying upgrade logic in app/upgrade.go, and refining command structures in cmd/initiad/root.go and cmd/move/move.go. Additionally, new functionalities and event structures are added to the Move module, along with improvements in testing coverage for submessage callbacks.

Changes

File Change Summary
Dockerfile Updated LIBMOVEVM_VERSION from v0.4.12 to v0.5.0.
app/upgrade.go Updated upgradeName constant from "0.2.2" to "0.5.4"; modified RegisterUpgradeHandlers to include new logic for handling module upgrades and error handling.
cmd/initiad/root.go Added a second argument false to movecmd.MoveCommand function call.
cmd/move/move.go Updated MoveCommand and moveNewCmd signatures to include useMinlib parameter; enhanced logic to read movevm version from build information.
x/move/keeper/common_test.go Added submsgModule variable to hold contents of a Move file; updated MsgExecuteJSON handler to include error handling for "fail" function name.
x/move/keeper/contracts/sources/Submsg.move Introduced TestAccount::submsg module with functionalities for stargate operations and event emissions.
x/move/keeper/handler.go Added dispatchMessage method for handling Cosmos messages; refactored DispatchMessages to utilize this new method.
x/move/keeper/handler_test.go Added TestSubmsgCallback to test submessage callback behavior; adjusted event retrieval logic in existing tests.
x/move/types/events.go Added EventTypeSubmsg, AttributeKeySuccess, and AttributeKeyReason to enhance event handling capabilities.
x/move/types/params.go Updated DefaultContractSharedRevenueRatio from math.LegacyNewDecWithPrec(50, 2) to math.LegacyZeroDec().

Possibly related PRs

Suggested reviewers

  • Vritra4
  • sh-cha

Poem

In the burrow deep, where the code does creep,
A version's changed, a leap so steep.
With stargate calls and messages bright,
We hop along, coding through the night!
From v0.4 to v0.5, we cheer with glee,
For every change, a new world to see! 🐇✨


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

github-actions bot commented Oct 4, 2024

Dependency Review

The following issues were found:
  • ✅ 0 vulnerable package(s)
  • ✅ 0 package(s) with incompatible licenses
  • ✅ 0 package(s) with invalid SPDX license definitions
  • ⚠️ 2 package(s) with unknown licenses.
See the Details below.

License Issues

go.mod

PackageVersionLicenseIssue Type
github.com/initia-labs/OPinit0.5.3NullUnknown License
github.com/initia-labs/movevm0.5.0NullUnknown License
Denied Licenses: GPL-1.0-or-later, LGPL-2.0-or-later

OpenSSF Scorecard

PackageVersionScoreDetails
gomod/github.com/initia-labs/OPinit 0.5.3 UnknownUnknown
gomod/github.com/initia-labs/movevm 0.5.0 UnknownUnknown

Scanned Manifest Files

go.mod

Copy link

codecov bot commented Oct 4, 2024

Codecov Report

Attention: Patch coverage is 61.61616% with 38 lines in your changes missing coverage. Please review.

Project coverage is 40.59%. Comparing base (1298e7f) to head (fff8273).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
app/upgrade.go 0.00% 20 Missing ⚠️
x/move/keeper/handler.go 77.21% 12 Missing and 6 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #277      +/-   ##
==========================================
+ Coverage   40.53%   40.59%   +0.05%     
==========================================
  Files         267      267              
  Lines       25314    25400      +86     
==========================================
+ Hits        10262    10310      +48     
- Misses      13464    13503      +39     
+ Partials     1588     1587       -1     
Files with missing lines Coverage Δ
x/move/types/params.go 75.60% <ø> (ø)
x/move/keeper/handler.go 78.09% <77.21%> (-0.48%) ⬇️
app/upgrade.go 12.50% <0.00%> (-37.50%) ⬇️

... and 3 files with indirect coverage changes

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

🧹 Outside diff range and nitpick comments (3)
x/move/keeper/common_test.go (1)

563-566: LGTM: Added failure condition for testing.

The new condition allows for testing failure scenarios in the MsgExecuteJSON handler, which is valuable for comprehensive testing.

Consider enhancing the error message to be more descriptive, e.g., fmt.Errorf("intentional failure for testing"). This would make the purpose of the error clearer in test outputs.

 if msg.FunctionName == "fail" {
-    return nil, fmt.Errorf("fail")
+    return nil, fmt.Errorf("intentional failure for testing")
 }
x/move/keeper/handler.go (2)

461-461: Typo in comment: "becuase" should be "because"

There's a minor typographical error in the comment at line 461. The word "becuase" should be corrected to "because".


471-473: Ensure correct formatting of callback arguments

When formatting the callback arguments using fmt.Sprintf, ensure that the values are correctly formatted:

  • Line 471: fmt.Sprintf("\"%d\"", callback.Id) adds extra quotes around the integer ID, resulting in a string like "\"123\"". If the callback expects a string representation of the integer without extra quotes, consider removing the escaped quotes.
  • Line 472: fmt.Sprintf("%v", success) formats a boolean value. Ensure that this matches the expected input type for the callback function.

Consider updating the code as follows:

fmt.Sprintf("%d", callback.Id),
fmt.Sprintf("%t", success),
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1298e7f and a07984f.

⛔ Files ignored due to path filters (2)
  • go.mod is excluded by !**/*.mod
  • go.sum is excluded by !**/*.sum, !**/*.sum
📒 Files selected for processing (10)
  • Dockerfile (1 hunks)
  • app/upgrade.go (1 hunks)
  • cmd/initiad/root.go (1 hunks)
  • cmd/move/move.go (5 hunks)
  • x/move/keeper/common_test.go (3 hunks)
  • x/move/keeper/contracts/sources/Submsg.move (1 hunks)
  • x/move/keeper/handler.go (2 hunks)
  • x/move/keeper/handler_test.go (9 hunks)
  • x/move/types/events.go (2 hunks)
  • x/move/types/params.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (15)
Dockerfile (2)

Line range hint 1-62: Verify build process with the new LIBMOVEVM version

The update to LIBMOVEVM v0.5.0 is the only change in this Dockerfile. While the change itself looks good, it's crucial to ensure that the entire build process works correctly with this new version.

Please make sure to:

  1. Run the full CI/CD pipeline to verify that the build succeeds with the new LIBMOVEVM version.
  2. Test the resulting Docker image to ensure all functionalities work as expected.
  3. If possible, perform a local build and test before merging this change.

This will help catch any potential issues that might arise from the version update early in the development process.


9-9: LGTM. Verify compatibility and update documentation.

The update of LIBMOVEVM_VERSION from v0.4.12 to v0.5.0 looks good. This change might introduce new features or bug fixes in the LIBMOVEVM library.

Please ensure the following:

  1. Verify that v0.5.0 of LIBMOVEVM is compatible with the rest of the project.
  2. Update any relevant documentation or dependency lists to reflect this version change.

To verify the compatibility and usage of this new version, you can run the following script:

This script will help identify any areas of the codebase that might need attention due to the version update.

✅ Verification successful

Verification Successful: All references to LIBMOVEVM version v0.4.12 have been successfully updated to v0.5.0. No issues found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for LIBMOVEVM version references and potential incompatibilities

# Check for any hardcoded version references that might need updating
echo "Checking for hardcoded LIBMOVEVM version references:"
rg --type-add 'go:*.{go,mod}' --type go -i 'libmovevm.*0\.4\.12'

# Check go.mod for any LIBMOVEVM dependencies that might need updating
echo "Checking go.mod for LIBMOVEVM dependencies:"
rg --type-add 'go:*.{go,mod}' --type go '^require.*libmovevm' go.mod

# Look for any LIBMOVEVM API usage that might have changed
echo "Checking for LIBMOVEVM API usage:"
rg --type-add 'go:*.go' --type go 'libmovevm\.'

# Check for any tests related to LIBMOVEVM that might need updating
echo "Checking for LIBMOVEVM-related tests:"
rg --type-add 'go:*.go' --type go 'Test.*LIBMOVEVM'

Length of output: 615


Script:

#!/bin/bash
# Description: Check for LIBMOVEVM version references and potential incompatibilities

# Check for any hardcoded version references that might need updating
echo "Checking for hardcoded LIBMOVEVM version references:"
rg --type-add 'go:*.{go,mod}' --type go -i 'libmovevm.*0\.4\.12'

# Check go.mod for any LIBMOVEVM dependencies that might need updating
echo "Checking go.mod for LIBMOVEVM dependencies:"
rg --type-add 'go:*.{go,mod}' --type go '^require.*libmovevm' go.mod

# Look for any LIBMOVEVM API usage that might have changed
echo "Checking for LIBMOVEVM API usage:"
rg --type-add 'go:*.go' --type go 'libmovevm\.'

# Check for any tests related to LIBMOVEVM that might need updating
echo "Checking for LIBMOVEVM-related tests:"
rg --type-add 'go:*.go' --type go 'Test.*LIBMOVEVM'

Length of output: 615

x/move/types/params.go (1)

23-23: Significant change in default contract shared revenue ratio

The DefaultContractSharedRevenueRatio has been changed from 50% (math.LegacyNewDecWithPrec(50, 2)) to 0% (math.LegacyZeroDec()). This change will affect the default behavior of the Move module's revenue sharing model for contracts.

Potential impacts:

  1. Existing systems or users expecting the previous 50% ratio might experience unexpected behavior.
  2. This change could significantly alter the economics of contract interactions within the system.

While this change aligns with the PR objectives of implementing new options for Stargate messages and handling failures, it's important to ensure that this modification is intentional and well-documented.

Could you please clarify the rationale behind this change and confirm if any documentation or migration guides need to be updated to reflect this new default behavior?

✅ Verification successful

DefaultContractSharedRevenueRatio Change Verified

The DefaultContractSharedRevenueRatio has been successfully changed from 50% to 0%, and this modification is localized to the parameter definition and its related tests. No references to the old default value were found in the documentation or other parts of the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any references to the old default value in comments, documentation, or test files

# Test: Search for references to the old 50% default value
echo "Searching for references to the old 50% default value:"
rg --type md --type go "50%" -C 2
echo "---"

# Test: Search for references to contract shared revenue ratio in test files
echo "Searching for contract shared revenue ratio tests:"
rg --type go "ContractSharedRevenueRatio" -C 2 $(fd -e go test)

Length of output: 11472

x/move/keeper/common_test.go (2)

490-490: LGTM: New variable for submsg module.

The addition of submsgModule is consistent with the existing pattern for other Move modules in this test file.


499-499: LGTM: Initialization of submsg module.

The submsgModule is properly initialized in the init() function, consistent with other module initializations.

x/move/keeper/contracts/sources/Submsg.move (3)

7-19: Function stargate is implemented correctly

The stargate function appropriately handles the allow_failure flag to determine the correct options for cosmos::stargate_with_options. The function parameters are well-defined, and the logic aligns with the intended functionality.


34-41: callback_with_signer function correctly emits event with signer

The callback_with_signer function properly emits the ResultEventWithSigner event (or ResultEvent if consolidated) with the correct account address and parameters. The use of signer::address_of(account) accurately captures the signer's address.


43-48: callback_without_signer function correctly emits event without signer

The callback_without_signer function correctly emits the ResultEvent event with the provided id and success parameters. The implementation is straightforward and functions as intended.

app/upgrade.go (1)

15-15: Update of upgradeName reflects the new version

The upgradeName constant has been updated to "0.5.4", which aligns with the PR objective of implementing changes for version 0.5.4. This is appropriate and ensures that the upgrade handler targets the correct version.

x/move/keeper/handler.go (2)

8-8: Importing "fmt" package is necessary

The addition of the "fmt" package import is appropriate, as fmt.Sprintf is used in the code for string formatting.


417-424: Refactoring improves code readability and maintainability

Extracting the message dispatch logic into the dispatchMessage method enhances code modularity and readability. This separation of concerns makes the DispatchMessages function cleaner and the codebase easier to maintain.

x/move/keeper/handler_test.go (1)

169-169: Verify event index calculations to prevent off-by-one errors

In several test functions (TestDispatchDelegateMessage, TestDispatchFundCommunityPoolMessage, TestDispatchTransferMessage, TestDispatchPayFeeMessage, TestDispatchFundMoveExecute, TestDispatchFundMoveExecuteWithJson, TestDispatchFundMoveScript, TestDispatchFundMoveScriptWithJson), the event is retrieved using events[len(events)-2].

Using hard-coded indices may lead to fragile tests if the number of emitted events changes. Please verify that this index accurately references the intended event after the test execution.

Consider refactoring the event retrieval logic to search for the event based on its type or attributes. This would make the tests more robust against changes in the event list.

Also applies to: 203-203, 272-272, 339-339, 390-390, 440-440, 483-483, 524-524

cmd/move/move.go (3)

102-102: Passing useMinlib to moveNewCmd

The call to moveNewCmd now includes the useMinlib parameter, allowing the move new command to utilize the minimal library option as intended.


311-311: Update function signature of moveNewCmd to accept useMinlib

The function moveNewCmd now accepts useMinlib as a parameter, enabling conditional logic based on this flag within the command.


89-89: Update function signature to include useMinlib

The function MoveCommand now accepts a new parameter useMinlib. Ensure that all calls to MoveCommand are updated to pass the correct useMinlib value to prevent compile-time errors.

Run the following script to verify that all invocations of MoveCommand are updated:

✅ Verification successful

Further Verification Needed

The previous script may have captured function definitions instead of function calls. Please run the following script to identify actual calls to MoveCommand that do not include the useMinlib parameter:


All MoveCommand Calls are Correctly Updated

All invocations of MoveCommand include the useMinlib parameter.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all calls to `MoveCommand` include the new `useMinlib` parameter.

# Test: Search for function calls to `MoveCommand` in Go files.
# Expect: All calls should pass `ac` and `useMinlib` arguments.

rg --type go -o 'MoveCommand\([^\)]*\)' | grep -v 'MoveCommand(ac, useMinlib)'

Length of output: 225


Script:

#!/bin/bash
# Description: Verify all calls to `MoveCommand` include the new `useMinlib` parameter, excluding function definitions.

# Test: Search for function calls to `MoveCommand` in Go files, excluding definitions.
# Expect: All calls should pass `ac` and `useMinlib` arguments.

rg --type go 'MoveCommand\(' | grep -v 'func MoveCommand' | grep -v 'MoveCommand(ac, useMinlib)'

Length of output: 232

x/move/types/events.go Show resolved Hide resolved
cmd/initiad/root.go Show resolved Hide resolved
x/move/keeper/contracts/sources/Submsg.move Show resolved Hide resolved
x/move/keeper/contracts/sources/Submsg.move Show resolved Hide resolved
app/upgrade.go Show resolved Hide resolved
x/move/keeper/handler.go Outdated Show resolved Hide resolved
x/move/keeper/handler.go Outdated Show resolved Hide resolved
x/move/keeper/handler_test.go Show resolved Hide resolved
cmd/move/move.go Show resolved Hide resolved
cmd/move/move.go Show resolved Hide resolved
x/move/keeper/handler.go Outdated Show resolved Hide resolved
x/move/keeper/handler.go Show resolved Hide resolved
Copy link
Contributor

@sh-cha sh-cha left a comment

Choose a reason for hiding this comment

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

LGTM

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

🧹 Outside diff range and nitpick comments (2)
x/move/keeper/handler.go (2)

509-525: LGTM: Proper message handling and event emission

The implementation of message handler lookup, execution, and event emission is well-structured and includes appropriate error handling.

Consider adding more context to the error returned when a handler is not found. This can help with debugging and provide more information about which message type caused the issue. Here's a suggested improvement:

 handler := k.msgRouter.Handler(msg)
 if handler == nil {
-    err = types.ErrNotSupportedCosmosMessage
+    err = fmt.Errorf("%w for message type %T", types.ErrNotSupportedCosmosMessage, msg)
     return
 }

This change will include the message type in the error, making it easier to identify unsupported message types during debugging.


433-435: LGTM: Robust panic recovery added

The addition of panic recovery in the deferred function is an excellent improvement that enhances the overall robustness of the code.

Consider adding more context to the panic error message to aid in debugging. Here's a suggested improvement:

 defer func() {
     if r := recover(); r != nil {
-        err = fmt.Errorf("panic: %v", r)
+        err = fmt.Errorf("panic in dispatchMessage: %v", r)
     }
     // ... rest of the deferred function
 }()

This change provides more specific information about where the panic occurred, which can be helpful during troubleshooting.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between a07984f and fff8273.

📒 Files selected for processing (1)
  • x/move/keeper/handler.go (2 hunks)
🧰 Additional context used
🔇 Additional comments (2)
x/move/keeper/handler.go (2)

417-424: LGTM: Improved code structure and error handling

The refactoring of DispatchMessages to use the new dispatchMessage function improves code organization and readability. The added error handling ensures that execution stops if any message dispatch fails, which is appropriate for maintaining consistency.


Line range hint 1-725: Overall assessment: Significant improvements in code structure and robustness

The changes in this file represent a substantial enhancement to the message handling logic. Key improvements include:

  1. Refactoring of the DispatchMessages function for better code organization.
  2. Introduction of the dispatchMessage function with comprehensive error handling and panic recovery.
  3. Improved handling of different message types (Stargate and non-Stargate).
  4. Enhanced event emission and callback execution.

These changes contribute to better readability, maintainability, and robustness of the code. The minor suggestions provided in the review comments are aimed at further improving consistency in error handling and enhancing debugging capabilities.

Great job on these improvements!

x/move/keeper/handler.go Show resolved Hide resolved
x/move/keeper/handler.go Show resolved Hide resolved
@beer-1 beer-1 requested a review from sh-cha October 7, 2024 05:15
@beer-1 beer-1 merged commit d14724b into main Oct 7, 2024
11 checks passed
@beer-1 beer-1 deleted the feat/sub-message branch October 7, 2024 05:16
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