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(rfq-relayer): add multicall support for prove / claim [SLT-355] #3261

Draft
wants to merge 9 commits into
base: master
Choose a base branch
from

Conversation

dwasse
Copy link
Collaborator

@dwasse dwasse commented Oct 9, 2024

Summary by CodeRabbit

  • New Features

    • The package has been renamed to fastbridgemulti, enhancing clarity and functionality.
    • Introduced multicall capabilities to improve transaction handling.
    • Expanded testing suite with new methods for concurrent transactions and multicall functionality.
  • Bug Fixes

    • Updated references in tests and deployment methods to ensure compatibility with the new package name.
  • Documentation

    • Enhanced comments and documentation to reflect the changes in the package structure and functionalities.

@dwasse dwasse marked this pull request as draft October 9, 2024 21:37
Copy link
Contributor

coderabbitai bot commented Oct 9, 2024

Walkthrough

The changes involve renaming the package from fastbridge to fastbridgemulti across multiple files, while maintaining the existing structure and logic. Import statements and embedded file references have been updated to reflect the new package name. Additionally, the rfq_test.go file has been modified to incorporate the new contract name, enhancing the test suite with new functionality. Several modifications in the relayer's configuration and methods have been introduced, including the addition of multicall capabilities. The testutil package has also been updated to align with the new package name.

Changes

File Path Change Summary
services/rfq/contracts/fastbridge/... Package renamed from fastbridge to fastbridgemulti, import statements and embedded references updated.
services/rfq/e2e/rfq_test.go References to fastbridge replaced with fastbridgemulti, new test methods added for concurrency.
services/rfq/relayer/... Added MulticallEnabled field, new methods for multicall functionality, updated class structures.
services/rfq/testutil/... Updated to replace fastbridge with fastbridgemulti, modified deployment methods accordingly.

Possibly related PRs

Suggested labels

go, size/l, M-synapse-interface, M-ci, needs-go-generate-services/rfq

Suggested reviewers

  • aureliusbtc
  • trajan0x
  • ChiTimesChi

🐇 In the meadow, we hop and play,
Fastbridgemulti leads the way!
With tests and changes, oh what a sight,
New paths to follow, all feels just right.
Let's celebrate with a joyful cheer,
For every update brings us near! 🌼


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.

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 Oct 9, 2024
Copy link

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: bdb2742
Status:🚫  Build failed.

View logs

Copy link

codecov bot commented Oct 9, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Please upload report for BASE (master@e74153c). Learn more about missing BASE report.
Report is 226 commits behind head on master.

Additional details and impacted files
@@             Coverage Diff              @@
##             master       #3261   +/-   ##
============================================
  Coverage          ?   43.82556%           
============================================
  Files             ?          74           
  Lines             ?        2316           
  Branches          ?          82           
============================================
  Hits              ?        1015           
  Misses            ?        1295           
  Partials          ?           6           
Flag Coverage Δ
promexporter 6.81642% <ø> (?)

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

🧹 Outside diff range and nitpick comments (10)
services/rfq/contracts/fastbridge/status.go (1)

Line range hint 29-42: Simplify init function and remove unnecessary comments

The init function and surrounding code can be improved for clarity and efficiency:

  1. The init function can be simplified by using a slice literal.
  2. There's an unnecessary commented line that can be removed.

Consider applying the following changes:

 var allBridgeStatuses []BridgeStatus

 func init() {
-    for i := 0; i < len(_BridgeStatus_index)-1; i++ {
-        contractType := BridgeStatus(i)
-        allBridgeStatuses = append(allBridgeStatuses, contractType)
-        // assert type is correct
-    }
+    allBridgeStatuses = []BridgeStatus{NULL, REQUESTED, RelayerProved, RelayerClaimed, REFUNDED}
 }

-// allBridgeStatuses is a list of all bridge statuses Since we use stringer and this is a testing library, instead
-// // of manually copying all these out we pull the names out of stringer. In order to make sure stringer is updated, we panic on
-// // any method called where the index is higher than the stringer array length.
+// allBridgeStatuses is a list of all bridge statuses.

This change simplifies the initialization logic and removes the unnecessary comment, making the code more concise and easier to maintain.

services/rfq/contracts/fastbridge/status_test.go (2)

4-6: Import statements updated correctly.

The import for the fastbridgemulti package has been correctly updated. The re-addition of math/big and testing imports is also good.

Consider grouping the standard library imports (math/big and testing) together at the top of the import block for better organization:

import (
	"math/big"
	"testing"

	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	// ... other imports ...
)

Also applies to: 12-12


Incomplete Package Renaming Detected

Several files still reference the old fastbridge package. Please update all remaining imports and usages to fastbridgemulti to ensure consistency and prevent potential issues.

  • services/rfq/testutil/contracttype.go
  • services/rfq/tools/rfqdecoder/main.go
  • services/rfq/relayer/reldb/db.go
  • ... (and other listed files)
🔗 Analysis chain

Line range hint 44-48: Function call updated correctly.

The GetAllBridgeStatuses() function call has been properly updated to use the fastbridgemulti package, which is consistent with the package renaming.

To ensure that all references to the old package name have been updated, please run the following command:

This will help catch any instances where the package name might have been missed during the update.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to the old 'fastbridge' package
rg --type go 'fastbridge[^m]'

Length of output: 18209

services/rfq/testutil/typecast.go (1)

19-22: LGTM! Consider adding error handling.

The GetFastBridge function has been correctly updated to use the new fastbridgemulti package. The changes are consistent with the import statement update and maintain the existing logic.

Consider adding error handling to the function. Currently, any error from manager.GetContract is silently ignored. You could update the function signature to return an error:

func (d *DeployManager) GetFastBridge(ctx context.Context, backend backends.SimulatedTestBackend) (contract contracts.DeployedContract, handle *fastbridgemulti.FastBridgeRef, err error) {
	d.T().Helper()
	return manager.GetContract[*fastbridgemulti.FastBridgeRef](ctx, d.T(), d, backend, FastBridgeType)
}

This would allow callers to handle any potential errors that occur during contract retrieval.

services/rfq/relayer/relconfig/getters.go (1)

111-119: LGTM! Consider a minor optimization.

The implementation of AnyMulticallEnabled is correct and efficient. It properly iterates through all chain configurations and returns true if any chain has multicall enabled.

For a slight performance improvement, consider using a separate boolean variable to store the result:

 func (c Config) AnyMulticallEnabled() bool {
+    result := false
 	for _, chainCfg := range c.Chains {
 		if chainCfg.MulticallEnabled {
-			return true
+			result = true
+			break
 		}
 	}
-	return false
+	return result
 }

This change allows for easier addition of any future logic after the loop if needed.

services/rfq/relayer/service/handlers.go (1)

627-630: Simplify code by removing unnecessary slice conversion

In submitClaim, the use of request.TransactionID[:] is unnecessary since request.TransactionID is already a byte slice. Removing the [:] makes the code cleaner and more idiomatic.

Apply this change:

-	callData, err := bridgeABI.Pack("claim", request.TransactionID[:], q.RelayerAddress)
+	callData, err := bridgeABI.Pack("claim", request.TransactionID, q.RelayerAddress)
services/rfq/e2e/rfq_test.go (2)

128-129: Consider removing debug print statement

The fmt.Printf statement seems to be used for debugging purposes. If it's not necessary for the test output, consider removing it to clean up the code.


619-622: Address the TODO: Refactor Anvil client setup

The TODO comment suggests improving the Anvil client setup. Consider refactoring this code to enhance readability and prevent code duplication if similar setups are used elsewhere.

Would you like assistance in refactoring this section of the code?

services/rfq/relayer/service/multicall.go (2)

20-23: Add Documentation for the MulticallDispatcher Interface Methods

Adding comments to the MulticallDispatcher interface methods improves code readability and provides clarity on their purpose and usage.

Enhance the interface with method comments:

 type MulticallDispatcher interface {
+    // Start initializes and runs the dispatcher.
     Start(ctx context.Context) error
+    // Dispatch sends the provided call data to the designated chain's queue.
     Dispatch(ctx context.Context, chainID int, callData []byte) error
 }

51-70: Handle Errors in Goroutines Appropriately

In the Start method, if any of the goroutines return an error, it causes the entire function to return. This might lead to the dispatcher stopping if one chain encounters an issue. Consider logging the error and continuing to process other chains.

