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

RFQ Relayer: add scroll rebalancing #2863

Merged
merged 200 commits into from
Aug 6, 2024
Merged

RFQ Relayer: add scroll rebalancing #2863

merged 200 commits into from
Aug 6, 2024

Conversation

dwasse
Copy link
Collaborator

@dwasse dwasse commented Jul 9, 2024

Summary by CodeRabbit

  • New Features

    • Introduced support for new rebalance methods, including the Scroll method for enhanced cross-chain interactions.
    • Implemented broader retrieval of rebalance methods, allowing for dynamic management of multiple rebalance strategies.
    • Added approval logic for L1GatewayRouter and L2GatewayRouter contracts.
  • Enhancements

    • Improved error handling and messaging for rebalance management, ensuring clarity when no valid rebalance method is found.
    • Enhanced the flexibility of token configurations by allowing multiple rebalance methods to be specified.
    • Streamlined address retrieval processes for improved type safety and reduced errors.
    • Added a new utility package to encapsulate reusable functions for the RFQ service.

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

coderabbitai bot commented Jul 9, 2024

Warning

Rate limit exceeded

@dwasse has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 1 minutes and 48 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 95f7f2a and 950ad1c.

Walkthrough

The recent updates enhance rebalancing mechanics across blockchain networks by introducing a versatile management system that supports multiple rebalance methods and improves error handling. The addition of RebalanceConfigs allows for more flexible configurations, streamlining operations and making the overall process more robust and adaptable. Moreover, synchronization improvements ensure better context management in test setups, enhancing the stability of the testing framework.

Changes

File Path Summary
services/rfq/relayer/inventory/.../manager.go, services/rfq/relayer/relconfig/.../config.go, services/rfq/relayer/inventory/rebalance.go Enhanced functions and structures to support multiple rebalance methods, improving configuration flexibility and error handling.
services/rfq/e2e/.../setup_test.go, services/rfq/e2e/.../rfq_test.go Updated test setups and streamlined test code for better readability and robustness.
services/rfq/relayer/inventory/.../scroll.go Introduced rebalanceManagerScroll struct for managing rebalances between Ethereum and Scroll chains.
services/rfq/relayer/quoter/.../quoter.go, services/rfq/relayer/relapi/.../client_test.go Updated quote generation methods to ensure proper address formatting and improved test suite references.
services/rfq/util/.../util.go Changed package structure for utility functions, enhancing code organization and reuse across the RFQ service.

Poem

In the world of chains, we glide so smooth,
With rebalancing magic, our codes do soothe.
Listeners set with care, in maps they thrive,
Across Ethereum realms, our features come alive.
A relayer's journey, precise and bright,
Through scrolls and gateways, we code the light.
🌐✨


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 Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

codecov bot commented Jul 9, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 25.37995%. Comparing base (0119884) to head (950ad1c).

Additional details and impacted files
@@                 Coverage Diff                 @@
##              master       #2863         +/-   ##
===================================================
- Coverage   25.76370%   25.37995%   -0.38375%     
===================================================
  Files            772         791         +19     
  Lines          55683       56718       +1035     
  Branches          82          82                 
===================================================
+ Hits           14346       14395         +49     
- Misses         39845       40837        +992     
+ Partials        1492        1486          -6     
Flag Coverage Δ
cctp-relayer 31.97848% <ø> (ø)
ethergo 47.91472% <100.00000%> (-0.22351%) ⬇️
omnirpc 33.23904% <ø> (ø)
opbot 0.48900% <ø> (ø)
promexporter 7.66551% <ø> (?)
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

@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 scroll-contracts submodule for scroll rebalancing functionality (services/cctp-relayer/external/scroll-contracts)
  • Introduced metadata handling for l1gateway and l2gateway contracts (services/rfq/contracts/l1gateway/l1gateway.metadata.go, services/rfq/contracts/l2gateway/l2gateway.metadata.go)
  • Initialized event topics for L1GatewayRouter and L2GatewayRouter contracts (services/rfq/contracts/l1gateway/topics.go, services/rfq/contracts/l2gateway/topics.go)
  • Added support for Scroll rebalance method in inventory manager (services/rfq/relayer/inventory/manager.go, services/rfq/relayer/inventory/scroll.go)
  • Updated configuration to include L1 and L2 Gateway addresses (services/rfq/relayer/relconfig/config.go, services/rfq/relayer/relconfig/enum.go, services/rfq/relayer/relconfig/getters.go)

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

var err error
err = json.Unmarshal(rawContracts, &Contracts)
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: Consider handling the error more gracefully instead of using panic.

var err error
err = json.Unmarshal(rawContracts, &Contracts)
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: Consider handling the error more gracefully instead of using panic.


parsedL2GatewayRouter, err := abi.JSON(strings.NewReader(L2GatewayRouterMetaData.ABI))
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: Consider handling the error more gracefully instead of using panic.

Comment on lines 150 to 155
if c.boundL1Gateway == nil {
return fmt.Errorf("l1 gateway contract not set")
}
if c.boundL2Gateway == nil {
return fmt.Errorf("l2 gateway contract not set")
}
Copy link

Choose a reason for hiding this comment

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

🧠 logic: Ensure both L1 and L2 gateway contracts are set.

}

func (c *rebalanceManagerScroll) listenL2Gateway(ctx context.Context, ethClient client.EVM) (err error) {
addr, err := c.cfg.GetL2GatewayAddress(c.l1ChainID)
Copy link

Choose a reason for hiding this comment

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

📚 spelling: Potential typo: should this be c.l2ChainID instead of c.l1ChainID?

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Outside diff range and nitpick comments (4)
services/rfq/contracts/l1gateway/l1gateway.metadata.go (1)

18-25: Consider adding logging for better debugging.

The init function correctly unmarshals the embedded JSON data. However, adding logging can help with debugging issues.

func init() {
	// load contract metadata
	var err error
	err = json.Unmarshal(rawContracts, &Contracts)
	if err != nil {
		panic(err)
	}
	// Log successful unmarshalling
	fmt.Println("Contract metadata successfully loaded.")
}
services/rfq/contracts/l2gateway/l2gateway.metadata.go (1)

18-25: Consider adding logging for better debugging.

The init function correctly unmarshals the embedded JSON data. However, adding logging can help with debugging issues.

func init() {
	// load contract metadata
	var err error
	err = json.Unmarshal(rawContracts, &Contracts)
	if err != nil {
		panic(err)
	}
	// Log successful unmarshalling
	fmt.Println("Contract metadata successfully loaded.")
}
services/rfq/contracts/l1gateway/topics.go (1)

10-35: Consider adding logging for better debugging.

The init function correctly initializes topic IDs for deposit and withdrawal events. However, adding logging can help with debugging issues.

func init() {
	var err error

	parsedL1GatewayRouter, err := abi.JSON(strings.NewReader(L1GatewayRouterMetaData.ABI))
	if err != nil {
		panic(err)
	}

	DepositETHTopic = parsedL1GatewayRouter.Events["DepositETH"].ID
	DepositERC20Topic = parsedL1GatewayRouter.Events["DepositERC20"].ID
	FinalizeWithdrawETHTopic = parsedL1GatewayRouter.Events["FinalizeWithdrawETH"].ID
	FinalizeWithdrawERC20Topic = parsedL1GatewayRouter.Events["FinalizeWithdrawERC20"].ID

	if DepositETHTopic == (common.Hash{}) {
		panic("topic is nil")
	}
	if DepositERC20Topic == (common.Hash{}) {
		panic("topic is nil")
	}
	if FinalizeWithdrawETHTopic == (common.Hash{}) {
		panic("topic is nil")
	}
	if FinalizeWithdrawERC20Topic == (common.Hash{}) {
		panic("topic is nil")
	}
	// Log successful initialization
	fmt.Println("L1 Gateway topics successfully initialized.")
}
services/rfq/contracts/l2gateway/topics.go (1)

1-1: Add a package comment.

The package declaration should be accompanied by a comment explaining the purpose of the package.

// Package l2gateway handles the initialization and management of event topics for the L2 gateway.
package l2gateway
Tools
GitHub Check: Lint (services/rfq)

[failure] 1-1:
package-comments: should have a package comment (revive)

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0a083a5 and 6112abd.

Files selected for processing (11)
  • .gitmodules (1 hunks)
  • services/cctp-relayer/external/scroll-contracts (1 hunks)
  • services/rfq/contracts/l1gateway/l1gateway.metadata.go (1 hunks)
  • services/rfq/contracts/l1gateway/topics.go (1 hunks)
  • services/rfq/contracts/l2gateway/l2gateway.metadata.go (1 hunks)
  • services/rfq/contracts/l2gateway/topics.go (1 hunks)
  • services/rfq/relayer/inventory/manager.go (1 hunks)
  • services/rfq/relayer/inventory/scroll.go (1 hunks)
  • services/rfq/relayer/relconfig/config.go (1 hunks)
  • services/rfq/relayer/relconfig/enum.go (3 hunks)
  • services/rfq/relayer/relconfig/getters.go (1 hunks)
Files skipped from review due to trivial changes (2)
  • .gitmodules
  • services/cctp-relayer/external/scroll-contracts
Additional context used
GitHub Check: Lint (services/rfq)
services/rfq/contracts/l1gateway/topics.go

[failure] 1-1:
package-comments: should have a package comment (revive)

services/rfq/contracts/l2gateway/topics.go

[failure] 1-1:
package-comments: should have a package comment (revive)

services/rfq/relayer/inventory/scroll.go

[failure] 120-120:
if isEthereumChain(chainID) has complex nested blocks (complexity: 7) (nestif)


[failure] 113-113:
calculated cyclomatic complexity for function initContracts is 13, max is 10 (cyclop)

Additional comments not posted (18)
services/rfq/contracts/l1gateway/l1gateway.metadata.go (2)

1-8: Imports look good.

The import statements are necessary and correctly included.


10-16: Variable declarations look good.

The variable declarations for rawContracts and Contracts are correct and follow best practices.

services/rfq/contracts/l2gateway/l2gateway.metadata.go (2)

1-8: Imports look good.

The import statements are necessary and correctly included.


10-16: Variable declarations look good.

The variable declarations for rawContracts and Contracts are correct and follow best practices.

services/rfq/relayer/relconfig/enum.go (3)

15-16: Constant addition looks good.

The new rebalance method RebalanceMethodScroll is correctly added.


26-27: Function modification looks good.

The RebalanceMethodFromString function correctly handles the new rebalance method scroll.


43-44: Method modification looks good.

The String method correctly handles the new rebalance method scroll.

services/rfq/contracts/l1gateway/topics.go (2)

1-8: Imports look good.

The import statements are necessary and correctly included.

Tools
GitHub Check: Lint (services/rfq)

[failure] 1-1:
package-comments: should have a package comment (revive)


37-47: Variable declarations look good.

The variable declarations for topic IDs are correct and follow best practices.

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

72-75: LGTM!

The added fields L1GatewayAddress and L2GatewayAddress in the ChainConfig struct are consistent and correctly formatted.

services/rfq/relayer/inventory/scroll.go (5)

1-48: LGTM!

The package declaration, imports, and rebalanceManagerScroll struct definition are correct and well-structured.


50-59: LGTM!

The newRebalanceManagerScroll function correctly initializes the rebalanceManagerScroll instance.


61-76: LGTM!

The constants and helper functions for identifying chain types are well-defined and improve code readability.


78-111: LGTM! Verify initialization process.

The Start method is well-structured. Ensure the initialization process is thoroughly tested.


163-470: LGTM!

The remaining methods for event listeners and transaction submissions are well-structured and handle errors appropriately.

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

134-146: LGTM!

The GetL1GatewayAddress method is well-implemented and follows the pattern of other getter methods.


148-160: LGTM!

The GetL2GatewayAddress method is well-implemented and follows the pattern of other getter methods.

services/rfq/relayer/inventory/manager.go (1)

192-193: Verify the new rebalance method addition.

The new rebalance method relconfig.RebalanceMethodScroll has been added correctly. Ensure that newRebalanceManagerScroll is implemented and tested thoroughly.

services/rfq/contracts/l2gateway/topics.go Show resolved Hide resolved
services/rfq/relayer/inventory/scroll.go Outdated Show resolved Hide resolved
Copy link

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

Deploying sanguine-fe with  Cloudflare Pages  Cloudflare Pages

Latest commit: 950ad1c
Status: ✅  Deploy successful!
Preview URL: https://8515dbba.sanguine-fe.pages.dev
Branch Preview URL: https://feat-scroll-rebalance.sanguine-fe.pages.dev

View logs

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)

Based on the provided information and the previous review, here's a summary of the recent changes in this pull request:

The PR continues to enhance the RFQ relayer system, focusing on Scroll rebalancing support and improving overall robustness. Key updates include:

  • Implemented Scroll rebalancing in the RFQ relayer system, adding a new rebalance method specifically for Scroll.
  • Enhanced the ApproveAllTokens function to include approval logic for L1GatewayRouter and L2GatewayRouter contracts, supporting Scroll's cross-chain functionality.
  • Improved error handling and configuration management, particularly in retrieving addresses for various contracts (RFQ, SynapseCCTP, TokenMessenger, L1Gateway, L2Gateway).
  • Updated the rebalance interval process with better context management and error handling, improving the system's reliability during rebalancing operations.
  • Increased flexibility in token configurations by allowing multiple rebalance methods to be specified for each token.

These changes build upon the previous improvements to error handling and configuration management for Circle's CCTP integration, further enhancing the system's capabilities and robustness in handling cross-chain operations.

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

Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 320abca and 344fc28.

Files selected for processing (1)
  • services/rfq/relayer/inventory/manager.go (16 hunks)
Additional comments not posted (3)
services/rfq/relayer/inventory/manager.go (3)

Line range hint 178-191:
LGTM! But verify the new rebalance method.

The changes to retrieve all rebalance methods and the addition of the new rebalance method relconfig.RebalanceMethodScroll look good.

However, ensure that the new rebalance method newRebalanceManagerScroll is correctly implemented and integrated.

Verification successful

Implementation of newRebalanceManagerScroll is correct.

The function newRebalanceManagerScroll has been implemented correctly in services/rfq/relayer/inventory/scroll.go. It initializes the rebalanceManagerScroll struct with the required parameters and additional configurations.

  • services/rfq/relayer/inventory/scroll.go: Implementation of newRebalanceManagerScroll.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of newRebalanceManagerScroll.

# Test: Search for the implementation of newRebalanceManagerScroll. Expect: The function should be implemented correctly.
rg --type go 'func newRebalanceManagerScroll'

Length of output: 322


Script:

#!/bin/bash
# Extract the implementation of the function `newRebalanceManagerScroll` from `services/rfq/relayer/inventory/scroll.go`
rg --type go --context 20 'func newRebalanceManagerScroll' services/rfq/relayer/inventory/scroll.go

Length of output: 1513


339-367: LGTM! But verify the new contract addresses.

The changes to include approval logic for L1GatewayRouter and L2GatewayRouter contracts look good.

However, ensure that the addresses for L1GatewayRouter and L2GatewayRouter are correctly retrieved and used.

Verification successful

Verified: The retrieval of L1GatewayRouter and L2GatewayRouter addresses is correctly implemented.

The functions GetL1GatewayAddress and GetL2GatewayAddress are properly defined and used in the codebase to retrieve the respective addresses.

  • services/rfq/relayer/relconfig/getters.go: Functions GetL1GatewayAddress and GetL2GatewayAddress are implemented here.
  • services/rfq/relayer/inventory/manager.go: These functions are used to retrieve the addresses.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the retrieval of L1GatewayRouter and L2GatewayRouter addresses.

# Test: Search for the address retrieval functions. Expect: The functions should correctly retrieve the addresses.
rg --type go 'func GetL1GatewayAddress'
rg --type go 'func GetL2GatewayAddress'

Length of output: 83


Script:

#!/bin/bash
# Description: Verify the retrieval of L1GatewayRouter and L2GatewayRouter addresses.

# Test: Search for the address retrieval methods using broader patterns.
rg --type go 'L1GatewayAddress'
rg --type go 'L2GatewayAddress'

Length of output: 2528


Line range hint 468-513:
LGTM! But verify the usage of the list-based approach.

The changes to use a list of rebalance methods and update the error message look good.

However, ensure that the list-based approach for rebalance methods is correctly used throughout the codebase.

Verification successful

To ensure the list-based approach for rebalance methods is correctly used throughout the codebase, we need to examine the context around each usage of GetRebalanceMethods.


LGTM! The list-based approach for rebalance methods is correctly used throughout the codebase.

The changes to use a list of rebalance methods have been consistently applied and the logic correctly handles the list of methods.

  • services/rfq/relayer/relconfig/getters.go
  • services/rfq/relayer/inventory/manager.go
  • services/rfq/relayer/inventory/rebalance.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the list-based approach for rebalance methods.

# Test: Search for the usage of GetRebalanceMethods. Expect: The function should be used consistently.
rg --type go 'GetRebalanceMethods'

Length of output: 788


Script:

#!/bin/bash
# Description: Examine the context around each usage of GetRebalanceMethods to verify the correct handling of the list-based approach.

# Extract context around GetRebalanceMethods in services/rfq/relayer/relconfig/getters.go
rg --type go --context 10 'GetRebalanceMethods' services/rfq/relayer/relconfig/getters.go

# Extract context around GetRebalanceMethods in services/rfq/relayer/inventory/manager.go
rg --type go --context 10 'GetRebalanceMethods' services/rfq/relayer/inventory/manager.go

# Extract context around GetRebalanceMethods in services/rfq/relayer/inventory/rebalance.go
rg --type go --context 10 'GetRebalanceMethods' services/rfq/relayer/inventory/rebalance.go

Length of output: 4090

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)

The PR introduces support for new rebalance methods, including the Scroll method, and updates the inventory manager to handle these new methods.

  • Enhanced services/rfq/relayer/inventory/circle.go to support new configurations and improve error handling.
  • Updated services/rfq/relayer/inventory/manager.go to include Scroll rebalancing, dynamic management of multiple rebalance strategies, and approval logic for L1GatewayRouter and L2GatewayRouter contracts.
  • Added services/rfq/relayer/inventory/scroll.go to introduce Scroll rebalancing, including contract initialization, listener setup, and periodic claiming of L2 to L1 transactions.

3 file(s) reviewed, 9 comment(s)
Edit PR Review Bot Settings

Comment on lines +218 to +222
return fmt.Errorf("l1 gateway contract not set")
}
if c.boundL1ScrollMessenger == nil {
return fmt.Errorf("l1 scroll messenger not set")
}
Copy link

Choose a reason for hiding this comment

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

logic: Ensure both L1 and L2 gateway contracts are set to avoid runtime errors.

// set API URL
baseURL := mainnetScrollAPIURL
if isTestnetChain(c.l1ChainID) {
baseURL = testnetScrollAPIURL
Copy link

Choose a reason for hiding this comment

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

syntax: Potential typo: should this be c.l2ChainID instead of c.l1ChainID?

Comment on lines +77 to +81
func newRebalanceManagerScroll(cfg relconfig.Config, handler metrics.Handler, chainClient submitter.ClientFetcher, txSubmitter submitter.TransactionSubmitter, relayerAddress common.Address, db reldb.Service) *rebalanceManagerScroll {
claimCache := ttlcache.New[uint64, bool](
ttlcache.WithTTL[uint64, bool](claimCacheTTL),
ttlcache.WithDisableTouchOnHit[uint64, bool](),
)
Copy link

Choose a reason for hiding this comment

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

logic: Consider defining claimCacheTTL as a constant outside the function to avoid re-creating it on each call.

Comment on lines +114 to +117
func (c *rebalanceManagerScroll) Start(ctx context.Context) (err error) {
err = c.initContracts(ctx)
if err != nil {
return fmt.Errorf("could not initialize contracts: %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: Ensure initContracts handles all possible error scenarios to avoid partial initialization.

return nil
}

func (c *rebalanceManagerScroll) initL1Contracts(parentCtx 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: Consider adding retries for network-related errors when fetching chain clients to improve robustness.

return nil
}

func (c *rebalanceManagerScroll) initL2Contracts(parentCtx 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: Check if chainClient.GetClient handles network failures gracefully to avoid runtime errors.

const scrollGasLimit = 200_000

func (c *rebalanceManagerScroll) initiateL1ToL2(parentCtx context.Context, rebalance *RebalanceData) (err error) {
scrollMsgFee, err := c.cfg.GetScrollMessageFee(c.l1ChainID)
Copy link

Choose a reason for hiding this comment

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

style: Ensure that the transaction submission logic handles all edge cases, such as network failures and gas estimation errors.

Comment on lines +879 to +880
defer resp.Body.Close()

Copy link

Choose a reason for hiding this comment

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

style: Ensure the response body is closed even if an error occurs to avoid potential resource leaks.

Comment on lines +960 to +962
c.claimCache.Set(uint64(nonce.Int64()), true, 0)
return tx, nil
})
Copy link

Choose a reason for hiding this comment

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

style: Check if apiURL is correctly set before making HTTP requests to avoid nil pointer dereference.

@github-actions github-actions bot removed the M-ci Module: CI label Aug 6, 2024
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 344fc28 and 4b34514.

Files selected for processing (3)
  • services/rfq/relayer/inventory/circle.go (6 hunks)
  • services/rfq/relayer/inventory/manager.go (18 hunks)
  • services/rfq/relayer/inventory/scroll.go (1 hunks)
Files skipped from review as they are similar to previous changes (2)
  • services/rfq/relayer/inventory/circle.go
  • services/rfq/relayer/inventory/scroll.go
Additional comments not posted (6)
services/rfq/relayer/inventory/manager.go (6)

178-178: Ensure GetAllRebalanceMethods is correctly implemented.

The function now uses cfg.GetAllRebalanceMethods(). Verify that this method is correctly implemented and returns the expected results.


190-191: New rebalance method added.

The new rebalance method relconfig.RebalanceMethodScroll has been added. Ensure that newRebalanceManagerScroll is correctly implemented and integrates well with the existing rebalance managers.


339-353: Verify new approval logic for L1GatewayRouter.

Ensure that the new approval logic for L1GatewayRouter is correctly implemented and that the contract interactions and error handling are appropriate.


355-369: Verify new approval logic for L2GatewayRouter.

Ensure that the new approval logic for L2GatewayRouter is correctly implemented and that the contract interactions and error handling are appropriate.


468-472: Ensure correct handling of multiple rebalance methods.

The function now retrieves multiple rebalance methods. Verify that this change correctly handles multiple methods and integrates well with the existing logic.


513-513: Update error message to reflect new rebalance method handling.

The error message has been updated to reflect the new list-based approach for rebalance methods. Ensure that this change is consistent with the rest of the code.

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)

The PR introduces support for new rebalance methods, including the Scroll method, and updates the inventory manager to handle these new methods.

  • Enhanced services/rfq/relayer/inventory/rebalance.go to support Scroll rebalancing and improve error handling.
  • Updated services/rfq/relayer/inventory/export_test.go to include tests for new rebalance methods.
  • Modified services/rfq/relayer/inventory/synapse.go to handle Scroll rebalancing, including contract initialization and listener setup.
  • Added approval logic for L1GatewayRouter and L2GatewayRouter contracts in services/rfq/relayer/inventory/manager.go.

7 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)

The PR introduces support for new rebalance methods, including the Scroll method, and updates the inventory manager to handle these new methods.

  • Enhanced services/rfq/relayer/inventory/rebalance.go to support Scroll rebalancing and improve error handling.
  • Updated services/rfq/relayer/inventory/export_test.go to include tests for new rebalance methods.
  • Modified services/rfq/relayer/inventory/synapse.go to handle Scroll rebalancing, including contract initialization and listener setup.
  • Added approval logic for L1GatewayRouter and L2GatewayRouter contracts in services/rfq/relayer/inventory/manager.go.

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

@@ -33,11 +33,11 @@ type RebalanceManager interface {
//nolint:cyclop,nilnil
func getRebalance(span trace.Span, cfg relconfig.Config, tokens map[int]map[common.Address]*TokenMetadata, chainID int, token common.Address) (rebalance *RebalanceData, err error) {
// get rebalance method
method, err := cfg.GetRebalanceMethod(chainID, token.Hex())
methods, err := cfg.GetRebalanceMethods(chainID, token.Hex())
Copy link

Choose a reason for hiding this comment

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

logic: Consider caching rebalance methods to avoid repeated configuration lookups.

@@ -51,7 +51,7 @@ func getRebalance(span trace.Span, cfg relconfig.Config, tokens map[int]map[comm
}

// evaluate the origin and dest of the rebalance based on min/max token balances
originTokenData, destTokenData := getRebalanceMetadatas(cfg, tokens, rebalanceTokenData.Name, method)
originTokenData, destTokenData, method := getRebalanceMetadatas(cfg, tokens, rebalanceTokenData.Name, methods)
if originTokenData == nil {
Copy link

Choose a reason for hiding this comment

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

style: Ensure originTokenData is always initialized to avoid potential nil pointer dereference.

@@ -64,6 +64,12 @@ func getRebalance(span trace.Span, cfg relconfig.Config, tokens map[int]map[comm
}
return nil, nil
}
if method == relconfig.RebalanceMethodNone {
Copy link

Choose a reason for hiding this comment

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

style: Handle cases where method is not recognized to avoid unexpected behavior.

destTokenData = tokenData
//
//nolint:nestif,cyclop,gocognit
func getRebalanceMetadatas(cfg relconfig.Config, tokens map[int]map[common.Address]*TokenMetadata, tokenName string, methods []relconfig.RebalanceMethod) (originTokenData, destTokenData *TokenMetadata, method relconfig.RebalanceMethod) {
Copy link

Choose a reason for hiding this comment

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

logic: Refactor nested loops to improve readability and maintainability.

return originTokenData, destTokenData, method
}

func isTokenCompatible(tokenData *TokenMetadata, method relconfig.RebalanceMethod, cfg relconfig.Config) bool {
Copy link

Choose a reason for hiding this comment

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

logic: Validate token compatibility more efficiently to reduce redundant checks.

//
//nolint:nestif,cyclop,gocognit
func getRebalanceMetadatas(cfg relconfig.Config, tokens map[int]map[common.Address]*TokenMetadata, tokenName string, methods []relconfig.RebalanceMethod) (originTokenData, destTokenData *TokenMetadata, method relconfig.RebalanceMethod) {
candidates := map[relconfig.RebalanceMethod][2]TokenMetadata{}
Copy link

Choose a reason for hiding this comment

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

logic: Consider initializing the candidates map with a predefined capacity to optimize memory allocation.

// select candidates with largest delta between origin and dest balance
maxDelta := big.NewInt(0)
for m, c := range candidates {
delta := new(big.Int).Sub(c[0].Balance, c[1].Balance)
Copy link

Choose a reason for hiding this comment

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

style: Ensure that the delta calculation handles potential integer overflow issues.

}

// select candidates with largest delta between origin and dest balance
maxDelta := big.NewInt(0)
Copy link

Choose a reason for hiding this comment

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

style: Consider adding a check to ensure that originTokenData and destTokenData are not nil before using them.

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 4b34514 and 95f7f2a.

Files selected for processing (1)
  • services/rfq/relayer/inventory/rebalance.go (4 hunks)
Files skipped from review as they are similar to previous changes (1)
  • services/rfq/relayer/inventory/rebalance.go

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)

The PR introduces support for new rebalance methods, including the Scroll method, and updates the inventory manager to handle these new methods.

  • Modified services/rfq/relayer/quoter/quoter_test.go to add OriginFastBridgeAddress and DestFastBridgeAddress to expected quotes, aligning tests with the updated quote structure.
  • Updated services/rfq/relayer/quoter/suite_test.go to include new RFQ addresses for origin, destination, and destinationEth chains, ensuring tests reflect the updated configuration.

No critical issues or potential pitfalls were identified in these changes.

2 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)

The PR introduces support for new rebalance methods, including the Scroll method, and updates the inventory manager to handle these new methods.

  • Updated services/rfq/relayer/relconfig/config_test.go to add and modify test cases for the new Scroll rebalance method.
  • Removed the test for GetRFQAddress in services/rfq/relayer/relconfig/config_test.go, which might need further investigation to ensure it is intentional.
  • Enhanced error handling and messaging for rebalance management.
  • Improved flexibility in token configurations by allowing multiple rebalance methods.
  • Added a new utility package for reusable functions in the RFQ service.

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

@dwasse dwasse merged commit 248dc89 into master Aug 6, 2024
47 checks passed
@dwasse dwasse deleted the feat/scroll-rebalance branch August 6, 2024 19:09
trajan0x added a commit that referenced this pull request Sep 16, 2024
trajan0x added a commit that referenced this pull request Sep 16, 2024
Co-authored-by: Trajan0x <trajan0x@users.noreply.github.com>
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 size/l
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants