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

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

Conversation

mani99brar
Copy link
Contributor

@mani99brar mani99brar commented Oct 15, 2024

PR-Codex overview

This PR updates the dependencies and enhances the functionality of the relayer CLI for handling messages between Arbitrum and Ethereum. It introduces new scripts, modifies existing functions, and improves state management for relaying operations.

Detailed summary

  • Updated @arbitrum/sdk from ^3.1.2 to 4.0.1.
  • Added start-testnet-sepolia script in relayer-cli/package.json.
  • Changed getL2Network to getArbitrumNetwork in watcherArbToEth.ts.
  • Introduced new relayer functionalities in arbSepToSepRelayer.ts and arbSepToChiadoRelayer.ts.
  • Implemented state file management in relayerHelpers.ts.
  • Updated message execution logic in messageExecutor function.
  • Enhanced relay and relayBatch functions to support dynamic batch sizes.
  • Modified integration tests for better handling of claims and challenges.
  • Added a new contract deployment JSON for VeaInboxArbToEthTestnet.

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

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 a new asynchronous function, messageExecutor, 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.
validator-cli/src/ArbToEth/watcherArbToEth.ts Changed import from getL2Network to getArbitrumNetwork.
validator-cli/src/utils/arbMsgExecutor.ts Added new function messageExecutor 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.

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 a4b6a90
🔍 Latest deploy log https://app.netlify.com/sites/veascan/deploys/6715f9e9cb6ea10008d2c27a
😎 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:

Comment on lines +385 to +442
"storageLayout": {
"storage": [
{
"astId": 24,
"contract": "src/arbitrumToEth/VeaInboxArbToEth.sol:VeaInboxArbToEth",
"label": "snapshots",
"offset": 0,
"slot": "0",
"type": "t_mapping(t_uint256,t_bytes32)"
},
{
"astId": 28,
"contract": "src/arbitrumToEth/VeaInboxArbToEth.sol:VeaInboxArbToEth",
"label": "inbox",
"offset": 0,
"slot": "1",
"type": "t_array(t_bytes32)64_storage"
},
{
"astId": 30,
"contract": "src/arbitrumToEth/VeaInboxArbToEth.sol:VeaInboxArbToEth",
"label": "count",
"offset": 0,
"slot": "65",
"type": "t_uint64"
}
],
"types": {
"t_array(t_bytes32)64_storage": {
"base": "t_bytes32",
"encoding": "inplace",
"label": "bytes32[64]",
"numberOfBytes": "2048"
},
"t_bytes32": {
"encoding": "inplace",
"label": "bytes32",
"numberOfBytes": "32"
},
"t_mapping(t_uint256,t_bytes32)": {
"encoding": "mapping",
"key": "t_uint256",
"label": "mapping(uint256 => bytes32)",
"numberOfBytes": "32",
"value": "t_bytes32"
},
"t_uint256": {
"encoding": "inplace",
"label": "uint256",
"numberOfBytes": "32"
},
"t_uint64": {
"encoding": "inplace",
"label": "uint64",
"numberOfBytes": "8"
}
}
}
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

Storage layout looks correct, but consider optimization

The contract's storage layout is as follows:

  1. snapshots: mapping(uint256 => bytes32) at slot 0
  2. inbox: bytes32[64] at slot 1
  3. count: uint64 at slot 65

The layout appears to be correct for the contract's functionality. However, there might be room for optimization:

  1. The count variable (uint64) is stored in a full 32-byte slot (slot 65). Consider packing it with other small-sized state variables if any are added in the future to save gas.
  2. The inbox array uses 64 slots (2048 bytes) of storage. Ensure this size is necessary for your use case, as it significantly impacts the contract's storage costs.

Consider the following optimizations if applicable to your use case:

  1. If possible, reduce the size of the inbox array to save on storage costs.
  2. If adding new state variables in the future, consider packing them with the count variable to optimize storage usage.

