-
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:
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.
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: 1
🧹 Outside diff range and nitpick comments (13)
relayer-cli/src/testnet/arbSepToChiadoRelayer.ts (4)
5-5
: Consider making the contract path configurable.The hardcoded contract path makes the code less flexible and harder to maintain. Consider:
- Moving it to a configuration file or environment variable
- Using dynamic import instead of require
-const _contract = require("@kleros/vea-contracts/deployments/chiado/VeaOutboxArbToGnosisTestnet.json"); +import contractConfig from process.env.CONTRACT_PATH || "@kleros/vea-contracts/deployments/chiado/VeaOutboxArbToGnosisTestnet.json";
7-10
: Consider making configuration values environment-dependent.These hardcoded values should be configurable based on the environment to improve flexibility and maintainability.
-const chainId = 10200; -const epochPeriod = 7200; // 3 hrs -const batchSize = 10; // 10 messages per batch -const network = "testnet"; +const chainId = parseInt(process.env.CHAIN_ID || "10200"); +const epochPeriod = parseInt(process.env.EPOCH_PERIOD || "7200"); // 3 hrs +const batchSize = parseInt(process.env.BATCH_SIZE || "10"); // messages per batch +const network = process.env.NETWORK || "testnet";
13-20
: Enhance cleanup logic with better error handling.The cleanup logic could be more robust by:
- Adding error handling for file operations
- Ensuring synchronous cleanup before exit
process.on(signal, async () => { - console.log("exit"); + console.log(`Received ${signal} signal, cleaning up...`); const lock_file_name = "./src/state/" + chainId + ".pid"; - if (fs.existsSync(lock_file_name)) { - fs.unlinkSync(lock_file_name); + try { + if (fs.existsSync(lock_file_name)) { + fs.unlinkSync(lock_file_name); + console.log('Lock file removed successfully'); + } + } catch (error) { + console.error('Error during cleanup:', error); } process.exit(0); })
29-32
: Consider improving delay precision.The current delay calculation adds a fixed 100 seconds buffer, which might be excessive. Consider:
- Making the buffer configurable
- Using a more precise timing mechanism
const currentTS = Math.floor(Date.now() / 1000); - const delayAmount = (epochPeriod - (currentTS % epochPeriod)) * 1000 + 100 * 1000; + const bufferSeconds = parseInt(process.env.EPOCH_BUFFER || "30"); + const delayAmount = (epochPeriod - (currentTS % epochPeriod)) * 1000 + bufferSeconds * 1000; console.log("waiting for the next epoch. . .", Math.floor(delayAmount / 1000), "seconds"); await delay(delayAmount);relayer-cli/src/utils/relay.ts (4)
Line range hint
13-29
: Add error handling for subgraph queries.While the function implementation is correct, consider adding error handling for the GraphQL request to handle potential network issues or API failures gracefully.
const getCount = async (veaOutbox: VeaOutboxArbToEth | VeaOutboxArbToGnosis, chainid: number): Promise<number> => { const subgraph = getInboxSubgraph(chainid); const stateRoot = await veaOutbox.stateRoot(); + try { const result = await request( `https://api.studio.thegraph.com/query/${subgraph}`, `{ snapshotSaveds(first: 1, where: { stateRoot: "${stateRoot}" }) { count } }` ); if (result["snapshotSaveds"].length == 0) return 0; return Number(result["snapshotSaveds"][0].count); + } catch (error) { + console.error(`Failed to fetch count from subgraph: ${error.message}`); + throw error; + } };🧰 Tools
🪛 eslint
[error] 13-13: Parsing error: Unexpected token :
Line range hint
31-40
: Add error handling for contract interactions.The relay function should handle potential contract interaction failures gracefully.
const relay = async (chainid: number, nonce: number) => { const routeParams = getBridgeConfig(chainid); const veaOutbox = getVeaOutbox(routeParams.veaOutbox, process.env.PRIVATE_KEY, routeParams.rpcOutbox, chainid); - const count = await getCount(veaOutbox, chainid); + try { + const count = await getCount(veaOutbox, chainid); - const proof = await getProofAtCount(chainid, nonce, count); - const [to, data] = await getMessageDataToRelay(chainid, nonce); + const proof = await getProofAtCount(chainid, nonce, count); + const [to, data] = await getMessageDataToRelay(chainid, nonce); - const txn = await veaOutbox.sendMessage(proof, nonce, to, data); - await txn.wait(); + const txn = await veaOutbox.sendMessage(proof, nonce, to, data); + await txn.wait(); + } catch (error) { + console.error(`Failed to relay message at nonce ${nonce}: ${error.message}`); + throw error; + } };
43-78
: Enhance batch processing robustness.While the new batching logic is an improvement, consider these enhancements:
- Add input validation for maxBatchSize
- Improve error message formatting
- Add gas estimation checks before batch execution
const relayBatch = async (chainid: number, nonce: number, maxBatchSize: number, _contract: any) => { + if (maxBatchSize <= 0 || maxBatchSize > 100) { + throw new Error('maxBatchSize must be between 1 and 100'); + } const routeParams = getBridgeConfig(chainid); const web3 = new Web3(routeParams.rpcOutbox); const batchedSend = _batchedSend(web3, routeParams.batcher, process.env.PRIVATE_KEY, 0); const contract = new web3.eth.Contract(_contract.abi, routeParams.veaOutbox); const veaOutbox = getVeaOutbox(routeParams.veaOutbox, process.env.PRIVATE_KEY, routeParams.rpcOutbox, chainid); const count = await getCount(veaOutbox, chainid); while (nonce < count) { let batchMessages = 0; let txns = []; while (batchMessages < maxBatchSize && nonce < count) { const isMsgRelayed = await veaOutbox.isMsgRelayed(nonce); if (isMsgRelayed) { nonce++; continue; } const proof = await getProofAtCount(chainid, nonce, count); const [to, data] = await getMessageDataToRelay(chainid, nonce); txns.push({ args: [proof, nonce, to, data], method: contract.methods.sendMessage, to: contract.options.address, }); batchMessages += 1; nonce++; } if (batchMessages > 0) { try { + // Estimate gas for the batch + const gasEstimate = await batchedSend.estimateGas(txns); + console.log(`Estimated gas for batch: ${gasEstimate}`); await batchedSend(txns); } catch (error) { - console.error(`Unable to execute messgae batch(${batchMessages} msgs) from nonce:${nonce} `, error); + console.error( + `Failed to execute message batch (size: ${batchMessages}, start nonce: ${nonce - batchMessages}): ${error.message}` + ); + throw error; } } } return nonce; };
Line range hint
81-115
: Add error handling and improve code organization.The function needs error handling for batch transactions and could benefit from better code organization.
const relayAllFrom = async (chainid: number, nonce: number, msgSender: string, _contract: any): Promise<number> => { const routeParams = getBridgeConfig(chainid); const web3 = new Web3(routeParams.rpcOutbox); - const batchedSend = _batchedSend( - web3, // Your web3 object. - // The address of the transaction batcher contract you wish to use. The addresses for the different networks are listed below. If the one you need is missing, feel free to deploy it yourself and make a PR to save the address here for others to use. - routeParams.batcher, - process.env.PRIVATE_KEY, // The private key of the account you want to send transactions from. - 0 // The debounce timeout period in milliseconds in which transactions are batched. - ); + const batchedSend = _batchedSend(web3, routeParams.batcher, process.env.PRIVATE_KEY, 0); const contract = new web3.eth.Contract(_contract.abi, routeParams.veaOutbox); const veaOutbox = getVeaOutbox(routeParams.veaOutbox, process.env.PRIVATE_KEY, routeParams.rpcOutbox, chainid); - const count = await getCount(veaOutbox, chainid); + try { + const count = await getCount(veaOutbox, chainid); + if (!count) return null; - if (!count) return null; + const nonces = await getNonceFrom(chainid, nonce, msgSender); + if (!nonces.length) { + console.log(`No messages found from sender ${msgSender} starting at nonce ${nonce}`); + return null; + } - let txns = []; + const txns = []; - const nonces = await getNonceFrom(chainid, nonce, msgSender); for (const x of nonces) { const proof = await getProofAtCount(chainid, x, count); const [to, data] = await getMessageDataToRelay(chainid, x); txns.push({ args: [proof, x, to, data], method: contract.methods.sendMessage, to: contract.options.address, }); } - await batchedSend(txns); + await batchedSend(txns); + return nonces[nonces.length - 1]; + } catch (error) { + console.error(`Failed to relay messages from ${msgSender}: ${error.message}`); + throw error; + } - return nonces[nonces.length - 1]; };Also, consider moving the batchedSend configuration details to the documentation.
relayer-cli/src/testnet/arbSepToSepRelayer.ts (3)
25-25
: Suppress linter error for constant condition in the while loopThe
while (true)
loop triggers a linting error: "Unexpected constant condition." Since the infinite loop is intentional, you can suppress the linter warning by adding an inline comment.Apply this diff to suppress the linter warning:
+ // eslint-disable-next-line no-constant-condition while (true) {
🧰 Tools
🪛 eslint
[error] 25-25: Unexpected constant condition.
(no-constant-condition)
16-18
: Use camelCase for variable namesIt's recommended to use camelCase for variable names in JavaScript/TypeScript. Rename
lock_file_name
tolockFileName
for consistency.Apply this diff:
- const lock_file_name = "./src/state/" + chainId + ".pid"; - if (fs.existsSync(lock_file_name)) { - fs.unlinkSync(lock_file_name); + const lockFileName = "./src/state/" + chainId + ".pid"; + if (fs.existsSync(lockFileName)) { + fs.unlinkSync(lockFileName);
6-6
: Use a descriptive variable name instead of_contract
Using a leading underscore in variable names is unconventional and may lead to confusion. Consider renaming
_contract
to a more descriptive name likeveaOutboxContract
.Apply this diff:
-const _contract = require("@kleros/vea-contracts/deployments/sepolia/VeaOutboxArbToEthTestnet.json"); +const veaOutboxContract = require("@kleros/vea-contracts/deployments/sepolia/VeaOutboxArbToEthTestnet.json");Ensure to update all references to
_contract
accordingly.relayer-cli/src/utils/relayerHelpers.ts (1)
6-9
: Consider handling stale lock files to improve robustnessThe current implementation checks for the existence of a lock file to prevent concurrent processes. However, if a previous process terminated unexpectedly without deleting the lock file, subsequent executions will fail unnecessarily. To improve robustness, consider verifying whether the process ID stored in the lock file corresponds to an active process before throwing an error. If the process is not running, the lock file can be safely removed.
relayer-cli/src/utils/ethers.ts (1)
20-27
: Consider refactoring repetitive contract connection functionsThe functions
getVeaInbox
,getVeaInboxProvider
,getVeaOutbox
, andgetVeaOutboxProvider
have similar structures and logic, differing mainly in contract factories and providers. Refactoring these into generic helper functions would reduce code duplication and enhance maintainability.Here is a suggested refactor:
// Generic function to connect to a Vea contract using provider URL function getVeaContract( contractFactories: { [key: number]: any }, address: string, privateKey: string, providerURL: string, chainId: number ) { const wallet = getWallet(privateKey, providerURL); const contractFactory = contractFactories[chainId]; if (!contractFactory) { throw new Error(`Unsupported chainId: ${chainId}`); } return contractFactory.connect(address, wallet); } // Generic function to connect to a Vea contract using JsonRpcProvider function getVeaContractWithProvider( contractFactories: { [key: number]: any }, address: string, privateKey: string, rpc: JsonRpcProvider, chainId: number ) { const wallet = getWalletRPC(privateKey, rpc); const contractFactory = contractFactories[chainId]; if (!contractFactory) { throw new Error(`Unsupported chainId: ${chainId}`); } return contractFactory.connect(address, wallet); }Then, replace the individual functions:
-function getVeaInbox(veaInboxAddress: string, privateKey: string, web3ProviderURL: string, chainId: number) { - if (chainId == 11155111) { - return VeaInboxArbToEth__factory.connect(veaInboxAddress, getWallet(privateKey, web3ProviderURL)); - } else if (chainId == 10200) { - return VeaInboxArbToGnosis__factory.connect(veaInboxAddress, getWallet(privateKey, web3ProviderURL)); - } else { - throw new Error(`Unsupported chainId: ${chainId}`); - } +function getVeaInbox(address: string, privateKey: string, web3ProviderURL: string, chainId: number) { + const contractFactories = { + 11155111: VeaInboxArbToEth__factory, + 10200: VeaInboxArbToGnosis__factory, + }; + return getVeaContract(contractFactories, address, privateKey, web3ProviderURL, chainId); } -function getVeaInboxProvider(veaInboxAddress: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) { - if (chainId == 11155111) { - return VeaInboxArbToEth__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc)); - } else if (chainId == 10200) { - return VeaInboxArbToGnosis__factory.connect(veaInboxAddress, getWalletRPC(privateKey, rpc)); - } +function getVeaInboxProvider(address: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) { + const contractFactories = { + 11155111: VeaInboxArbToEth__factory, + 10200: VeaInboxArbToGnosis__factory, + }; + return getVeaContractWithProvider(contractFactories, address, privateKey, rpc, chainId); } -function getVeaOutbox(veaInboxAddress: string, privateKey: string, web3ProviderURL: string, chainId: number) { - if (chainId == 11155111) { - return VeaOutboxArbToEth__factory.connect(veaInboxAddress, getWallet(privateKey, web3ProviderURL)); - } else if (chainId == 10200) { - return VeaOutboxArbToGnosis__factory.connect(veaInboxAddress, getWallet(privateKey, web3ProviderURL)); - } else { - throw new Error(`Unsupported chainId: ${chainId}`); - } +function getVeaOutbox(address: string, privateKey: string, web3ProviderURL: string, chainId: number) { + const contractFactories = { + 11155111: VeaOutboxArbToEth__factory, + 10200: VeaOutboxArbToGnosis__factory, + }; + return getVeaContract(contractFactories, address, privateKey, web3ProviderURL, chainId); } -function getVeaOutboxProvider(veaOutboxAddress: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) { - if (chainId == 11155111) { - return VeaOutboxArbToEth__factory.connect(veaOutboxAddress, getWalletRPC(privateKey, rpc)); - } else if (chainId == 10200) { - return VeaOutboxArbToGnosis__factory.connect(veaOutboxAddress, getWalletRPC(privateKey, rpc)); - } else { - throw new Error(`Unsupported chainId: ${chainId}`); - } +function getVeaOutboxProvider(address: string, privateKey: string, rpc: JsonRpcProvider, chainId: number) { + const contractFactories = { + 11155111: VeaOutboxArbToEth__factory, + 10200: VeaOutboxArbToGnosis__factory, + }; + return getVeaContractWithProvider(contractFactories, address, privateKey, rpc, chainId); }Also applies to: 30-35, 38-45, 48-55
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (5)
relayer-cli/src/testnet/arbSepToChiadoRelayer.ts
(1 hunks)relayer-cli/src/testnet/arbSepToSepRelayer.ts
(1 hunks)relayer-cli/src/utils/ethers.ts
(3 hunks)relayer-cli/src/utils/relay.ts
(4 hunks)relayer-cli/src/utils/relayerHelpers.ts
(1 hunks)
🧰 Additional context used
🪛 eslint
relayer-cli/src/testnet/arbSepToChiadoRelayer.ts
[error] 24-24: Unexpected constant condition.
(no-constant-condition)
relayer-cli/src/testnet/arbSepToSepRelayer.ts
[error] 25-25: Unexpected constant condition.
(no-constant-condition)
relayer-cli/src/utils/relay.ts
[error] 13-13: Parsing error: Unexpected token :
relayer-cli/src/utils/relayerHelpers.ts
[error] 3-3: Parsing error: Unexpected token :
🔇 Additional comments (1)
relayer-cli/src/utils/relay.ts (1)
2-4
: LGTM! Import changes align with multi-network support.
The changes to imports and type definitions appropriately support the generalization of the outbox functionality across different networks.
@@ -0,0 +1,51 @@ | |||
import * as fs from "fs"; | |||
|
|||
async function initialize(chain_id: number, network: string): Promise<number> { |
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.
Fix ESLint parsing error by configuring ESLint for TypeScript
The ESLint error indicates a parsing error at line 3, likely because ESLint is not properly configured to handle TypeScript syntax. To resolve this issue, ensure that ESLint is set up with the appropriate parser (@typescript-eslint/parser
) and plugins (@typescript-eslint/eslint-plugin
) for TypeScript files.
🧰 Tools
🪛 eslint
[error] 3-3: Parsing error: Unexpected token :
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: 4
🧹 Outside diff range and nitpick comments (5)
validator-cli/.env.dist (2)
3-6
: Consider adding backup RPC endpoints and documenting empty variables.While the RPC endpoints are correctly configured, consider:
- Adding fallback RPC endpoints to prevent single point of failure
- Documenting the expected format for
RPC_SEPOLIA
Example documentation to add:
# Devnet RPCs +# Format: https://rpc-endpoint-url +# For improved reliability, consider using multiple RPC endpoints separated by comma RPC_CHIADO=https://rpc.chiadochain.net RPC_ARB_SEPOLIA=https://sepolia-rollup.arbitrum.io/rpc RPC_SEPOLIA=
8-11
: Document the required RPC endpoints for production.The empty RPC variables need documentation to guide users on which networks they should point to.
Add documentation:
# Testnet or Mainnet RPCs +# RPC_ARB: Arbitrum One mainnet RPC endpoint +# RPC_ETH: Ethereum mainnet RPC endpoint RPC_ARB= RPC_ETH=validator-cli/src/utils/arbMsgExecutor.ts (2)
13-13
: Add JSDoc documentation for the exported function.Since this is an exported function, it should have proper documentation explaining its purpose, parameters, return value, and possible errors.
+/** + * Executes a child-to-parent message from Arbitrum to Ethereum + * @param trnxHash - The transaction hash containing the message to execute + * @param childRpc - The RPC URL for the Arbitrum network + * @param parentRpc - The RPC URL for the Ethereum network + * @returns Promise resolving to the executed transaction + * @throws Error if message execution fails or prerequisites are not met + */ async function messageExecutor(
1-87
: Consider architectural improvements for better maintainability.
- Consider extracting provider initialization into a reusable utility function to avoid duplication between
messageExecutor
andgetMessageStatus
.- Implement a consistent error handling strategy across both functions, preferably using custom error classes for better error categorization.
- Consider adding retry mechanisms for transient failures, especially for RPC calls.
Example implementation of a provider utility:
interface ProviderConfig { childRpc: string; parentRpc: string; privateKey: string; } interface NetworkProviders { childProvider: ArbitrumProvider; parentProvider: JsonRpcProvider; parentSigner: Signer; } function initializeProviders(config: ProviderConfig): NetworkProviders { const childJsonRpc = new JsonRpcProvider(config.childRpc); const childProvider = new ArbitrumProvider(childJsonRpc); const parentProvider = new JsonRpcProvider(config.parentRpc); const parentSigner = new Wallet(config.privateKey, parentProvider); return { childProvider, parentProvider, parentSigner }; }validator-cli/src/ArbToEth/watcherArbToEth.ts (1)
19-24
: Consider implementing monitoring and alerting system.The watcher script handles critical cross-chain message verification. While the code comments explain the core flow well, the system would benefit from:
- Structured logging with severity levels
- Metrics collection for:
- Number of claims processed
- Challenge success/failure rates
- Gas usage patterns
- Health check endpoints
- Alert triggers for:
- Failed message executions
- Gas price anomalies
- Network issues
Would you like assistance in implementing a monitoring solution?
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (4)
validator-cli/.env.dist
(1 hunks)validator-cli/package.json
(1 hunks)validator-cli/src/ArbToEth/watcherArbToEth.ts
(13 hunks)validator-cli/src/utils/arbMsgExecutor.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- validator-cli/package.json
🔇 Additional comments (6)
validator-cli/.env.dist (2)
Line range hint 1-24
: LGTM! Well-organized environment template.
The environment template is well-structured with clear sections for different networks and purposes. The new variables are properly integrated into the existing organization.
12-15
: Verify the contract addresses match the deployed contracts.
The contract addresses need to be verified against the deployment artifacts to ensure they match the actual deployed contracts.
✅ Verification successful
Based on the deployment artifacts, I can verify that the contract addresses match correctly:
- VeaInbox (arbitrumSepolia): 0xE12daFE59Bc3A996362d54b37DFd2BA9279cAd06
- VeaOutbox (sepolia): 0x209BFdC6B7c66b63A8382196Ba3d06619d0F12c9
The contracts are correctly linked to each other:
- VeaInbox constructor was called with VeaOutbox address
- VeaOutbox constructor was called with VeaInbox address
The addresses in the .env.dist file match the deployed contract addresses.
Contract addresses are correctly configured and match the deployment artifacts.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify contract addresses match deployment artifacts
# Search for contract addresses in deployment files
echo "Searching for VeaInbox contract address..."
rg -l "0xE12daFE59Bc3A996362d54b37DFd2BA9279cAd06" contracts/deployments/
echo "Searching for VeaOutbox contract address..."
rg -l "0x209BFdC6B7c66b63A8382196Ba3d06619d0F12c9" contracts/deployments/
Length of output: 593
Script:
#!/bin/bash
# Let's examine the actual content of these deployment files to verify the addresses
echo "Content of VeaOutboxArbToEthTestnet.json in sepolia:"
cat contracts/deployments/sepolia/VeaOutboxArbToEthTestnet.json
echo -e "\nContent of VeaInboxArbToEthTestnet.json in arbitrumSepolia:"
cat contracts/deployments/arbitrumSepolia/VeaInboxArbToEthTestnet.json
Length of output: 186109
validator-cli/src/utils/arbMsgExecutor.ts (2)
1-11
: LGTM! Imports are well-organized and necessary.
All imported modules are utilized effectively in the implementation.
87-87
: LGTM! Clean and clear exports.
The named exports are well-structured.
validator-cli/src/ArbToEth/watcherArbToEth.ts (2)
1-11
: LGTM: Import statements correctly updated for new Arbitrum SDK.
The changes align with the PR objective of updating to @arbitrum/sdk
v4.0.1, particularly the change from getL2Network
to getArbitrumNetwork
.
475-488
: Review gas fee calculation logic.
The gas fee calculation logic has potential issues:
- The
maxFeePerGasProfitable
calculation divides the deposit bygasEstimate.mul(6)
, which might result in very low gas fees during high network congestion. - The hardcoded priority fee of 6667 gwei might be too high or too low depending on network conditions.
Consider implementing a more dynamic gas fee calculation:
- Use an oracle or gas price feed
- Implement exponential backoff for retries with increasing gas prices
- Add configurable minimum/maximum gas price bounds
const messages = await messageReceipt.getChildToParentMessages(parentSigner); | ||
childToParentMessage = messages[0]; | ||
if (!childToParentMessage) { | ||
throw new Error("No child-to-parent messages found"); | ||
} |
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 array length check before accessing messages[0].
The code assumes there's at least one message without first checking the array length.
try {
const messages = await messageReceipt.getChildToParentMessages(parentSigner);
+ if (!messages || messages.length === 0) {
+ throw new Error("No child-to-parent messages found");
+ }
childToParentMessage = messages[0];
- if (!childToParentMessage) {
- throw new Error("No child-to-parent messages found");
- }
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const messages = await messageReceipt.getChildToParentMessages(parentSigner); | |
childToParentMessage = messages[0]; | |
if (!childToParentMessage) { | |
throw new Error("No child-to-parent messages found"); | |
} | |
const messages = await messageReceipt.getChildToParentMessages(parentSigner); | |
if (!messages || messages.length === 0) { | |
throw new Error("No child-to-parent messages found"); | |
} | |
childToParentMessage = messages[0]; |
async function getMessageStatus( | ||
trnxHash: string, | ||
childRpc: string, | ||
parentRpc: string | ||
): Promise<ChildToParentMessageStatus> { | ||
const PRIVATE_KEY = process.env.PRIVATE_KEY; | ||
const childJsonRpc = new JsonRpcProvider(childRpc); | ||
const childProvider = new ArbitrumProvider(childJsonRpc); | ||
const parentProvider = new JsonRpcProvider(parentRpc); | ||
|
||
let childReceipt: TransactionReceipt | null; | ||
try { | ||
childReceipt = await childProvider.getTransactionReceipt(trnxHash); | ||
} catch (error) { | ||
throw new Error(`Failed to get child transaction receipt: ${error.message}`); | ||
} | ||
if (!childReceipt) { | ||
throw new Error(`Transaction receipt not found for hash: ${trnxHash}`); | ||
} | ||
const messageReceipt = new ChildTransactionReceipt(childReceipt); | ||
const parentSigner: Signer = new Wallet(PRIVATE_KEY, parentProvider); | ||
const messages = await messageReceipt.getChildToParentMessages(parentSigner); | ||
const childToParentMessage = messages[0]; | ||
if (!childToParentMessage) { | ||
console.error("No child-to-parent messages found"); | ||
} | ||
try { | ||
const status = await childToParentMessage.status(childProvider); | ||
return status; | ||
} catch (error) { | ||
console.error(`Failed to get message status: ${error.message}`); | ||
return undefined; | ||
} | ||
} |
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.
Improve error handling consistency and type safety.
The function has several issues that need attention:
- Inconsistent error handling (mixing throws and console.error)
- Return type doesn't match implementation (can return undefined)
- Missing array length validation
Apply these improvements:
async function getMessageStatus(
trnxHash: string,
childRpc: string,
parentRpc: string
-): Promise<ChildToParentMessageStatus> {
+): Promise<ChildToParentMessageStatus | undefined> {
const PRIVATE_KEY = process.env.PRIVATE_KEY;
const childJsonRpc = new JsonRpcProvider(childRpc);
const childProvider = new ArbitrumProvider(childJsonRpc);
const parentProvider = new JsonRpcProvider(parentRpc);
let childReceipt: TransactionReceipt | null;
try {
childReceipt = await childProvider.getTransactionReceipt(trnxHash);
} catch (error) {
throw new Error(`Failed to get child transaction receipt: ${error.message}`);
}
if (!childReceipt) {
throw new Error(`Transaction receipt not found for hash: ${trnxHash}`);
}
const messageReceipt = new ChildTransactionReceipt(childReceipt);
const parentSigner: Signer = new Wallet(PRIVATE_KEY, parentProvider);
const messages = await messageReceipt.getChildToParentMessages(parentSigner);
+ if (!messages || messages.length === 0) {
+ throw new Error("No child-to-parent messages found");
+ }
const childToParentMessage = messages[0];
- if (!childToParentMessage) {
- console.error("No child-to-parent messages found");
- }
try {
const status = await childToParentMessage.status(childProvider);
return status;
} catch (error) {
- console.error(`Failed to get message status: ${error.message}`);
- return undefined;
+ throw new Error(`Failed to get message status: ${error.message}`);
}
}
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
async function getMessageStatus( | |
trnxHash: string, | |
childRpc: string, | |
parentRpc: string | |
): Promise<ChildToParentMessageStatus> { | |
const PRIVATE_KEY = process.env.PRIVATE_KEY; | |
const childJsonRpc = new JsonRpcProvider(childRpc); | |
const childProvider = new ArbitrumProvider(childJsonRpc); | |
const parentProvider = new JsonRpcProvider(parentRpc); | |
let childReceipt: TransactionReceipt | null; | |
try { | |
childReceipt = await childProvider.getTransactionReceipt(trnxHash); | |
} catch (error) { | |
throw new Error(`Failed to get child transaction receipt: ${error.message}`); | |
} | |
if (!childReceipt) { | |
throw new Error(`Transaction receipt not found for hash: ${trnxHash}`); | |
} | |
const messageReceipt = new ChildTransactionReceipt(childReceipt); | |
const parentSigner: Signer = new Wallet(PRIVATE_KEY, parentProvider); | |
const messages = await messageReceipt.getChildToParentMessages(parentSigner); | |
const childToParentMessage = messages[0]; | |
if (!childToParentMessage) { | |
console.error("No child-to-parent messages found"); | |
} | |
try { | |
const status = await childToParentMessage.status(childProvider); | |
return status; | |
} catch (error) { | |
console.error(`Failed to get message status: ${error.message}`); | |
return undefined; | |
} | |
} | |
async function getMessageStatus( | |
trnxHash: string, | |
childRpc: string, | |
parentRpc: string | |
): Promise<ChildToParentMessageStatus | undefined> { | |
const PRIVATE_KEY = process.env.PRIVATE_KEY; | |
const childJsonRpc = new JsonRpcProvider(childRpc); | |
const childProvider = new ArbitrumProvider(childJsonRpc); | |
const parentProvider = new JsonRpcProvider(parentRpc); | |
let childReceipt: TransactionReceipt | null; | |
try { | |
childReceipt = await childProvider.getTransactionReceipt(trnxHash); | |
} catch (error) { | |
throw new Error(`Failed to get child transaction receipt: ${error.message}`); | |
} | |
if (!childReceipt) { | |
throw new Error(`Transaction receipt not found for hash: ${trnxHash}`); | |
} | |
const messageReceipt = new ChildTransactionReceipt(childReceipt); | |
const parentSigner: Signer = new Wallet(PRIVATE_KEY, parentProvider); | |
const messages = await messageReceipt.getChildToParentMessages(parentSigner); | |
if (!messages || messages.length === 0) { | |
throw new Error("No child-to-parent messages found"); | |
} | |
const childToParentMessage = messages[0]; | |
try { | |
const status = await childToParentMessage.status(childProvider); | |
return status; | |
} catch (error) { | |
throw new Error(`Failed to get message status: ${error.message}`); | |
} | |
} |
} catch (error) { | ||
console.error("Error sending snapshot for epoch " + veaEpochOutboxCheck + " with error " + error); | ||
} | ||
} else { |
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
Enhance error handling for critical operations.
The current error handling only logs errors without proper error classification or recovery strategies.
Consider implementing:
- } catch (error) {
- console.error("Error sending snapshot for epoch " + veaEpochOutboxCheck + " with error " + error);
+ } catch (error) {
+ if (error.code === 'NETWORK_ERROR') {
+ console.error(`Network error while sending snapshot for epoch ${veaEpochOutboxCheck}. Retrying...`);
+ // Implement retry logic
+ } else if (error.code === 'INSUFFICIENT_FUNDS') {
+ console.error(`Insufficient funds for snapshot at epoch ${veaEpochOutboxCheck}`);
+ process.exit(1); // Critical error, exit
+ } else {
+ console.error(`Unknown error sending snapshot for epoch ${veaEpochOutboxCheck}:`, error);
+ // Log to monitoring service
+ }
Also applies to: 510-512
const findLatestL2BatchAndBlock = async ( | ||
nodeInterface: NodeInterface, | ||
fromArbBlock: number, | ||
latestBlockNumber: number | ||
): Promise<[number, number]> => { | ||
let low = fromArbBlock; | ||
let high = latestBlockNumber; | ||
|
||
while (low <= high) { | ||
const mid = Math.floor((low + high) / 2); | ||
try { | ||
(await nodeInterface.functions.findBatchContainingBlock(mid, { blockTag: "latest" })) as any; | ||
low = mid + 1; | ||
} catch (e) { | ||
high = mid - 1; | ||
} | ||
} | ||
if (high < low) return [undefined, undefined]; | ||
// high is now the latest L2 block number that has a corresponding batch on L1 | ||
const result = (await nodeInterface.functions.findBatchContainingBlock(high, { blockTag: "latest" })) as any; | ||
return [result.batch.toNumber(), high]; | ||
}; |
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.
Validate binary search edge cases in findLatestL2BatchAndBlock.
The binary search implementation has potential issues:
- Line 736: Returns
[undefined, undefined]
which doesn't match the return typePromise<[number, number]>
- No validation for
fromArbBlock
being less thanlatestBlockNumber
Apply this fix:
const findLatestL2BatchAndBlock = async (
nodeInterface: NodeInterface,
fromArbBlock: number,
latestBlockNumber: number
): Promise<[number, number]> => {
+ if (fromArbBlock > latestBlockNumber) {
+ throw new Error('fromArbBlock must be less than latestBlockNumber');
+ }
let low = fromArbBlock;
let high = latestBlockNumber;
while (low <= high) {
const mid = Math.floor((low + high) / 2);
try {
(await nodeInterface.functions.findBatchContainingBlock(mid, { blockTag: "latest" })) as any;
low = mid + 1;
} catch (e) {
high = mid - 1;
}
}
- if (high < low) return [undefined, undefined];
+ if (high < low) return [-1, -1]; // Return sentinel values instead of undefined
const result = (await nodeInterface.functions.findBatchContainingBlock(high, { blockTag: "latest" })) as any;
return [result.batch.toNumber(), high];
};
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
const findLatestL2BatchAndBlock = async ( | |
nodeInterface: NodeInterface, | |
fromArbBlock: number, | |
latestBlockNumber: number | |
): Promise<[number, number]> => { | |
let low = fromArbBlock; | |
let high = latestBlockNumber; | |
while (low <= high) { | |
const mid = Math.floor((low + high) / 2); | |
try { | |
(await nodeInterface.functions.findBatchContainingBlock(mid, { blockTag: "latest" })) as any; | |
low = mid + 1; | |
} catch (e) { | |
high = mid - 1; | |
} | |
} | |
if (high < low) return [undefined, undefined]; | |
// high is now the latest L2 block number that has a corresponding batch on L1 | |
const result = (await nodeInterface.functions.findBatchContainingBlock(high, { blockTag: "latest" })) as any; | |
return [result.batch.toNumber(), high]; | |
}; | |
const findLatestL2BatchAndBlock = async ( | |
nodeInterface: NodeInterface, | |
fromArbBlock: number, | |
latestBlockNumber: number | |
): Promise<[number, number]> => { | |
if (fromArbBlock > latestBlockNumber) { | |
throw new Error('fromArbBlock must be less than latestBlockNumber'); | |
} | |
let low = fromArbBlock; | |
let high = latestBlockNumber; | |
while (low <= high) { | |
const mid = Math.floor((low + high) / 2); | |
try { | |
(await nodeInterface.functions.findBatchContainingBlock(mid, { blockTag: "latest" })) as any; | |
low = mid + 1; | |
} catch (e) { | |
high = mid - 1; | |
} | |
} | |
if (high < low) return [-1, -1]; // Return sentinel values instead of undefined | |
const result = (await nodeInterface.functions.findBatchContainingBlock(high, { blockTag: "latest" })) as any; | |
return [result.batch.toNumber(), high]; | |
}; |
@coderabbitai summary |
✅ Actions performedSummary regeneration triggered. |
PR-Codex overview
This PR primarily focuses on adding new functionality for relaying messages between different blockchain networks, specifically between Arbitrum and Ethereum, while enhancing existing scripts and configurations for better integration and testing.
Detailed summary
start-testnet-sepolia
script inrelayer-cli/package.json
.@arbitrum/sdk
version invalidator-cli/package.json
.validator-cli/.env.dist
.arbSepToSepRelayer.ts
for relaying messages on Sepolia.arbSepToChiadoRelayer.ts
for relaying messages to Chiado.relayerHelpers.ts
withinitialize
andupdateStateFile
functions.relay.ts
to support bothVeaOutboxArbToEth
andVeaOutboxArbToGnosis
.ethers.ts
to handle multiple inbox/outbox connections based onchainId
.contracts/test/integration/ArbToEth.ts
.watcherArbToEth.ts
.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.