-
Notifications
You must be signed in to change notification settings - Fork 6
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
base: dev
Are you sure you want to change the base?
Conversation
WalkthroughThe changes introduce a new smart contract deployment file, Changes
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
✅ Deploy Preview for veascan ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
✅ Deploy Preview for veascan ready!
To edit notification comments on pull requests, go to your Netlify site configuration. |
There was a problem hiding this 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:
- The
watch
function is quite long and complex. Consider breaking it down into smaller, more manageable functions.- Replace magic numbers and hardcoded values with named constants. For example,
300
inconst finalityBuffer = 300;
could beconst FINALITY_BUFFER_SECONDS = 300;
.- The extensive use of
retryOperation
suggests that error handling could be centralized or improved. Consider implementing a more robust error handling strategy.- 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 ofgetArbitrumNetwork
) 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 clarityThe parameter name
trnxHash
can be renamed totxnHash
for better readability and consistency, astxn
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
⛔ 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
to4.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
togetArbitrumNetwork
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 outsidewatcherArbToGnosis.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 tsLength of output: 461
contracts/deployments/arbitrumSepolia/VeaInboxArbToEthTestnet.json (4)
3-270
: ABI structure looks correct and comprehensiveThe ABI includes the following key components:
- Constructor with parameters
_epochPeriod
and_veaOutboxArbToEth
- Events:
MessageSent
,SnapshotSaved
, andSnapshotSent
- Functions:
count
,epochAt
,epochFinalized
,epochNow
,epochPeriod
,saveSnapshot
,sendMessage
,sendSnapshot
,snapshots
, andveaOutboxArbToEth
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 correctThe 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 addressThe contract is deployed at address
0xE12daFE59Bc3A996362d54b37DFd2BA9279cAd06
. Please ensure this address matches the intended deployment address on the Arbitrum Sepolia testnet.
288-291
: Verify constructor argumentsThe contract was deployed with the following constructor arguments:
epochPeriod
: 7200 (2 hours in seconds)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 theveaOutboxArbToEth
address is correct.validator-cli/src/utils/arbMsgExecutor.ts (1)
44-44
: Verify that the correct provider is passed toexecute
The
execute
method is currently called withchildProvider
, but for executing a child-to-parent message, it should typically be invoked on the parent chain usingparentProvider
. 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 theexecute
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 2Length 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 2Length 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 constantsThe updated
EPOCH_PERIOD
andCHALLENGE_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 resolutionThe test case effectively verifies that the
latestVerifiedEpoch
andstateRoot
are updated correctly after dispute resolution, ensuring the contract behaves as expected in this scenario.
981-1105
: Test ensures correct state after failed dispute resolutionThe test case appropriately confirms that after a disputed and failed claim, the
latestVerifiedEpoch
andstateRoot
are updated to reflect the subsequent valid epoch, maintaining contract integrity.
781-790
: Ensure verification parameters match expected typesVerify 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 typesVerify 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 contractEnsure 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:
"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" | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
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:
snapshots
: mapping(uint256 => bytes32) at slot 0inbox
: bytes32[64] at slot 1count
: uint64 at slot 65
The layout appears to be correct for the contract's functionality. However, there might be room for optimization:
- 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. - 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:
- If possible, reduce the size of the
inbox
array to save on storage costs. - 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; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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."); | |
} |
Quality Gate passedIssues Measures |
There was a problem hiding this 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 commentThere'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 Sepoliarelayer-cli/src/utils/relayerHelpers.ts (2)
22-22
: Remove debug logging or make it conditionalThe
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 messagesWhen 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 forgetCount
function signatureThe
getCount
function now accepts eitherVeaOutboxArbToEth
orVeaOutboxArbToGnosis
. Please ensure that any associated documentation or comments are updated to reflect this change for clarity.
71-71
: Fix typo in error messageThere'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
📒 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 correctionThe added comma is a necessary syntax correction to accommodate the new script entry.
14-14
: New script added for Sepolia testnetThe 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." fiLength of output: 171
Script:
#!/bin/bash # Search for the TypeScript file in the codebase fd "arbSepToSepRelayer\.ts" . --extension tsLength of output: 94
relayer-cli/src/testnet/arbSepToSepRelayer.ts (1)
30-30
: 🛠️ Refactor suggestionClarify 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 secondsIn 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
: LGTMThe import of
initialize
andupdateStateFile
fromrelayerHelpers
is appropriate and improves modularity.
27-27
: Ensure all calls toinitialize
include the newnetwork
parameterThe
initialize
function now acceptsnetwork
as a second parameter. Verify that all other invocations ofinitialize
in the codebase are updated accordingly to prevent unexpected behavior.Run the following script to identify any calls to
initialize
missing thenetwork
parameter:relayer-cli/src/utils/relayerHelpers.ts (1)
3-31
: 🛠️ Refactor suggestionRemove unnecessary 'async' from 'initialize' function
The
initialize
function is marked asasync
but only performs synchronous operations, except for the call toupdateStateFile
. SinceupdateStateFile
doesn't contain anyawait
statements, theasync
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 callingupdateStateFile
:- 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 appropriateThe addition of
VeaInboxArbToGnosis__factory
andVeaOutboxArbToGnosis__factory
imports is correct and necessary for handling connections to Gnosis-related contracts.
63-67
: Updated exports are correct and ensure availabilityThe 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 correctlyThe import statements have been updated to include
getVeaOutbox
,VeaOutboxArbToEth
, andVeaOutboxArbToGnosis
, aligning with the updated SDK version4.0.1
.
33-33
: EnsuregetVeaOutbox
handleschainid
parameter correctlyVerify that the
getVeaOutbox
function correctly utilizes thechainid
parameter to instantiate the appropriateveaOutbox
instance. This ensures correct contract interactions based on the network.
90-90
: Confirm correct initialization ofveaOutbox
withchainid
Ensure that the
veaOutbox
instance is correctly initialized with thechainid
parameter in therelayAllFrom
function. This is crucial for accurate network-specific operations.
51-74
:⚠️ Potential issueReview batch relay logic for correctness and efficiency
The new batching mechanism introduced in the
relayBatch
function processes messages based onmaxBatchSize
. Please verify the following:
Nonce Increment Logic: The line
nonce += batchMessages + 1;
may result in skipping nonces. Ensure thatnonce
is incremented correctly bybatchMessages
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 thatbatchMessages
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.
["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); | ||
}) | ||
); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
function delay(ms: number) { | ||
return new Promise((resolve) => setTimeout(resolve, ms)); | ||
} |
There was a problem hiding this comment.
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; |
There was a problem hiding this comment.
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.
let chain_id = 11155111; | |
const chainId = 11155111; |
); | ||
|
||
(async () => { | ||
while (1) { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
while (1) { | |
(async () => { | |
while (true) { |
🧰 Tools
🪛 Biome
[error] 25-25: Unexpected constant condition.
(lint/correctness/noConstantCondition)
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); | ||
} | ||
})(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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)
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)); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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}`); | |
} | |
} |
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.
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}`); | |
} | |
} |
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)); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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}`); | |
} | |
} |
// 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)); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
// 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) => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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> => { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
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
@arbitrum/sdk
from^3.1.2
to4.0.1
.start-testnet-sepolia
script inrelayer-cli/package.json
.getL2Network
togetArbitrumNetwork
inwatcherArbToEth.ts
.arbSepToSepRelayer.ts
andarbSepToChiadoRelayer.ts
.relayerHelpers.ts
.messageExecutor
function.relay
andrelayBatch
functions to support dynamic batch sizes.VeaInboxArbToEthTestnet
.Summary by CodeRabbit
New Features
VeaInboxArbToEth
, with functionalities for message sending and snapshot management on the Arbitrum Sepolia testnet.messageExecutor
, for executing messages from Arbitrum to Ethereum.Bug Fixes
Chores
@arbitrum/sdk
in the project configuration.