Modify the goroutine error handling to prevent a single chain's failure from stopping the entire dispatcher:

 func (m *multicallDispatcher) Start(ctx context.Context) error {
     g, gctx := errgroup.WithContext(ctx)
     for c := range m.cfg.Chains {
         chainID := c
         g.Go(func() error {
             err := m.runQueue(gctx, chainID)
             if err != nil {
-                return fmt.Errorf("could not run dispatch: %w", err)
+                // Log the error and continue
+                m.metricHandler.Logger().Warnf("could not run dispatch for chain %d: %v", chainID, err)
             }
             return nil
         })
     }

     err := g.Wait()
     if err != nil {
-        return fmt.Errorf("could not start multicall dispatcher: %w", err)
+        // Log the error and proceed
+        m.metricHandler.Logger().Errorf("error in multicall dispatcher: %v", err)
     }

     return nil
 }

Additionally, ensure that errors are properly logged and monitored for operational awareness.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between c0fa19e and bdb2742.

📒 Files selected for processing (20)
  • services/rfq/contracts/fastbridge/bridgestatus_string.go (1 hunks)
  • services/rfq/contracts/fastbridge/events.go (1 hunks)
  • services/rfq/contracts/fastbridge/eventtype_string.go (1 hunks)
  • services/rfq/contracts/fastbridge/export_test.go (1 hunks)
  • services/rfq/contracts/fastbridge/fastbridgemulti.metadata.go (2 hunks)
  • services/rfq/contracts/fastbridge/generate.go (1 hunks)
  • services/rfq/contracts/fastbridge/helper.go (1 hunks)
  • services/rfq/contracts/fastbridge/parser.go (1 hunks)
  • services/rfq/contracts/fastbridge/status.go (1 hunks)
  • services/rfq/contracts/fastbridge/status_test.go (2 hunks)
  • services/rfq/e2e/rfq_test.go (10 hunks)
  • services/rfq/relayer/chain/chain.go (1 hunks)
  • services/rfq/relayer/relconfig/config.go (1 hunks)
  • services/rfq/relayer/relconfig/getters.go (1 hunks)
  • services/rfq/relayer/service/handlers.go (2 hunks)
  • services/rfq/relayer/service/multicall.go (1 hunks)
  • services/rfq/relayer/service/relayer.go (3 hunks)
  • services/rfq/relayer/service/statushandler.go (2 hunks)
  • services/rfq/testutil/deployers.go (2 hunks)
  • services/rfq/testutil/typecast.go (2 hunks)
✅ Files skipped from review due to trivial changes (4)
  • services/rfq/contracts/fastbridge/events.go
  • services/rfq/contracts/fastbridge/export_test.go
  • services/rfq/contracts/fastbridge/generate.go
  • services/rfq/contracts/fastbridge/helper.go
🧰 Additional context used
🪛 GitHub Check: Build (1.22.x)
services/rfq/relayer/service/multicall.go

[failure] 14-14:
no required module provides package github.com/synapsecns/sanguine/services/rfq/contracts/fastbridgemulti; to add it:

🔇 Additional comments (26)
services/rfq/contracts/fastbridge/fastbridgemulti.metadata.go (2)

2-2: Package name updated correctly.

The package name has been changed from fastbridge to fastbridgemulti, which is consistent with the file renaming.

To ensure all references to this package have been updated throughout the codebase, run the following script:

#!/bin/bash
# Description: Check for any remaining references to the old package name

# Test: Search for import statements or usage of the old package name
rg --type go 'fastbridge' --glob '!**/fastbridge/**'

If the script returns any results, those files may need to be updated to use the new package name.


12-12: Embedded file reference updated correctly.

The embedded file reference has been updated from fastbridge.contractinfo.json to fastbridgemulti.contractinfo.json, which is consistent with the package renaming.

To ensure the new JSON file exists and contains the correct data, run the following script:

This script will verify the existence of the new JSON file, compare its content with the old file (if it still exists), and check if it contains valid JSON data.

✅ Verification successful

Embedded File Reference Update Verified

  • The new JSON file services/rfq/contracts/fastbridge/fastbridgemulti.contractinfo.json exists.
  • The file contains valid JSON.
  • The old JSON file does not exist, consistent with the package renaming.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and content of the new JSON file

# Test 1: Check if the file exists
if [ -f "services/rfq/contracts/fastbridge/fastbridgemulti.contractinfo.json" ]; then
    echo "File exists"
else
    echo "File does not exist"
    exit 1
fi

# Test 2: Compare the content with the old file (if it still exists)
if [ -f "services/rfq/contracts/fastbridge/fastbridge.contractinfo.json" ]; then
    diff "services/rfq/contracts/fastbridge/fastbridge.contractinfo.json" "services/rfq/contracts/fastbridge/fastbridgemulti.contractinfo.json"
else
    echo "Old file does not exist for comparison"
fi

# Test 3: Check if the file is valid JSON
jq . "services/rfq/contracts/fastbridge/fastbridgemulti.contractinfo.json" > /dev/null
if [ $? -eq 0 ]; then
    echo "File contains valid JSON"
else
    echo "File does not contain valid JSON"
    exit 1
fi

Length of output: 428

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

3-3: Package rename looks good.

The package name has been successfully updated from fastbridge to fastbridgemulti, which is consistent with the changes described in the PR summary.

Let's verify the impact of this package rename on other files in the codebase:

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

3-3: Package rename looks good.

The package name has been successfully changed from fastbridge to fastbridgemulti, which is consistent with the project's renaming strategy.

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

1-1: Approve package rename and verify consistency

The package name change from fastbridge to fastbridgemulti has been implemented correctly. This change suggests an expansion of functionality, possibly related to the addition of multicall support mentioned in the PR title.

To ensure consistency across the module, please run the following script:

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

1-1: Package name change looks good.

The package name has been updated from fastbridge_test to fastbridgemulti_test, which is consistent with the shift to a multi-bridge context mentioned in the PR objectives.

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

Line range hint 3-105: The rest of the file remains unchanged.

The existing structure, interfaces, and functionality of the file have been maintained. This includes:

  • The Parser interface and its implementation
  • Event type definitions and constants
  • The NewParser function
  • The ParseEvent method

The consistency in the rest of the file is good, as it minimizes the impact of the package rename.

services/rfq/testutil/typecast.go (1)

9-9: LGTM! Verify usage of the new package.

The import statement has been correctly updated to use the new fastbridgemulti package, which aligns with the PR objective of adding multicall support.

Let's verify that the new package is used consistently throughout the file:

✅ Verification successful

Verified: No remaining references to 'fastbridge' found and fastbridgemulti is used consistently.

The import statement and all related usages have been correctly updated to the new fastbridgemulti package, aligning with the PR's objective of adding multicall support.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining references to the old 'fastbridge' package

# Test: Search for any remaining 'fastbridge' references
rg --type go 'fastbridge[^m]' services/rfq/testutil/typecast.go

# Test: Confirm usage of 'fastbridgemulti'
rg --type go 'fastbridgemulti' services/rfq/testutil/typecast.go

Length of output: 480

services/rfq/relayer/chain/chain.go (1)

95-96: Approve: Logging enhancement improves observability

The addition of transaction hash logging is a valuable improvement to the SubmitRelay function. It enhances the observability of the relay process without altering the core logic or performance of the function. The log statement is correctly placed after the successful creation of the transaction but before returning, ensuring that only successfully created transactions are logged.

services/rfq/testutil/deployers.go (1)

116-118: LGTM! Verify interface compatibility.

The Deploy method has been correctly updated to use the new fastbridgemulti package. The changes are consistent with the import statement update and the PR objective.

To ensure the new contract's interface is compatible with the old one, run the following command to compare the function signatures:

If there are any differences in the function signatures, please ensure that they are intentional and don't break existing functionality.

✅ Verification successful

Verified! The Deploy method properly integrates the new fastbridgemulti package, and all related references have been correctly updated across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Compare function signatures of old and new FastBridge contracts
echo "Old FastBridge functions:"
ast-grep --lang go --pattern 'func ($v *FastBridge) $f($p) $r' services/rfq/contracts/fastbridge
echo "New FastBridgeMulti functions:"
ast-grep --lang go --pattern 'func ($v *FastBridge) $f($p) $r' services/rfq/contracts/fastbridgemulti

Length of output: 420


Script:

#!/bin/bash
# Search for directories named 'fastbridgemulti' within 'services/rfq/contracts'
fd 'fastbridgemulti' services/rfq/contracts/ --type d

Length of output: 53


Script:

#!/bin/bash
# Search for any files or directories containing 'fastbridgemulti' within 'services/rfq/contracts/'
fd 'fastbridgemulti' services/rfq/contracts/ --type f,d

Length of output: 226


Script:

#!/bin/bash
# Corrected search for files and directories named 'fastbridgemulti' within 'services/rfq/contracts/'
fd 'fastbridgemulti' services/rfq/contracts/ --type file --type directory

# Additionally, search for any references to 'fastbridgemulti' in the codebase
rg 'fastbridgemulti' services/rfq/

Length of output: 4259

services/rfq/relayer/service/statushandler.go (1)

112-115: LGTM: Proper initialization of the new multicallDispatcher field.

The multicallDispatcher field is correctly initialized in the requestToHandler function, consistent with the existing pattern for other fields.

To ensure the Relayer struct has been updated with the multicallDispatcher field, please run the following script:

#!/bin/bash
# Description: Verify the Relayer struct update

# Test: Check for the addition of multicallDispatcher field in the Relayer struct
rg --type go "type Relayer struct {" -A 30 ./services/rfq | rg "multicallDispatcher"
services/rfq/relayer/relconfig/config.go (1)

115-116: LGTM! Consider verifying usage in dependent code.

The addition of the MulticallEnabled field to the ChainConfig struct is well-implemented and documented. It follows the existing naming conventions and provides a clear way to enable multicall support on a per-chain basis.

To ensure this change is properly integrated, please run the following script to check for any code that might need updating to handle this new field:

This script will help identify areas of the codebase that might need to be updated to handle the new MulticallEnabled field.

✅ Verification successful

Verified the addition of MulticallEnabled. No issues found with its integration.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for potential places where ChainConfig is used and might need updating.

# Search for ChainConfig usage
echo "Searching for ChainConfig usage:"
rg --type go "ChainConfig" ./services/rfq

# Search for yaml unmarshaling of chain configs
echo "Searching for yaml unmarshaling of chain configs:"
rg --type go "yaml.Unmarshal.*ChainConfig" ./services/rfq

# Search for direct access to chain config fields
echo "Searching for direct access to chain config fields:"
rg --type go "chainConfig\.[A-Za-z]+" ./services/rfq

Length of output: 13217

services/rfq/relayer/service/relayer.go (4)

67-69: LGTM: Added 'multicallDispatcher' field to 'Relayer' struct

The new field multicallDispatcher has been added to the Relayer struct appropriately to support multicall functionality.


154-158: Conditional initialization of 'multicallDispatcher'

The code correctly initializes multicallDispatcher only when multicall is enabled in the configuration via cfg.AnyMulticallEnabled().


161-178: Proper inclusion of 'multicallDispatcher' in 'Relayer' initialization

In the NewRelayer function, the multicallDispatcher field is correctly assigned to the Relayer struct, ensuring it is available for use elsewhere in the service.


239-248: Starting 'multicallDispatcher' in the 'Start' method

The Start method now includes logic to start the multicallDispatcher in a separate goroutine when multicall is enabled. This integrates multicall functionality into the relayer's operational flow as intended.

services/rfq/relayer/service/handlers.go (1)

439-449: Code changes look good

The addition of the submitProve call and status update in the handleRelayCompleted method is appropriate and aligns with the intended bridge process enhancements.

services/rfq/e2e/rfq_test.go (9)

24-24: Import updated to 'fastbridgemulti'

The import statement has been correctly updated to use the new package fastbridgemulti.


171-171: Updated Bridge method to use fastbridgemulti.IFastBridgeBridgeParams

The call to originFastBridge.Bridge has been updated to use fastbridgemulti.IFastBridgeBridgeParams. Ensure that all parameters are correctly set according to the new interface.


325-325: Updated Bridge method to use fastbridgemulti.IFastBridgeBridgeParams


435-435: Updated Bridge method to use fastbridgemulti.IFastBridgeBridgeParams


451-451: Updated parser to use fastbridgemulti.NewParser

The parser initialization now correctly uses fastbridgemulti.NewParser with originFastBridge.Address().


461-461: Updated event parsing to use fastbridgemulti.FastBridgeBridgeRequested

The event casting has been updated to reflect the new fastbridgemulti package.


557-559: Initialize parser with fastbridgemulti.NewParser

The parser is correctly initialized using the new fastbridgemulti package, and error handling is appropriately performed with i.NoError(err).


Line range hint 731-773: Address potential concurrency issues in sendBridgeReq function


Line range hint 755-795: Fix variable capture issue in goroutines

@@ -1,6 +1,6 @@
// Code generated by "stringer -type=EventType"; DO NOT EDIT.

package fastbridge
package fastbridgemulti
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Issues Found: Residual References to fastbridge Detected

Several files still reference the old package name fastbridge. Please update all remaining import statements and usages to fastbridgemulti to ensure consistency and prevent potential issues.

  • Example affected files:
    • services/explorer/types/utils.go
    • services/rfq/e2e/rfq_test.go
    • services/rfq/testutil/contracttype.go
    • (and others as listed in the shell script output)
🔗 Analysis chain

Verify impact of package rename.

As the package has been renamed, we need to ensure that all import statements referencing this package have been updated accordingly throughout the project.

Let's run a script to check for any remaining references to the old package name:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for any remaining references to the old package name 'fastbridge'

# Test: Search for 'fastbridge' in all Go files, excluding the current directory
# Expect: No results, indicating all references have been updated
rg --type go -g '!./services/rfq/contracts/fastbridge*' 'fastbridge'

Length of output: 25891

@@ -1,7 +1,8 @@
package fastbridge
package fastbridgemulti
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Package renaming incomplete

The package name has been changed to fastbridgemulti, but there are still imports referencing fastbridge, and the directory services/rfq/contracts/fastbridge remains unchanged. Please update these imports and rename the directory to ensure consistency across the codebase.

  • Update all remaining imports from fastbridge to fastbridgemulti.
  • Rename the directory services/rfq/contracts/fastbridge to services/rfq/contracts/fastbridgemulti.
🔗 Analysis chain

Package name has been updated.

The package name has been changed from fastbridge to fastbridgemulti. This change might require updates in other parts of the codebase that import this package.

Let's verify if all imports have been updated correctly:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining imports of the old package name

# Test 1: Search for imports of the old package name
echo "Searching for imports of the old package name 'fastbridge':"
rg --type go 'import.*".*fastbridge"'

# Test 2: Search for qualified imports using the old package name
echo "Searching for qualified imports using the old package name:"
rg --type go 'fastbridge\.'

# Test 3: Check if the directory name has been updated
echo "Checking if the directory name has been updated:"
if [ -d "services/rfq/contracts/fastbridge" ]; then
    echo "Warning: Directory 'services/rfq/contracts/fastbridge' still exists"
else
    echo "Directory name has been updated successfully"
fi

Length of output: 12044

Comment on lines +95 to +96
fmt.Printf("relayed with tx hash: %s\n", tx.Hash())

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider enhancing the logging approach

While adding transaction hash logging is beneficial for tracking and debugging, there are a few improvements we could make:

  1. Instead of using fmt.Printf, consider using a proper logging framework (e.g., log, logrus, or zap) for better control over log levels and output destinations in production environments.

  2. Include more context in the log message, such as the chain ID or relevant request details. This will make it easier to correlate logs with specific operations.

Here's a suggested improvement:

-		fmt.Printf("relayed with tx hash: %s\n", tx.Hash())
+		log.WithFields(log.Fields{
+			"chainID": c.ChainID,
+			"txHash":  tx.Hash().Hex(),
+		}).Info("Transaction relayed successfully")

Make sure to import the chosen logging package at the top of the file.

Committable suggestion was skipped due to low confidence.

@@ -14,7 +14,7 @@ import (
"github.com/synapsecns/sanguine/ethergo/contracts"
"github.com/synapsecns/sanguine/ethergo/deployer"
"github.com/synapsecns/sanguine/ethergo/manager"
"github.com/synapsecns/sanguine/services/rfq/contracts/fastbridge"
"github.com/synapsecns/sanguine/services/rfq/contracts/fastbridgemulti"
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Issue: fastbridgemulti package does not exist

The import statement references fastbridgemulti, but the package was not found in services/rfq/contracts. Please ensure that the fastbridgemulti package is correctly added.

🔗 Analysis chain

LGTM! Verify the new package.

The import statement has been correctly updated to use the new fastbridgemulti package, which aligns with the PR objective of adding multicall support.

To ensure the new package exists and is correctly placed, run the following command:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence of the fastbridgemulti package
fd -t d fastbridgemulti services/rfq/contracts

Length of output: 420

Comment on lines +63 to +64
// multicallDispatcher is the multicall dispatcher.
multicallDispatcher MulticallDispatcher
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Missing Import for MulticallDispatcher

The multicallDispatcher field is of type MulticallDispatcher, but there is no import statement for MulticallDispatcher in statushandler.go. Please add the necessary import to ensure the type is recognized.

🔗 Analysis chain

LGTM: New field added for multicall support.

The addition of the multicallDispatcher field aligns with the PR objective of adding multicall support. This change enhances the QuoteRequestHandler struct with new functionality.

To ensure the MulticallDispatcher type is properly defined and imported, please run the following script:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the MulticallDispatcher type definition and import

# Test 1: Check for the import of MulticallDispatcher
rg --type go "import.*MulticallDispatcher" ./services/rfq

# Test 2: Check for the definition of MulticallDispatcher type
rg --type go "type MulticallDispatcher" ./services/rfq

Length of output: 437


Script:

#!/bin/bash
# Description: Corrected script to verify the MulticallDispatcher type definition and import

# Test 1: Correctly check for the import of MulticallDispatcher
rg --type go 'import\s+\(".*MulticallDispatcher.*"\)' ./services/rfq

# Test 2: Check for the definition of MulticallDispatcher type
rg --type go "type MulticallDispatcher" ./services/rfq

Length of output: 208

"github.com/synapsecns/sanguine/core/metrics"
"github.com/synapsecns/sanguine/ethergo/submitter"
omniClient "github.com/synapsecns/sanguine/services/omnirpc/client"
"github.com/synapsecns/sanguine/services/rfq/contracts/fastbridgemulti"
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Missing Module Dependency for fastbridgemulti

The package github.com/synapsecns/sanguine/services/rfq/contracts/fastbridgemulti is imported but not found in the module dependencies. This will cause a build failure.

To resolve this, ensure that the fastbridgemulti package is properly added to your go.mod file. Run the following command to add the missing module:

# Add the missing module dependency
go get github.com/synapsecns/sanguine/services/rfq/contracts/fastbridgemulti
🧰 Tools
🪛 GitHub Check: Build (1.22.x)

[failure] 14-14:
no required module provides package github.com/synapsecns/sanguine/services/rfq/contracts/fastbridgemulti; to add it:

}
contract, err := fastbridgemulti.NewFastBridgeRef(rfqAddr, chainClient)
if err != nil {
return fmt.Errorf("could not create fast bridge contract at address %s: %w", contract.Address(), err)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid Using Uninitialized contract in Error Message

If an error occurs while creating the FastBridgeRef contract, the contract variable may be nil, leading to a panic when calling contract.Address() in the error message.

Modify the error message to use the rfqAddr instead:

 contract, err := fastbridgemulti.NewFastBridgeRef(rfqAddr, chainClient)
 if err != nil {
-    return fmt.Errorf("could not create fast bridge contract at address %s: %w", contract.Address(), err)
+    return fmt.Errorf("could not create fast bridge contract at address %s: %w", rfqAddr.Hex(), err)
 }
📝 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 fmt.Errorf("could not create fast bridge contract at address %s: %w", contract.Address(), err)
return fmt.Errorf("could not create fast bridge contract at address %s: %w", rfqAddr.Hex(), err)

Comment on lines +118 to +122
if len(callQueue) >= maxBatchSize {
if err := m.multicall(ctx, contract, chainID, callQueue); err != nil {
return fmt.Errorf("could not multicall: %w", err)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Call Queue Not Cleared After Multicall Execution

When the callQueue reaches the maxBatchSize, the queue is sent via multicall, but the callQueue is not cleared afterward. This could result in duplicate calls being sent in subsequent batches.

Clear the callQueue after a successful multicall:

 if len(callQueue) >= maxBatchSize {
     if err := m.multicall(ctx, contract, chainID, callQueue); err != nil {
         return fmt.Errorf("could not multicall: %w", err)
     }
+    // Empty the call queue
+    callQueue = [][]byte{}
 }
📝 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 len(callQueue) >= maxBatchSize {
if err := m.multicall(ctx, contract, chainID, callQueue); err != nil {
return fmt.Errorf("could not multicall: %w", err)
}
}
if len(callQueue) >= maxBatchSize {
if err := m.multicall(ctx, contract, chainID, callQueue); err != nil {
return fmt.Errorf("could not multicall: %w", err)
}
// Empty the call queue
callQueue = [][]byte{}
}

Comment on lines +135 to +149
_, err := m.submitter.SubmitTransaction(ctx, big.NewInt(int64(chainID)), func(transactor *bind.TransactOpts) (tx *types.Transaction, err error) {
tx, err = contract.MulticallNoResults(transactor, callQueue, true)
if err != nil {
return nil, fmt.Errorf("could not multicall: %w", err)
}
return tx, nil
})
if err != nil {
return fmt.Errorf("could not submit transaction: %w", err)
}

// empty the call queue
callQueue = [][]byte{}
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.

⚠️ Potential issue

callQueue Clearance Inside multicall Function Has No Effect

Reassigning callQueue within the multicall function does not clear the slice in the runQueue function due to Go's pass-by-value for slices. This means the original callQueue remains unchanged.

Remove the reinitialization of callQueue inside the multicall function:

 func (m *multicallDispatcher) multicall(ctx context.Context, contract *fastbridgemulti.FastBridgeRef, chainID int, callQueue [][]byte) error {
     // Existing code...
     if err != nil {
         return fmt.Errorf("could not submit transaction: %w", err)
     }

-    // Empty the call queue (this has no effect here)
-    callQueue = [][]byte{}
     return nil
 }

Ensure that callQueue is cleared in the runQueue function after successful execution:

 case <-ticker.C:
     if len(callQueue) > 0 {
         if err := m.multicall(ctx, contract, chainID, callQueue); err != nil {
             return fmt.Errorf("could not multicall: %w", err)
         }
+        // Empty the call queue
+        callQueue = [][]byte{}
     }

Committable suggestion was skipped due to low confidence.

Comment on lines +85 to +88
// TODO: configure
var dispatchInterval = 30 * time.Second
var maxBatchSize = 100

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Make Dispatch Interval and Batch Size Configurable

The dispatchInterval and maxBatchSize are currently hardcoded constants. Making these values configurable would enhance the flexibility and adaptability of the dispatcher in different environments.

Consider adding these configurations to relconfig.Config and updating the code accordingly:

 // In your configuration struct
 type Config struct {
     // Existing fields...
+    DispatchInterval time.Duration
+    MaxBatchSize     int
 }

 // In the code
-var dispatchInterval = 30 * time.Second
-var maxBatchSize = 100
+dispatchInterval := m.cfg.DispatchInterval
+maxBatchSize := m.cfg.MaxBatchSize

Committable suggestion was skipped due to low confidence.

@trajan0x trajan0x changed the title feat(rfq-relayer): add multicall support for prove / claim feat(rfq-relayer): add multicall support for prove / claim [SLT-355] Oct 17, 2024
Base automatically changed from feat/FastBridgeV1-MulticallTarget to master October 18, 2024 17:16
Copy link

github-actions bot commented Nov 2, 2024

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days.

@github-actions github-actions bot added the Stale label Nov 2, 2024
@ChiTimesChi ChiTimesChi removed the Stale label Nov 6, 2024
Copy link

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days.

@github-actions github-actions bot added Stale and removed Stale labels Nov 21, 2024
Copy link

github-actions bot commented Dec 6, 2024

This PR is stale because it has been open 14 days with no activity. Remove stale label or comment or this will be closed in 5 days.

@github-actions github-actions bot added the Stale label Dec 6, 2024
@github-actions github-actions bot removed the Stale label Dec 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants