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: initialize pkg/contracts/sui #3500

Merged
merged 4 commits into from
Feb 12, 2025
Merged

Conversation

lumtis
Copy link
Member

@lumtis lumtis commented Feb 7, 2025

Description

Closes #3471

Conflicts with #3485

No changelog as no user facing changes

Summary by CodeRabbit

  • New Features

    • Integrated an enhanced Sui blockchain gateway that now delivers the gateway binary in a more efficient format.
    • Added support for querying deposit events and identifying gas deposits.
  • Tests

    • Implemented comprehensive tests to validate the new gateway interactions and deposit event processing.
  • Chores

    • Updated internal dependencies by replacing legacy components with the new implementation.

Copy link
Contributor

coderabbitai bot commented Feb 7, 2025

📝 Walkthrough

Walkthrough

This pull request updates the Sui gateway integration across the project. The SetupSui function now retrieves the gateway bytecode via a new package (zetasui) instead of the deprecated sui_utils. A legacy gateway file is removed, and new packages and modules under pkg/contracts/sui are introduced. These include implementations for the Gateway contract, inbound event parsing, comprehensive unit tests, and mock clients for Sui API interactions. The changes preserve existing control flow and error handling.

Changes

File(s) Change Summary
e2e/runner/setup_sui.go, e2e/utils/sui/gateway.go Updated SetupSui to use zetasui.GatewayBytecodeBase64() instead of sui_utils.GetEncodedGateway(); removed the legacy gateway file.
pkg/contracts/sui/gateway.go Introduced a new Gateway package including the Gateway struct, constants, and functions (e.g., NewGateway, GatewayBytecodeBase64, QueryDepositInbounds, and QueryDepositAndCallInbounds) for blockchain interactions.
pkg/contracts/sui/inbound.go Added the Inbound struct with helper functions (parseInbound and convertPayload) and the IsGasDeposit method for processing inbound events.
pkg/contracts/sui/gateway_test.go, pkg/contracts/sui/inbound_test.go Added unit tests to validate the functionality of the Gateway methods and inbound parsing, ensuring proper handling of valid and erroneous inputs.
pkg/contracts/sui/mocks/mocks.go, pkg/contracts/sui/mocks/sui_client.go Introduced the SuiClientMock interface and provided comprehensive mock implementations for the SuiClient, enabling controlled testing of transactions and API interactions.

Sequence Diagram(s)

sequenceDiagram
    participant R as E2ERunner.SetupSui
    participant Z as zetasui
    participant C as SuiClient

    R->>Z: GatewayBytecodeBase64()
    Z-->>R: gateway bytecode (base64)
    R->>C: PublishTransaction(PublishRequest with gateway bytecode)
    C-->>R: TransactionResponse
Loading
sequenceDiagram
    participant G as Gateway
    participant API as Sui API Client
    participant P as Parser

    G->>API: QueryDepositInbounds(ctx, from, to)
    API-->>G: PaginatedEventsResponse
    G->>P: parseInbound(event)
    P-->>G: Inbound struct (or error)
    G-->>Caller: Return list of Inbound events
Loading

Possibly related PRs

Suggested reviewers

  • fbac
  • kingpinXD
  • swift1337
  • brewmaster012
  • ws4charlie
✨ 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.

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.

@gartnera gartnera added no-changelog Skip changelog CI check SUI_TESTS Run make start-sui-tests labels Feb 7, 2025
@lumtis lumtis marked this pull request as ready for review February 12, 2025 13:31
@lumtis lumtis requested a review from a team as a code owner February 12, 2025 13:31
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.

Actionable comments posted: 2

🧹 Nitpick comments (7)
pkg/contracts/sui/inbound.go (3)

29-33: Consider handling the TODO more explicitly.
The TODO at line 31 references a dedicated error type for invalid event data. Implementing a custom error type, for instance ErrInvalidEventData, would streamline error handling and allow consumers to distinguish parse errors more accurately.

Would you like help implementing this specific error type and updating the call sites accordingly?


34-69: Refine error checking for event.ParsedJson.
This function leverages parsedJSON heavily but does not explicitly check if event.ParsedJson is nil. If the upstream API behavior changes, parsedJSON might become nil and cause a runtime panic. Adding a guard clause or early return for nil would make the parsing logic more robust.

 func parseInbound(event models.SuiEventResponse, eventType string) (Inbound, error) {
+   if event.ParsedJson == nil {
+       return Inbound{}, errors.New("parsed JSON is nil")
+   }
    parsedJSON := event.ParsedJson
    ...
 }

98-113: Consider Go 1.13+ native error wrapping.
The convertPayload function uses fmt.Errorf(...) but also relies on errors.Wrap in other sections of the file. To keep the codebase consistent and embrace newer language features, switching to native error wrapping (fmt.Errorf("... %w", err)) is an option. This is purely a stylistic choice and not functionally mandatory.

pkg/contracts/sui/inbound_test.go (1)

10-52: Expand test coverage to parse inbound data.
Currently, the test only covers the IsGasDeposit method. Consider also testing parseInbound and convertPayload to ensure event fields (e.g., CoinType, Amount, Sender, and Payload) are parsed correctly and error cases are handled as intended.

e2e/runner/setup_sui.go (2)

33-33: Consider making the gas budget configurable.

The gas budget is currently hardcoded to "5000000000". Consider making it configurable through a constant or configuration parameter for better maintainability and flexibility.

+const defaultGasBudget = "5000000000"
+
 func (r *E2ERunner) SetupSui(faucetURL string) {
     // ...
-    GasBudget: "5000000000",
+    GasBudget: defaultGasBudget,

29-32: Consider documenting the hardcoded addresses.

The dependencies array contains hardcoded addresses without explanation. Add comments explaining what these addresses represent.

 Dependencies: []string{
+    // Sui framework package ID
     "0x0000000000000000000000000000000000000000000000000000000000000001",
+    // Sui system package ID
     "0x0000000000000000000000000000000000000000000000000000000000000002",
 },
pkg/contracts/sui/gateway_test.go (1)

22-22: Consider making the testnet endpoint configurable.

The testnet endpoint is hardcoded. Consider making it configurable through environment variables or test flags.

+const defaultTestnetEndpoint = "https://sui-testnet-endpoint.blockvision.org"
+
+func getTestnetEndpoint() string {
+    if endpoint := os.Getenv("SUI_TESTNET_ENDPOINT"); endpoint != "" {
+        return endpoint
+    }
+    return defaultTestnetEndpoint
+}
+
 func TestLiveGateway_ReadInbounds(t *testing.T) {
-    client := sui.NewSuiClient("https://sui-testnet-endpoint.blockvision.org")
+    client := sui.NewSuiClient(getTestnetEndpoint())
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 97c82cc and e84bf2c.

📒 Files selected for processing (8)
  • e2e/runner/setup_sui.go (2 hunks)
  • e2e/utils/sui/gateway.go (0 hunks)
  • pkg/contracts/sui/gateway.go (1 hunks)
  • pkg/contracts/sui/gateway_test.go (1 hunks)
  • pkg/contracts/sui/inbound.go (1 hunks)
  • pkg/contracts/sui/inbound_test.go (1 hunks)
  • pkg/contracts/sui/mocks/mocks.go (1 hunks)
  • pkg/contracts/sui/mocks/sui_client.go (1 hunks)
💤 Files with no reviewable changes (1)
  • e2e/utils/sui/gateway.go
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.go`: Review the Go code, point out issues relative to ...

**/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

  • pkg/contracts/sui/mocks/mocks.go
  • e2e/runner/setup_sui.go
  • pkg/contracts/sui/inbound_test.go
  • pkg/contracts/sui/inbound.go
  • pkg/contracts/sui/gateway_test.go
  • pkg/contracts/sui/gateway.go
  • pkg/contracts/sui/mocks/sui_client.go
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: start-sui-test / e2e
  • GitHub Check: start-e2e-test / e2e
  • GitHub Check: gosec
  • GitHub Check: build-and-test
  • GitHub Check: build
  • GitHub Check: Analyze (go)
🔇 Additional comments (6)
pkg/contracts/sui/inbound.go (2)

25-27: Looks great!
The IsGasDeposit method is concise and clearly communicates intent.


72-84: Payload format concern overlaps with a previous reviewer’s feedback.
We see from past review notes that some payloads could arrive in a different format (e.g., base64-encoded string). The current logic strictly expects a float64 array. If future updates allow a string-based payload, it will break here.

Please confirm whether you anticipate additional payload formats. If so, we can extend convertPayload to handle those cases.

pkg/contracts/sui/mocks/mocks.go (1)

14-20: Mock setup looks good.
This approach effectively sets the mock's expectations for SuiXQueryEvents within a single call. It keeps tests predictable and well structured.

pkg/contracts/sui/gateway.go (1)

64-80: Time range query functionality is commented out.

The time range query functionality is commented out due to an API issue. This should be tracked and fixed to ensure proper event filtering.

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Check if the issue is still open
gh issue view 3523 --json state,title,body

Length of output: 454


Time Range Query Functionality Comment Verified: Issue Still Open
The GitHub CLI output confirms that GitHub issue #3523 remains open, which justifies the commented out time range query functionality in the code. This open issue should be tracked, and once it is resolved or a viable workaround is found, the functionality can be reinstated or replaced accordingly.

  • File: pkg/contracts/sui/gateway.go (lines 64-80)
  • Issue: API error when querying events by time range (#3523 remains open)
pkg/contracts/sui/gateway_test.go (1)

60-66: LGTM! Well-structured test table.

The test table is well-organized with clear test cases and expected outcomes.

pkg/contracts/sui/mocks/sui_client.go (1)

1-1678: LGTM! Well-generated mock implementation.

The mock implementation is comprehensive and follows good practices for testing. The auto-generated code provides good coverage of the Sui client interface.

pkg/contracts/sui/gateway.go Outdated Show resolved Hide resolved
pkg/contracts/sui/gateway.go Outdated Show resolved Hide resolved
Copy link

codecov bot commented Feb 12, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Please upload report for BASE (feat/sui-observer@446276f). Learn more about missing BASE report.

Additional details and impacted files

Impacted file tree graph

@@                 Coverage Diff                  @@
##             feat/sui-observer    #3500   +/-   ##
====================================================
  Coverage                     ?   65.52%           
====================================================
  Files                        ?      445           
  Lines                        ?    30606           
  Branches                     ?        0           
====================================================
  Hits                         ?    20055           
  Misses                       ?     9697           
  Partials                     ?      854           

@lumtis lumtis requested a review from swift1337 February 12, 2025 13:41
@lumtis lumtis changed the base branch from develop to feat/sui-observer February 12, 2025 14:42
@swift1337 swift1337 merged commit 1cfa054 into feat/sui-observer Feb 12, 2025
49 checks passed
@swift1337 swift1337 deleted the feat/sui-client-pkg branch February 12, 2025 16:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-changelog Skip changelog CI check SUI_TESTS Run make start-sui-tests
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Initialize a pkg/contracts/sui package for parsing Deposit and DepositAndCall events
3 participants