Skip to content

Allow CHAIN_ID env var to override default chain selection#55

Open
koko1123 wants to merge 2 commits into
mainfrom
koko/arbitrum-chain-id
Open

Allow CHAIN_ID env var to override default chain selection#55
koko1123 wants to merge 2 commits into
mainfrom
koko/arbitrum-chain-id

Conversation

@koko1123

@koko1123 koko1123 commented Mar 27, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Adds optional CHAIN_ID env var that overrides the hardcoded ENV -> chain_id mapping
  • Enables deploying the beaconator to non-Base chains (e.g. Arbitrum Sepolia 421614) while keeping ENV=testnet
  • Fully backward-compatible: existing deployments without CHAIN_ID behave identically

Context

We're deploying beacons to Arbitrum Sepolia as Phase 1 of the Base -> Arbitrum migration. The Arbitrum beaconator instance will set CHAIN_ID=421614 alongside ENV=testnet.

Test plan

  • make fmt-check passes
  • make lint passes
  • make test-fast passes (183 unit + 7 integration)
  • Deploy the-beaconator-arb on Railway with CHAIN_ID=421614 and verify health

Summary by CodeRabbit

  • New Features

    • Chain ID can now be overridden via a CHAIN_ID environment variable, allowing explicit network selection instead of relying solely on default mappings.
  • Chores

    • CI container health-check behavior improved: more robust failure logging and explicit container removal on success or failure.

Enables deploying the beaconator to non-Base chains (e.g. Arbitrum
Sepolia 421614) by setting CHAIN_ID explicitly, while keeping the
existing ENV-based mapping as fallback for backward compatibility.
@coderabbitai

coderabbitai Bot commented Mar 27, 2026

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7ff24569-dc77-4bf8-b3ac-7641925296dd

📥 Commits

Reviewing files that changed from the base of the PR and between 8534eae and 569b883.

📒 Files selected for processing (1)
  • .github/workflows/ci.yml

📝 Walkthrough

Walkthrough

create_rocket now prefers a numeric CHAIN_ID environment variable (parsed as u64) and falls back to the prior rpc_config.env_type→chain ID mapping when absent or invalid. The CI workflow test step no longer uses --rm and changes container health-check teardown to explicit log/docker rm -f handling.

Changes

Cohort / File(s) Summary
Environment Variable Override
src/lib.rs
Added CHAIN_ID env var lookup in create_rocket to override chain ID when parseable as u64; otherwise keep existing rpc_config.env_type→chain ID mapping.
CI container health-check
.github/workflows/ci.yml
Removed --rm from test container run; replaced inline curl failure handler with explicit conditional that prints logs and force-removes the container (docker rm -f) on failure or success.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped through code, found a chain to guide,
A CHAIN_ID carrot, parsed with pride,
If it’s shy, the old map still leads the way,
CI watches logs, then clears the tray,
Hooray — the rabbit fixed the day! 🎋

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main change: introducing a CHAIN_ID environment variable override for chain selection in the create_rocket function.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch koko/arbitrum-chain-id

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/lib.rs`:
- Around line 177-193: The current CHAIN_ID handling silently ignores parse
errors because of .ok().and_then(...).unwrap_or_else, which can cause accidental
wrong-chain deployments; change this to fail fast when CHAIN_ID is set but
unparseable: explicitly check env::var("CHAIN_ID") and if it returns Ok(s)
attempt s.parse::<u64>() and panic (or return an error) with a clear message if
parse fails, otherwise use the parsed value; only fall back to the ENV-based
mapping (using env_type) when env::var returns Err (i.e., CHAIN_ID not set).
Ensure the code paths reference the existing symbols chain_id and env_type so
callers remain unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 69ac0aad-016b-4c2f-940a-b3ee5e2463b5

📥 Commits

Reviewing files that changed from the base of the PR and between a7a6d25 and 8534eae.

📒 Files selected for processing (1)
  • src/lib.rs

Comment thread src/lib.rs
Comment on lines 177 to +193
// Get environment configuration and chain ID
// CHAIN_ID env var overrides the default ENV-based mapping, enabling
// deployment to chains like Arbitrum Sepolia (421614) while keeping ENV=testnet.
let env_type = &rpc_config.env_type;
let chain_id = match env_type.to_lowercase().as_str() {
"testnet" => 84532u64, // Base Sepolia testnet
"mainnet" => 8453u64, // Base mainnet
"localnet" => 84532u64, // Use testnet chain ID for local development/CI
_ => panic!(
"Invalid ENV value '{env_type}'. Must be either 'mainnet', 'testnet', or 'localnet'"
),
};
let chain_id = env::var("CHAIN_ID")
.ok()
.and_then(|s| s.parse::<u64>().ok())
.unwrap_or_else(|| {
match env_type.to_lowercase().as_str() {
"testnet" => 84532u64, // Base Sepolia testnet
"mainnet" => 8453u64, // Base mainnet
"localnet" => 84532u64, // Use testnet chain ID for local development/CI
_ => panic!(
"Invalid ENV value '{env_type}'. Must be either 'mainnet', 'testnet', or 'localnet'"
),
}
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Silent fallback on invalid CHAIN_ID could lead to wrong-chain deployment.

If a user sets CHAIN_ID=arbitrum (string instead of number) or CHAIN_ID= (empty), the .parse::<u64>().ok() silently discards the error and falls back to the ENV-based default. This could result in deploying to Base when Arbitrum was intended, with no warning.

Consider either:

  1. Fail fast if CHAIN_ID is set but unparseable (safer), or
  2. Log a warning when CHAIN_ID is present but invalid (backward-compatible)
Option 1: Fail fast (recommended for safety-critical config)
     // CHAIN_ID env var overrides the default ENV-based mapping, enabling
     // deployment to chains like Arbitrum Sepolia (421614) while keeping ENV=testnet.
     let env_type = &rpc_config.env_type;
-    let chain_id = env::var("CHAIN_ID")
-        .ok()
-        .and_then(|s| s.parse::<u64>().ok())
-        .unwrap_or_else(|| {
-            match env_type.to_lowercase().as_str() {
-                "testnet" => 84532u64,  // Base Sepolia testnet
-                "mainnet" => 8453u64,   // Base mainnet
-                "localnet" => 84532u64, // Use testnet chain ID for local development/CI
-                _ => panic!(
-                    "Invalid ENV value '{env_type}'. Must be either 'mainnet', 'testnet', or 'localnet'"
-                ),
-            }
-        });
+    let chain_id = match env::var("CHAIN_ID") {
+        Ok(s) if !s.is_empty() => {
+            let id = s.parse::<u64>().unwrap_or_else(|e| {
+                panic!("Invalid CHAIN_ID '{s}': must be a valid u64 chain ID ({e})")
+            });
+            tracing::info!("Using CHAIN_ID override: {id}");
+            id
+        }
+        _ => {
+            let id = match env_type.to_lowercase().as_str() {
+                "testnet" => 84532u64,  // Base Sepolia testnet
+                "mainnet" => 8453u64,   // Base mainnet
+                "localnet" => 84532u64, // Use testnet chain ID for local development/CI
+                _ => panic!(
+                    "Invalid ENV value '{env_type}'. Must be either 'mainnet', 'testnet', or 'localnet'"
+                ),
+            };
+            tracing::info!("Using ENV-based chain ID: {id} (env_type={env_type})");
+            id
+        }
+    };
Option 2: Warn but continue (backward-compatible)
     let env_type = &rpc_config.env_type;
-    let chain_id = env::var("CHAIN_ID")
-        .ok()
-        .and_then(|s| s.parse::<u64>().ok())
+    let chain_id = env::var("CHAIN_ID")
+        .ok()
+        .and_then(|s| {
+            if s.is_empty() {
+                return None;
+            }
+            match s.parse::<u64>() {
+                Ok(id) => {
+                    tracing::info!("Using CHAIN_ID override: {id}");
+                    Some(id)
+                }
+                Err(e) => {
+                    tracing::warn!(
+                        "CHAIN_ID '{s}' is not a valid u64 ({e}), falling back to ENV-based default"
+                    );
+                    None
+                }
+            }
+        })
         .unwrap_or_else(|| {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib.rs` around lines 177 - 193, The current CHAIN_ID handling silently
ignores parse errors because of .ok().and_then(...).unwrap_or_else, which can
cause accidental wrong-chain deployments; change this to fail fast when CHAIN_ID
is set but unparseable: explicitly check env::var("CHAIN_ID") and if it returns
Ok(s) attempt s.parse::<u64>() and panic (or return an error) with a clear
message if parse fails, otherwise use the parsed value; only fall back to the
ENV-based mapping (using env_type) when env::var returns Err (i.e., CHAIN_ID not
set). Ensure the code paths reference the existing symbols chain_id and env_type
so callers remain unchanged.

Remove --rm flag so container logs are available when the health
check fails, making it possible to diagnose startup crashes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant