Skip to content

Conversation

@smypmsa
Copy link
Member

@smypmsa smypmsa commented Jun 12, 2025

This update adds a False flag to the newHeads subscription parameters to exclude transaction details and reduce payload size. Since not all EVM providers support this flag, the code includes fallback logic that retries the subscription without the flag if the initial attempt fails.

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of WebSocket event subscriptions for Ethereum block updates, reducing the likelihood of missed connections.

@vercel
Copy link

vercel bot commented Jun 12, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
chainstack-rpc-dashboard-germany ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 12, 2025 1:56pm
chainstack-rpc-dashboard-singapore ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 12, 2025 1:56pm
chainstack-rpc-dashboard-us-west ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 12, 2025 1:56pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 12, 2025

Walkthrough

The subscribe method in the WSBlockLatencyMetric class was updated to attempt subscribing to the "newHeads" event via WebSocket with an initial parameter set. If this attempt fails, it logs a warning and retries with alternative parameters before raising an error if both attempts fail.

Changes

File(s) Change Summary
metrics/ethereum.py Enhanced the subscribe method to retry with different parameters if the initial subscription fails.

Poem

A rabbit hops with code so neat,
When "newHeads" stumble, it won’t retreat.
First with a flag, then without,
It tries again, without a doubt.
Robust subscriptions, no need to fear—
The blockchain’s whispers, crisp and clear! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b161de4 and 53a41e1.

📒 Files selected for processing (1)
  • metrics/ethereum.py (1 hunks)

Comment on lines +182 to +191
# First attempt: with False flag, not all providers support this
subscription_msg: str = json.dumps(
{
"id": 1,
"jsonrpc": "2.0",
"method": "eth_subscribe",
"params": ["newHeads"],
"params": ["newHeads", False],
}
)

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using the official includeTransactions object form instead of a bare False flag

Geth & Erigon accept the form ["newHeads", {"includeTransactions": false}].
Some providers silently ignore an unrecognised second positional argument, which means you may think you reduced payload while in fact you did not.

-"params": ["newHeads", False],
+"params": ["newHeads", {"includeTransactions": False}],

This keeps the call explicit, self-documenting, and maximises provider compatibility.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# First attempt: with False flag, not all providers support this
subscription_msg: str = json.dumps(
{
"id": 1,
"jsonrpc": "2.0",
"method": "eth_subscribe",
"params": ["newHeads"],
"params": ["newHeads", False],
}
)
# First attempt: with False flag, not all providers support this
subscription_msg: str = json.dumps(
{
"id": 1,
"jsonrpc": "2.0",
"method": "eth_subscribe",
- "params": ["newHeads", False],
+ "params": ["newHeads", {"includeTransactions": False}],
}
)
🤖 Prompt for AI Agents
In metrics/ethereum.py around lines 182 to 191, replace the second parameter in
the "params" list from the bare False flag to the explicit object
{"includeTransactions": false}. This means changing the "params" entry from
["newHeads", False] to ["newHeads", {"includeTransactions": false}] to ensure
compatibility with providers like Geth and Erigon and to make the call explicit
and self-documenting.

Comment on lines +196 to 225
# If subscription failed, try without the False flag
if subscription_data.get("result") is None:
raise ValueError("Subscription to newHeads failed")
self.subscription_id = subscription_data["result"]
logging.warning(
"Subscription with False flag failed, retrying without flag"
)

fallback_subscription_msg: str = json.dumps(
{
"id": 1,
"jsonrpc": "2.0",
"method": "eth_subscribe",
"params": ["newHeads"],
}
)

await self.send_with_timeout(
websocket, fallback_subscription_msg, WS_DEFAULT_TIMEOUT
)
fallback_response: str = await self.recv_with_timeout(
websocket, WS_DEFAULT_TIMEOUT
)
fallback_subscription_data = json.loads(fallback_response)

if fallback_subscription_data.get("result") is None:
raise ValueError("Subscription to newHeads failed even without flag")

self.subscription_id = fallback_subscription_data["result"]
else:
self.subscription_id = subscription_data["result"]

Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Two follow-ups for the fallback logic

  1. Re-using the same id (1) for the second request can confuse JSON-RPC multiplexers.
    Safer to increment it:
-    "id": 1,
+    "id": 2,
  1. The current check only looks at result is None.
    Providers usually reply with an "error" field on failure; when that happens you’ll silently continue thinking the subscription succeeded (because result may be an empty string or omitted).
    Guard against this:
-if subscription_data.get("result") is None:
+if (subscription_data.get("result") is None) or ("error" in subscription_data):

Same for the fallback response.

Addressing both points prevents false-positives and avoids “dangling” subscriptions.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# If subscription failed, try without the False flag
if subscription_data.get("result") is None:
raise ValueError("Subscription to newHeads failed")
self.subscription_id = subscription_data["result"]
logging.warning(
"Subscription with False flag failed, retrying without flag"
)
fallback_subscription_msg: str = json.dumps(
{
"id": 1,
"jsonrpc": "2.0",
"method": "eth_subscribe",
"params": ["newHeads"],
}
)
await self.send_with_timeout(
websocket, fallback_subscription_msg, WS_DEFAULT_TIMEOUT
)
fallback_response: str = await self.recv_with_timeout(
websocket, WS_DEFAULT_TIMEOUT
)
fallback_subscription_data = json.loads(fallback_response)
if fallback_subscription_data.get("result") is None:
raise ValueError("Subscription to newHeads failed even without flag")
self.subscription_id = fallback_subscription_data["result"]
else:
self.subscription_id = subscription_data["result"]
# If subscription failed, try without the False flag
if (subscription_data.get("result") is None) or ("error" in subscription_data):
logging.warning(
"Subscription with False flag failed, retrying without flag"
)
fallback_subscription_msg: str = json.dumps(
{
"id": 2,
"jsonrpc": "2.0",
"method": "eth_subscribe",
"params": ["newHeads"],
}
)
await self.send_with_timeout(
websocket, fallback_subscription_msg, WS_DEFAULT_TIMEOUT
)
fallback_response: str = await self.recv_with_timeout(
websocket, WS_DEFAULT_TIMEOUT
)
fallback_subscription_data = json.loads(fallback_response)
if (fallback_subscription_data.get("result") is None) or ("error" in fallback_subscription_data):
raise ValueError("Subscription to newHeads failed even without flag")
self.subscription_id = fallback_subscription_data["result"]
else:
self.subscription_id = subscription_data["result"]
🤖 Prompt for AI Agents
In metrics/ethereum.py between lines 196 and 225, the fallback subscription
logic reuses the same JSON-RPC request id (1), which can cause confusion with
multiplexers; increment the id for the fallback request to a unique value. Also,
improve the failure check by verifying if the response contains an "error" field
in addition to checking if "result" is None, for both the initial and fallback
subscription responses, and raise an error if an "error" is present to avoid
false success assumptions.

@smypmsa
Copy link
Member Author

smypmsa commented Jun 12, 2025

Alchemy doesn't support this flag at all (ignoring it silently) and doesn't provide a parameter for disabling a transaction array (which is disabled by other providers by default). I will contact their support.

@smypmsa
Copy link
Member Author

smypmsa commented Jun 14, 2025

Alchemy fixed their message structure. Cancelling this PR since there is no need in it.

@smypmsa smypmsa closed this Jun 14, 2025
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.

2 participants