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/arb-sep-to-sep-testnet #344

Open
wants to merge 11 commits into
base: dev
Choose a base branch
from
Open

Conversation

mani99brar
Copy link
Contributor

@mani99brar mani99brar commented Oct 15, 2024

PR-Codex overview

This PR primarily focuses on adding new functionality for relaying messages between different blockchain networks, specifically between Arbitrum and Ethereum, while enhancing existing scripts and configurations for better integration and testing.

Detailed summary

  • Added start-testnet-sepolia script in relayer-cli/package.json.
  • Updated @arbitrum/sdk version in validator-cli/package.json.
  • Introduced new RPC and addresses in validator-cli/.env.dist.
  • Created arbSepToSepRelayer.ts for relaying messages on Sepolia.
  • Added arbSepToChiadoRelayer.ts for relaying messages to Chiado.
  • Enhanced relayerHelpers.ts with initialize and updateStateFile functions.
  • Modified relay.ts to support both VeaOutboxArbToEth and VeaOutboxArbToGnosis.
  • Updated ethers.ts to handle multiple inbox/outbox connections based on chainId.
  • Improved error handling and logging in the new relayer scripts.
  • Added integration tests for new functionalities in contracts/test/integration/ArbToEth.ts.
  • Enhanced monitoring and challenge mechanisms in watcherArbToEth.ts.

The following files were skipped due to too many changes: contracts/deployments/arbitrumSepolia/VeaInboxArbToEthTestnet.json, contracts/deployments/sepolia/VeaOutboxArbToEthTestnet.json

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • New Features

    • Introduced a new smart contract, VeaInboxArbToEth, with functionalities for message sending and snapshot management on the Arbitrum Sepolia testnet.
    • Added a new asynchronous function, messageExecutor, for executing messages from Arbitrum to Ethereum.
    • Implemented helper functions for state initialization and management within the relay process.
    • Added new relayer scripts for batch message relaying on the Chiado and Sepolia testnets.
    • Enhanced relaying functionality with improved batching and error handling.
    • Introduced new environment variables for RPC endpoints and contract addresses to support additional networks.
  • Bug Fixes

    • Updated error messages in integration tests for clarity regarding epoch-related errors.
  • Chores

    • Updated the dependency version for @arbitrum/sdk in the project configuration.
    • Added new scripts for relayer operations in the project configuration.

Copy link
Contributor

coderabbitai bot commented Oct 15, 2024

Walkthrough

The changes introduce a new smart contract deployment file, VeaInboxArbToEthTestnet.json, detailing the VeaInboxArbToEth contract on the Arbitrum Sepolia testnet, including its ABI, constructor, functions, and events. Additionally, integration tests in ArbToEth.ts are updated for new epoch timing parameters, and the @arbitrum/sdk dependency is upgraded in the package.json. Other modifications include a method signature change in the watcher file and the introduction of new asynchronous functions, messageExecutor and getMessageStatus, for executing messages between the Arbitrum and Ethereum networks.

Changes

File Path Change Summary
contracts/deployments/arbitrumSepolia/... Added VeaInboxArbToEthTestnet.json with deployment details, ABI, constructor, functions, and events.
contracts/test/integration/ArbToEth.ts Updated constants for EPOCH_PERIOD and CHALLENGE_PERIOD, modified test cases for epoch calculations and error handling.
validator-cli/package.json Updated @arbitrum/sdk dependency from ^3.1.2 to 4.0.1 and added script for starting the Sepolia testnet.
validator-cli/src/ArbToEth/watcherArbToEth.ts Changed import from getL2Network to getArbitrumNetwork.
validator-cli/src/utils/arbMsgExecutor.ts Added new functions messageExecutor and getMessageStatus for executing child-to-parent messages on Arbitrum.
validator-cli/src/utils/ethers.ts Updated functions for Vea inbox and outbox connections to handle multiple chain IDs and removed old functions.
validator-cli/src/utils/relay.ts Modified outbox handling and relay logic to accommodate batching and error handling.
relayer-cli/package.json Added script for starting the testnet Sepolia relayer and updated existing scripts.
relayer-cli/src/devnetRelayExample.ts Refactored state initialization and updates, removing old function definitions.
relayer-cli/src/testnet/arbSepToChiadoRelayer.ts Introduced a new relayer for the Chiado testnet with batch message relaying functionality.
relayer-cli/src/testnet/arbSepToSepRelayer.ts Introduced a new relayer for the Sepolia testnet with batch message relaying functionality.
relayer-cli/src/utils/relayerHelpers.ts Added functions for state management of the relayer process, including initialization and state file updates.
relayer-cli/src/utils/ethers.ts Updated functions for Vea inbox and outbox connections to handle multiple chain IDs and removed old functions.

Possibly related PRs

Suggested labels

Type: Feature🗿, Package: Contracts

Suggested reviewers

  • jaybuidl
  • alcercu

Poem

In the fields where smart contracts play,
A new inbox hops in, brightening the day.
With epochs and messages, it dances in glee,
Sending snapshots and whispers, oh so free!
From Arbitrum to Ethereum, it leaps with delight,
A rabbit's new journey, shining so bright! 🐇✨


🪧 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 or @coderabbitai title anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

netlify bot commented Oct 15, 2024

Deploy Preview for veascan ready!

Name Link
🔨 Latest commit 63c93b0
🔍 Latest deploy log https://app.netlify.com/sites/veascan/deploys/670e4cd62d41ba0008510090
😎 Deploy Preview https://deploy-preview-344--veascan.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

Copy link

netlify bot commented Oct 15, 2024

Deploy Preview for veascan ready!

Name Link
🔨 Latest commit 14a5228
🔍 Latest deploy log https://app.netlify.com/sites/veascan/deploys/672870cbd8a4110008820fec
😎 Deploy Preview https://deploy-preview-344--veascan.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

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 (3)
validator-cli/src/ArbToEth/watcherArbToEth.ts (2)

Line range hint 1-624: Consider refactoring for improved maintainability and readability.

While the changes related to the SDK update are correct, there are several areas where the overall code structure could be improved:

  1. The watch function is quite long and complex. Consider breaking it down into smaller, more manageable functions.
  2. Replace magic numbers and hardcoded values with named constants. For example, 300 in const finalityBuffer = 300; could be const FINALITY_BUFFER_SECONDS = 300;.
  3. The extensive use of retryOperation suggests that error handling could be centralized or improved. Consider implementing a more robust error handling strategy.
  4. Replace console.log statements with a proper logging system that supports different log levels and can be easily configured for different environments.

Here's an example of how you might start refactoring the watch function:

const FINALITY_BUFFER_SECONDS = 300;
const MAX_FINALITY_TIME_SECONDS_ETH = (slotsPerEpochEth * 3 - 1) * secondsPerSlotEth;

async function watch() {
  const providers = await initializeProviders();
  const contracts = await initializeContracts(providers);
  const params = await getSequencerParams(contracts);

  while (true) {
    const [blockArbFoundOnL1, blockFinalizedEth, finalityIssueFlagEth] = await getBlocksAndCheckFinality(
      providers.eth,
      providers.arb,
      contracts.sequencer,
      params.maxDelaySeconds
    );

    if (!blockArbFoundOnL1) {
      console.error("Critical Error: Arbitrum block is not found on L1.");
      return;
    }

    await processEpochs(blockArbFoundOnL1, blockFinalizedEth, finalityIssueFlagEth, contracts, params);

    await wait(3000); // 3 second delay
  }
}

// Implement other functions like initializeProviders, initializeContracts, getSequencerParams, processEpochs, etc.

This refactoring suggestion provides a starting point. You would need to implement the new functions and adjust the logic accordingly.


Line range hint 1-624: Summary: SDK update changes are correct, but consider overall code improvements.

The changes related to the @arbitrum/sdk update (import and usage of getArbitrumNetwork) are correct and align with the PR objectives. However, the file could benefit from refactoring to improve maintainability and readability. Consider breaking down complex functions, replacing magic numbers with named constants, improving error handling, and implementing a proper logging system.

These improvements would make the code easier to understand, maintain, and debug in the long run.

validator-cli/src/utils/arbMsgExecutor.ts (1)

9-9: Rename 'trnxHash' to 'txnHash' for clarity

The parameter name trnxHash can be renamed to txnHash for better readability and consistency, as txn is a common abbreviation for "transaction".

Apply this diff to rename the parameter:

-  trnxHash: string,
+  txnHash: string,

Also, update all occurrences of trnxHash within the function accordingly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e22031e and f313f3a.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (5)
  • contracts/deployments/arbitrumSepolia/VeaInboxArbToEthTestnet.json (1 hunks)
  • contracts/test/integration/ArbToEth.ts (8 hunks)
  • validator-cli/package.json (1 hunks)
  • validator-cli/src/ArbToEth/watcherArbToEth.ts (2 hunks)
  • validator-cli/src/utils/arbMsgExecutor.ts (1 hunks)
🧰 Additional context used
🔇 Additional comments (16)
validator-cli/package.json (1)

18-18: Approve the dependency update with a recommendation for thorough testing.

The update of @arbitrum/sdk from ^3.1.2 to 4.0.1 is a major version bump, which could potentially introduce breaking changes. While the PR objectives indicate that related code has been modified to align with the SDK changes, it's crucial to ensure comprehensive testing across the entire project.

To verify the impact of this change, please run the following script:

This script will help identify areas of the codebase that might be affected by the SDK update. Please review the results and ensure all necessary adjustments have been made.

Would you like assistance in reviewing any specific areas of the codebase that might be affected by this update?

validator-cli/src/ArbToEth/watcherArbToEth.ts (1)

3-3: LGTM! Verify impact on dependent code.

The update from getL2Network to getArbitrumNetwork aligns with the @arbitrum/sdk package upgrade mentioned in the PR objectives. This change appears to be correct and more specific to the Arbitrum network.

To ensure this change doesn't affect other parts of the codebase, run the following script:

Also applies to: 35-35

✅ Verification successful

Verification Successful: No conflicting usages of getL2Network detected outside watcherArbToGnosis.ts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining usage of getL2Network
rg "getL2Network" --type ts

# Search for new usage of getArbitrumNetwork
rg "getArbitrumNetwork" --type ts

Length of output: 461

contracts/deployments/arbitrumSepolia/VeaInboxArbToEthTestnet.json (4)

3-270: ABI structure looks correct and comprehensive

The ABI includes the following key components:

  1. Constructor with parameters _epochPeriod and _veaOutboxArbToEth
  2. Events: MessageSent, SnapshotSaved, and SnapshotSent
  3. Functions: count, epochAt, epochFinalized, epochNow, epochPeriod, saveSnapshot, sendMessage, sendSnapshot, snapshots, and veaOutboxArbToEth

The function and event signatures appear to be correct and align with the expected functionality of a VeaInbox contract. Please verify that all required functions and events are present and correctly defined.


272-286: Deployment transaction details look correct

The contract was deployed with the following details:

  • Transaction hash: 0x6e499d37ad3867970cef46cfd3cf46eda955b36197f9e8703e2ed7ecb546c5f1
  • From: 0xFa00D29d378EDC57AA1006946F0fc6230a5E3288
  • To: null (contract creation)
  • Contract address: 0xE12daFE59Bc3A996362d54b37DFd2BA9279cAd06
  • Block number: 77452741
  • Gas used: 7438794
  • Status: 1 (Success)

The deployment was successful. Please verify these details on the Arbitrum Sepolia block explorer to ensure everything is correct.

#!/bin/bash
# Verify the deployment transaction on Arbitrum Sepolia explorer
echo "Please manually verify the deployment transaction 0x6e499d37ad3867970cef46cfd3cf46eda955b36197f9e8703e2ed7ecb546c5f1 on the Arbitrum Sepolia explorer: https://sepolia.arbiscan.io/tx/0x6e499d37ad3867970cef46cfd3cf46eda955b36197f9e8703e2ed7ecb546c5f1"

2-2: Verify the contract address

The contract is deployed at address 0xE12daFE59Bc3A996362d54b37DFd2BA9279cAd06. Please ensure this address matches the intended deployment address on the Arbitrum Sepolia testnet.


288-291: Verify constructor arguments

The contract was deployed with the following constructor arguments:

  1. epochPeriod: 7200 (2 hours in seconds)
  2. veaOutboxArbToEth: "0x209BFdC6B7c66b63A8382196Ba3d06619d0F12c9"

Please confirm that these values are correct for the Arbitrum Sepolia testnet deployment. Ensure that the epochPeriod matches the corresponding VeaOutboxArbToEth contract on Ethereum and that the veaOutboxArbToEth address is correct.

validator-cli/src/utils/arbMsgExecutor.ts (1)

44-44: Verify that the correct provider is passed to execute

The execute method is currently called with childProvider, but for executing a child-to-parent message, it should typically be invoked on the parent chain using parentProvider. Please verify that the correct provider is being used according to the Arbitrum SDK documentation.

Run the following script to check the usage of execute in the codebase:

✅ Verification successful

Verification Successful: The childProvider is correctly used with the execute method for child-to-parent messages.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify which provider is passed to the `execute` method for child-to-parent messages.

# Test: Search for `childToParentMessage.execute` and inspect the provider used.
rg --type ts 'childToParentMessage\.execute\(' -A 2

Length of output: 282


Script:

#!/bin/bash
# Description: Locate the definition and usage of `childProvider` and `parentProvider` to verify correct usage.

# Search for the definition of `childProvider`
rg --type ts 'const\s+childProvider\s*='

# Search for all usages of `parentProvider` with the `execute` method
rg --type ts 'parentProvider\.execute\(' -A 2

Length of output: 192


Script:

#!/bin/bash
# Description: Locate the definition and all usages of `parentProvider` to verify correct usage.

# Search for the definition of `parentProvider`
rg --type ts 'const\s+parentProvider\s*='

# Search for all usages of `parentProvider` in the codebase
rg --type ts 'parentProvider' 

Length of output: 385

contracts/test/integration/ArbToEth.ts (9)

29-30: LGTM for updated constants

The updated EPOCH_PERIOD and CHALLENGE_PERIOD constants set to 600 seconds (10 minutes) are appropriate for Hardhat testing environments.


563-577: Duplicate of previous comment regarding challenge parameters


668-682: Duplicate of previous comment regarding challenge parameters


800-816: Duplicate of previous comment regarding challenge parameters


870-979: Test correctly verifies state updates after dispute resolution

The test case effectively verifies that the latestVerifiedEpoch and stateRoot are updated correctly after dispute resolution, ensuring the contract behaves as expected in this scenario.


981-1105: Test ensures correct state after failed dispute resolution

The test case appropriately confirms that after a disputed and failed claim, the latestVerifiedEpoch and stateRoot are updated to reflect the subsequent valid epoch, maintaining contract integrity.


781-790: Ensure verification parameters match expected types

Verify that the parameters provided to the startVerification function align with expected types, particularly the timestamp fields, to avoid potential type issues.

Run the following script to verify the parameter types:

#!/bin/bash
# Description: Verify the parameter types of the `startVerification` function in the VeaOutbox contract.

# Test: Display the `startVerification` function definition to confirm parameter types.
# Expect: Parameter types in the contract match those used in the test.

rg --type solidity -A 10 'function startVerification'

525-539: Ensure challenge parameters match expected types

Verify that the parameters provided to the challenge function match the expected types, especially the timestamp fields, to prevent potential type mismatches or overflows.

Run the following script to verify the parameter types:

#!/bin/bash
# Description: Verify the parameter types of the `challenge` function in the VeaOutbox contract.

# Test: Display the `challenge` function definitions to confirm parameter types.
# Expect: Parameter types in the contract match those used in the test.

rg --type solidity -A 15 'function challenge'

136-136: Verify that the error message matches the contract

Ensure that the claim function in the contract reverts with "Invalid epoch." when an invalid epoch is provided, so the test assertion remains accurate.

Run the following script to verify the error message:

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

🧹 Outside diff range and nitpick comments (5)
relayer-cli/src/devnetRelayExample.ts (1)

28-28: Fix typo in the comment

There's a typo in the comment: "libghtbulb" should be "lightbulb".

Apply this diff to correct the typo:

-  // This is libghtbulb switch address in arbitrum sepolia
+  // This is lightbulb switch address in Arbitrum Sepolia
relayer-cli/src/utils/relayerHelpers.ts (2)

22-22: Remove debug logging or make it conditional

The console.log(process.cwd()); statement is used for debugging purposes. If left in production code, it may clutter the logs with unnecessary information. Consider removing it or making it conditional based on a debug flag.

Option 1: Remove the debug statement:

- console.log(process.cwd());

Option 2: Make it conditional:

+ if (process.env.DEBUG) {
    console.log(process.cwd());
+ }

6-9: Provide more informative error messages

When the lock file exists, the error thrown is generic: throw new Error("Already running");. Providing a more informative error message can help with debugging and understanding the issue.

Enhance the error message:

- throw new Error("Already running");
+ throw new Error(`Process already running for chain ${chain_id} on network ${network}. Lock file exists at ${lock_file_name}`);
relayer-cli/src/utils/relay.ts (2)

13-13: Update documentation for getCount function signature

The getCount function now accepts either VeaOutboxArbToEth or VeaOutboxArbToGnosis. Please ensure that any associated documentation or comments are updated to reflect this change for clarity.


71-71: Fix typo in error message

There's a typo in the error message on line 71:

  • "Unable to execute messgae batch..." should be corrected to "Unable to execute message batch...".
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f313f3a and a4b6a90.

📒 Files selected for processing (7)
  • relayer-cli/package.json (1 hunks)
  • relayer-cli/src/devnetRelayExample.ts (2 hunks)
  • relayer-cli/src/testnet/arbSepToChiadoRelayer.ts (1 hunks)
  • relayer-cli/src/testnet/arbSepToSepRelayer.ts (1 hunks)
  • relayer-cli/src/utils/ethers.ts (3 hunks)
  • relayer-cli/src/utils/relay.ts (4 hunks)
  • relayer-cli/src/utils/relayerHelpers.ts (1 hunks)
🧰 Additional context used
🪛 Biome
relayer-cli/src/testnet/arbSepToChiadoRelayer.ts

[error] 24-24: Unexpected constant condition.

(lint/correctness/noConstantCondition)

relayer-cli/src/testnet/arbSepToSepRelayer.ts

[error] 25-25: Unexpected constant condition.

(lint/correctness/noConstantCondition)

🔇 Additional comments (13)
relayer-cli/package.json (2)

13-13: LGTM: Syntax correction

The added comma is a necessary syntax correction to accommodate the new script entry.


14-14: New script added for Sepolia testnet

The new script start-testnet-sepolia has been added to run the Arbitrum Sepolia to Sepolia relayer. This aligns with the PR objectives of updating the code to work with the new Arbitrum SDK version and focusing on testnet updates.

Let's verify if the referenced TypeScript file exists:

✅ Verification successful

Verification Successful: TypeScript file exists as referenced.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify the existence of the new TypeScript file
if [ -f "./src/testnet/arbSepToSepRelayer.ts" ]; then
    echo "File ./src/testnet/arbSepToSepRelayer.ts exists."
else
    echo "File ./src/testnet/arbSepToSepRelayer.ts does not exist."
fi

Length of output: 171


Script:

#!/bin/bash
# Search for the TypeScript file in the codebase
fd "arbSepToSepRelayer\.ts" . --extension ts

Length of output: 94

relayer-cli/src/testnet/arbSepToSepRelayer.ts (1)

30-30: 🛠️ Refactor suggestion

Clarify the delay calculation and explain the extra 100 seconds

The delay calculation adds an extra 100 * 1000 milliseconds (100 seconds) to the delay amount. If this is intentional to account for network delays or synchronization buffers, consider adding a comment to explain the reason.

Add a comment to clarify:

  const delayAmount = (epochPeriod - (currentTS % epochPeriod)) * 1000 + 100 * 1000;
+ // Added extra 100 seconds to ensure the next epoch has started

If the extra delay is not necessary, adjust the calculation accordingly.

relayer-cli/src/testnet/arbSepToChiadoRelayer.ts (1)

31-31: Verify the delay calculation and additional 100 seconds

In the delay calculation, an extra 100 seconds (100 * 1000 milliseconds) is added after computing the time until the next epoch. Please verify whether this additional time is intentional, as it could cause the relayer to wait longer than necessary between epochs.

relayer-cli/src/devnetRelayExample.ts (2)

3-3: LGTM

The import of initialize and updateStateFile from relayerHelpers is appropriate and improves modularity.


27-27: Ensure all calls to initialize include the new network parameter

The initialize function now accepts network as a second parameter. Verify that all other invocations of initialize in the codebase are updated accordingly to prevent unexpected behavior.

Run the following script to identify any calls to initialize missing the network parameter:

relayer-cli/src/utils/relayerHelpers.ts (1)

3-31: 🛠️ Refactor suggestion

Remove unnecessary 'async' from 'initialize' function

The initialize function is marked as async but only performs synchronous operations, except for the call to updateStateFile. Since updateStateFile doesn't contain any await statements, the async keyword is unnecessary. Removing it can simplify the code and prevent potential confusion about asynchronous behavior.

Apply this diff to remove the async keyword:

- async function initialize(chain_id: number, network: string): Promise<number> {
+ function initialize(chain_id: number, network: string): number {

Also, remove the await keyword when calling updateStateFile:

-     await updateStateFile(chain_id, tsnow, 0, network);
+     updateStateFile(chain_id, tsnow, 0, network);

Likely invalid or redundant comment.

relayer-cli/src/utils/ethers.ts (2)

7-8: Imports added for Gnosis factories are appropriate

The addition of VeaInboxArbToGnosis__factory and VeaOutboxArbToGnosis__factory imports is correct and necessary for handling connections to Gnosis-related contracts.


63-67: Updated exports are correct and ensure availability

The export statements have been updated appropriately, making the new functions available for import elsewhere in the codebase.

relayer-cli/src/utils/relay.ts (4)

2-4: Imports updated to reflect SDK changes correctly

The import statements have been updated to include getVeaOutbox, VeaOutboxArbToEth, and VeaOutboxArbToGnosis, aligning with the updated SDK version 4.0.1.


33-33: Ensure getVeaOutbox handles chainid parameter correctly

Verify that the getVeaOutbox function correctly utilizes the chainid parameter to instantiate the appropriate veaOutbox instance. This ensures correct contract interactions based on the network.


90-90: Confirm correct initialization of veaOutbox with chainid

Ensure that the veaOutbox instance is correctly initialized with the chainid parameter in the relayAllFrom function. This is crucial for accurate network-specific operations.


51-74: ⚠️ Potential issue

Review batch relay logic for correctness and efficiency

The new batching mechanism introduced in the relayBatch function processes messages based on maxBatchSize. Please verify the following:

  • Nonce Increment Logic: The line nonce += batchMessages + 1; may result in skipping nonces. Ensure that nonce is incremented correctly by batchMessages without the additional + 1 to prevent skipping messages.

  • Batch Size Control: Confirm that the conditions in the for loop correctly control the batch size and that batchMessages accurately reflects the number of messages processed.

  • Error Handling: In the catch block, consider implementing a retry mechanism or logging additional context to facilitate troubleshooting.

relayer-cli/src/testnet/arbSepToSepRelayer.ts Outdated Show resolved Hide resolved
relayer-cli/src/testnet/arbSepToSepRelayer.ts Outdated Show resolved Hide resolved
relayer-cli/src/testnet/arbSepToSepRelayer.ts Outdated Show resolved Hide resolved
relayer-cli/src/testnet/arbSepToSepRelayer.ts Outdated Show resolved Hide resolved
relayer-cli/src/testnet/arbSepToSepRelayer.ts Outdated Show resolved Hide resolved
relayer-cli/src/utils/ethers.ts Outdated Show resolved Hide resolved
relayer-cli/src/utils/ethers.ts Show resolved Hide resolved
relayer-cli/src/utils/ethers.ts Outdated Show resolved Hide resolved
relayer-cli/src/utils/relay.ts Show resolved Hide resolved
relayer-cli/src/utils/relay.ts Show resolved Hide resolved
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

🧹 Outside diff range and nitpick comments (13)
relayer-cli/src/testnet/arbSepToChiadoRelayer.ts (4)

5-5: Consider making the contract path configurable.

The hardcoded contract path makes the code less flexible and harder to maintain. Consider:

  1. Moving it to a configuration file or environment variable
  2. Using dynamic import instead of require
-const _contract = require("@kleros/vea-contracts/deployments/chiado/VeaOutboxArbToGnosisTestnet.json");
+import contractConfig from process.env.CONTRACT_PATH || "@kleros/vea-contracts/deployments/chiado/VeaOutboxArbToGnosisTestnet.json";

7-10: Consider making configuration values environment-dependent.

These hardcoded values should be configurable based on the environment to improve flexibility and maintainability.

-const chainId = 10200;
-const epochPeriod = 7200; // 3 hrs
-const batchSize = 10; // 10 messages per batch
-const network = "testnet";
+const chainId = parseInt(process.env.CHAIN_ID || "10200");
+const epochPeriod = parseInt(process.env.EPOCH_PERIOD || "7200"); // 3 hrs
+const batchSize = parseInt(process.env.BATCH_SIZE || "10"); // messages per batch
+const network = process.env.NETWORK || "testnet";

13-20: Enhance cleanup logic with better error handling.

The cleanup logic could be more robust by:

  1. Adding error handling for file operations
  2. Ensuring synchronous cleanup before exit
   process.on(signal, async () => {
-    console.log("exit");
+    console.log(`Received ${signal} signal, cleaning up...`);
     const lock_file_name = "./src/state/" + chainId + ".pid";
-    if (fs.existsSync(lock_file_name)) {
-      fs.unlinkSync(lock_file_name);
+    try {
+      if (fs.existsSync(lock_file_name)) {
+        fs.unlinkSync(lock_file_name);
+        console.log('Lock file removed successfully');
+      }
+    } catch (error) {
+      console.error('Error during cleanup:', error);
     }
     process.exit(0);
   })

29-32: Consider improving delay precision.

The current delay calculation adds a fixed 100 seconds buffer, which might be excessive. Consider:

  1. Making the buffer configurable
  2. Using a more precise timing mechanism
     const currentTS = Math.floor(Date.now() / 1000);
-    const delayAmount = (epochPeriod - (currentTS % epochPeriod)) * 1000 + 100 * 1000;
+    const bufferSeconds = parseInt(process.env.EPOCH_BUFFER || "30");
+    const delayAmount = (epochPeriod - (currentTS % epochPeriod)) * 1000 + bufferSeconds * 1000;
     console.log("waiting for the next epoch. . .", Math.floor(delayAmount / 1000), "seconds");
     await delay(delayAmount);
relayer-cli/src/utils/relay.ts (4)

Line range hint 13-29: Add error handling for subgraph queries.

While the function implementation is correct, consider adding error handling for the GraphQL request to handle potential network issues or API failures gracefully.

 const getCount = async (veaOutbox: VeaOutboxArbToEth | VeaOutboxArbToGnosis, chainid: number): Promise<number> => {
   const subgraph = getInboxSubgraph(chainid);
   const stateRoot = await veaOutbox.stateRoot();
 
+  try {
     const result = await request(
       `https://api.studio.thegraph.com/query/${subgraph}`,
       `{
               snapshotSaveds(first: 1, where: { stateRoot: "${stateRoot}" }) {
                 count
               }
             }`
     );
 
     if (result["snapshotSaveds"].length == 0) return 0;
 
     return Number(result["snapshotSaveds"][0].count);
+  } catch (error) {
+    console.error(`Failed to fetch count from subgraph: ${error.message}`);
+    throw error;
+  }
 };
🧰 Tools
🪛 eslint

[error] 13-13: Parsing error: Unexpected token :


Line range hint 31-40: Add error handling for contract interactions.

The relay function should handle potential contract interaction failures gracefully.

 const relay = async (chainid: number, nonce: number) => {
   const routeParams = getBridgeConfig(chainid);
   const veaOutbox = getVeaOutbox(routeParams.veaOutbox, process.env.PRIVATE_KEY, routeParams.rpcOutbox, chainid);
-  const count = await getCount(veaOutbox, chainid);
+  try {
+    const count = await getCount(veaOutbox, chainid);
 
-  const proof = await getProofAtCount(chainid, nonce, count);
-  const [to, data] = await getMessageDataToRelay(chainid, nonce);
+    const proof = await getProofAtCount(chainid, nonce, count);
+    const [to, data] = await getMessageDataToRelay(chainid, nonce);
 
-  const txn = await veaOutbox.sendMessage(proof, nonce, to, data);
-  await txn.wait();
+    const txn = await veaOutbox.sendMessage(proof, nonce, to, data);
+    await txn.wait();
+  } catch (error) {
+    console.error(`Failed to relay message at nonce ${nonce}: ${error.message}`);
+    throw error;
+  }
 };

43-78: Enhance batch processing robustness.

While the new batching logic is an improvement, consider these enhancements:

  1. Add input validation for maxBatchSize
  2. Improve error message formatting
  3. Add gas estimation checks before batch execution
 const relayBatch = async (chainid: number, nonce: number, maxBatchSize: number, _contract: any) => {
+  if (maxBatchSize <= 0 || maxBatchSize > 100) {
+    throw new Error('maxBatchSize must be between 1 and 100');
+  }
   const routeParams = getBridgeConfig(chainid);
   const web3 = new Web3(routeParams.rpcOutbox);
   const batchedSend = _batchedSend(web3, routeParams.batcher, process.env.PRIVATE_KEY, 0);
   const contract = new web3.eth.Contract(_contract.abi, routeParams.veaOutbox);
   const veaOutbox = getVeaOutbox(routeParams.veaOutbox, process.env.PRIVATE_KEY, routeParams.rpcOutbox, chainid);
   const count = await getCount(veaOutbox, chainid);

   while (nonce < count) {
     let batchMessages = 0;
     let txns = [];
     while (batchMessages < maxBatchSize && nonce < count) {
       const isMsgRelayed = await veaOutbox.isMsgRelayed(nonce);
       if (isMsgRelayed) {
         nonce++;
         continue;
       }
       const proof = await getProofAtCount(chainid, nonce, count);
       const [to, data] = await getMessageDataToRelay(chainid, nonce);
       txns.push({
         args: [proof, nonce, to, data],
         method: contract.methods.sendMessage,
         to: contract.options.address,
       });
       batchMessages += 1;
       nonce++;
     }
     if (batchMessages > 0) {
       try {
+        // Estimate gas for the batch
+        const gasEstimate = await batchedSend.estimateGas(txns);
+        console.log(`Estimated gas for batch: ${gasEstimate}`);
         await batchedSend(txns);
       } catch (error) {
-        console.error(`Unable to execute messgae batch(${batchMessages} msgs) from nonce:${nonce} `, error);
+        console.error(
+          `Failed to execute message batch (size: ${batchMessages}, start nonce: ${nonce - batchMessages}): ${error.message}`
+        );
+        throw error;
       }
     }
   }
   return nonce;
 };

Line range hint 81-115: Add error handling and improve code organization.

The function needs error handling for batch transactions and could benefit from better code organization.

 const relayAllFrom = async (chainid: number, nonce: number, msgSender: string, _contract: any): Promise<number> => {
   const routeParams = getBridgeConfig(chainid);
   const web3 = new Web3(routeParams.rpcOutbox);
-  const batchedSend = _batchedSend(
-    web3, // Your web3 object.
-    // The address of the transaction batcher contract you wish to use. The addresses for the different networks are listed below. If the one you need is missing, feel free to deploy it yourself and make a PR to save the address here for others to use.
-    routeParams.batcher,
-    process.env.PRIVATE_KEY, // The private key of the account you want to send transactions from.
-    0 // The debounce timeout period in milliseconds in which transactions are batched.
-  );
+  const batchedSend = _batchedSend(web3, routeParams.batcher, process.env.PRIVATE_KEY, 0);

   const contract = new web3.eth.Contract(_contract.abi, routeParams.veaOutbox);
   const veaOutbox = getVeaOutbox(routeParams.veaOutbox, process.env.PRIVATE_KEY, routeParams.rpcOutbox, chainid);
-  const count = await getCount(veaOutbox, chainid);
+  try {
+    const count = await getCount(veaOutbox, chainid);
+    if (!count) return null;

-  if (!count) return null;
+    const nonces = await getNonceFrom(chainid, nonce, msgSender);
+    if (!nonces.length) {
+      console.log(`No messages found from sender ${msgSender} starting at nonce ${nonce}`);
+      return null;
+    }

-  let txns = [];
+    const txns = [];
-  const nonces = await getNonceFrom(chainid, nonce, msgSender);

   for (const x of nonces) {
     const proof = await getProofAtCount(chainid, x, count);
     const [to, data] = await getMessageDataToRelay(chainid, x);
     txns.push({
       args: [proof, x, to, data],
       method: contract.methods.sendMessage,
       to: contract.options.address,
     });
   }

-  await batchedSend(txns);
+    await batchedSend(txns);
+    return nonces[nonces.length - 1];
+  } catch (error) {
+    console.error(`Failed to relay messages from ${msgSender}: ${error.message}`);
+    throw error;
+  }
-  return nonces[nonces.length - 1];
 };

Also, consider moving the batchedSend configuration details to the documentation.

relayer-cli/src/testnet/arbSepToSepRelayer.ts (3)

25-25: Suppress linter error for constant condition in the while loop

The while (true) loop triggers a linting error: "Unexpected constant condition." Since the infinite loop is intentional, you can suppress the linter warning by adding an inline comment.

Apply this diff to suppress the linter warning:

+    // eslint-disable-next-line no-constant-condition
     while (true) {
🧰 Tools
🪛 eslint

[error] 25-25: Unexpected constant condition.

(no-constant-condition)


16-18: Use camelCase for variable names

It's recommended to use camelCase for variable names in JavaScript/TypeScript. Rename lock_file_name to lockFileName for consistency.

Apply this diff:

-    const lock_file_name = "./src/state/" + chainId + ".pid";
-    if (fs.existsSync(lock_file_name)) {
-      fs.unlinkSync(lock_file_name);
+    const lockFileName = "./src/state/" + chainId + ".pid";
+    if (fs.existsSync(lockFileName)) {
+      fs.unlinkSync(lockFileName);

6-6: Use a descriptive variable name instead of _contract

Using a leading underscore in variable names is unconventional and may lead to confusion. Consider renaming _contract to a more descriptive name like veaOutboxContract.

Apply this diff:

-const _contract = require("@kleros/vea-contracts/deployments/sepolia/VeaOutboxArbToEthTestnet.json");
+const veaOutboxContract = require("@kleros/vea-contracts/deployments/sepolia/VeaOutboxArbToEthTestnet.json");

Ensure to update all references to _contract accordingly.

relayer-cli/src/utils/relayerHelpers.ts (1)

6-9: Consider handling stale lock files to improve robustness

The current implementation checks for the existence of a lock file to prevent concurrent processes. However, if a previous process terminated unexpectedly without deleting the lock file, subsequent executions will fail unnecessarily. To improve robustness, consider verifying whether the process ID stored in the lock file corresponds to an active process before throwing an error. If the process is not running, the lock file can be safely removed.

relayer-cli/src/utils/ethers.ts (1)

20-27: Consider refactoring repetitive contract connection functions

The functions getVeaInbox, getVeaInboxProvider, getVeaOutbox, and getVeaOutboxProvider have similar structures and logic, differing mainly in contract factories and providers. Refactoring these into generic helper functions would reduce code duplication and enhance maintainability.

Here is a suggested refactor:

// Generic function to connect to a Vea contract using provider URL
function getVeaContract(
  contractFactories: { [key: number]: any },
  address: string,
  privateKey: string,
  providerURL: string,
  chainId: number
) {
  const wallet = getWallet(privateKey, providerURL);
  const contractFactory = contractFactories[chainId];
  if (!contractFactory) {
    throw new Error(`Unsupported chainId: ${chainId}`);
  }
  return contractFactory.connect(address, wallet);
}

// Generic function to connect to a Vea contract using JsonRpcProvider
function getVeaContractWithProvider(
  contractFactories: { [key: number]: any },
  address: string,
  privateKey: string,
  rpc: JsonRpcProvider,
  chainId: number
) {
  const wallet = getWalletRPC(privateKey, rpc);
  const contractFactory = contractFactories[chainId];
  if (!contractFactory) {
    throw new Error(`Unsupported chainId: ${chainId}`);
  }
  return contractFactory.connect(address, wallet);
}

Then, replace the individual functions:

-function getVeaInbox(veaInboxAddress: string, privateKey: string, web3ProviderURL: string, chainId: number) {
-  if (chainId == 11155111) {
-    return VeaInboxArbToEth__factory.connect(veaInboxAddress, getWallet(privateKey, web3ProviderURL));
-  } else if (chainId == 10200) {
-    return VeaInboxArbToGnosis__factory.connect(veaInboxAddress, getWallet(privateKey, web3ProviderURL));
-  } else {
-    throw new Error(`Unsupported chainId: ${chainId}`);
-  }
+function getVeaInbox(address: string, privateKey: string, web3ProviderURL: string, chainId: number) {
+  const contractFactories = {
+    11155111: VeaInboxArbToEth__factory,
+    10200: VeaInboxArbToGnosis__factory,
+  };
+  return getVeaContract(contractFactories, address, privateKey, web3ProviderURL, chainId);
}

-function getVeaInboxProvider(veaInboxAddress: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) {
-  if (chainId == 11155111) {
-    return VeaInboxArbToEth__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
-  } else if (chainId == 10200) {
-    return VeaInboxArbToGnosis__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
-  }
+function getVeaInboxProvider(address: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) {
+  const contractFactories = {
+    11155111: VeaInboxArbToEth__factory,
+    10200: VeaInboxArbToGnosis__factory,
+  };
+  return getVeaContractWithProvider(contractFactories, address, privateKey, rpc, chainId);
}

-function getVeaOutbox(veaInboxAddress: string, privateKey: string, web3ProviderURL: string, chainId: number) {
-  if (chainId == 11155111) {
-    return VeaOutboxArbToEth__factory.connect(veaInboxAddress, getWallet(privateKey, web3ProviderURL));
-  } else if (chainId == 10200) {
-    return VeaOutboxArbToGnosis__factory.connect(veaInboxAddress, getWallet(privateKey, web3ProviderURL));
-  } else {
-    throw new Error(`Unsupported chainId: ${chainId}`);
-  }
+function getVeaOutbox(address: string, privateKey: string, web3ProviderURL: string, chainId: number) {
+  const contractFactories = {
+    11155111: VeaOutboxArbToEth__factory,
+    10200: VeaOutboxArbToGnosis__factory,
+  };
+  return getVeaContract(contractFactories, address, privateKey, web3ProviderURL, chainId);
}

-function getVeaOutboxProvider(veaOutboxAddress: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) {
-  if (chainId == 11155111) {
-    return VeaOutboxArbToEth__factory.connect(veaOutboxAddress, getWalletRPC(privateKey, rpc));
-  } else if (chainId == 10200) {
-    return VeaOutboxArbToGnosis__factory.connect(veaOutboxAddress, getWalletRPC(privateKey, rpc));
-  } else {
-    throw new Error(`Unsupported chainId: ${chainId}`);
-  }
+function getVeaOutboxProvider(address: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) {
+  const contractFactories = {
+    11155111: VeaOutboxArbToEth__factory,
+    10200: VeaOutboxArbToGnosis__factory,
+  };
+  return getVeaContractWithProvider(contractFactories, address, privateKey, rpc, chainId);
}

Also applies to: 30-35, 38-45, 48-55

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between a4b6a90 and 8a440c5.

📒 Files selected for processing (5)
  • relayer-cli/src/testnet/arbSepToChiadoRelayer.ts (1 hunks)
  • relayer-cli/src/testnet/arbSepToSepRelayer.ts (1 hunks)
  • relayer-cli/src/utils/ethers.ts (3 hunks)
  • relayer-cli/src/utils/relay.ts (4 hunks)
  • relayer-cli/src/utils/relayerHelpers.ts (1 hunks)
🧰 Additional context used
🪛 eslint
relayer-cli/src/testnet/arbSepToChiadoRelayer.ts

[error] 24-24: Unexpected constant condition.

(no-constant-condition)

relayer-cli/src/testnet/arbSepToSepRelayer.ts

[error] 25-25: Unexpected constant condition.

(no-constant-condition)

relayer-cli/src/utils/relay.ts

[error] 13-13: Parsing error: Unexpected token :

relayer-cli/src/utils/relayerHelpers.ts

[error] 3-3: Parsing error: Unexpected token :

🔇 Additional comments (1)
relayer-cli/src/utils/relay.ts (1)

2-4: LGTM! Import changes align with multi-network support.

The changes to imports and type definitions appropriately support the generalization of the outbox functionality across different networks.

@@ -0,0 +1,51 @@
import * as fs from "fs";

async function initialize(chain_id: number, network: string): Promise<number> {
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

Fix ESLint parsing error by configuring ESLint for TypeScript

The ESLint error indicates a parsing error at line 3, likely because ESLint is not properly configured to handle TypeScript syntax. To resolve this issue, ensure that ESLint is set up with the appropriate parser (@typescript-eslint/parser) and plugins (@typescript-eslint/eslint-plugin) for TypeScript files.

🧰 Tools
🪛 eslint

[error] 3-3: Parsing error: Unexpected token :

Copy link

sonarcloud bot commented Nov 4, 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: 4

🧹 Outside diff range and nitpick comments (5)
validator-cli/.env.dist (2)

3-6: Consider adding backup RPC endpoints and documenting empty variables.

While the RPC endpoints are correctly configured, consider:

  1. Adding fallback RPC endpoints to prevent single point of failure
  2. Documenting the expected format for RPC_SEPOLIA

Example documentation to add:

 # Devnet RPCs
+# Format: https://rpc-endpoint-url
+# For improved reliability, consider using multiple RPC endpoints separated by comma
 RPC_CHIADO=https://rpc.chiadochain.net
 RPC_ARB_SEPOLIA=https://sepolia-rollup.arbitrum.io/rpc
 RPC_SEPOLIA=

8-11: Document the required RPC endpoints for production.

The empty RPC variables need documentation to guide users on which networks they should point to.

Add documentation:

 # Testnet or Mainnet RPCs
+# RPC_ARB: Arbitrum One mainnet RPC endpoint
+# RPC_ETH: Ethereum mainnet RPC endpoint
 RPC_ARB=
 RPC_ETH=
validator-cli/src/utils/arbMsgExecutor.ts (2)

13-13: Add JSDoc documentation for the exported function.

Since this is an exported function, it should have proper documentation explaining its purpose, parameters, return value, and possible errors.

+/**
+ * Executes a child-to-parent message from Arbitrum to Ethereum
+ * @param trnxHash - The transaction hash containing the message to execute
+ * @param childRpc - The RPC URL for the Arbitrum network
+ * @param parentRpc - The RPC URL for the Ethereum network
+ * @returns Promise resolving to the executed transaction
+ * @throws Error if message execution fails or prerequisites are not met
+ */
 async function messageExecutor(

1-87: Consider architectural improvements for better maintainability.

  1. Consider extracting provider initialization into a reusable utility function to avoid duplication between messageExecutor and getMessageStatus.
  2. Implement a consistent error handling strategy across both functions, preferably using custom error classes for better error categorization.
  3. Consider adding retry mechanisms for transient failures, especially for RPC calls.

Example implementation of a provider utility:

interface ProviderConfig {
  childRpc: string;
  parentRpc: string;
  privateKey: string;
}

interface NetworkProviders {
  childProvider: ArbitrumProvider;
  parentProvider: JsonRpcProvider;
  parentSigner: Signer;
}

function initializeProviders(config: ProviderConfig): NetworkProviders {
  const childJsonRpc = new JsonRpcProvider(config.childRpc);
  const childProvider = new ArbitrumProvider(childJsonRpc);
  const parentProvider = new JsonRpcProvider(config.parentRpc);
  const parentSigner = new Wallet(config.privateKey, parentProvider);
  
  return { childProvider, parentProvider, parentSigner };
}
validator-cli/src/ArbToEth/watcherArbToEth.ts (1)

19-24: Consider implementing monitoring and alerting system.

The watcher script handles critical cross-chain message verification. While the code comments explain the core flow well, the system would benefit from:

  1. Structured logging with severity levels
  2. Metrics collection for:
    • Number of claims processed
    • Challenge success/failure rates
    • Gas usage patterns
  3. Health check endpoints
  4. Alert triggers for:
    • Failed message executions
    • Gas price anomalies
    • Network issues

Would you like assistance in implementing a monitoring solution?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8a440c5 and 14a5228.

📒 Files selected for processing (4)
  • validator-cli/.env.dist (1 hunks)
  • validator-cli/package.json (1 hunks)
  • validator-cli/src/ArbToEth/watcherArbToEth.ts (13 hunks)
  • validator-cli/src/utils/arbMsgExecutor.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • validator-cli/package.json
🔇 Additional comments (6)
validator-cli/.env.dist (2)

Line range hint 1-24: LGTM! Well-organized environment template.

The environment template is well-structured with clear sections for different networks and purposes. The new variables are properly integrated into the existing organization.


12-15: Verify the contract addresses match the deployed contracts.

The contract addresses need to be verified against the deployment artifacts to ensure they match the actual deployed contracts.

✅ Verification successful

Based on the deployment artifacts, I can verify that the contract addresses match correctly:

  1. VeaInbox (arbitrumSepolia): 0xE12daFE59Bc3A996362d54b37DFd2BA9279cAd06
  2. VeaOutbox (sepolia): 0x209BFdC6B7c66b63A8382196Ba3d06619d0F12c9

The contracts are correctly linked to each other:

  • VeaInbox constructor was called with VeaOutbox address
  • VeaOutbox constructor was called with VeaInbox address

The addresses in the .env.dist file match the deployed contract addresses.

Contract addresses are correctly configured and match the deployment artifacts.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify contract addresses match deployment artifacts

# Search for contract addresses in deployment files
echo "Searching for VeaInbox contract address..."
rg -l "0xE12daFE59Bc3A996362d54b37DFd2BA9279cAd06" contracts/deployments/

echo "Searching for VeaOutbox contract address..."
rg -l "0x209BFdC6B7c66b63A8382196Ba3d06619d0F12c9" contracts/deployments/

Length of output: 593


Script:

#!/bin/bash
# Let's examine the actual content of these deployment files to verify the addresses

echo "Content of VeaOutboxArbToEthTestnet.json in sepolia:"
cat contracts/deployments/sepolia/VeaOutboxArbToEthTestnet.json

echo -e "\nContent of VeaInboxArbToEthTestnet.json in arbitrumSepolia:"
cat contracts/deployments/arbitrumSepolia/VeaInboxArbToEthTestnet.json

Length of output: 186109

validator-cli/src/utils/arbMsgExecutor.ts (2)

1-11: LGTM! Imports are well-organized and necessary.

All imported modules are utilized effectively in the implementation.


87-87: LGTM! Clean and clear exports.

The named exports are well-structured.

validator-cli/src/ArbToEth/watcherArbToEth.ts (2)

1-11: LGTM: Import statements correctly updated for new Arbitrum SDK.

The changes align with the PR objective of updating to @arbitrum/sdk v4.0.1, particularly the change from getL2Network to getArbitrumNetwork.


475-488: Review gas fee calculation logic.

The gas fee calculation logic has potential issues:

  1. The maxFeePerGasProfitable calculation divides the deposit by gasEstimate.mul(6), which might result in very low gas fees during high network congestion.
  2. The hardcoded priority fee of 6667 gwei might be too high or too low depending on network conditions.

Consider implementing a more dynamic gas fee calculation:

  1. Use an oracle or gas price feed
  2. Implement exponential backoff for retries with increasing gas prices
  3. Add configurable minimum/maximum gas price bounds

Comment on lines +34 to +38
const messages = await messageReceipt.getChildToParentMessages(parentSigner);
childToParentMessage = messages[0];
if (!childToParentMessage) {
throw new Error("No child-to-parent messages found");
}
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

Add array length check before accessing messages[0].

The code assumes there's at least one message without first checking the array length.

   try {
     const messages = await messageReceipt.getChildToParentMessages(parentSigner);
+    if (!messages || messages.length === 0) {
+      throw new Error("No child-to-parent messages found");
+    }
     childToParentMessage = messages[0];
-    if (!childToParentMessage) {
-      throw new Error("No child-to-parent messages found");
-    }
📝 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
const messages = await messageReceipt.getChildToParentMessages(parentSigner);
childToParentMessage = messages[0];
if (!childToParentMessage) {
throw new Error("No child-to-parent messages found");
}
const messages = await messageReceipt.getChildToParentMessages(parentSigner);
if (!messages || messages.length === 0) {
throw new Error("No child-to-parent messages found");
}
childToParentMessage = messages[0];

Comment on lines +52 to +85
async function getMessageStatus(
trnxHash: string,
childRpc: string,
parentRpc: string
): Promise<ChildToParentMessageStatus> {
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const childJsonRpc = new JsonRpcProvider(childRpc);
const childProvider = new ArbitrumProvider(childJsonRpc);
const parentProvider = new JsonRpcProvider(parentRpc);

let childReceipt: TransactionReceipt | null;
try {
childReceipt = await childProvider.getTransactionReceipt(trnxHash);
} catch (error) {
throw new Error(`Failed to get child transaction receipt: ${error.message}`);
}
if (!childReceipt) {
throw new Error(`Transaction receipt not found for hash: ${trnxHash}`);
}
const messageReceipt = new ChildTransactionReceipt(childReceipt);
const parentSigner: Signer = new Wallet(PRIVATE_KEY, parentProvider);
const messages = await messageReceipt.getChildToParentMessages(parentSigner);
const childToParentMessage = messages[0];
if (!childToParentMessage) {
console.error("No child-to-parent messages found");
}
try {
const status = await childToParentMessage.status(childProvider);
return status;
} catch (error) {
console.error(`Failed to get message status: ${error.message}`);
return undefined;
}
}
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

Improve error handling consistency and type safety.

The function has several issues that need attention:

  1. Inconsistent error handling (mixing throws and console.error)
  2. Return type doesn't match implementation (can return undefined)
  3. Missing array length validation

Apply these improvements:

 async function getMessageStatus(
   trnxHash: string,
   childRpc: string,
   parentRpc: string
-): Promise<ChildToParentMessageStatus> {
+): Promise<ChildToParentMessageStatus | undefined> {
   const PRIVATE_KEY = process.env.PRIVATE_KEY;
   const childJsonRpc = new JsonRpcProvider(childRpc);
   const childProvider = new ArbitrumProvider(childJsonRpc);
   const parentProvider = new JsonRpcProvider(parentRpc);

   let childReceipt: TransactionReceipt | null;
   try {
     childReceipt = await childProvider.getTransactionReceipt(trnxHash);
   } catch (error) {
     throw new Error(`Failed to get child transaction receipt: ${error.message}`);
   }
   if (!childReceipt) {
     throw new Error(`Transaction receipt not found for hash: ${trnxHash}`);
   }
   const messageReceipt = new ChildTransactionReceipt(childReceipt);
   const parentSigner: Signer = new Wallet(PRIVATE_KEY, parentProvider);
   const messages = await messageReceipt.getChildToParentMessages(parentSigner);
+  if (!messages || messages.length === 0) {
+    throw new Error("No child-to-parent messages found");
+  }
   const childToParentMessage = messages[0];
-  if (!childToParentMessage) {
-    console.error("No child-to-parent messages found");
-  }
   try {
     const status = await childToParentMessage.status(childProvider);
     return status;
   } catch (error) {
-    console.error(`Failed to get message status: ${error.message}`);
-    return undefined;
+    throw new Error(`Failed to get message status: ${error.message}`);
   }
 }
📝 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
async function getMessageStatus(
trnxHash: string,
childRpc: string,
parentRpc: string
): Promise<ChildToParentMessageStatus> {
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const childJsonRpc = new JsonRpcProvider(childRpc);
const childProvider = new ArbitrumProvider(childJsonRpc);
const parentProvider = new JsonRpcProvider(parentRpc);
let childReceipt: TransactionReceipt | null;
try {
childReceipt = await childProvider.getTransactionReceipt(trnxHash);
} catch (error) {
throw new Error(`Failed to get child transaction receipt: ${error.message}`);
}
if (!childReceipt) {
throw new Error(`Transaction receipt not found for hash: ${trnxHash}`);
}
const messageReceipt = new ChildTransactionReceipt(childReceipt);
const parentSigner: Signer = new Wallet(PRIVATE_KEY, parentProvider);
const messages = await messageReceipt.getChildToParentMessages(parentSigner);
const childToParentMessage = messages[0];
if (!childToParentMessage) {
console.error("No child-to-parent messages found");
}
try {
const status = await childToParentMessage.status(childProvider);
return status;
} catch (error) {
console.error(`Failed to get message status: ${error.message}`);
return undefined;
}
}
async function getMessageStatus(
trnxHash: string,
childRpc: string,
parentRpc: string
): Promise<ChildToParentMessageStatus | undefined> {
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const childJsonRpc = new JsonRpcProvider(childRpc);
const childProvider = new ArbitrumProvider(childJsonRpc);
const parentProvider = new JsonRpcProvider(parentRpc);
let childReceipt: TransactionReceipt | null;
try {
childReceipt = await childProvider.getTransactionReceipt(trnxHash);
} catch (error) {
throw new Error(`Failed to get child transaction receipt: ${error.message}`);
}
if (!childReceipt) {
throw new Error(`Transaction receipt not found for hash: ${trnxHash}`);
}
const messageReceipt = new ChildTransactionReceipt(childReceipt);
const parentSigner: Signer = new Wallet(PRIVATE_KEY, parentProvider);
const messages = await messageReceipt.getChildToParentMessages(parentSigner);
if (!messages || messages.length === 0) {
throw new Error("No child-to-parent messages found");
}
const childToParentMessage = messages[0];
try {
const status = await childToParentMessage.status(childProvider);
return status;
} catch (error) {
throw new Error(`Failed to get message status: ${error.message}`);
}
}

Comment on lines +411 to +414
} catch (error) {
console.error("Error sending snapshot for epoch " + veaEpochOutboxCheck + " with error " + error);
}
} else {
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

Enhance error handling for critical operations.

The current error handling only logs errors without proper error classification or recovery strategies.

Consider implementing:

-  } catch (error) {
-    console.error("Error sending snapshot for epoch " + veaEpochOutboxCheck + " with error " + error);
+  } catch (error) {
+    if (error.code === 'NETWORK_ERROR') {
+      console.error(`Network error while sending snapshot for epoch ${veaEpochOutboxCheck}. Retrying...`);
+      // Implement retry logic
+    } else if (error.code === 'INSUFFICIENT_FUNDS') {
+      console.error(`Insufficient funds for snapshot at epoch ${veaEpochOutboxCheck}`);
+      process.exit(1); // Critical error, exit
+    } else {
+      console.error(`Unknown error sending snapshot for epoch ${veaEpochOutboxCheck}:`, error);
+      // Log to monitoring service
+    }

Also applies to: 510-512

Comment on lines +719 to +740
const findLatestL2BatchAndBlock = async (
nodeInterface: NodeInterface,
fromArbBlock: number,
latestBlockNumber: number
): Promise<[number, number]> => {
let low = fromArbBlock;
let high = latestBlockNumber;

while (low <= high) {
const mid = Math.floor((low + high) / 2);
try {
(await nodeInterface.functions.findBatchContainingBlock(mid, { blockTag: "latest" })) as any;
low = mid + 1;
} catch (e) {
high = mid - 1;
}
}
if (high < low) return [undefined, undefined];
// high is now the latest L2 block number that has a corresponding batch on L1
const result = (await nodeInterface.functions.findBatchContainingBlock(high, { blockTag: "latest" })) as any;
return [result.batch.toNumber(), high];
};
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

Validate binary search edge cases in findLatestL2BatchAndBlock.

The binary search implementation has potential issues:

  1. Line 736: Returns [undefined, undefined] which doesn't match the return type Promise<[number, number]>
  2. No validation for fromArbBlock being less than latestBlockNumber

Apply this fix:

 const findLatestL2BatchAndBlock = async (
   nodeInterface: NodeInterface,
   fromArbBlock: number,
   latestBlockNumber: number
 ): Promise<[number, number]> => {
+  if (fromArbBlock > latestBlockNumber) {
+    throw new Error('fromArbBlock must be less than latestBlockNumber');
+  }
   let low = fromArbBlock;
   let high = latestBlockNumber;

   while (low <= high) {
     const mid = Math.floor((low + high) / 2);
     try {
       (await nodeInterface.functions.findBatchContainingBlock(mid, { blockTag: "latest" })) as any;
       low = mid + 1;
     } catch (e) {
       high = mid - 1;
     }
   }
-  if (high < low) return [undefined, undefined];
+  if (high < low) return [-1, -1]; // Return sentinel values instead of undefined
   const result = (await nodeInterface.functions.findBatchContainingBlock(high, { blockTag: "latest" })) as any;
   return [result.batch.toNumber(), high];
 };
📝 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
const findLatestL2BatchAndBlock = async (
nodeInterface: NodeInterface,
fromArbBlock: number,
latestBlockNumber: number
): Promise<[number, number]> => {
let low = fromArbBlock;
let high = latestBlockNumber;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
try {
(await nodeInterface.functions.findBatchContainingBlock(mid, { blockTag: "latest" })) as any;
low = mid + 1;
} catch (e) {
high = mid - 1;
}
}
if (high < low) return [undefined, undefined];
// high is now the latest L2 block number that has a corresponding batch on L1
const result = (await nodeInterface.functions.findBatchContainingBlock(high, { blockTag: "latest" })) as any;
return [result.batch.toNumber(), high];
};
const findLatestL2BatchAndBlock = async (
nodeInterface: NodeInterface,
fromArbBlock: number,
latestBlockNumber: number
): Promise<[number, number]> => {
if (fromArbBlock > latestBlockNumber) {
throw new Error('fromArbBlock must be less than latestBlockNumber');
}
let low = fromArbBlock;
let high = latestBlockNumber;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
try {
(await nodeInterface.functions.findBatchContainingBlock(mid, { blockTag: "latest" })) as any;
low = mid + 1;
} catch (e) {
high = mid - 1;
}
}
if (high < low) return [-1, -1]; // Return sentinel values instead of undefined
const result = (await nodeInterface.functions.findBatchContainingBlock(high, { blockTag: "latest" })) as any;
return [result.batch.toNumber(), high];
};

@mani99brar
Copy link
Contributor Author

@coderabbitai summary

Copy link
Contributor

coderabbitai bot commented Nov 4, 2024

✅ Actions performed

Summary regeneration triggered.

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.

1 participant