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

Add RFQ Guard #2840

Merged
merged 40 commits into from
Jul 6, 2024
Merged

Add RFQ Guard #2840

merged 40 commits into from
Jul 6, 2024

Conversation

dwasse
Copy link
Collaborator

@dwasse dwasse commented Jul 2, 2024

Addresses #2833

Summary by CodeRabbit

  • New Features

    • Introduced pending proven event management, including storing, updating, and retrieving processes.
    • Added bridge request handling with conversion functions.
    • Launched the Guard service to monitor and verify Ethereum smart contract calls, manage bridge transactions, and handle proof validations.
    • Implemented SQLite and MySQL database support for the Guard service.
    • Expanded integration tests to include dispute handling and Guard service setup.
  • Bug Fixes

    • Addressed various database connection and transaction handling issues.
  • Tests

    • Enhanced end-to-end tests to cover new Guard functionalities and dispute scenarios.

03bae19: docs preview link
47da4c8: docs preview link
27d978f: docs preview link
3104af9: docs preview link
0d653c4: docs preview link
277cac1: docs preview link
2cde201: docs preview link

@dwasse dwasse marked this pull request as draft July 2, 2024 22:05
Copy link
Contributor

coderabbitai bot commented Jul 2, 2024

Warning

Rate limit exceeded

@trajan0x has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 50 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 71133e6 and 63e553c.

Walkthrough

The recent changes introduce a new guard functionality to the RFQ service for monitoring and ensuring the integrity of prove() calls on the FastBridge contract. This includes database schema updates, new structs and methods for handling pending provable events and bridge requests, and functionalities for validating, storing, and disputing these events.

Changes

Files/Paths Change Summary
services/rfq/guard/guarddb/base/model.go Added new models and conversion functions for pending provens and bridge requests. Included utilities for handling fields and hash conversions.
services/rfq/guard/guarddb/base/proven.go Introduced methods for storing, updating, and retrieving pending provens in the database using GORM.
services/rfq/guard/guarddb/base/store.go Implemented Store struct for accessing database operations and added methods to interact with the database and submitter services.
services/rfq/guard/guarddb/sqlite/sqlite.go Provided interface for managing SQLite databases, including creation, connection, and handling migrations.
services/rfq/guard/guarddb/pendingprovenstatus_string.go Added string representation method for PendingProvenStatus enum.
services/rfq/guard/guarddb/db.go Defined interfaces and types for database interactions, including functions for status updates and data retrieval.
services/rfq/guard/guarddb/connect/sql.go Introduced database connection logic for RFQ relayer, allowing connections to different database types based on specified database type.
services/rfq/guard/guarddb/mysql/mysql.go Provided interface for managing MySQL databases, including querying and handling connections.
services/rfq/guard/service/guard.go Added Guard struct and methods for monitoring and verifying prove() calls, handling bridge transactions, chain indexing, and database processing.
services/rfq/guard/service/handlers.go Introduced functions to handle bridge events and transactions, manage proof validation, and resolve disputes in the Ethereum client and contracts.
ethergo/backends/anvil/anvil.go Updated NewAnvilBackend function to include Platform field set to "linux/amd64".
services/rfq/e2e/rfq_test.go, services/rfq/e2e/setup_test.go Added setup and test methods for integrating the new Guard service, including setupGuard() and database interactions.

Sequence Diagram(s)

sequenceDiagram
    participant Guard as Guard Service
    participant DB as Database
    participant Contract as FastBridge Contract
    participant Client as Ethereum Client

    Note over Guard, DB: Initialization
    Guard->>DB: Initialize and connect
    Guard->>Contract: Monitor `prove()` events

    Note over Guard, Contract: Monitoring
    Contract-->>Guard: Emit `prove()` event with details
    Guard->>DB: Store `prove()` event

    Note over Guard, Client: Verification
    Guard->>Client: Verify corresponding event on destination chain
    Client-->>Guard: Event exists / doesn't exist

    Note over Guard, Contract: Dispute
    Guard->>Contract: Call `dispute()` for invalid `prove()`
    Contract-->>Guard: Confirm dispute
    Guard->>DB: Update status to `Disputed`
Loading

Possibly related issues

Poem

In the realm of code and guards so wise,
The prove() calls watch with keen rabbit eyes,
Through databases deep and contracts vast,
Integrity ensured, disputes are cast.
With every hash and bridge request,
The fast bridge guarded, code at its best.
🎉🚀🐰


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 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

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.
  • 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.

@github-actions github-actions bot added go Pull requests that update Go code size/l labels Jul 2, 2024
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

  • Added StoreBridgeRequest and GetBridgeRequestByID functions in services/rfq/guard/guarddb/base/bridge.go
  • Introduced PendingProvenModel and BridgeRequestModel in services/rfq/guard/guarddb/base/model.go
  • Implemented CRUD operations for 'PendingProven' records in services/rfq/guard/guarddb/base/proven.go
  • Created Store struct and NewStore function in services/rfq/guard/guarddb/base/store.go
  • Established database connections in services/rfq/guard/guarddb/connect/sql.go

12 file(s) reviewed, 19 comment(s)
Edit PR Review Bot Settings

}

if tx.Error != nil {
return nil, fmt.Errorf("could not get request")
Copy link

Choose a reason for hiding this comment

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

🪶 style: Include the original error in the returned error message for better debugging.


qr, err := modelResult.ToBridgeRequest()
if err != nil {
return nil, err
Copy link

Choose a reason for hiding this comment

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

🪶 style: Wrap the error with additional context for better error tracing.

@@ -0,0 +1,2 @@
// Package base contains the base implementation for different sql driers.
Copy link

Choose a reason for hiding this comment

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

📚 spelling: Typo in 'driers'. It should be 'drivers'.

Comment on lines +92 to +94
txID, err := hexutil.Decode(p.TransactionID)
if err != nil {
return nil, fmt.Errorf("could not get transaction id: %w", err)
Copy link

Choose a reason for hiding this comment

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

🧠 logic: Error handling for hexutil.Decode should be more descriptive.

Comment on lines +97 to +99
transactionID, err := sliceToArray(txID)
if err != nil {
return nil, fmt.Errorf("could not convert transaction id: %w", err)
Copy link

Choose a reason for hiding this comment

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

🧠 logic: Consider adding more context to the error message for sliceToArray.


var logger = log.Logger("mysql-logger")

// Store is the sqlite store. It extends the base store for sqlite specific queries.
Copy link

Choose a reason for hiding this comment

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

📚 spelling: The comment should refer to MySQL instead of SQLite.

// MaxIdleConns is exported here for testing. Tests execute too slowly with a reconnect each time.
var MaxIdleConns = 0

// NamingStrategy is used to exported here for testing.
Copy link

Choose a reason for hiding this comment

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

📚 spelling: Typo: 'is used to exported here' should be 'is exported here'.

// create the directory to the store if it doesn't exist
err = os.MkdirAll(dbPath, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("could not create sqlite store")
Copy link

Choose a reason for hiding this comment

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

🪶 style: Consider including the original error message for better debugging.

Suggested change
return nil, fmt.Errorf("could not create sqlite store")
return nil, fmt.Errorf("could not create sqlite store: %w", err)

SkipDefaultTransaction: true,
})
if err != nil {
return nil, fmt.Errorf("could not connect to db %s: %w", dbPath, err)
Copy link

Choose a reason for hiding this comment

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

🪶 style: Include the original error message for better debugging.

Suggested change
return nil, fmt.Errorf("could not connect to db %s: %w", dbPath, err)
return nil, fmt.Errorf("could not connect to db %s: %w", dbPath, err)


err = gdb.WithContext(ctx).AutoMigrate(base.GetAllModels()...)
if err != nil {
return nil, fmt.Errorf("could not migrate models: %w", err)
Copy link

Choose a reason for hiding this comment

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

🪶 style: Include the original error message for better debugging.

Suggested change
return nil, fmt.Errorf("could not migrate models: %w", err)
return nil, fmt.Errorf("could not migrate models: %w", err)

Copy link

codecov bot commented Jul 2, 2024

Codecov Report

Attention: Patch coverage is 0.27739% with 719 lines in your changes missing coverage. Please review.

Project coverage is 17.44358%. Comparing base (ea2520e) to head (63e553c).

Files Patch % Lines
services/rfq/guard/service/guard.go 0.00000% 170 Missing ⚠️
services/rfq/guard/service/handlers.go 0.00000% 168 Missing ⚠️
services/rfq/guard/guarddb/base/model.go 0.00000% 87 Missing ⚠️
services/rfq/guard/guardconfig/config.go 0.00000% 54 Missing ⚠️
services/rfq/guard/guarddb/base/proven.go 0.00000% 50 Missing ⚠️
services/rfq/guard/guarddb/sqlite/sqlite.go 0.00000% 29 Missing ⚠️
services/rfq/guard/guarddb/mysql/mysql.go 0.00000% 27 Missing ⚠️
services/rfq/guard/guarddb/base/bridge.go 0.00000% 24 Missing ⚠️
services/rfq/relayer/service/relayer.go 0.00000% 20 Missing ⚠️
services/rfq/guard/cmd/cmd.go 0.00000% 19 Missing ⚠️
... and 6 more
Additional details and impacted files
@@                 Coverage Diff                 @@
##              master       #2840         +/-   ##
===================================================
- Coverage   25.80877%   17.44358%   -8.36519%     
===================================================
  Files            713         534        -179     
  Lines          52827       43248       -9579     
  Branches          80           0         -80     
===================================================
- Hits           13634        7544       -6090     
+ Misses         37792       34663       -3129     
+ Partials        1401        1041        -360     
Flag Coverage Δ
cctp-relayer 31.93780% <ø> (?)
core ?
ethergo ?
git-changes-action ?
omnirpc 33.23904% <ø> (ø)
opbot 0.18541% <ø> (ø)
packages ?
promexporter 8.50242% <ø> (?)
screener-api ?
tools 30.55118% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link

cloudflare-workers-and-pages bot commented Jul 2, 2024

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 63e553c
Status: ✅  Deploy successful!
Preview URL: https://cedd6e53.sanguine-fe.pages.dev
Branch Preview URL: https://feat-rfq-guard.sanguine-fe.pages.dev

View logs

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

Outside diff range and nitpick comments (3)
services/rfq/guard/guarddb/base/model.go (2)

42-56: Consider adding JSON tags to the struct fields.

Adding JSON tags to the struct fields can improve serialization and deserialization when working with JSON data.

type PendingProvenModel struct {
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
	Origin        uint32    `json:"origin"`
	TransactionID string    `json:"transaction_id"`
	TxHash        string    `json:"tx_hash"`
	Status        guarddb.PendingProvenStatus `json:"status"`
}

110-144: Consider adding JSON tags to the struct fields.

Adding JSON tags to the struct fields can improve serialization and deserialization when working with JSON data.

type BridgeRequestModel struct {
	CreatedAt      time.Time `json:"created_at"`
	UpdatedAt      time.Time `json:"updated_at"`
	TransactionID  string    `json:"transaction_id"`
	OriginChainID  uint32    `json:"origin_chain_id"`
	DestChainID    uint32    `json:"dest_chain_id"`
	OriginSender   string    `json:"origin_sender"`
	DestRecipient  string    `json:"dest_recipient"`
	OriginToken    string    `json:"origin_token"`
	DestToken      string    `json:"dest_token"`
	OriginAmount   string    `json:"origin_amount"`
	DestAmount     string    `json:"dest_amount"`
	Deadline       time.Time `json:"deadline"`
	OriginNonce    int       `json:"origin_nonce"`
	RawRequest     string    `json:"raw_request"`
	SendChainGas   bool      `json:"send_chain_gas"`
}
services/rfq/guard/service/guard.go (1)

31-40: Consider adding comments for struct fields.

Adding comments for each struct field can improve readability and maintainability.

type Guard struct {
	cfg            relconfig.Config         // Configuration for the Guard
	metrics        metrics.Handler          // Metrics handler
	db             guarddb.Service          // Database service
	client         omniClient.RPCClient     // RPC client
	chainListeners map[int]listener.ContractListener // Map of chain listeners
	contracts      map[int]*fastbridge.FastBridgeRef // Map of FastBridge contracts
	txSubmitter    submitter.TransactionSubmitter    // Transaction submitter
}
Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between bdf657c and 1aea042.

Files selected for processing (12)
  • services/rfq/guard/guarddb/base/bridge.go (1 hunks)
  • services/rfq/guard/guarddb/base/doc.go (1 hunks)
  • services/rfq/guard/guarddb/base/model.go (1 hunks)
  • services/rfq/guard/guarddb/base/proven.go (1 hunks)
  • services/rfq/guard/guarddb/base/store.go (1 hunks)
  • services/rfq/guard/guarddb/connect/sql.go (1 hunks)
  • services/rfq/guard/guarddb/db.go (1 hunks)
  • services/rfq/guard/guarddb/doc.go (1 hunks)
  • services/rfq/guard/guarddb/mysql/mysql.go (1 hunks)
  • services/rfq/guard/guarddb/pendingprovenstatus_string.go (1 hunks)
  • services/rfq/guard/guarddb/sqlite/sqlite.go (1 hunks)
  • services/rfq/guard/service/guard.go (1 hunks)
Files skipped from review due to trivial changes (2)
  • services/rfq/guard/guarddb/base/doc.go
  • services/rfq/guard/guarddb/doc.go
Additional context used
GitHub Check: Build (1.22.x, ubuntu-latest)
services/rfq/guard/guarddb/base/store.go

[failure] 44-44:
cannot use &Store{} (value of type *Store) as guarddb.Service value in variable declaration: *Store does not implement guarddb.Service (wrong type for method GetPendingProvensByStatus)

GitHub Check: Lint (services/rfq)
services/rfq/guard/guarddb/mysql/mysql.go

[failure] 12-12:
could not import github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base (-: # github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base

services/rfq/guard/guarddb/sqlite/sqlite.go

[failure] 10-10:
could not import github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base (-: # github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base


[failure] 62-62:
cannot use &Store{} (value of type *Store) as guarddb.Service value in variable declaration: *Store does not implement guarddb.Service (missing method GetBridgeRequestByID) (typecheck)

Additional comments not posted (33)
services/rfq/guard/guarddb/pendingprovenstatus_string.go (1)

1-27: LGTM!

The String method for PendingProvenStatus enum is correctly implemented and follows the standard pattern used by stringer.

services/rfq/guard/guarddb/connect/sql.go (1)

1-39: LGTM!

The Connect function correctly handles database connections for MySQL, SQLite, and Clickhouse with appropriate error handling.

services/rfq/guard/guarddb/base/bridge.go (2)

14-25: LGTM!

The StoreBridgeRequest function correctly handles storing bridge requests in the database with proper conflict resolution and error handling.


27-44: LGTM!

The GetBridgeRequestByID function correctly handles retrieving bridge requests by ID with proper error handling for record not found and other errors.

services/rfq/guard/guarddb/base/store.go (4)

19-24: LGTM!

The NewStore function correctly initializes the Store struct with the necessary components.


26-29: LGTM!

The DB function correctly returns the gorm.DB object.


31-34: LGTM!

The SubmitterDB function correctly returns the submitterDB.Service object.


36-41: LGTM!

The GetAllModels function correctly aggregates all models for migration.

services/rfq/guard/guarddb/mysql/mysql.go (1)

12-12: Address the import issue.

Static analysis reported an import issue with github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base.

Ensure that the import path is correct and the package is available.

Verification successful

Import path is correct and the package is available.

  • The services/rfq/guard/guarddb/base/ directory contains multiple .go files, confirming it is a valid package.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the import path for `base` package.

# Test: Check if the `base` package is available. Expect: The package should be present.
fd 'base' services/rfq/guard/guarddb

Length of output: 69



Script:

#!/bin/bash
# Description: Verify the presence of Go files in the `base` package.

# Test: Check if there are any `.go` files in the `base` package directory. Expect: At least one `.go` file should be present.
fd '.go' services/rfq/guard/guarddb/base

Length of output: 245

Tools
GitHub Check: Lint (services/rfq)

[failure] 12-12:
could not import github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base (-: # github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base

services/rfq/guard/guarddb/sqlite/sqlite.go (1)

10-10: Address the import issue.

Static analysis reported an import issue with github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base.

Ensure that the import path is correct and the package is available.

Verification successful

Import path is correct.

The base package is available at the specified path: services/rfq/guard/guarddb/base/.

  • The import path github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base is correct.
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify the import path for `base` package.

# Test: Check if the `base` package is available. Expect: The package should be present.
fd 'base' services/rfq/guard/guarddb

Length of output: 69

Tools
GitHub Check: Lint (services/rfq)

[failure] 10-10:
could not import github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base (-: # github.com/synapsecns/sanguine/services/rfq/guard/guarddb/base

services/rfq/guard/guarddb/base/proven.go (1)

14-25: LGTM!

The StorePendingProven method is well-structured and correctly handles storing pending proven events with conflict resolution.

services/rfq/guard/guarddb/db.go (3)

24-32: LGTM!

The Writer interface is well-defined and includes methods for managing bridge requests and pending proven events.


34-42: LGTM!

The Reader interface is well-defined and includes methods for retrieving bridge requests and pending proven events by status and ID.


44-51: LGTM!

The Service interface is well-defined and includes methods for managing bridge requests, pending proven events, and retrieving the submitter database service.

services/rfq/guard/guarddb/base/model.go (7)

58-66: LGTM!

The function correctly converts PendingProven to PendingProvenModel.


70-78: LGTM!

The function correctly converts a common.Hash to sql.NullString.


80-88: LGTM!

The function correctly converts a string to sql.NullString.


90-108: LGTM!

The function correctly converts PendingProvenModel to PendingProven.


146-161: LGTM!

The function correctly converts BridgeRequest to BridgeRequestModel.


164-205: LGTM!

The function correctly converts BridgeRequestModel to BridgeRequest.


208-215: LGTM!

The function correctly converts a slice to a fixed-size array.

services/rfq/guard/service/guard.go (12)

42-109: LGTM!

The function correctly initializes a new Guard instance with proper error handling.


114-138: LGTM!

The function correctly starts the Guard with proper error handling.


140-154: LGTM!

The function correctly runs the database selector with proper error handling.


156-171: LGTM!

The function correctly starts the chain indexers with proper error handling.


173-228: LGTM!

The function correctly runs the chain indexer with proper error handling.


232-266: LGTM!

The function correctly handles the BridgeRequested log with proper error handling.


268-281: LGTM!

The function correctly handles the ProofProvided log with proper error handling.


283-290: LGTM!

The function correctly handles the ProofDisputed log with proper error handling.


292-302: LGTM!

The function correctly processes the database with proper error handling.


304-348: LGTM!

The function correctly handles the ProveCalled event with proper error handling.


350-382: LGTM!

The function correctly checks if the prove is valid with proper error handling.


384-408: LGTM!

The function correctly checks if the relay matches the bridge request.

return allModels
}

var _ guarddb.Service = &Store{}
Copy link
Contributor

Choose a reason for hiding this comment

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

Implement the missing method GetPendingProvensByStatus.

The Store struct does not fully implement the guarddb.Service interface. It lacks the GetPendingProvensByStatus method.

+ func (s Store) GetPendingProvensByStatus(ctx context.Context, matchStatuses ...guarddb.PendingProvenStatus) ([]guarddb.PendingProven, error) {
+     // Implementation here
+ }

Committable suggestion was skipped due to low confidence.

Tools
GitHub Check: Build (1.22.x, ubuntu-latest)

[failure] 44-44:
cannot use &Store{} (value of type *Store) as guarddb.Service value in variable declaration: *Store does not implement guarddb.Service (wrong type for method GetPendingProvensByStatus)

Comment on lines 1 to 2
// Package mysql provides a common interface for starting sql-lite databases
package mysql
Copy link
Contributor

Choose a reason for hiding this comment

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

Correct the package description.

The package description mentions sql-lite databases, but this file is for MySQL databases.

- // Package mysql provides a common interface for starting sql-lite databases
+ // Package mysql provides a common interface for starting MySQL databases
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
// Package mysql provides a common interface for starting sql-lite databases
package mysql
// Package mysql provides a common interface for starting MySQL databases
package mysql

Comment on lines +35 to +39
gdb, err := gorm.Open(mysql.Open(dbURL), &gorm.Config{
Logger: dbcommon.GetGormLogger(logger),
FullSaveAssociations: true,
NamingStrategy: NamingStrategy,
NowFunc: time.Now,
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix the error message for MySQL connection.

The error message on line 38 should specify that it is related to MySQL.

- return nil, fmt.Errorf("could not create mysql connection: %w", err)
+ return nil, fmt.Errorf("could not create MySQL connection: %w", err)

Committable suggestion was skipped due to low confidence.

Comment on lines 20 to 29
// Store is the sqlite store. It extends the base store for sqlite specific queries.
type Store struct {
*base.Store
}

// MaxIdleConns is exported here for testing. Tests execute too slowly with a reconnect each time.
var MaxIdleConns = 0

// NamingStrategy is used to exported here for testing.
var NamingStrategy = schema.NamingStrategy{}
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve comments for clarity.

The comments for Store, MaxIdleConns, and NamingStrategy could be more descriptive.

- // Store is the sqlite store. It extends the base store for sqlite specific queries.
+ // Store is the MySQL store. It extends the base store for MySQL-specific queries.

- // MaxIdleConns is exported here for testing. Tests execute too slowly with a reconnect each time.
+ // MaxIdleConns specifies the maximum number of idle connections. Exported for testing purposes.

- // NamingStrategy is used to exported here for testing.
+ // NamingStrategy specifies the naming strategy for GORM. Exported for testing purposes.
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
// Store is the sqlite store. It extends the base store for sqlite specific queries.
type Store struct {
*base.Store
}
// MaxIdleConns is exported here for testing. Tests execute too slowly with a reconnect each time.
var MaxIdleConns = 0
// NamingStrategy is used to exported here for testing.
var NamingStrategy = schema.NamingStrategy{}
// Store is the MySQL store. It extends the base store for MySQL-specific queries.
type Store struct {
*base.Store
}
// MaxIdleConns specifies the maximum number of idle connections. Exported for testing purposes.
var MaxIdleConns = 0
// NamingStrategy specifies the naming strategy for GORM. Exported for testing purposes.
var NamingStrategy = schema.NamingStrategy{}

// create the directory to the store if it doesn't exist
err = os.MkdirAll(dbPath, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("could not create sqlite store")
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix the error message for SQLite store creation.

The error message on line 38 should specify that it is related to SQLite.

- return nil, fmt.Errorf("could not create sqlite store")
+ return nil, fmt.Errorf("could not create SQLite store")
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
return nil, fmt.Errorf("could not create sqlite store")
return nil, fmt.Errorf("could not create SQLite store")

Comment on lines +1 to +2
// Package sqlite provides a common interface for starting sql-lite databases
package sqlite
Copy link
Contributor

Choose a reason for hiding this comment

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

Correct the package description.

The package description mentions sql-lite databases, which should be SQLite.

- // Package sqlite provides a common interface for starting sql-lite databases
+ // Package sqlite provides a common interface for starting SQLite databases
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
// Package sqlite provides a common interface for starting sql-lite databases
package sqlite
// Package sqlite provides a common interface for starting SQLite databases
package sqlite

Comment on lines 38 to 61
// GetPendingProvensByStatus gets pending provens by status.
func (s Store) GetPendingProvensByStatus(ctx context.Context, matchStatuses ...guarddb.PendingProvenStatus) (res []guarddb.PendingProven, _ error) {
var provenResults []PendingProvenModel

inArgs := make([]int, len(matchStatuses))
for i := range matchStatuses {
inArgs[i] = int(matchStatuses[i].Int())
}

// TODO: consider pagination
tx := s.DB().WithContext(ctx).Model(&PendingProvenModel{}).Where(fmt.Sprintf("%s IN ?", statusFieldName), inArgs).Find(&provenResults)
if tx.Error != nil {
return []guarddb.PendingProven{}, fmt.Errorf("could not get db results: %w", tx.Error)
}

for _, result := range provenResults {
marshaled, err := result.ToPendingProven()
if err != nil {
return []guarddb.PendingProven{}, fmt.Errorf("could not get provens")
}
res = append(res, *marshaled)
}
return res, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider implementing pagination.

The TODO comment suggests considering pagination for large result sets. Implementing pagination would improve performance and prevent potential memory issues.

Do you want me to help implement pagination for this method?

Comment on lines +28 to +36
func (s Store) UpdatePendingProvenStatus(ctx context.Context, id [32]byte, status guarddb.PendingProvenStatus) error {
tx := s.DB().WithContext(ctx).Model(&PendingProvenModel{}).
Where(fmt.Sprintf("%s = ?", transactionIDFieldName), hexutil.Encode(id[:])).
Update(statusFieldName, status)
if tx.Error != nil {
return fmt.Errorf("could not update: %w", tx.Error)
}
return nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Use parameterized query for WHERE clause.

The WHERE clause should use parameterized queries to prevent SQL injection.

- .Where(fmt.Sprintf("%s = ?", transactionIDFieldName), hexutil.Encode(id[:])).
+ .Where(fmt.Sprintf("%s = ?", transactionIDFieldName), hexutil.Encode(id[:])).

Committable suggestion was skipped due to low confidence.

Comment on lines +71 to +72
if tx.Error != nil {
return nil, fmt.Errorf("could not get proven")
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve error message for GetPendingProvenByID.

The error message on line 72 should be more descriptive.

- return nil, fmt.Errorf("could not get proven")
+ return nil, fmt.Errorf("could not get pending proven by ID: %w", tx.Error)
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
if tx.Error != nil {
return nil, fmt.Errorf("could not get proven")
if tx.Error != nil {
return nil, fmt.Errorf("could not get pending proven by ID: %w", tx.Error)

Comment on lines +68 to +87
// PendingProvenStatus is the status of a quote request in the db.
// This is the primary mechanism for moving data through the app.
//
// TODO: consider making this an interface and exporting that.
//
// EXTREMELY IMPORTANT: DO NOT ADD NEW VALUES TO THIS ENUM UNLESS THEY ARE AT THE END.
//
//go:generate go run golang.org/x/tools/cmd/stringer -type=PendingProvenStatus
type PendingProvenStatus uint8

const (
// ProveCalled means the prove() function has been called.
ProveCalled PendingProvenStatus = iota + 1
// Validated means the prove() call has been properly validated on the dest chain.
Validated
// DisputePending means dispute() has been called in the event of an invalid prove().
DisputePending
// Disputed means the dispute() call has been confirmed.
Disputed
)
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider making PendingProvenStatus an interface.

The TODO comment suggests considering making the PendingProvenStatus enum an interface. This would provide more flexibility and allow for easier extension in the future.

Do you want me to help refactor the PendingProvenStatus enum into an interface?

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

  • Added documentation for 'Relay ack' API endpoint in docs/bridge/docs/rfq/API/relay-ack.api.mdx
  • Introduced Codecov Webpack plugin in docs/bridge/docusaurus.config.ts
  • Updated package.json files across multiple packages to include Codecov plugins and version bumps
  • Enhanced ChainInfo.tsx to make chain information clickable
  • Updated submodule reference for services/cctp-relayer/external/evm-cctp-contracts

28 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ed153b7 and f5a00e6.

Files selected for processing (4)
  • services/rfq/e2e/setup_test.go (7 hunks)
  • services/rfq/guard/cmd/commands.go (1 hunks)
  • services/rfq/guard/service/guard.go (1 hunks)
  • services/rfq/relayer/service/relayer.go (3 hunks)
Files skipped from review as they are similar to previous changes (3)
  • services/rfq/e2e/setup_test.go
  • services/rfq/guard/service/guard.go
  • services/rfq/relayer/service/relayer.go
Additional context used
GitHub Check: codecov/patch
services/rfq/guard/cmd/commands.go

[warning] 26-31: services/rfq/guard/cmd/commands.go#L26-L31
Added lines #L26 - L31 were not covered by tests


[warning] 33-34: services/rfq/guard/cmd/commands.go#L33-L34
Added lines #L33 - L34 were not covered by tests


[warning] 36-38: services/rfq/guard/cmd/commands.go#L36-L38
Added lines #L36 - L38 were not covered by tests


[warning] 40-44: services/rfq/guard/cmd/commands.go#L40-L44
Added lines #L40 - L44 were not covered by tests

Additional comments not posted (5)
services/rfq/guard/cmd/commands.go (5)

29-31: Improve error message for configuration loading.

Include the path of the configuration file in the error message for better context.

-	if err != nil {
-		return fmt.Errorf("could not read config file: %w", err)
-	}
+	if err != nil {
+		return fmt.Errorf("could not read config file (%s): %w", c.String(configFlag.Name), err)
+	}
Tools
GitHub Check: codecov/patch

[warning] 26-31: services/rfq/guard/cmd/commands.go#L26-L31
Added lines #L26 - L31 were not covered by tests


33-34: Add tests for metrics provider initialization.

The initialization of the metrics provider is not covered by tests. Ensure that this functionality is tested to verify correct initialization.

Tools
GitHub Check: codecov/patch

[warning] 33-34: services/rfq/guard/cmd/commands.go#L33-L34
Added lines #L33 - L34 were not covered by tests


36-37: Improve error message for guard creation.

Include the configuration details in the error message for better context.

-	if err != nil {
-		return fmt.Errorf("could not create guard: %w", err)
-	}
+	if err != nil {
+		return fmt.Errorf("could not create guard with config (%v): %w", cfg, err)
+	}
Tools
GitHub Check: codecov/patch

[warning] 36-38: services/rfq/guard/cmd/commands.go#L36-L38
Added lines #L36 - L38 were not covered by tests


41-42: Improve error message for guard start.

Include the configuration details in the error message for better context.

-	if err != nil {
-		return fmt.Errorf("could not start guard: %w", err)
-	}
+	if err != nil {
+		return fmt.Errorf("could not start guard with config (%v): %w", cfg, err)
+	}

26-31: Add tests for configuration loading, metrics provider initialization, guard creation, and guard start.

These lines are not covered by tests. Ensure that tests are added to verify the correct functionality of these operations.

Also applies to: 33-34, 36-38, 40-44

Tools
GitHub Check: codecov/patch

[warning] 26-31: services/rfq/guard/cmd/commands.go#L26-L31
Added lines #L26 - L31 were not covered by tests

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

  • Introduced Guard service for monitoring and verifying transactions in services/rfq/e2e/rfq_test.go and services/rfq/e2e/setup_test.go.
  • Added command-line tool for RFQ Guard in services/rfq/guard/cmd/cmd.go and services/rfq/guard/cmd/commands.go.
  • Defined Guard configuration structures in services/rfq/guard/guardconfig/config.go.
  • Implemented database methods for bridge requests and pending provens in services/rfq/guard/guarddb/base/bridge.go, services/rfq/guard/guarddb/base/proven.go, and related files.
  • Integrated Guard service into relayer with configuration option UseEmbeddedGuard in services/rfq/relayer/relconfig/config.go and services/rfq/relayer/service/relayer.go.

21 file(s) reviewed, 17 comment(s)
Edit PR Review Bot Settings


err := app.Run(args)
if err != nil {
panic(err)
Copy link

Choose a reason for hiding this comment

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

🪶 style: Using panic for error handling might not be ideal in a CLI tool. Consider returning an error or logging it instead.

Columns: []clause.Column{{Name: transactionIDFieldName}},
DoUpdates: clause.AssignmentColumns([]string{transactionIDFieldName}),
}).Create(&model)
if dbTx.Error != nil {
Copy link

Choose a reason for hiding this comment

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

🪶 style: 🪶 style: Include the original error in the returned error message for better debugging.

}

if tx.Error != nil {
return nil, fmt.Errorf("could not get request")
Copy link

Choose a reason for hiding this comment

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

🪶 style: 🪶 style: Wrap the error with additional context for better error tracing.

Comment on lines +57 to +59
txID, err := hexutil.Decode(p.TransactionID)
if err != nil {
return nil, fmt.Errorf("could not get transaction id: %w", err)
Copy link

Choose a reason for hiding this comment

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

🧠 logic: Error handling for hexutil.Decode should be more descriptive.

Comment on lines +62 to +64
transactionID, err := sliceToArray(txID)
if err != nil {
return nil, fmt.Errorf("could not convert transaction id: %w", err)
Copy link

Choose a reason for hiding this comment

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

🧠 logic: Consider adding more context to the error message for sliceToArray.

// create the directory to the store if it doesn't exist
err = os.MkdirAll(dbPath, os.ModePerm)
if err != nil {
return nil, fmt.Errorf("could not create sqlite store")
Copy link

Choose a reason for hiding this comment

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

🪶 style: Consider including the original error message for better debugging.

Suggested change
return nil, fmt.Errorf("could not create sqlite store")
return nil, fmt.Errorf("could not create sqlite store: %w", err)

SkipDefaultTransaction: true,
})
if err != nil {
return nil, fmt.Errorf("could not connect to db %s: %w", dbPath, err)
Copy link

Choose a reason for hiding this comment

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

🪶 style: Include the original error message for better debugging.

Suggested change
return nil, fmt.Errorf("could not connect to db %s: %w", dbPath, err)
return nil, fmt.Errorf("could not connect to db %s: %w", dbPath, err)


err = gdb.WithContext(ctx).AutoMigrate(base.GetAllModels()...)
if err != nil {
return nil, fmt.Errorf("could not migrate models: %w", err)
Copy link

Choose a reason for hiding this comment

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

🪶 style: Include the original error message for better debugging.

Suggested change
return nil, fmt.Errorf("could not migrate models: %w", err)
return nil, fmt.Errorf("could not migrate models: %w", err)

}

//nolint:cyclop
func (g Guard) runChainIndexer(ctx context.Context, chainID int) (err error) {
Copy link

Choose a reason for hiding this comment

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

🪶 style: 🪶 style: The //nolint:cyclop directive is used to suppress cyclomatic complexity warnings. Ensure this is necessary and justified.

}

func relayMatchesBridgeRequest(event *fastbridge.FastBridgeBridgeRelayed, bridgeRequest *guarddb.BridgeRequest) bool {
//TODO: is this exhaustive?
Copy link

Choose a reason for hiding this comment

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

🪶 style: 🪶 style: Consider elaborating on the TODO comment to specify what additional checks might be needed.

@github-actions github-actions bot added the M-docs label Jul 5, 2024
Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

  • Added enable_embedded_guard configuration parameter in docs/bridge/docs/rfq/Relayer/Relayer.md
  • Updated submodule commit in services/cctp-relayer/external/evm-cctp-contracts
  • Corrected spelling in services/rfq/guard/guarddb/doc.go and services/rfq/relayer/reldb/doc.go
  • Clarified package description in services/rfq/guard/guarddb/mysql/mysql.go
  • Renamed UseEmbeddedGuard to enable_guard in services/rfq/relayer/relconfig/config.go

6 file(s) reviewed, 1 comment(s)
Edit PR Review Bot Settings

// MaxIdleConns is exported here for testing. Tests execute too slowly with a reconnect each time.
var MaxIdleConns = 0

// NamingStrategy is used to exported here for testing.
Copy link

Choose a reason for hiding this comment

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

📚 spelling: Typo: 'is used to exported here' should be 'is exported here'.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

  • Modified transaction submission logic in services/rfq/guard/service/handlers.go for Dispute function
  • Ensured transactor parameter is correctly passed to Dispute method in handleProveCalled
  • No major changes found since last review

1 file(s) reviewed, 2 comment(s)
Edit PR Review Bot Settings

}
err = g.db.StoreBridgeRequest(ctx, dbReq)
if err != nil {
return fmt.Errorf("could not get db: %w", err)
Copy link

Choose a reason for hiding this comment

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

🪶 style: The error message should specify that it failed to store the bridge request in the database.

}

func relayMatchesBridgeRequest(event *fastbridge.FastBridgeBridgeRelayed, bridgeRequest *guarddb.BridgeRequest) bool {
//TODO: is this exhaustive?
Copy link

Choose a reason for hiding this comment

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

🪶 style: Consider elaborating on the TODO comment to specify what additional checks might be needed.

Copy link

codecov bot commented Jul 5, 2024

Bundle Report

Changes will decrease total bundle size by 367.51kB ⬇️

Bundle name Size Change
docs-bridge-client-array-push 7.89MB 387 bytes ⬆️
docs-bridge-server-cjs 14.79MB 1.09kB ⬆️
sdk-router-@synapsecns/sdk-router-cjs (removed) 116.91kB ⬇️
sdk-router-@synapsecns/sdk-router-esm (removed) 252.08kB ⬇️

if !ok {
return fmt.Errorf("could not get contract for chain: %d", bridgeRequest.Transaction.DestChainId)
}
_, err = g.txSubmitter.SubmitTransaction(ctx, big.NewInt(int64(proven.Origin)), func(transactor *bind.TransactOpts) (tx *types.Transaction, err error) {
Copy link
Contributor

Choose a reason for hiding this comment

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

@dwasse test is failing WARN [07-05|17:06:42.900] Served eth_estimateGas conn=127.0.0.1:63211 reqid=77 duration="412.333µs" err="execution reverted" errdata=0xe2517d3f0000000000000000000000000000000000000000000000000000000000000000043c983c49d46f0e102151eaf8085d4a2e6571d5df2d47b013f39bddfd4a639d

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

  • New Features

    • Introduced RFQ Guard component in contrib/opbot/botmd/botmd.go and contrib/opbot/botmd/commands.go
    • Added SQLite and MySQL support in contrib/opbot/sql/*
    • New API endpoints for bulk quotes and contract addresses in services/rfq/api/*
  • Improvements

    • Enhanced configuration management in contrib/opbot/config/config.go
    • Improved context propagation in contrib/opbot/botmd/middleware.go
  • Dependency Updates

    • Updated github.com/gorilla/websocket to v1.5.3 across multiple go.mod files

53 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

  • Added Started method and mutex in /ethergo/submitter/submitter.go for thread-safe transaction submission.
  • Introduced BridgeProofDisputedTopic in /services/rfq/contracts/fastbridge/events.go for handling bridge disputes.
  • Added BridgeDisputeEvent to EventType enum in /services/rfq/contracts/fastbridge/eventtype_string.go.
  • Implemented parsing logic for BridgeDisputeEvent in /services/rfq/contracts/fastbridge/parser.go.
  • Integrated new Guard component in /services/rfq/guard/service/guard.go for monitoring and verifying bridge transactions.
  • Modified chain ID references in /services/rfq/guard/service/handlers.go to ensure correct dispute handling.

6 file(s) reviewed, 1 comment(s)
Edit PR Review Bot Settings

if !g.txSubmitter.Started() {
err = g.txSubmitter.Start(ctx)
// defensive coding against potential race.
if err != nil && !errors.Is(err, submitter.ErrSubmitterAlreadyStarted) {
Copy link

Choose a reason for hiding this comment

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

🧠 logic: Potential race condition check for ErrSubmitterAlreadyStarted.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

  • Enhanced generateQuotes method in services/rfq/relayer/quoter/quoter.go to use goroutines for parallel execution.
  • Added mutex for synchronization in generateQuotes to ensure thread safety.
  • Improved performance and efficiency of quote generation process.

1 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f5a00e6 and e576f34.

Files selected for processing (11)
  • docs/bridge/docs/rfq/Relayer/Relayer.md (1 hunks)
  • ethergo/submitter/submitter.go (6 hunks)
  • services/rfq/contracts/fastbridge/events.go (4 hunks)
  • services/rfq/contracts/fastbridge/eventtype_string.go (1 hunks)
  • services/rfq/contracts/fastbridge/parser.go (2 hunks)
  • services/rfq/guard/guarddb/doc.go (1 hunks)
  • services/rfq/guard/guarddb/mysql/mysql.go (1 hunks)
  • services/rfq/guard/service/guard.go (1 hunks)
  • services/rfq/guard/service/handlers.go (1 hunks)
  • services/rfq/relayer/relconfig/config.go (1 hunks)
  • services/rfq/relayer/reldb/doc.go (1 hunks)
Files skipped from review due to trivial changes (2)
  • services/rfq/guard/guarddb/doc.go
  • services/rfq/relayer/reldb/doc.go
Files skipped from review as they are similar to previous changes (4)
  • services/rfq/guard/guarddb/mysql/mysql.go
  • services/rfq/guard/service/guard.go
  • services/rfq/guard/service/handlers.go
  • services/rfq/relayer/relconfig/config.go
Additional context used
GitHub Check: codecov/patch
services/rfq/contracts/fastbridge/events.go

[warning] 56-56: services/rfq/contracts/fastbridge/events.go#L56
Added line #L56 was not covered by tests


[warning] 68-68: services/rfq/contracts/fastbridge/events.go#L68
Added line #L68 was not covered by tests

services/rfq/contracts/fastbridge/parser.go

[warning] 87-92: services/rfq/contracts/fastbridge/parser.go#L87-L92
Added lines #L87 - L92 were not covered by tests

Additional comments not posted (22)
services/rfq/contracts/fastbridge/eventtype_string.go (2)

15-15: LGTM!

The added check for BridgeDisputeEvent ensures that the constant values remain unchanged.


18-20: LGTM!

The added string representation and index for BridgeDisputeEvent are correctly implemented.

services/rfq/contracts/fastbridge/events.go (4)

20-21: LGTM!

The added topic for BridgeProofDisputed is correctly implemented.


37-37: LGTM!

The initialization of the BridgeProofDisputed topic is correctly implemented.


53-57: LGTM!

The check for the existence of the BridgeProofDisputed event in the ABI is correctly implemented.

Tools
GitHub Check: codecov/patch

[warning] 56-56: services/rfq/contracts/fastbridge/events.go#L56
Added line #L56 was not covered by tests


68-68: LGTM!

The addition of the BridgeDisputeEvent to the topic map is correctly implemented.

Tools
GitHub Check: codecov/patch

[warning] 68-68: services/rfq/contracts/fastbridge/events.go#L68
Added line #L68 was not covered by tests

services/rfq/contracts/fastbridge/parser.go (1)

23-24: LGTM!

The addition of the BridgeDisputeEvent constant is correctly implemented.

docs/bridge/docs/rfq/Relayer/Relayer.md (1)

196-197: LGTM!

The additions of the enable_guard and submit_single_quotes configuration options are correctly implemented.

ethergo/submitter/submitter.go (14)

116-121: LGTM!

The Started function is simple and correctly uses a read lock to ensure thread safety.


142-152: LGTM!

The attemptMarkStarted function correctly uses a write lock to ensure thread safety and returns an error if the submitter is already started.


154-155: LGTM!

The ErrSubmitterAlreadyStarted variable is appropriately defined as an error.


347-354: LGTM!

The triggerProcessQueue function correctly triggers the process queue without blocking if the channel is full.


349-350: LGTM!

The ErrNotStarted variable is appropriately defined as an error.


Line range hint 351-387: LGTM! Verify error handling and tracing.

The SubmitTransaction function correctly submits a transaction to the chain, handling nonce and gas price settings with appropriate error handling and tracing. Ensure that all errors are properly handled and traced.

Verification successful

Verified: Error handling and tracing are properly implemented in the SubmitTransaction function.

  • The function uses fmt.Errorf for descriptive error messages.
  • Tracing is implemented with trace.WithAttributes to capture relevant details.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling and tracing in the SubmitTransaction function.

# Test: Search for error handling and tracing. Expect: Proper error handling and tracing in the function.
rg --type go 'fmt\.Errorf|trace\.WithAttributes' ethergo/submitter/submitter.go

Length of output: 2444


Line range hint 323-335: LGTM! Verify error handling and tracing.

The storeTX function correctly stores a transaction in the database with a given status and UUID. It includes context tracing and error handling. Ensure that all errors are properly handled and traced.

Verification successful

Verification successful: Error handling and tracing are appropriately implemented in the storeTX function.

The storeTX function includes proper error handling using fmt.Errorf and context tracing with trace.WithAttributes. No further action is required.

  • Error Handling: fmt.Errorf("could not put tx: %w", err)
  • Tracing: ctx, span := t.metrics.Tracer().Start(ctx, "submitter.StoreTX", trace.WithAttributes(
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling and tracing in the storeTX function.

# Test: Search for error handling and tracing. Expect: Proper error handling and tracing in the function.
rg --type go 'fmt\.Errorf|trace\.WithAttributes' ethergo/submitter/submitter.go

Length of output: 2444


Line range hint 287-321: LGTM! Verify error handling and tracing.

The getNonce function correctly retrieves the nonce for a given chain ID and address using both on-chain and database sources. It parallelizes the retrieval with an errgroup and includes error handling and context tracing. Ensure that all errors are properly handled and traced.

Verification successful

The getNonce function contains proper error handling and tracing through the use of fmt.Errorf and trace.WithAttributes. These implementations are consistent with the expected patterns for error reporting and tracing.

  • Error Handling: Proper use of fmt.Errorf to wrap errors with contextual information.
  • Tracing: Usage of trace.WithAttributes to add attributes to spans for better observability.

Verification Complete

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling and tracing in the getNonce function.

# Test: Search for error handling and tracing. Expect: Proper error handling and tracing in the function.
rg --type go 'fmt\.Errorf|trace\.WithAttributes' ethergo/submitter/submitter.go

Length of output: 2444


Line range hint 491-511: LGTM! Verify context tracing.

The applyGasFloor function correctly applies the minimum gas price from the config if values are unset, considering dynamic gas pricing. It includes context tracing. Ensure that the context tracing is properly implemented.

Verification successful

Context tracing verified in applyGasFloor function

The applyGasFloor function includes proper context tracing, starting a span and setting attributes related to gas pricing before ending the span.

  • Location: ethergo/submitter/submitter.go lines 535-558
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify context tracing in the applyGasFloor function.

# Test: Search for context tracing. Expect: Proper context tracing in the function.
rg --type go 'trace\.WithAttributes' ethergo/submitter/submitter.go

Length of output: 841


Script:

#!/bin/bash
# Description: Verify context tracing in the applyGasFloor function.

# Test: Search for the applyGasFloor function and ensure it includes proper context tracing.
ast-grep --lang go --pattern 'func (t *txSubmitterImpl) applyGasFloor(ctx context.Context, $$$) {
  $$$
}' ethergo/submitter/submitter.go

Length of output: 1880


Line range hint 156-206: LGTM! Verify context cancellation handling.

The Start function correctly initializes the transaction submitter and starts reaper and distinct chain ID update processes using goroutines. Ensure that context cancellation is properly handled to avoid potential goroutine leaks.

Verification successful

Context cancellation handling verified

The Start function correctly handles context cancellation by calling the cancel function when the shouldExit condition is met, ensuring proper termination of goroutines.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify context cancellation handling in the Start function.

# Test: Search for context cancellation handling. Expect: Proper cancellation handling in all goroutines.
rg --type go 'context\.WithCancel' ethergo/submitter/submitter.go

Length of output: 113


Script:

#!/bin/bash
# Description: Verify proper usage of the cancel function in the Start function.

# Test: Search for the usage of the cancel function. Expect: Proper usage of cancel function to handle context cancellation.
rg --type go '\bcancel\(\)' ethergo/submitter/submitter.go

Length of output: 72


Script:

#!/bin/bash
# Description: Extract the lines around the cancel function call to understand its context.

# Test: Extract lines around the cancel function call. Expect: Proper context cancellation handling.
rg --type go -C 5 '\bcancel\(\)' ethergo/submitter/submitter.go

Length of output: 209


Line range hint 539-560: LGTM! Verify error handling and tracing.

The applyGasCeil function correctly evaluates current gas values versus the configured maximum and returns an error if they exceed the maximum. It includes context tracing and error handling. Ensure that all errors are properly handled and traced.


Line range hint 407-455: LGTM! Verify error handling and tracing.

The setGasPrice function correctly sets the gas price for a transaction, considering dynamic gas pricing and applying gas floor and ceiling. It includes context tracing and error handling. Ensure that all errors are properly handled and traced.


Line range hint 577-599: LGTM! Verify error handling and tracing.

The getGasBlock function correctly retrieves the gas block for a given chain, using a retry mechanism and a cache as a fallback. It includes context tracing and error handling. Ensure that all errors are properly handled and traced.

Verification successful

Verification of Error Handling and Tracing in getGasBlock Function

The getGasBlock function in ethergo/submitter/submitter.go correctly implements error handling and tracing. The function uses context tracing (span) and manages errors using fmt.Errorf. Additionally, it employs a retry mechanism and falls back to a cached value if the gas block cannot be retrieved.

Key points:

  • The function starts a trace span and ensures it ends with the error status.
  • Errors are properly wrapped with context using fmt.Errorf.
  • If the gas block retrieval fails, the function attempts to use a cached value and logs this event.

Code Locations:

  • ethergo/submitter/submitter.go:642-675
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling and tracing in the getGasBlock function.

# Test: Search for error handling and tracing. Expect: Proper error handling and tracing in the function.
rg --type go 'fmt\.Errorf|trace\.WithAttributes' ethergo/submitter/submitter.go

Length of output: 2444


Script:

#!/bin/bash
# Extract the getGasBlock function from ethergo/submitter/submitter.go to verify error handling and tracing.
ast-grep --lang go --pattern 'func getGasBlock($_, $_) $_' ethergo/submitter/submitter.go

Length of output: 91


Script:

#!/bin/bash
# Search for the getGasBlock function in ethergo/submitter/submitter.go to verify its existence and locate it.
rg 'func getGasBlock' ethergo/submitter/submitter.go

Length of output: 54


Script:

#!/bin/bash
# Search for all function definitions in ethergo/submitter/submitter.go to identify any relevant functions.
rg --type go 'func ' ethergo/submitter/submitter.go

Length of output: 2209


Script:

#!/bin/bash
# Extract the full implementation of the getGasBlock function from ethergo/submitter/submitter.go to verify error handling and tracing.
ast-grep --lang go --pattern 'func (t *txSubmitterImpl) getGasBlock(ctx context.Context, chainClient client.EVM, chainID int) (gasBlock *types.Header, err error) { $$$ }' ethergo/submitter/submitter.go

Length of output: 2527


Line range hint 513-537: LGTM! Verify error handling and tracing.

The applyGasFromOracle function correctly fetches gas values from an RPC endpoint and attempts to set them, overriding existing values if the oracle values are higher. It includes context tracing and error handling. Ensure that all errors are properly handled and traced.

Verification successful

Verification successful: Error handling and tracing in applyGasFromOracle are properly implemented.

The applyGasFromOracle function includes appropriate error handling using fmt.Errorf and context tracing with trace.WithAttributes.

  • Error handling is present at:

    • Line 572: return fmt.Errorf("could not get gas fee cap: %w", err)
    • Line 577: return fmt.Errorf("could not get gas tip cap: %w", err)
    • Line 589: return fmt.Errorf("could not get gas price: %w", err)
  • Tracing is implemented at:

    • Line 563: ctx, span := t.metrics.Tracer().Start(ctx, "submitter.applyGasFromOracle")
    • Line 566: metrics.EndSpanWithErr(span, err)
    • Line 580: span.SetAttributes(...)
    • Line 592: span.SetAttributes(...)

This confirms that the function is correctly using error handling and tracing mechanisms.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify error handling and tracing in the applyGasFromOracle function.

# Test: Search for error handling and tracing. Expect: Proper error handling and tracing in the function.
rg --type go 'fmt\.Errorf|trace\.WithAttributes' ethergo/submitter/submitter.go

Length of output: 2444


Script:

#!/bin/bash
# Description: Verify error handling and tracing in the applyGasFromOracle function.

# Find the applyGasFromOracle function definition and its scope
ast-grep --lang go --pattern 'func (t *txSubmitterImpl) applyGasFromOracle(ctx context.Context, transactor *bind.TransactOpts, chainID int) error { $$$ }' ethergo/submitter/submitter.go

Length of output: 187


Script:

#!/bin/bash
# Description: Verify error handling and tracing in the applyGasFromOracle function.

# Find the applyGasFromOracle function definition by its name
rg --type go 'func.*applyGasFromOracle' ethergo/submitter/submitter.go

Length of output: 219


Script:

#!/bin/bash
# Description: Verify error handling and tracing in the applyGasFromOracle function.

# Find the applyGasFromOracle function definition and its scope
ast-grep --lang go --pattern 'func (t *txSubmitterImpl) applyGasFromOracle(ctx context.Context, transactor *bind.TransactOpts, client client.EVM, useDynamic bool) (err error) { $$$ }' ethergo/submitter/submitter.go

Length of output: 2988

Comment on lines +87 to +93
case BridgeDisputeEvent:
disputed, err := p.filterer.ParseBridgeProofDisputed(log)
if err != nil {
return noOpEvent, nil, false
}
return eventType, disputed, true

Copy link
Contributor

Choose a reason for hiding this comment

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

LGTM! But add tests for the new case.

The addition of the BridgeDisputeEvent case in the ParseEvent method is correctly implemented.

However, the new lines are not covered by tests. Do you want me to generate the unit testing code or open a GitHub issue to track this task?

Tools
GitHub Check: codecov/patch

[warning] 87-92: services/rfq/contracts/fastbridge/parser.go#L87-L92
Added lines #L87 - L92 were not covered by tests

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

  • Updated Docker image tag and specified platform as linux/amd64 in /ethergo/backends/anvil/anvil.go
  • Added error logging when submitter is not started in /ethergo/submitter/submitter.go
  • Removed CI conditional skips and added guard service setup in /services/rfq/e2e/rfq_test.go
  • Switched backend setup to Anvil and added guard wallet setup in /services/rfq/e2e/setup_test.go

4 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e576f34 and 71133e6.

Files selected for processing (4)
  • ethergo/backends/anvil/anvil.go (1 hunks)
  • ethergo/submitter/submitter.go (6 hunks)
  • services/rfq/e2e/rfq_test.go (7 hunks)
  • services/rfq/e2e/setup_test.go (9 hunks)
Files skipped from review as they are similar to previous changes (3)
  • ethergo/submitter/submitter.go
  • services/rfq/e2e/rfq_test.go
  • services/rfq/e2e/setup_test.go
Additional comments not posted (1)
ethergo/backends/anvil/anvil.go (1)

83-84: LGTM! The addition of the Platform field is appropriate.

The Platform field in the runOptions struct ensures that the Docker container runs on the specified platform architecture ("linux/amd64"), which is a standard and necessary configuration.

Copy link

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

PR Summary

(updates since last review)

  • Introduced Guard service in /services/rfq/e2e/rfq_test.go
  • Expanded integration tests for dispute handling and Guard setup in /services/rfq/e2e/rfq_test.go
  • Minor formatting adjustments in /ethergo/backends/anvil/anvil.go

2 file(s) reviewed, no comment(s)
Edit PR Review Bot Settings

@trajan0x trajan0x merged commit 1e61249 into master Jul 6, 2024
49 of 50 checks passed
@trajan0x trajan0x deleted the feat/rfq-guard branch July 6, 2024 05:20
trajan0x added a commit that referenced this pull request Jul 6, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
go Pull requests that update Go code M-docs size/l
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants