Skip to content

feat(api): add pending transaction support in the eth subscription API#6941

Open
akaladarshi wants to merge 6 commits into
mainfrom
akaladarshi/add-pending-tx-eth-subscribe
Open

feat(api): add pending transaction support in the eth subscription API#6941
akaladarshi wants to merge 6 commits into
mainfrom
akaladarshi/add-pending-tx-eth-subscribe

Conversation

@akaladarshi
Copy link
Copy Markdown
Collaborator

@akaladarshi akaladarshi commented Apr 20, 2026

Summary of changes

Changes introduced in this pull request:

  • Adds support for the pending transaction API
  • Refactor the existing subscription API's to use stream instead of creating extra channel to sending data to the sink

Reference issue to close (if applicable)

Closes #6031

Other information and links

Change checklist

  • I have performed a self-review of my own code,
  • I have made corresponding changes to the documentation. All new code adheres to the team's documentation standards,
  • I have added tests that prove my fix is effective or that my feature works (if possible),
  • I have made sure the CHANGELOG is up-to-date. All user-facing changes should be reflected in this document.

Outside contributions

  • I have read and agree to the CONTRIBUTING document.
  • I have read and agree to the AI Policy document. I understand that failure to comply with the guidelines will lead to rejection of the pull request.

Summary by CodeRabbit

  • New Features

    • Added Ethereum pubsub support for pendingTransactions, logs, and newHeads (live subscription notifications).
  • Refactor

    • Reworked subscription/stream routing and forwarding for more reliable JSON‑RPC subscriptions and added a reusable broadcast-to-stream utility.
  • Bug Fixes

    • Adjusted logs subscription to emit a single log object per notification.
  • Tests

    • Added integration tests covering eth_subscribe scenarios and broadcast stream behavior.
  • Documentation

    • Updated CHANGELOG to document pendingTransactions support and logs behavior change.

Review Change Stack

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 20, 2026

Walkthrough

Refactors eth_subscribe to stream-based handlers (newHeads/logs/pendingTransactions), adds a broadcast->Stream adapter and tests, exposes an eth tx-hash helper, removes obsolete chain helpers, narrows dead-code allows, and adds end-to-end eth_subscribe tests plus changelog updates.

Changes

ETH Pubsub Stream-based Refactoring

Layer / File(s) Summary
Broadcast stream infrastructure
src/utils/broadcast/mod.rs, src/utils/broadcast/tests.rs
New subscription_stream utility wraps Tokio broadcast receivers into pinned async streams, drops/logs lagged events, and includes tests validating termination and lag handling.
ETH helper function visibility
src/rpc/methods/eth.rs
eth_tx_hash_from_signed_message is promoted from private to pub(crate) for use by the pendingTransactions subscription flow.
ETH pubsub stream-based subscription handlers
src/rpc/methods/eth/pubsub.rs
EthPubSub::subscribe now dispatches to spawn_new_heads, spawn_logs, and spawn_pending_transactions; adds pipe_stream_to_sink to serialize and forward items to the JSON-RPC subscription sink.
Chain RPC helper cleanup
src/rpc/methods/chain.rs
Removes new_heads and logs helper functions and their JoinHandle/imports as they are replaced by the pubsub stream handlers.
Dead code suppression refinement
src/message_pool/msgpool/events.rs, src/message_pool/msgpool/msg_pool.rs, src/message_pool/msgpool/pending_store.rs
Relocates #[allow(dead_code)] from enum/method-level to only the specific Remove variant and removes redundant allow attributes from subscribe/subscribe_to_updates.
eth_subscribe tests and tooling
src/tool/subcommands/api_cmd/stateful_tests.rs
Adds WebSocket EthSubStream helper, subscription lifecycle helpers, and three eth_subscribe integration tests: newHeads, pendingTransactions, and logs; registers them in create_tests.
Changelog update
CHANGELOG.md
Documents that eth_subscribe now supports pendingTransactions and that logs emits one log object per notification.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant EthPubSub
  participant spawn_newHeads
  participant spawn_logs
  participant spawn_pendingTransactions
  participant pipe_stream_to_sink
  participant SubscriptionSink
  Client->>EthPubSub: eth_subscribe request
  EthPubSub->>spawn_newHeads: spawn stream for newHeads
  EthPubSub->>spawn_logs: spawn stream for logs
  EthPubSub->>spawn_pendingTransactions: spawn stream for pendingTransactions
  spawn_newHeads->>pipe_stream_to_sink: EthBlock items
  spawn_logs->>pipe_stream_to_sink: filtered log items
  spawn_pendingTransactions->>pipe_stream_to_sink: tx-hash items
  pipe_stream_to_sink->>SubscriptionSink: send SubscriptionMessage
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • ChainSafe/forest#5749: Introduced chain::new_heads/chain::logs helpers that this PR removes and replaces with stream-based handlers.
  • ChainSafe/forest#6965: Prior movement of MpoolUpdate and related subscription changes that this PR further refines.
  • ChainSafe/forest#6402: Related changes to newHeads output formatting (EthBlock conversion) connected to the newHeads pipeline refactor.

Suggested reviewers

  • LesnyRumcajs
  • sudo-shashank
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the primary change: adding pending transaction support to the eth subscription API, which is the main focus of this pull request.
Linked Issues check ✅ Passed The PR successfully implements both completion criteria from issue #6031: pending transaction subscription support is added via the new pubsub refactoring, and integration tests are included in the stateful tests.
Out of Scope Changes check ✅ Passed All changes are scoped to implementing pending transaction support and refactoring the subscription infrastructure. Cleanup of unused attributes and dead code is directly related to the refactoring effort.
Docstring Coverage ✅ Passed Docstring coverage is 84.62% 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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch akaladarshi/add-pending-tx-eth-subscribe
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch akaladarshi/add-pending-tx-eth-subscribe

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

@akaladarshi akaladarshi force-pushed the akaladarshi/add-pending-tx-eth-subscribe branch from c221f29 to f4b122e Compare April 23, 2026 08:01
@akaladarshi akaladarshi added the RPC requires calibnet RPC checks to run on CI label Apr 23, 2026
@akaladarshi akaladarshi force-pushed the akaladarshi/add-pending-tx-eth-subscribe branch from f4b122e to 6f51115 Compare May 20, 2026 08:17
@akaladarshi akaladarshi marked this pull request as ready for review May 21, 2026 09:57
@akaladarshi akaladarshi requested a review from a team as a code owner May 21, 2026 09:57
@akaladarshi akaladarshi requested review from hanabi1224 and sudo-shashank and removed request for a team May 21, 2026 09:57
Copy link
Copy Markdown
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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/rpc/methods/eth/pubsub.rs`:
- Around line 126-128: The stream currently iterates only changes.applies so
reverted tipsets are ignored; update the flat_map over
subscription_stream(head_rx) to emit both applies and reverts (e.g., pair each
tipset with a boolean or enum indicating is_revert) instead of only
changes.applies, then adjust the subsequent filter_map closure that binds ts to
accept that (tipset, is_revert) and produce log removal events for reverts and
normal events for applies; target the subscription_stream/head_rx pipeline and
the closure capturing ts in pubsub.rs so reorg-driven log removals are emitted.
🪄 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 023ea685-f51d-4356-8476-c6eea9c54e3d

📥 Commits

Reviewing files that changed from the base of the PR and between dba0196 and 6f51115.

📒 Files selected for processing (7)
  • src/message_pool/msgpool/events.rs
  • src/message_pool/msgpool/msg_pool.rs
  • src/rpc/methods/chain.rs
  • src/rpc/methods/eth.rs
  • src/rpc/methods/eth/pubsub.rs
  • src/utils/broadcast/mod.rs
  • src/utils/broadcast/tests.rs
💤 Files with no reviewable changes (2)
  • src/message_pool/msgpool/msg_pool.rs
  • src/rpc/methods/chain.rs

Comment thread src/rpc/methods/eth/pubsub.rs Outdated
@codecov
Copy link
Copy Markdown

codecov Bot commented May 21, 2026

Codecov Report

❌ Patch coverage is 14.81481% with 69 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.39%. Comparing base (df636b3) to head (c76e413).
⚠️ Report is 1 commits behind head on main.
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/rpc/methods/eth/pubsub.rs 0.00% 69 Missing ⚠️
Additional details and impacted files
Files with missing lines Coverage Δ
src/message_pool/msgpool/msg_pool.rs 87.75% <ø> (-0.16%) ⬇️
src/message_pool/msgpool/pending_store.rs 97.08% <ø> (ø)
src/rpc/methods/chain.rs 57.93% <ø> (+2.28%) ⬆️
src/rpc/methods/eth.rs 65.40% <100.00%> (ø)
src/utils/broadcast/mod.rs 100.00% <100.00%> (ø)
src/rpc/methods/eth/pubsub.rs 0.00% <0.00%> (ø)

... and 7 files with indirect coverage changes


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update df636b3...c76e413. Read the comment docs.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@akaladarshi akaladarshi marked this pull request as draft May 21, 2026 18:06
@akaladarshi akaladarshi force-pushed the akaladarshi/add-pending-tx-eth-subscribe branch from 6f51115 to 709de17 Compare May 22, 2026 10:16
@akaladarshi akaladarshi marked this pull request as ready for review May 22, 2026 10:17
Copy link
Copy Markdown
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: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/tool/subcommands/api_cmd/stateful_tests.rs`:
- Around line 529-551: The current loops call next_subscription_payload(&mut
ws_stream, &subscription_id, Duration::from_secs(...)).await with a
per-notification timeout which resets on every unrelated event; change to use a
total deadline by recording let deadline = Instant::now() + TOTAL_DURATION (e.g.
120s for pending tx loop, 300s for logs loop) before the loop, then each
iteration compute remaining = deadline.saturating_duration_since(Instant::now())
and pass that remaining duration into next_subscription_payload; if
remaining.is_zero() or elapsed >= TOTAL_DURATION return an error (or bail) so
the test fails instead of hanging. Apply this same pattern to both the
pendingTransactions loop (using tx_hash, ws_stream, subscription_id) and the
logs loop (the one using 300s budget).
- Around line 182-188: The connect_ws helper currently forces the URL scheme to
"ws" and breaks secure endpoints; update the connect_ws function to derive the
websocket scheme from the rpc::Client's base URL (use "wss" when original scheme
is "https", "ws" when "http", and preserve existing "ws"/"wss" if present), call
url.set_scheme(...) with that derived scheme (handling set_scheme errors as
before), then set_path("/rpc/v1") and proceed to connect_async(url.as_str()) to
return the EthSubStream.
- Around line 596-606: The test currently treats the `eth_subscribe("logs")`
payload as an array; instead require a single object: check
`payload.is_object()` (not `is_array()`), deserialize into a single `LogView`
(not `Vec<LogView>`), remove the empty-array check, and update the matching
logic to compare the single `log`'s `transaction_hash` and `topics` against
`tx_hash` and `tx.topic` (the code around `payload`, `LogView`, `tx_hash`,
`tx.topic`, and the `matched` variable).
🪄 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 73ae3705-5e85-4aec-9388-62e6528b206f

📥 Commits

Reviewing files that changed from the base of the PR and between 6f51115 and 709de17.

📒 Files selected for processing (10)
  • CHANGELOG.md
  • src/message_pool/msgpool/events.rs
  • src/message_pool/msgpool/msg_pool.rs
  • src/message_pool/msgpool/pending_store.rs
  • src/rpc/methods/chain.rs
  • src/rpc/methods/eth.rs
  • src/rpc/methods/eth/pubsub.rs
  • src/tool/subcommands/api_cmd/stateful_tests.rs
  • src/utils/broadcast/mod.rs
  • src/utils/broadcast/tests.rs
💤 Files with no reviewable changes (2)
  • src/message_pool/msgpool/pending_store.rs
  • src/rpc/methods/chain.rs
✅ Files skipped from review due to trivial changes (2)
  • CHANGELOG.md
  • src/message_pool/msgpool/msg_pool.rs

Comment thread src/tool/subcommands/api_cmd/stateful_tests.rs
Comment thread src/tool/subcommands/api_cmd/stateful_tests.rs Outdated
Comment thread src/tool/subcommands/api_cmd/stateful_tests.rs Outdated
Copy link
Copy Markdown
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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@CHANGELOG.md`:
- Line 46: Replace the PR reference
"[`#6941`](https://github.com/ChainSafe/forest/pull/6941)" in the changelog entry
that reads "The `eth_subscribe` `logs` subscription now emits one log object per
notification instead of one array of logs per tipset." with the issue reference
"`#6031`" (e.g. "[`#6031`](https://github.com/ChainSafe/forest/issues/6031)") so the
entry references the tracked issue rather than the PR, keeping the rest of the
sentence 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: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: d5adcb12-68bc-45d4-abd9-fb0add710a1e

📥 Commits

Reviewing files that changed from the base of the PR and between 709de17 and 0571359.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • src/rpc/methods/eth/pubsub.rs
  • src/tool/subcommands/api_cmd/stateful_tests.rs

Comment thread CHANGELOG.md

### Fixed

- [#6941](https://github.com/ChainSafe/forest/pull/6941): The `eth_subscribe` `logs` subscription now emits one log object per notification instead of one array of logs per tipset.
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 | 🟡 Minor | ⚡ Quick win

Use the linked issue number instead of PR number in this changelog entry.

Line 46 should reference issue #6031 (the tracked objective) rather than PR #6941, to match the project’s changelog convention.

Suggested edit
-- [`#6941`](https://github.com/ChainSafe/forest/pull/6941): The `eth_subscribe` `logs` subscription now emits one log object per notification instead of one array of logs per tipset.
+- [`#6031`](https://github.com/ChainSafe/forest/issues/6031): The `eth_subscribe` `logs` subscription now emits one log object per notification instead of one array of logs per tipset.

Based on learnings: “In CHANGELOG.md entries, when both an issue and a PR exist for a change, reference the issue number… Use PR numbers only if there is no corresponding issue.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@CHANGELOG.md` at line 46, Replace the PR reference
"[`#6941`](https://github.com/ChainSafe/forest/pull/6941)" in the changelog entry
that reads "The `eth_subscribe` `logs` subscription now emits one log object per
notification instead of one array of logs per tipset." with the issue reference
"`#6031`" (e.g. "[`#6031`](https://github.com/ChainSafe/forest/issues/6031)") so the
entry references the tracked issue rather than the PR, keeping the rest of the
sentence unchanged.

Ok(m) => m,
Err(e) => {
tracing::error!("Failed to serialize subscription message: {e:?}");
break;
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.

should we continue here instead of break if we fail to serialize next subscription message?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I don't think so because we are only sending specific data (logs, hashes, tipset) to the stream, if json is not able to serialised then even if we continue it will fail again.

let MpoolUpdate::Add(msg) = update else {
return None;
};
eth_tx_hash_from_signed_message(&msg, eth_chain_id).ok()
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.

instead of dropping failures silently we could log them

Copy link
Copy Markdown
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.

🧹 Nitpick comments (1)
src/rpc/methods/eth.rs (1)

3106-3118: ⚡ Quick win

Add error context for better debugging.

The function propagates errors without adding context, which makes debugging harder when failures occur. Per coding guidelines, errors should be wrapped with .context() to create helpful error chains.

🔍 Suggested improvement
 pub(crate) fn eth_tx_hash_from_signed_message(
     message: &SignedMessage,
     eth_chain_id: EthChainIdType,
 ) -> anyhow::Result<EthHash> {
     if message.is_delegated() {
-        let (_, tx) = eth_tx_from_signed_eth_message(message, eth_chain_id)?;
-        Ok(tx.eth_hash()?.into())
+        let (_, tx) = eth_tx_from_signed_eth_message(message, eth_chain_id)
+            .context("failed to convert delegated message to eth tx")?;
+        Ok(tx.eth_hash()
+            .context("failed to compute eth hash from tx")?.into())
     } else if message.is_secp256k1() {
         Ok(message.cid().into())
     } else {
         Ok(message.message().cid().into())
     }
 }

As per coding guidelines: Use anyhow::Result<T> for most operations and add context with .context() when errors occur.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/rpc/methods/eth.rs` around lines 3106 - 3118, The function
eth_tx_hash_from_signed_message currently propagates errors raw; update it to
wrap error-producing calls with context: when calling
eth_tx_from_signed_eth_message(...) add .context("failed to build eth tx from
signed eth message") and when calling tx.eth_hash()? add .context("failed to
compute eth hash from tx") before converting to EthHash (ensure anyhow::Context
is in scope); keep other branches unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/rpc/methods/eth.rs`:
- Around line 3106-3118: The function eth_tx_hash_from_signed_message currently
propagates errors raw; update it to wrap error-producing calls with context:
when calling eth_tx_from_signed_eth_message(...) add .context("failed to build
eth tx from signed eth message") and when calling tx.eth_hash()? add
.context("failed to compute eth hash from tx") before converting to EthHash
(ensure anyhow::Context is in scope); keep other branches unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 32e45654-46b9-45d7-b17b-f00c761fa172

📥 Commits

Reviewing files that changed from the base of the PR and between 0571359 and c76e413.

📒 Files selected for processing (2)
  • CHANGELOG.md
  • src/rpc/methods/eth.rs
✅ Files skipped from review due to trivial changes (1)
  • CHANGELOG.md

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

RPC requires calibnet RPC checks to run on CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add PendingTransaction support in the EthSubscribe API

2 participants