Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

fix: allow string callback id #315

Merged
merged 2 commits into from
Dec 3, 2024
Merged

fix: allow string callback id #315

merged 2 commits into from
Dec 3, 2024

Conversation

beer-1
Copy link
Contributor

@beer-1 beer-1 commented Dec 3, 2024

Description

The IBC callback is using a standard JSON decoder, which allows only numbers as valid async callback IDs. However, our MoveVM JSON encoder encodes uint64 values as strings. To maintain consistency with this implementation, our AsyncCallback uses a custom UnmarshalJSON method, which accommodates both string and numeric callback IDs.


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 Dec 3, 2024
@beer-1 beer-1 requested a review from a team as a code owner December 3, 2024 05:53
Copy link

coderabbitai bot commented Dec 3, 2024

📝 Walkthrough

Walkthrough

The pull request includes updates to two files: app/upgrade.go and x/ibc-hooks/move-hooks/message.go. In app/upgrade.go, the version number constant upgradeName is changed from "0.6.2" to "0.6.4", affecting the registration of upgrade handlers. In x/ibc-hooks/move-hooks/message.go, new types asyncCallback and asyncCallbackStringID are introduced, along with a custom JSON unmarshaler for the AsyncCallback type to handle different representations of the Id field. Additionally, a new test file message_test.go is created to validate the unmarshalling functionality.

Changes

File Change Summary
app/upgrade.go Updated constant upgradeName from "0.6.2" to "0.6.4".
x/ibc-hooks/move-hooks/message.go Added types asyncCallback and asyncCallbackStringID, and implemented UnmarshalJSON method for AsyncCallback.
x/ibc-hooks/move-hooks/message_test.go Introduced message_test.go with a test function Test_Unmarshal_AsyncCallback for JSON unmarshalling validation.

Possibly related PRs

  • bump: opinit #278: This PR updates the upgradeName constant in the same app/upgrade.go file, indicating a version increment similar to the main PR.
  • fix: has relayer permission #279: This PR also modifies the upgradeName constant in app/upgrade.go, reflecting another version update that is directly related to the changes in the main PR.
  • release: prepare v0.6.2 release #307: This PR updates the upgradeName constant in app/upgrade.go as well, showing a version change that aligns with the context of the main PR's modifications.

🐰 In the code, we hop and play,
Upgrading versions, hip-hip-hooray!
New types for callbacks, oh what a treat,
JSON unmarshalling, can't be beat!
With tests in place, we leap with glee,
Code so fine, as fine as can be! 🌟


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 Dec 3, 2024

Dependency Review

✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.

OpenSSF Scorecard

PackageVersionScoreDetails

Scanned Files

Copy link
Contributor

@Vritra4 Vritra4 left a comment

Choose a reason for hiding this comment

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

LGTM

@beer-1 beer-1 merged commit 103a58e into main Dec 3, 2024
9 checks passed
@beer-1 beer-1 deleted the fix/allow-string-callback-id branch December 3, 2024 06:11
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: 1

🧹 Outside diff range and nitpick comments (3)
x/ibc-hooks/move-hooks/message_test.go (1)

11-33: Add test cases for edge scenarios

While the current tests cover the basic functionality, consider adding test cases for:

  • Invalid JSON format
  • Negative numbers
  • Numbers exceeding uint64 max value
  • Malformed string IDs (e.g., "abc", "-123", "1.23")

Here's a suggested addition:

 func Test_Unmarshal_AsyncCallback(t *testing.T) {
+	testCases := []struct {
+		name    string
+		json    string
+		wantErr bool
+		want    movehooks.AsyncCallback
+	}{
+		{
+			name: "valid uint64",
+			json: `{"id": 99, "module_address": "0x1", "module_name": "Counter"}`,
+			want: movehooks.AsyncCallback{Id: 99, ModuleAddress: "0x1", ModuleName: "Counter"},
+		},
+		{
+			name: "valid string id",
+			json: `{"id": "99", "module_address": "0x1", "module_name": "Counter"}`,
+			want: movehooks.AsyncCallback{Id: 99, ModuleAddress: "0x1", ModuleName: "Counter"},
+		},
+		{
+			name:    "negative number",
+			json:    `{"id": -1, "module_address": "0x1", "module_name": "Counter"}`,
+			wantErr: true,
+		},
+		{
+			name:    "overflow uint64",
+			json:    `{"id": 18446744073709551616, "module_address": "0x1", "module_name": "Counter"}`,
+			wantErr: true,
+		},
+		{
+			name:    "invalid string id",
+			json:    `{"id": "abc", "module_address": "0x1", "module_name": "Counter"}`,
+			wantErr: true,
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			var callback movehooks.AsyncCallback
+			err := json.Unmarshal([]byte(tc.json), &callback)
+			if tc.wantErr {
+				require.Error(t, err)
+				return
+			}
+			require.NoError(t, err)
+			require.Equal(t, tc.want, callback)
+		})
+	}
x/ibc-hooks/move-hooks/message.go (2)

56-62: Consider using type embedding to reduce code duplication

The asyncCallback struct is identical to AsyncCallback. Consider using type embedding to reduce maintenance burden:

-type asyncCallback struct {
-	Id            uint64 `json:"id"`
-	ModuleAddress string `json:"module_address"`
-	ModuleName    string `json:"module_name"`
-}
+type asyncCallback AsyncCallback

64-71: Consider using type embedding for string ID variant

Similar to the previous comment, asyncCallbackStringID could use type embedding with just the ID field being different:

-type asyncCallbackStringID struct {
-	Id            uint64 `json:"id,string"`
-	ModuleAddress string `json:"module_address"`
-	ModuleName    string `json:"module_name"`
-}
+type asyncCallbackStringID struct {
+	AsyncCallback `json:",inline"`
+	Id           uint64 `json:"id,string"`
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c79d331 and 6a93737.

📒 Files selected for processing (3)
  • app/upgrade.go (1 hunks)
  • x/ibc-hooks/move-hooks/message.go (2 hunks)
  • x/ibc-hooks/move-hooks/message_test.go (1 hunks)
🔇 Additional comments (1)
app/upgrade.go (1)

10-10: Verify version bump from 0.6.2 to 0.6.4

The version increment seems large for this change. Could you clarify if there are other changes that justify skipping 0.6.3?

Comment on lines +76 to +96
func (a *AsyncCallback) UnmarshalJSON(bz []byte) error {
var ac asyncCallback
err := json.Unmarshal(bz, &ac)
if err != nil {
var acStr asyncCallbackStringID
err := json.Unmarshal(bz, &acStr)
if err != nil {
return err
}

a.Id = acStr.Id
a.ModuleAddress = acStr.ModuleAddress
a.ModuleName = acStr.ModuleName
return nil
}

a.Id = ac.Id
a.ModuleAddress = ac.ModuleAddress
a.ModuleName = ac.ModuleName
return nil
}
Copy link

@coderabbitai coderabbitai bot Dec 3, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance error handling and add validation

The UnmarshalJSON implementation could be improved in several ways:

  1. Add validation for ModuleAddress format
  2. Return more specific error messages
  3. Optimize memory allocation by using a single intermediate struct
 func (a *AsyncCallback) UnmarshalJSON(bz []byte) error {
-	var ac asyncCallback
-	err := json.Unmarshal(bz, &ac)
-	if err != nil {
-		var acStr asyncCallbackStringID
-		err := json.Unmarshal(bz, &acStr)
-		if err != nil {
-			return err
-		}
+	var raw struct {
+		Id            interface{} `json:"id"`
+		ModuleAddress string     `json:"module_address"`
+		ModuleName    string     `json:"module_name"`
+	}
 
-		a.Id = acStr.Id
-		a.ModuleAddress = acStr.ModuleAddress
-		a.ModuleName = acStr.ModuleName
-		return nil
-	}
+	if err := json.Unmarshal(bz, &raw); err != nil {
+		return fmt.Errorf("failed to unmarshal AsyncCallback: %w", err)
+	}
 
-	a.Id = ac.Id
-	a.ModuleAddress = ac.ModuleAddress
-	a.ModuleName = ac.ModuleName
+	// Validate ModuleAddress format
+	if !strings.HasPrefix(raw.ModuleAddress, "0x") {
+		return fmt.Errorf("invalid module address format: %s", raw.ModuleAddress)
+	}
+
+	// Handle both string and number ID formats
+	switch v := raw.Id.(type) {
+	case float64:
+		if v < 0 || v > math.MaxUint64 {
+			return fmt.Errorf("id %v out of range for uint64", v)
+		}
+		a.Id = uint64(v)
+	case string:
+		id, err := strconv.ParseUint(v, 10, 64)
+		if err != nil {
+			return fmt.Errorf("invalid string id %q: %w", v, err)
+		}
+		a.Id = id
+	default:
+		return fmt.Errorf("id must be a number or string, got %T", raw.Id)
+	}
+
+	a.ModuleAddress = raw.ModuleAddress
+	a.ModuleName = raw.ModuleName
 	return nil
 }

Don't forget to add the required imports:

import (
    "fmt"
    "math"
    "strconv"
    "strings"
)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Please make it as issue for later update

Copy link

Choose a reason for hiding this comment

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

@beer-1, I have created a new GitHub issue to track this enhancement: #317.

🔗 Analysis chain
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
gh issue create \
  --title "Enhance error handling and add validation in UnmarshalJSON" \
  --body "As per the discussion in PR #315 (https://github.com/initia-labs/initia/pull/315#discussion_r1867109085), @beer-1 requested to enhance the error handling and add validation in the UnmarshalJSON implementation of AsyncCallback. This issue will track the enhancement for a future update." \
  --assignee beer-1

Length of output: 448

Copy link

codecov bot commented Dec 3, 2024

Codecov Report

Attention: Patch coverage is 82.35294% with 3 lines in your changes missing coverage. Please review.

Project coverage is 41.14%. Comparing base (c79d331) to head (6a93737).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
x/ibc-hooks/move-hooks/message.go 82.35% 2 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #315      +/-   ##
==========================================
+ Coverage   41.11%   41.14%   +0.02%     
==========================================
  Files         268      269       +1     
  Lines       25682    25699      +17     
==========================================
+ Hits        10559    10573      +14     
- Misses      13486    13488       +2     
- Partials     1637     1638       +1     
Files with missing lines Coverage Δ
app/upgrade.go 50.00% <ø> (ø)
x/ibc-hooks/move-hooks/message.go 82.35% <82.35%> (ø)

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