childRpc: string,
parentRpc: string
): Promise<ContractTransaction> {
const PRIVATE_KEY = process.env.PRIVATE_KEY;
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 a check for undefined PRIVATE_KEY

Currently, if PRIVATE_KEY is undefined, creating a new Wallet instance will throw an error. It's recommended to check if PRIVATE_KEY is set and provide a clear error message if it's not.

Insert this code after line 13 to handle the case when PRIVATE_KEY is undefined:

+  if (!PRIVATE_KEY) {
+    throw new Error("PRIVATE_KEY is not defined in environment variables.");
+  }
📝 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 PRIVATE_KEY = process.env.PRIVATE_KEY;
const PRIVATE_KEY = process.env.PRIVATE_KEY;
if (!PRIVATE_KEY) {
throw new Error("PRIVATE_KEY is not defined in environment variables.");
}

Copy link

sonarcloud bot commented Oct 21, 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: 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.

Comment on lines +13 to +22
["SIGINT", "SIGTERM", "SIGQUIT", "EXIT", "MODULE_NOT_FOUND"].forEach((signal) =>
process.on(signal, async () => {
console.log("exit");
const lock_file_name = "./src/state/" + chain_id + ".pid";
if (fs.existsSync(lock_file_name)) {
fs.unlinkSync(lock_file_name);
}
process.exit(0);
})
);
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

Correct the list of signals in the signal handler

The signals 'EXIT' and 'MODULE_NOT_FOUND' are not valid signals in Node.js. 'exit' is an event, not a signal, and 'MODULE_NOT_FOUND' is an error code. Including them in process.on(signal, ...) may lead to unexpected behavior.

Consider modifying the signal handling as follows:

-["SIGINT", "SIGTERM", "SIGQUIT", "EXIT", "MODULE_NOT_FOUND"].forEach((signal) =>
+["SIGINT", "SIGTERM", "SIGQUIT"].forEach((signal) =>
  process.on(signal, async () => {
    console.log("exit");
    const lock_file_name = "./src/state/" + chainId + ".pid";
    if (fs.existsSync(lock_file_name)) {
      fs.unlinkSync(lock_file_name);
    }
    process.exit(0);
  })
);

If you need to handle the 'exit' event, add a separate listener:

process.on('exit', () => {
  console.log("Process exiting");
  const lockFileName = "./src/state/" + chainId + ".pid";
  if (fs.existsSync(lockFileName)) {
    fs.unlinkSync(lockFileName);
  }
});

Please note that asynchronous code inside an 'exit' event handler may not complete before the process exits. Keep the 'exit' handler synchronous.

Comment on lines +36 to +38
function delay(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
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

Refactor delay function to a shared utility module

The delay function is commonly used and might exist in other files. Consider moving it to a shared utility module for reusability and to avoid code duplication.

Create a utils/delay.ts file:

export function delay(ms: number) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

Then import it where needed:

+import { delay } from "utils/delay";

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

let chain_id = 11155111;
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

Use camelCase and const for chain_id

It's recommended to use camelCase for variable names in JavaScript/TypeScript. Also, since chain_id is not reassigned, it can be declared as const instead of let.

Apply this diff:

-let chain_id = 11155111;
+const chainId = 11155111;

Ensure you update all occurrences of chain_id to chainId throughout the code.

📝 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
let chain_id = 11155111;
const chainId = 11155111;

);

(async () => {
while (1) {
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

Replace constant condition while (1) with while (true)

Using while (1) can cause linting errors for unexpected constant conditions. Replace it with while (true) for better readability and to satisfy linting rules.

Apply this diff:

-(async () => {
-  while (1) {
+(async () => {
+  while (true) {
📝 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
while (1) {
(async () => {
while (true) {
🧰 Tools
🪛 Biome

[error] 25-25: Unexpected constant condition.

(lint/correctness/noConstantCondition)

Comment on lines +25 to +34
while (1) {
let nonce = await initialize(chain_id, network);
nonce = await relayBatch(chain_id, nonce, batchSize, _contract);
if (nonce != null) await updateStateFile(chain_id, Math.floor(Date.now() / 1000), nonce, network);
const currentTS = Math.floor(Date.now() / 1000);
const delayAmount = (epochPeriod - (currentTS % epochPeriod)) * 1000 + 100 * 1000;
console.log("waiting for the next epoch. . .", Math.floor(delayAmount / 1000), "seconds");
await delay(delayAmount);
}
})();
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 error handling in the main loop

If an error occurs during initialize, relayBatch, or updateStateFile, the exception will exit the loop and stop the relayer. To ensure the relayer runs continuously, wrap the loop contents in a try-catch block.

Apply this diff:

  while (true) {
+   try {
      let nonce = await initialize(chainId, network);
      nonce = await relayBatch(chainId, nonce, batchSize, _contract);
      if (nonce != null) await updateStateFile(chainId, Math.floor(Date.now() / 1000), nonce, network);
      const currentTS = Math.floor(Date.now() / 1000);
      const delayAmount = (epochPeriod - (currentTS % epochPeriod)) * 1000 + 100 * 1000;
      console.log("waiting for the next epoch. . .", Math.floor(delayAmount / 1000), "seconds");
      await delay(delayAmount);
+   } catch (error) {
+     console.error("An error occurred during the relay loop:", error);
+     // Optionally, handle the error, retry, or perform cleanup
+   }
  }

This will log the error and allow the loop to continue running.

📝 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
while (1) {
let nonce = await initialize(chain_id, network);
nonce = await relayBatch(chain_id, nonce, batchSize, _contract);
if (nonce != null) await updateStateFile(chain_id, Math.floor(Date.now() / 1000), nonce, network);
const currentTS = Math.floor(Date.now() / 1000);
const delayAmount = (epochPeriod - (currentTS % epochPeriod)) * 1000 + 100 * 1000;
console.log("waiting for the next epoch. . .", Math.floor(delayAmount / 1000), "seconds");
await delay(delayAmount);
}
})();
while (true) {
try {
let nonce = await initialize(chain_id, network);
nonce = await relayBatch(chain_id, nonce, batchSize, _contract);
if (nonce != null) await updateStateFile(chain_id, Math.floor(Date.now() / 1000), nonce, network);
const currentTS = Math.floor(Date.now() / 1000);
const delayAmount = (epochPeriod - (currentTS % epochPeriod)) * 1000 + 100 * 1000;
console.log("waiting for the next epoch. . .", Math.floor(delayAmount / 1000), "seconds");
await delay(delayAmount);
} catch (error) {
console.error("An error occurred during the relay loop:", error);
// Optionally, handle the error, retry, or perform cleanup
}
}
})();
🧰 Tools
🪛 Biome

[error] 25-25: Unexpected constant condition.

(lint/correctness/noConstantCondition)

Comment on lines +44 to +49
function getVeaOutboxProvider(veaInboxAddress: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) {
if (chainId == 11155111) {
return VeaOutboxArbToEth__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
} else if (chainId == 10200) {
return VeaOutboxArbToGnosis__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
}
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

Correct parameter name to veaOutboxAddress in getVeaOutboxProvider

The parameter veaInboxAddress should be renamed to veaOutboxAddress in the getVeaOutboxProvider function for clarity.

Apply this diff:

-function getVeaOutboxProvider(veaInboxAddress: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) {
+function getVeaOutboxProvider(veaOutboxAddress: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) {
  if (chainId == 11155111) {
-   return VeaOutboxArbToEth__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
+   return VeaOutboxArbToEth__factory.connect(veaOutboxAddress, getWalletRPC(privateKey, rpc));
  } else if (chainId == 10200) {
-   return VeaOutboxArbToGnosis__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
+   return VeaOutboxArbToGnosis__factory.connect(veaOutboxAddress, getWalletRPC(privateKey, rpc));
  } else {
    throw new Error(`Unsupported chainId: ${chainId}`);
  }
}
📝 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
function getVeaOutboxProvider(veaInboxAddress: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) {
if (chainId == 11155111) {
return VeaOutboxArbToEth__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
} else if (chainId == 10200) {
return VeaOutboxArbToGnosis__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
}
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}`);
}
}

⚠️ Potential issue

Handle unexpected chainId values in getVeaOutboxProvider

The getVeaOutboxProvider function should handle cases where chainId does not match expected values to prevent unintended behavior.

Add an else clause to manage unsupported chainId values:

  } else if (chainId == 10200) {
    return VeaOutboxArbToGnosis__factory.connect(veaOutboxAddress, getWalletRPC(privateKey, rpc));
+ } else {
+   throw new Error(`Unsupported chainId: ${chainId}`);
  }
📝 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
function getVeaOutboxProvider(veaInboxAddress: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) {
if (chainId == 11155111) {
return VeaOutboxArbToEth__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
} else if (chainId == 10200) {
return VeaOutboxArbToGnosis__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
}
function getVeaOutboxProvider(veaInboxAddress: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) {
if (chainId == 11155111) {
return VeaOutboxArbToEth__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
} else if (chainId == 10200) {
return VeaOutboxArbToGnosis__factory.connect(veaOutboxAddress, getWalletRPC(privateKey, rpc));
} else {
throw new Error(`Unsupported chainId: ${chainId}`);
}
}

Comment on lines +28 to +33
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));
}
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

Ensure getVeaInboxProvider handles all possible chainId values

Similar to getVeaInbox, the getVeaInboxProvider function lacks handling for unexpected chainId values, which may result in runtime issues.

Add an else clause to handle unsupported chainId values:

  } else if (chainId == 10200) {
    return VeaInboxArbToGnosis__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc));
+ } else {
+   throw new Error(`Unsupported chainId: ${chainId}`);
  }
📝 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
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(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));
} else {
throw new Error(`Unsupported chainId: ${chainId}`);
}
}

Comment on lines +19 to +25
// Using destination chainId as identifier, Ex: Arbitrum One (42161) -> Ethereum Mainnet (1): Use "1" as chainId
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));
}
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

Handle unexpected chainId values in getVeaInbox function

The getVeaInbox function does not handle cases where chainId is neither 11155111 nor 10200. This could lead to undefined being returned, causing runtime errors when the returned value is used.

Consider adding an else clause to handle unexpected chainId values by throwing an error:

  } else if (chainId == 10200) {
    return VeaInboxArbToGnosis__factory.connect(veaInboxAddress, getWallet(privateKey, web3ProviderURL));
+ } else {
+   throw new Error(`Unsupported chainId: ${chainId}`);
  }
📝 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
// Using destination chainId as identifier, Ex: Arbitrum One (42161) -> Ethereum Mainnet (1): Use "1" as chainId
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));
}
// Using destination chainId as identifier, Ex: Arbitrum One (42161) -> Ethereum Mainnet (1): Use "1" as chainId
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}`);
}
}

@@ -42,32 +40,41 @@ const relay = async (chainid: number, nonce: number) => {
await txn.wait();
};

const relayBatch = async (chainid: number, nonce: number, iterations: number) => {
const relayBatch = async (chainid: number, nonce: number, maxBatchSize: number, _contract: any) => {
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

Update all calls to relayBatch with new _contract parameter

The relayBatch function signature now includes an additional _contract parameter. Ensure that all invocations of this function pass the required contract instance to prevent runtime errors.

};

const relayAllFrom = async (chainid: number, nonce: number, msgSender: string): Promise<number> => {
const relayAllFrom = async (chainid: number, nonce: number, msgSender: string, _contract: any): 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

Synchronize function signature changes for relayAllFrom

The relayAllFrom function now includes an additional _contract parameter. Ensure that all calls to this function are updated accordingly and that any related documentation reflects this change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant