Skip to main content

walletkit/core/wallet/executor/
mod.rs

1//! `AccountExecutor` — the per-account tracking loop that turns broadcast txs into
2//! terminal outcomes. Separate from the one-shot send pipeline
3//! ([`TransactionManager`](super::TransactionManager)) because it is a distinct
4//! concern: the send path builds and submits once, the executor tracks forever.
5//!
6//! The pure state machine it drives lives in [`lifecycle`]; this module is its
7//! imperative shell.
8
9mod lifecycle;
10
11pub use lifecycle::{ChainEvent, ChainView, Finality, FinalityConfig, Outcome, transition};
12
13use super::{TransactionManager, signing};
14use crate::core::deps::{
15    Clock, GasOracle, GasOracleError, NonceManager, NonceManagerError, PolicyEngine,
16    PolicyEngineError, Rpc, RpcError, Signer, SignerError, StateStore, StateStoreError,
17    SubmissionError, SubmissionStrategy,
18};
19use crate::core::wallet::{Decision, HandleId, PolicyApproval, SigningRequest, TxHandle, TxStatus};
20use crate::obs::{debug, info, warn};
21use alloy_eips::eip1559::Eip1559Estimation;
22use alloy_primitives::Address;
23use alloy_rpc_types_eth::TransactionReceipt;
24use parking_lot::Mutex;
25use std::collections::HashMap;
26use std::sync::Arc;
27use std::sync::atomic::{AtomicU64, Ordering};
28
29/// Confirmation depth before a mined tx is treated as final. OZ uses 12 for mainnet;
30/// L2s want fewer. Per-chain, tunable via [`AccountExecutor::with_confirmations`].
31const DEFAULT_REQUIRED_CONFIRMATIONS: u64 = 12;
32
33/// Resubmit (bump) a tx that has been pending at least this long (seconds) — OZ's
34/// time-based resubmit. Tunable via [`AccountExecutor::with_bump_timeout`].
35const DEFAULT_BUMP_TIMEOUT_SECS: u64 = 30;
36
37/// The single consistent chain snapshot a confirm cycle works from — read once up
38/// front so every per-handle decision uses the same view and finality rule.
39struct Cycle {
40    view: ChainView,
41    finality: FinalityConfig,
42    mined_nonce: u64,
43}
44
45/// Per-account tracking executor (thirdweb engine-core pattern): the nonce is
46/// per-account, so one executor serializes an account's in-flight txs. The host
47/// drives [`tick`](Self::tick) on a `Clock` cadence; each tick runs
48/// Recover → Confirm → Escalate.
49pub struct AccountExecutor {
50    rpc: Arc<dyn Rpc>,
51    nonce_manager: Arc<dyn NonceManager>,
52    submission: Arc<dyn SubmissionStrategy>,
53    state_store: Arc<dyn StateStore>,
54    gas_oracle: Arc<dyn GasOracle>,
55    policy: Arc<dyn PolicyEngine>,
56    signer: Arc<dyn Signer>,
57    clock: Arc<dyn Clock>,
58    account: Address,
59    required_confirmations: u64,
60    bump_timeout: u64,
61    /// When set, a foreign `Replaced` re-executes the intent through this send pipeline at a
62    /// fresh nonce (opt-in intent-refill). `None` disables it.
63    refill: Option<Arc<TransactionManager>>,
64    /// Lossy cache of the one thing a handle can't persist — the bump approval
65    /// capability. A cache miss just means "re-evaluate policy on the next bump", so
66    /// every persisted handle is bump-eligible with or without an entry here.
67    approvals: Mutex<HashMap<HandleId, PolicyApproval>>,
68    /// Highest `latest` block seen; a lower reading next cycle is a lagging node and
69    /// the cycle is skipped (a stale head must not drive transitions).
70    last_latest: AtomicU64,
71}
72
73impl AccountExecutor {
74    /// Wire an executor for one `account` from the ports it drives.
75    #[allow(clippy::too_many_arguments)]
76    pub fn new(
77        rpc: Arc<dyn Rpc>,
78        nonce_manager: Arc<dyn NonceManager>,
79        submission: Arc<dyn SubmissionStrategy>,
80        state_store: Arc<dyn StateStore>,
81        gas_oracle: Arc<dyn GasOracle>,
82        policy: Arc<dyn PolicyEngine>,
83        signer: Arc<dyn Signer>,
84        clock: Arc<dyn Clock>,
85        account: Address,
86    ) -> Self {
87        // The executor signs bumps for `account`; a signer for a different key would put
88        // them on the wrong sender. This is a wiring invariant (the facade enforces it).
89        debug_assert_eq!(
90            signer.address(),
91            account,
92            "AccountExecutor signer must control the account"
93        );
94        Self {
95            rpc,
96            nonce_manager,
97            submission,
98            state_store,
99            gas_oracle,
100            policy,
101            signer,
102            clock,
103            account,
104            required_confirmations: DEFAULT_REQUIRED_CONFIRMATIONS,
105            bump_timeout: DEFAULT_BUMP_TIMEOUT_SECS,
106            refill: None,
107            approvals: Mutex::new(HashMap::new()),
108            last_latest: AtomicU64::new(0),
109        }
110    }
111
112    /// Override the confirmation depth (per-chain reorg table).
113    pub fn with_confirmations(mut self, depth: u64) -> Self {
114        self.required_confirmations = depth;
115        self
116    }
117
118    /// Override the pending-before-bump timeout (seconds).
119    pub fn with_bump_timeout(mut self, secs: u64) -> Self {
120        self.bump_timeout = secs;
121        self
122    }
123
124    /// Enable intent-refill: re-execute an intent displaced by a foreign tx via `manager`'s
125    /// send pipeline. Off unless set.
126    pub fn with_refill(mut self, manager: Arc<TransactionManager>) -> Self {
127        self.refill = Some(manager);
128        self
129    }
130
131    /// Seed the approval cache for a freshly-sent tx so its first bump reuses the
132    /// approval instead of re-evaluating policy. Optional: a bump with no cached
133    /// approval simply re-evaluates from the handle's persisted intent.
134    pub fn track(&self, handle: HandleId, approval: PolicyApproval) {
135        self.approvals.lock().insert(handle, approval);
136    }
137
138    /// One executor cycle: recover in-flight txs, confirm progress, bump the stuck.
139    /// The host calls this per `Clock` tick.
140    #[cfg_attr(
141        feature = "tracing",
142        tracing::instrument(name = "wallet.tick", level = "debug", skip_all)
143    )]
144    pub async fn tick(&self) -> Result<(), ExecutorError> {
145        self.recover().await?;
146        self.confirm().await?;
147        self.escalate().await
148    }
149
150    /// Rebroadcast persisted txs that should be in the mempool (Pending/Sent).
151    /// Idempotent — an already-known tx is fine — so a per-handle submit failure is
152    /// skipped; only a store read failure aborts the cycle. Mined/Replacing handles
153    /// are Confirm's job (rebroadcasting them only earns a nonce-too-low).
154    pub async fn recover(&self) -> Result<(), ExecutorError> {
155        for handle in self.state_store.pending_handles(self.account).await? {
156            if matches!(handle.status, TxStatus::Pending | TxStatus::Sent) {
157                let _ = self.submission.submit(handle.signed.clone()).await;
158            }
159        }
160        Ok(())
161    }
162
163    /// Advance in-flight handles against one consistent chain view: reconcile the nonce
164    /// forward, then move each handle by the pure [`transition`]. Every unreliable read
165    /// collapses to [`ChainEvent::Unknown`] (per handle) or a skipped cycle (bad view),
166    /// so a wrong read can neither advance nor rewind the lifecycle.
167    pub async fn confirm(&self) -> Result<(), ExecutorError> {
168        let Some(cycle) = self.read_cycle().await? else {
169            return Ok(()); // stale/inconsistent head — skip the whole cycle
170        };
171        // Reconcile the allocator forward — a foreign/out-of-band tx can advance the
172        // chain nonce without our allocation.
173        self.nonce_manager
174            .reset(self.account, cycle.mined_nonce)
175            .await?;
176        for mut handle in self.state_store.pending_handles(self.account).await? {
177            let event = self.event_for(&handle, cycle.mined_nonce).await;
178            let Some(next) = transition(&handle.status, &event, &cycle.view, &cycle.finality)
179            else {
180                continue;
181            };
182            let next = match next {
183                TxStatus::Replaced if handle.cancelled => TxStatus::Dropped,
184                other => other,
185            };
186            // `_prev` is read only by the transition events below; the underscore keeps a
187            // `--no-default-features` build (where the obs macros are no-ops) warning-free.
188            let _prev = std::mem::replace(&mut handle.status, next);
189            if handle.status.is_terminal() {
190                info!(intent_hash = ?handle.intent_hash, from = ?_prev, to = ?handle.status, "transaction settled");
191            } else {
192                debug!(intent_hash = ?handle.intent_hash, from = ?_prev, to = ?handle.status, "status advanced");
193            }
194            // Refill is gated on the persist succeeding: a terminal handle that failed to
195            // persist stays in `pending_handles` and re-transitions next tick, so firing
196            // refill here would double-spawn the intent.
197            if self.state_store.put_handle(&handle).await.is_ok() && handle.status.is_terminal() {
198                self.approvals.lock().remove(&handle.id);
199                // A foreign replacement (never a cancel — that settled Dropped above)
200                // re-executes the intent when refill is on.
201                if let Some(manager) = &self.refill
202                    && handle.status == TxStatus::Replaced
203                {
204                    self.refill_intent(manager, &handle).await;
205                }
206            }
207        }
208        Ok(())
209    }
210
211    /// Best-effort re-execution of a displaced intent at a fresh nonce + fresh approval. The
212    /// child is a fresh handle, so if it too is displaced it refills again until an attempt
213    /// mines. A failure is logged, never aborts the tick.
214    async fn refill_intent(&self, manager: &TransactionManager, handle: &TxHandle) {
215        // Underscore keeps `_child`/`_err` warning-free when the obs macros are no-ops.
216        match manager.send(&handle.intent).await {
217            Ok(_child) => debug!(nonce = _child.nonce, "intent refilled after replacement"),
218            Err(_err) => warn!(error = %_err, nonce = handle.nonce, "refill failed"),
219        }
220    }
221
222    /// Read one consistent [`Cycle`] snapshot and resolve its finality rule: prefer the
223    /// `finalized` tag, fall back to a depth count when the chain lacks it. Returns
224    /// `None` — skip the cycle — when the head regressed since last cycle or `finalized`
225    /// is above `latest`, both signs of a stale/lagging node.
226    async fn read_cycle(&self) -> Result<Option<Cycle>, ExecutorError> {
227        let latest = self.rpc.block_number().await?;
228        let mined_nonce = self.rpc.tx_count(self.account).await?;
229        if latest < self.last_latest.load(Ordering::Relaxed) {
230            return Ok(None);
231        }
232        let (mode, finalized) = match self.rpc.finalized_block().await? {
233            Some(finalized) => (Finality::Finalized, finalized),
234            None => (Finality::Depth, 0),
235        };
236        if finalized > latest {
237            return Ok(None);
238        }
239        self.last_latest.store(latest, Ordering::Relaxed);
240        Ok(Some(Cycle {
241            view: ChainView { latest, finalized },
242            finality: FinalityConfig {
243                mode,
244                required: self.required_confirmations,
245            },
246            mined_nonce,
247        }))
248    }
249
250    /// Distill one handle's chain reads into a single trustworthy [`ChainEvent`]. Our
251    /// own tx is the strongest evidence, so a hash-anchored receipt wins over the nonce
252    /// count — a lagging `tx_count` can neither hide nor un-mine a canonical tx. With no
253    /// receipt, the nonce decides: consumed by a foreign tx (`Replaced`) or still ours
254    /// (`Pending`). Any read error or non-canonical receipt is `Unknown`.
255    async fn event_for(&self, handle: &TxHandle, mined: u64) -> ChainEvent {
256        // Newest-first: after an RBF bump the latest replacement is the one that mines.
257        for hash in handle.broadcasts.iter().rev() {
258            match self.rpc.receipt(*hash).await {
259                Ok(None) => continue, // this broadcast isn't mined; try an older one
260                Ok(Some(receipt)) => return self.anchor(receipt).await,
261                Err(_) => return ChainEvent::Unknown,
262            }
263        }
264        match handle.nonce < mined {
265            true => ChainEvent::Replaced, // a foreign tx consumed our nonce
266            false => ChainEvent::Pending, // still in the mempool
267        }
268    }
269
270    /// Trust a receipt only if its block is still canonical — `block_hash(n)` must equal
271    /// the receipt's hash (geth serves receipts from stale forks after a reorg). A
272    /// non-canonical block, a receipt with no block anchor, or a read error is `Unknown`.
273    async fn anchor(&self, receipt: TransactionReceipt) -> ChainEvent {
274        let (Some(block), Some(block_hash)) = (receipt.block_number, receipt.block_hash) else {
275            return ChainEvent::Unknown;
276        };
277        match self.rpc.block_hash(block).await {
278            Ok(Some(canonical)) if canonical == block_hash => ChainEvent::Mined {
279                block,
280                block_hash,
281                outcome: match receipt.status() {
282                    true => Outcome::Executed,
283                    false => Outcome::Reverted,
284                },
285            },
286            _ => ChainEvent::Unknown,
287        }
288    }
289
290    /// Bump every still-pending tx that has outstayed the timeout: raise its fees at
291    /// the **same nonce** (RBF). Everything a bump needs comes from the persisted
292    /// handle (only the approval is a cache). Best-effort per handle — one failure
293    /// doesn't abort the cycle.
294    pub async fn escalate(&self) -> Result<(), ExecutorError> {
295        let now = self.clock.now_unix();
296        for mut handle in self.state_store.pending_handles(self.account).await? {
297            let stuck = matches!(handle.status, TxStatus::Sent)
298                && now.saturating_sub(handle.last_broadcast_at) >= self.bump_timeout;
299            if stuck {
300                let _ = self.bump(&mut handle, now).await;
301            }
302        }
303        Ok(())
304    }
305
306    #[cfg_attr(
307        feature = "tracing",
308        tracing::instrument(
309            level = "debug",
310            skip_all,
311            fields(intent_hash = ?handle.intent_hash, nonce = handle.nonce, bump_count = handle.broadcasts.len())
312        )
313    )]
314    async fn bump(&self, handle: &mut TxHandle, now: u64) -> Result<(), ExecutorError> {
315        // Re-check right before bumping: if the nonce mined since the handle was
316        // selected, don't broadcast a doomed replacement — Confirm will settle it.
317        if handle.nonce < self.rpc.tx_count(self.account).await? {
318            return Ok(());
319        }
320        // The current fees + gas limit live in the persisted signed tx.
321        let Some(current) = signing::decode_fees(&handle.signed) else {
322            return Ok(()); // undecodable (never our own tx) -> leave it
323        };
324        let bumped = match self.gas_oracle.bump(current.fees).await {
325            Ok(fees) => fees,
326            // At the ceiling we stop and leave the tx as-is (an operator signal, not a retry).
327            Err(GasOracleError::CeilingExceeded { .. }) => {
328                warn!(intent_hash = ?handle.intent_hash, "bump halted at gas ceiling");
329                return Ok(());
330            }
331            Err(e) => return Err(e.into()),
332        };
333        // The originally-approved envelope is a hard per-intent spend ceiling. A bump
334        // beyond it stops (operator signal) rather than silently escalating the approved
335        // spend — raising it requires a fresh authorization.
336        if !handle
337            .envelope
338            .admits(bumped.max_fee_per_gas, bumped.max_priority_fee_per_gas)
339        {
340            warn!(intent_hash = ?handle.intent_hash, "bump halted at approval envelope");
341            return Ok(());
342        }
343        let Some(approval) = self.bump_approval(handle, bumped, now).await? else {
344            return Ok(()); // policy revoked or tightened below the bump -> leave the tx
345        };
346
347        let tx = signing::build_tx(&handle.intent, handle.nonce, current.gas_limit, bumped);
348        let signed =
349            signing::sign_encode(&*self.signer, tx, handle.intent_hash, &approval, now).await?;
350        match self.submission.submit(signed.rlp.clone()).await {
351            Ok(_) => {}
352            // Already in the mempool (a prior round's replacement): record it, not an error.
353            Err(e) if e.is_already_accepted() => {}
354            Err(e) => return Err(e.into()),
355        }
356
357        handle.signed = signed.rlp;
358        handle.broadcasts.push(signed.hash);
359        handle.last_broadcast_at = now;
360        self.state_store.put_handle(handle).await?;
361        self.approvals.lock().insert(handle.id, approval);
362        warn!(intent_hash = ?handle.intent_hash, nonce = handle.nonce, "bumped fees (RBF)");
363        Ok(())
364    }
365
366    /// The approval to sign a bump with: reuse the cached one while it is valid and
367    /// covers the bumped fees, else re-evaluate policy from the persisted intent (which
368    /// mirrors the signer gate, so a lapsed TTL can't wedge RBF). `None` means policy
369    /// denied or returned an envelope that no longer covers the bump — leave the tx.
370    async fn bump_approval(
371        &self,
372        handle: &TxHandle,
373        bumped: Eip1559Estimation,
374        now: u64,
375    ) -> Result<Option<PolicyApproval>, ExecutorError> {
376        let admits = |a: &PolicyApproval| {
377            a.gas_envelope()
378                .admits(bumped.max_fee_per_gas, bumped.max_priority_fee_per_gas)
379        };
380        let cached = self.approvals.lock().get(&handle.id).cloned();
381        if let Some(approval) = cached
382            && approval.valid_until() >= now
383            && admits(&approval)
384        {
385            return Ok(Some(approval));
386        }
387        // `Cancel` default-allows a self-send; `Transaction` doesn't, so a stuck cancel
388        // would wedge on the wrong shape.
389        let intent = handle.intent.clone();
390        let request = if intent.is_self_send() {
391            SigningRequest::Cancel(intent)
392        } else {
393            SigningRequest::Transaction(intent)
394        };
395        match self.policy.evaluate(&request).await? {
396            Decision::Allow(approval) => Ok(admits(&approval).then_some(approval)),
397            Decision::Deny(_) => Ok(None),
398        }
399    }
400}
401
402/// Operational failures the executor surfaces from the ports it drives. Its own type
403/// (not the pipeline's) — tracking and one-shot send are separate concerns.
404#[derive(Debug, thiserror::Error)]
405#[non_exhaustive]
406pub enum ExecutorError {
407    /// An RPC call failed.
408    #[error(transparent)]
409    Rpc(#[from] RpcError),
410    /// Fee estimation/bumping failed.
411    #[error(transparent)]
412    Gas(#[from] GasOracleError),
413    /// Policy evaluation failed operationally (fail-closed).
414    #[error(transparent)]
415    Policy(#[from] PolicyEngineError),
416    /// Nonce allocation/reconciliation failed.
417    #[error(transparent)]
418    Nonce(#[from] NonceManagerError),
419    /// Signing failed.
420    #[error(transparent)]
421    Signer(#[from] SignerError),
422    /// A durable-store operation failed.
423    #[error(transparent)]
424    Store(#[from] StateStoreError),
425    /// Broadcasting the transaction failed.
426    #[error(transparent)]
427    Submission(#[from] SubmissionError),
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433    use crate::core::wallet::GasEnvelope;
434    use crate::testutils::{
435        Harness, MockClock, MockGas, MockPolicy, MockRpc, MockStore, MockSubmit, Submit,
436        estimation, handle, receipt, receipt_unanchored, signed_legacy,
437    };
438    use alloy_primitives::{B256, Bytes};
439
440    // --- Recover / confirm ---
441
442    #[tokio::test]
443    async fn recover_rebroadcasts_persisted_inflight_after_restart() {
444        let store = Arc::new(MockStore::default());
445        let h = handle(4, TxStatus::Sent);
446        store.put_handle(&h).await.unwrap();
447        let submit = Arc::new(MockSubmit::default());
448        let exec = Harness::default()
449            .submit(submit.clone())
450            .store(store.clone())
451            .executor();
452        exec.recover().await.unwrap();
453        assert_eq!(*submit.seen.lock(), vec![h.signed]);
454    }
455
456    #[tokio::test]
457    async fn recover_rebroadcasts_only_pending_and_sent_across_multiple_inflight_handles() {
458        // recover()'s `matches!(status, Pending | Sent)` guard rebroadcasts exactly the
459        // live handles; Mined/Replacing are Confirm's job (rebroadcasting them only earns
460        // a nonce-too-low). Distinct signed bytes per nonce make the set falsifiable.
461        let store = Arc::new(MockStore::default());
462        let h4 = handle(4, TxStatus::Sent);
463        let h5 = handle(5, TxStatus::Pending);
464        store.put_handle(&h4).await.unwrap();
465        store.put_handle(&h5).await.unwrap();
466        store
467            .put_handle(&handle(
468                6,
469                TxStatus::Mined {
470                    block: 8,
471                    block_hash: B256::repeat_byte(1),
472                },
473            ))
474            .await
475            .unwrap();
476        store
477            .put_handle(&handle(7, TxStatus::Replacing { since_block: 8 }))
478            .await
479            .unwrap();
480        let submit = Arc::new(MockSubmit::default());
481        let exec = Harness::default()
482            .submit(submit.clone())
483            .store(store.clone())
484            .executor();
485
486        exec.recover().await.unwrap();
487
488        let seen = submit.seen.lock();
489        assert_eq!(seen.len(), 2); // only the two live handles
490        assert!(seen.contains(&h4.signed));
491        assert!(seen.contains(&h5.signed));
492    }
493
494    #[tokio::test]
495    async fn recover_swallows_a_per_handle_submit_failure_and_still_attempts_later_handles() {
496        // The `let _ =` on the per-handle submit result must not abort recovery for the
497        // rest. Every submit errors (non-transient), but the mock records each attempt.
498        let store = Arc::new(MockStore::default());
499        let h4 = handle(4, TxStatus::Sent);
500        let h5 = handle(5, TxStatus::Sent);
501        store.put_handle(&h4).await.unwrap();
502        store.put_handle(&h5).await.unwrap();
503        let submit = Arc::new(MockSubmit {
504            outcome: Submit::Deterministic,
505            ..Default::default()
506        });
507        let exec = Harness::default()
508            .submit(submit.clone())
509            .store(store.clone())
510            .executor();
511
512        assert!(exec.recover().await.is_ok()); // the first handle's error did not abort
513        let seen = submit.seen.lock();
514        assert_eq!(seen.len(), 2); // both attempted despite the first erroring
515        assert!(seen.contains(&h4.signed));
516        assert!(seen.contains(&h5.signed));
517    }
518
519    #[tokio::test]
520    async fn terminal_handles_are_readable_after_restart_but_not_rebroadcast() {
521        // Terminal handles are excluded from the pending set (not re-tracked); only the
522        // live Sent handle is rebroadcast on recovery. Fails if any terminal variant leaks.
523        let store = Arc::new(MockStore::default());
524        store
525            .put_handle(&handle(4, TxStatus::Confirmed { block: 8 }))
526            .await
527            .unwrap();
528        store
529            .put_handle(&handle(5, TxStatus::Failed { reason: "x".into() }))
530            .await
531            .unwrap();
532        store
533            .put_handle(&handle(6, TxStatus::Replaced))
534            .await
535            .unwrap();
536        let live = handle(7, TxStatus::Sent);
537        store.put_handle(&live).await.unwrap();
538        let submit = Arc::new(MockSubmit::default());
539        let exec = Harness::default()
540            .submit(submit.clone())
541            .store(store.clone())
542            .executor();
543
544        exec.recover().await.unwrap();
545
546        let seen = submit.seen.lock();
547        assert_eq!(seen.len(), 1);
548        assert_eq!(seen[0], live.signed);
549    }
550
551    /// Run one confirm cycle against a fixed chain view. `canonical` is the hash
552    /// `block_hash(_)` returns, so a receipt anchors only when it matches. Depth mode
553    /// (no `finalized` tag), `confirmations` required.
554    async fn run_confirm(
555        store: &Arc<MockStore>,
556        tx_count: u64,
557        head: u64,
558        receipt: Option<TransactionReceipt>,
559        canonical: Option<B256>,
560        confirmations: u64,
561    ) {
562        Harness::default()
563            .rpc(Arc::new(MockRpc {
564                tx_count,
565                block_number: head,
566                receipt,
567                canonical,
568                ..Default::default()
569            }))
570            .store(store.clone())
571            .confirmations(confirmations)
572            .executor()
573            .confirm()
574            .await
575            .unwrap();
576    }
577
578    #[tokio::test]
579    async fn confirm_advances_on_anchored_receipt_at_required_depth() {
580        let store = Arc::new(MockStore::default());
581        store.put_handle(&handle(4, TxStatus::Sent)).await.unwrap();
582        let h = B256::repeat_byte(1);
583        // receipt at block 8 anchors to the canonical hash; head 10 -> depth 3 >= 2.
584        run_confirm(&store, 5, 10, Some(receipt(true, 8, h)), Some(h), 2).await;
585        assert_eq!(store.all()[0].status, TxStatus::Confirmed { block: 8 });
586    }
587
588    #[tokio::test]
589    async fn reverted_receipt_fails_only_at_depth() {
590        let store = Arc::new(MockStore::default());
591        store.put_handle(&handle(4, TxStatus::Sent)).await.unwrap();
592        let h = B256::repeat_byte(1);
593        run_confirm(&store, 5, 10, Some(receipt(false, 8, h)), Some(h), 2).await;
594        assert!(matches!(store.all()[0].status, TxStatus::Failed { .. }));
595    }
596
597    #[tokio::test]
598    async fn stale_receipt_from_a_reorged_block_holds_the_state() {
599        // The crux at the shell: our receipt claims block 8/hash h2, but the canonical
600        // hash at 8 is h1 -> the read is stale -> Unknown -> no transition.
601        let store = Arc::new(MockStore::default());
602        let mined = TxStatus::Mined {
603            block: 8,
604            block_hash: B256::repeat_byte(1),
605        };
606        store.put_handle(&handle(4, mined.clone())).await.unwrap();
607        run_confirm(
608            &store,
609            5,
610            10,
611            Some(receipt(true, 8, B256::repeat_byte(2))),
612            Some(B256::repeat_byte(1)),
613            2,
614        )
615        .await;
616        assert_eq!(store.all()[0].status, mined); // unchanged
617    }
618
619    #[tokio::test]
620    async fn freed_nonce_un_mines_a_tentative_handle() {
621        // A reorg dropped our mined tx and freed the nonce (tx_count back to our nonce)
622        // with no receipt remaining -> Pending -> re-track from Sent.
623        let store = Arc::new(MockStore::default());
624        store
625            .put_handle(&handle(
626                4,
627                TxStatus::Mined {
628                    block: 8,
629                    block_hash: B256::repeat_byte(1),
630                },
631            ))
632            .await
633            .unwrap();
634        run_confirm(&store, 4, 10, None, None, 12).await;
635        assert_eq!(store.all()[0].status, TxStatus::Sent);
636    }
637
638    #[tokio::test]
639    async fn replacement_is_tentative_until_depth_then_final() {
640        let store = Arc::new(MockStore::default());
641        store.put_handle(&handle(4, TxStatus::Sent)).await.unwrap();
642        // nonce consumed (mined 5 > 4) but none of our broadcasts mined -> a foreign tx.
643        run_confirm(&store, 5, 10, None, None, 3).await;
644        assert_eq!(
645            store.all()[0].status,
646            TxStatus::Replacing { since_block: 10 } // tentative, not yet final
647        );
648        // Head advances past the depth window -> final.
649        run_confirm(&store, 5, 13, None, None, 3).await;
650        assert_eq!(store.all()[0].status, TxStatus::Replaced);
651    }
652
653    #[tokio::test]
654    async fn replacement_reorg_frees_the_nonce_and_recovers_to_sent() {
655        let store = Arc::new(MockStore::default());
656        store
657            .put_handle(&handle(4, TxStatus::Replacing { since_block: 5 }))
658            .await
659            .unwrap();
660        // A reorg dropped the replacing tx: the mined nonce fell back to 4, so our
661        // nonce is free again and our tx must be re-tracked.
662        run_confirm(&store, 4, 10, None, None, 12).await;
663        assert_eq!(store.all()[0].status, TxStatus::Sent);
664    }
665
666    #[tokio::test]
667    async fn finalized_tag_gates_terminality() {
668        // With a finalized tag, a receipt is terminal only once its block <= finalized,
669        // regardless of how far ahead `latest` is.
670        let store = Arc::new(MockStore::default());
671        store.put_handle(&handle(4, TxStatus::Sent)).await.unwrap();
672        let h = B256::repeat_byte(1);
673        let confirm_with_finalized = async |finalized: u64| {
674            Harness::default()
675                .rpc(Arc::new(MockRpc {
676                    tx_count: 5,
677                    block_number: 100,
678                    finalized: Some(finalized),
679                    receipt: Some(receipt(true, 8, h)),
680                    canonical: Some(h),
681                    ..Default::default()
682                }))
683                .store(store.clone())
684                .executor()
685                .confirm()
686                .await
687                .unwrap();
688        };
689        // finalized 7 < block 8 -> tentative Mined despite the far-ahead head.
690        confirm_with_finalized(7).await;
691        assert_eq!(
692            store.all()[0].status,
693            TxStatus::Mined {
694                block: 8,
695                block_hash: h
696            }
697        );
698        // finalized advances to 8 -> now irreversible.
699        confirm_with_finalized(8).await;
700        assert_eq!(store.all()[0].status, TxStatus::Confirmed { block: 8 });
701    }
702
703    #[tokio::test]
704    async fn regressed_head_between_cycles_skips_confirm_and_makes_no_transition() {
705        // A lagging/failover node serving an older head must short-circuit read_cycle
706        // *before* the nonce reset (and thus before any transition). One executor (the
707        // guard is stateful in last_latest) drives three cycles: 100 advances -> 90
708        // regressed (skip) -> 95 still below 100 (skip — proving the skip didn't corrupt
709        // last_latest down to 90). reset() runs exactly once (cycle 1); counting it is the
710        // decisive proof the two regressed cycles never entered the confirm body. Distinct
711        // from inconsistent_view_skips_the_cycle (which trips the finalized > latest guard).
712        use crate::testutils::{MockNonce, shared_log};
713
714        let log = shared_log();
715        let store = Arc::new(MockStore::default());
716        store.put_handle(&handle(4, TxStatus::Sent)).await.unwrap();
717        let exec = Harness::default()
718            .rpc(Arc::new(MockRpc {
719                tx_count: 4, // nonce not consumed -> cycle 1 is a Pending no-op
720                block_numbers: Mutex::new([100, 90, 95].into()),
721                ..Default::default()
722            }))
723            .nonce(Arc::new(MockNonce {
724                next: 0,
725                log: log.clone(),
726            }))
727            .store(store.clone())
728            .confirmations(2)
729            .executor();
730
731        for _ in 0..3 {
732            exec.confirm().await.unwrap();
733        }
734
735        assert_eq!(store.all()[0].status, TxStatus::Sent); // no transition, ever
736        let resets = log.lock().iter().filter(|e| **e == "reset").count();
737        assert_eq!(resets, 1); // only cycle 1 ran the body; both regressed cycles skipped
738    }
739
740    #[tokio::test]
741    async fn inconsistent_view_skips_the_cycle() {
742        // finalized above latest is a stale/inconsistent read -> skip, no transition,
743        // even though the receipt would otherwise confirm.
744        let store = Arc::new(MockStore::default());
745        store.put_handle(&handle(4, TxStatus::Sent)).await.unwrap();
746        let h = B256::repeat_byte(1);
747        Harness::default()
748            .rpc(Arc::new(MockRpc {
749                tx_count: 5,
750                block_number: 100,
751                finalized: Some(200), // > latest -> inconsistent
752                receipt: Some(receipt(true, 8, h)),
753                canonical: Some(h),
754                ..Default::default()
755            }))
756            .store(store.clone())
757            .executor()
758            .confirm()
759            .await
760            .unwrap();
761        assert_eq!(store.all()[0].status, TxStatus::Sent); // unchanged
762    }
763
764    // --- Send / bump ---
765
766    /// Executor wired for a single stuck (Sent, nonce 4) tx at clock 1000, bump
767    /// timeout disabled; `bump` is the oracle's next fees (`None` = at ceiling).
768    fn send_setup(
769        bump: Option<Eip1559Estimation>,
770    ) -> (AccountExecutor, Arc<MockStore>, Arc<MockPolicy>) {
771        let store = Arc::new(MockStore::default());
772        let policy = Arc::new(MockPolicy::default());
773        let exec = Harness::default()
774            .rpc(Arc::new(MockRpc {
775                tx_count: 4,
776                ..Default::default()
777            }))
778            .gas(Arc::new(MockGas {
779                bump,
780                ..Default::default()
781            }))
782            .policy(policy.clone())
783            .clock(Arc::new(MockClock(1000)))
784            .store(store.clone())
785            .bump_timeout(0)
786            .executor();
787        (exec, store, policy)
788    }
789
790    async fn seed_and_track(exec: &AccountExecutor, store: &MockStore, envelope: GasEnvelope) {
791        let mut h = handle(4, TxStatus::Sent);
792        h.envelope = envelope;
793        store.put_handle(&h).await.unwrap();
794        exec.track(
795            h.id,
796            PolicyApproval::mint(h.intent_hash, envelope, u64::MAX),
797        );
798    }
799
800    /// Escalate a stuck (Sent, nonce 4, wide DEFAULT envelope) handle whose bump has **no
801    /// cached approval**, so `bump_approval` re-evaluates `policy`. Returns the store for
802    /// outcome assertions. The wide handle envelope keeps the per-intent hard cap out of
803    /// the way, so the only gate is the fresh policy decision.
804    async fn escalate_with_fresh_policy(policy: Arc<MockPolicy>) -> Arc<MockStore> {
805        let store = Arc::new(MockStore::default());
806        let exec = Harness::default()
807            .rpc(Arc::new(MockRpc {
808                tx_count: 4,
809                ..Default::default()
810            }))
811            .gas(Arc::new(MockGas {
812                bump: Some(estimation(200, 1)),
813                ..Default::default()
814            }))
815            .policy(policy)
816            .clock(Arc::new(MockClock(1000)))
817            .store(store.clone())
818            .bump_timeout(0)
819            .executor();
820        store.put_handle(&handle(4, TxStatus::Sent)).await.unwrap();
821        exec.escalate().await.unwrap();
822        store
823    }
824
825    /// Escalate a stuck (Sent, nonce 4) handle whose persisted `signed` is `signed`. A
826    /// working gas oracle (bump 200/1) and allowing policy are wired, so the tx staying
827    /// unbumped can only mean `decode_fees` rejected the body. Returns store + policy.
828    async fn escalate_with_signed(signed: Bytes) -> (Arc<MockStore>, Arc<MockPolicy>) {
829        let policy = Arc::new(MockPolicy::default());
830        let store = Arc::new(MockStore::default());
831        let exec = Harness::default()
832            .rpc(Arc::new(MockRpc {
833                tx_count: 4,
834                ..Default::default()
835            }))
836            .gas(Arc::new(MockGas {
837                bump: Some(estimation(200, 1)),
838                ..Default::default()
839            }))
840            .policy(policy.clone())
841            .clock(Arc::new(MockClock(1000)))
842            .store(store.clone())
843            .bump_timeout(0)
844            .executor();
845        let mut h = handle(4, TxStatus::Sent);
846        h.signed = signed;
847        store.put_handle(&h).await.unwrap();
848        exec.escalate().await.unwrap();
849        (store, policy)
850    }
851
852    #[tokio::test]
853    async fn bump_within_envelope_reuses_approval() {
854        let (exec, store, policy) = send_setup(Some(estimation(200, 1)));
855        seed_and_track(&exec, &store, GasEnvelope::DEFAULT).await; // wide -> 200 admitted
856        exec.escalate().await.unwrap();
857        assert_eq!(store.all()[0].broadcasts.len(), 2); // original + bump
858        assert_eq!(*policy.calls.lock(), 0); // approval reused, no re-policy
859    }
860
861    #[tokio::test]
862    async fn bump_beyond_approved_envelope_stops() {
863        // Bumped fees exceed the original per-intent ceiling -> hard-stop, no silent
864        // widening: no new broadcast and no re-policy.
865        let (exec, store, policy) = send_setup(Some(estimation(200, 1)));
866        let tight = GasEnvelope {
867            max_fee_cap: 150,
868            max_priority_cap: 150,
869        };
870        seed_and_track(&exec, &store, tight).await; // 200 > 150 -> stop
871        exec.escalate().await.unwrap();
872        assert_eq!(store.all()[0].broadcasts.len(), 1);
873        assert_eq!(*policy.calls.lock(), 0);
874    }
875
876    #[tokio::test]
877    async fn bump_refreshes_expired_approval_within_envelope() {
878        // Approval expired (valid_until 0 < clock 1000) but the bump stays within the
879        // envelope -> refresh via policy (not stuck), then bump.
880        let (exec, store, policy) = send_setup(Some(estimation(200, 1)));
881        let h = handle(4, TxStatus::Sent);
882        store.put_handle(&h).await.unwrap();
883        exec.track(
884            h.id,
885            PolicyApproval::mint(h.intent_hash, GasEnvelope::DEFAULT, 0),
886        );
887        exec.escalate().await.unwrap();
888        assert_eq!(store.all()[0].broadcasts.len(), 2); // bumped
889        assert_eq!(*policy.calls.lock(), 1); // refreshed (was expired), not reused
890    }
891
892    #[tokio::test]
893    async fn bump_stops_at_gas_ceiling() {
894        let (exec, store, policy) = send_setup(None); // gas oracle at ceiling
895        seed_and_track(&exec, &store, GasEnvelope::DEFAULT).await;
896        exec.escalate().await.unwrap();
897        assert_eq!(store.all()[0].broadcasts.len(), 1); // no new broadcast
898        assert_eq!(*policy.calls.lock(), 0);
899    }
900
901    #[tokio::test]
902    async fn bump_records_broadcast_when_already_known_and_persists_new_hash() {
903        // "already known" == the replacement is already in the mempool -> record it as a
904        // broadcast (so Confirm can match its receipt), not an error that drops it. The
905        // shared mutation block must also advance `signed` to the bumped body, so a later
906        // recover() rebroadcasts the replacement rather than the stale original.
907        let store = Arc::new(MockStore::default());
908        let exec = Harness::default()
909            .rpc(Arc::new(MockRpc {
910                tx_count: 4,
911                ..Default::default()
912            }))
913            .gas(Arc::new(MockGas {
914                bump: Some(estimation(200, 1)),
915                ..Default::default()
916            }))
917            .submit(Arc::new(MockSubmit {
918                outcome: Submit::AlreadyKnown,
919                ..Default::default()
920            }))
921            .clock(Arc::new(MockClock(1000)))
922            .store(store.clone())
923            .bump_timeout(0)
924            .executor();
925        let h = handle(4, TxStatus::Sent);
926        store.put_handle(&h).await.unwrap();
927        exec.track(
928            h.id,
929            PolicyApproval::mint(h.intent_hash, GasEnvelope::DEFAULT, u64::MAX),
930        );
931        exec.escalate().await.unwrap();
932        assert_eq!(store.all()[0].broadcasts.len(), 2);
933        // signed advanced to the bumped 200/1 body, not the original 100/1.
934        let fees = signing::decode_fees(&store.all()[0].signed)
935            .expect("bumped 1559 body")
936            .fees;
937        assert_eq!(fees.max_fee_per_gas, 200);
938        assert_eq!(fees.max_priority_fee_per_gas, 1);
939    }
940
941    #[tokio::test]
942    async fn bump_aborts_if_nonce_already_mined() {
943        // tx_count advanced past our nonce between selection and bump -> no doomed
944        // replacement broadcast; Confirm will settle it.
945        let store = Arc::new(MockStore::default());
946        let exec = Harness::default()
947            .rpc(Arc::new(MockRpc {
948                tx_count: 5, // our nonce 4 is already mined
949                ..Default::default()
950            }))
951            .gas(Arc::new(MockGas {
952                bump: Some(estimation(200, 1)),
953                ..Default::default()
954            }))
955            .clock(Arc::new(MockClock(1000)))
956            .store(store.clone())
957            .bump_timeout(0)
958            .executor();
959        let h = handle(4, TxStatus::Sent);
960        store.put_handle(&h).await.unwrap();
961        exec.track(
962            h.id,
963            PolicyApproval::mint(h.intent_hash, GasEnvelope::DEFAULT, u64::MAX),
964        );
965        exec.escalate().await.unwrap();
966        assert_eq!(store.all()[0].broadcasts.len(), 1); // aborted, no bump
967    }
968
969    #[tokio::test]
970    async fn bump_denied_by_fresh_policy_leaves_the_tx() {
971        // Policy revoked between send and bump: with no cached approval the bump
972        // re-evaluates, gets Deny, and leaves the tx — no broadcast, no cycle error.
973        let policy = Arc::new(MockPolicy {
974            allow: false,
975            ..Default::default()
976        });
977        let store = escalate_with_fresh_policy(policy.clone()).await;
978        assert_eq!(store.all()[0].broadcasts.len(), 1);
979        assert_eq!(store.all()[0].status, TxStatus::Sent);
980        // calls==1 proves control reached the Deny arm, not an earlier envelope/ceiling
981        // short-circuit (both of which leave calls==0).
982        assert_eq!(*policy.calls.lock(), 1);
983    }
984
985    #[tokio::test]
986    async fn bump_denied_when_refreshed_envelope_no_longer_admits_the_bump() {
987        // Policy re-approves but returns a *tightened* envelope that no longer admits the
988        // bumped fees -> stop, not broadcast (the false arm of `then_some`). The handle's
989        // own envelope stays wide, so the fresh approval's envelope is the sole rejection.
990        let policy = Arc::new(MockPolicy {
991            allow: true,
992            envelope: GasEnvelope {
993                max_fee_cap: 150,
994                max_priority_cap: 150,
995            },
996            valid_until: u64::MAX,
997            ..Default::default()
998        });
999        let store = escalate_with_fresh_policy(policy.clone()).await;
1000        assert_eq!(store.all()[0].broadcasts.len(), 1);
1001        assert_eq!(store.all()[0].status, TxStatus::Sent);
1002        // calls==1 distinguishes this from bump_beyond_approved_envelope_stops (calls==0,
1003        // stopped earlier at the per-intent hard cap).
1004        assert_eq!(*policy.calls.lock(), 1);
1005    }
1006
1007    #[tokio::test]
1008    async fn bump_exactly_at_envelope_ceiling_is_admitted() {
1009        // A bump landing exactly on the envelope caps is admitted (inclusive `<=` in
1010        // GasEnvelope::admits) — not stranded one wei short. The cached approval carries
1011        // the same caps and is reused (calls==0), so the boundary is the only site tested.
1012        let (exec, store, policy) = send_setup(Some(estimation(200, 1)));
1013        let caps = GasEnvelope {
1014            max_fee_cap: 200,
1015            max_priority_cap: 1,
1016        };
1017        seed_and_track(&exec, &store, caps).await;
1018        exec.escalate().await.unwrap();
1019        assert_eq!(store.all()[0].broadcasts.len(), 2); // bumped
1020        assert_eq!(*policy.calls.lock(), 0); // cached approval reused
1021    }
1022
1023    #[tokio::test]
1024    async fn decode_fees_leaves_a_non_1559_signed_tx_unbumped() {
1025        // A cleanly-decoding but non-1559 (legacy) body -> decode_fees returns None, so the
1026        // bump bails before the oracle/policy. A working oracle is wired, so broadcasts
1027        // staying at 1 can only mean decode_fees rejected the body.
1028        let signed = signed_legacy(4);
1029        let (store, policy) = escalate_with_signed(signed.clone()).await;
1030        let h = &store.all()[0];
1031        assert_eq!(h.broadcasts.len(), 1);
1032        assert_eq!(h.signed, signed); // untouched
1033        assert_eq!(h.status, TxStatus::Sent);
1034        assert_eq!(*policy.calls.lock(), 0); // never reached policy
1035    }
1036
1037    #[tokio::test]
1038    async fn decode_fees_leaves_a_handle_with_undecodable_signed_bytes() {
1039        // Garbled persisted bytes (corrupt WAL): a bad EIP-2718 type byte makes decode_2718
1040        // Err, so decode_fees returns None via `.ok()?` — the bump short-circuits, no crash.
1041        let signed = Bytes::from(vec![0xff, 0x00, 0x01]);
1042        let (store, policy) = escalate_with_signed(signed.clone()).await;
1043        let h = &store.all()[0];
1044        assert_eq!(h.broadcasts.len(), 1);
1045        assert_eq!(h.signed, signed);
1046        assert_eq!(h.status, TxStatus::Sent);
1047        assert_eq!(*policy.calls.lock(), 0);
1048    }
1049
1050    #[tokio::test]
1051    async fn bump_transient_submit_error_aborts_without_advancing_broadcasts() {
1052        // A non-already-accepted submit error must return before the mutation block,
1053        // recording nothing (check submit *before* recording the broadcast). Driven via
1054        // the direct bump() since escalate() swallows the per-handle Err.
1055        let submit = Arc::new(MockSubmit {
1056            outcome: Submit::Transient,
1057            ..Default::default()
1058        });
1059        let store = Arc::new(MockStore::default());
1060        let exec = Harness::default()
1061            .rpc(Arc::new(MockRpc {
1062                tx_count: 4,
1063                ..Default::default()
1064            }))
1065            .gas(Arc::new(MockGas {
1066                bump: Some(estimation(200, 1)),
1067                ..Default::default()
1068            }))
1069            .submit(submit.clone())
1070            .clock(Arc::new(MockClock(1000)))
1071            .store(store.clone())
1072            .bump_timeout(0)
1073            .executor();
1074        let mut h = handle(4, TxStatus::Sent);
1075        let original = h.signed.clone();
1076        store.put_handle(&h).await.unwrap();
1077        exec.track(
1078            h.id,
1079            PolicyApproval::mint(h.intent_hash, GasEnvelope::DEFAULT, u64::MAX),
1080        );
1081        let result = exec.bump(&mut h, 1000).await;
1082        assert!(matches!(result, Err(ExecutorError::Submission(_))));
1083        assert_eq!(submit.seen.lock().len(), 1); // the bump did attempt a broadcast
1084        // The mutation block was skipped: no phantom hash, signed still the original.
1085        assert_eq!(store.all()[0].broadcasts.len(), 1);
1086        assert_eq!(store.all()[0].signed, original);
1087    }
1088
1089    #[tokio::test]
1090    async fn repeated_bumps_across_ticks_append_broadcasts_at_the_same_nonce() {
1091        // Each stuck tick appends a broadcast (never overwrites) at a stable nonce/id —
1092        // the OZ/thirdweb stable-id contract; a bump never advances the lifecycle.
1093        let (exec, store, policy) = send_setup(Some(estimation(200, 1)));
1094        seed_and_track(&exec, &store, GasEnvelope::DEFAULT).await;
1095        for _ in 0..3 {
1096            exec.escalate().await.unwrap();
1097        }
1098        let h = &store.all()[0];
1099        assert_eq!(h.broadcasts.len(), 4); // original + one appended per tick
1100        assert_eq!(h.nonce, 4);
1101        assert_eq!(h.id, handle(4, TxStatus::Sent).id); // id stable across bumps
1102        assert_eq!(h.status, TxStatus::Sent);
1103        assert_eq!(*policy.calls.lock(), 0); // cached approval reused every round
1104    }
1105
1106    #[tokio::test]
1107    async fn newest_broadcast_receipt_wins_over_stale_older_hash() {
1108        // After an RBF bump, event_for scans broadcasts newest-first. Two cases pin it.
1109        use alloy_primitives::TxHash;
1110        use std::collections::HashMap;
1111        let h_old = TxHash::repeat_byte(0x11);
1112        let h_new = TxHash::repeat_byte(0x22);
1113        let canonical = B256::repeat_byte(0x88);
1114
1115        // Case A (ordering): both broadcasts have receipts at different blocks; the newer
1116        // (block 8) must win over the older (block 6). A forward scan would not confirm 8.
1117        let store = Arc::new(MockStore::default());
1118        let mut h = handle(4, TxStatus::Sent);
1119        h.broadcasts = vec![h_old, h_new];
1120        store.put_handle(&h).await.unwrap();
1121        Harness::default()
1122            .rpc(Arc::new(MockRpc {
1123                tx_count: 5,
1124                block_number: 20,
1125                canonical: Some(canonical),
1126                receipts: HashMap::from([
1127                    (h_old, receipt(true, 6, B256::repeat_byte(0x66))),
1128                    (h_new, receipt(true, 8, canonical)),
1129                ]),
1130                ..Default::default()
1131            }))
1132            .store(store.clone())
1133            .confirmations(2)
1134            .executor()
1135            .confirm()
1136            .await
1137            .unwrap();
1138        assert_eq!(store.all()[0].status, TxStatus::Confirmed { block: 8 });
1139
1140        // Case B (receipt beats nonce): our nonce is consumed (tx_count 5 > 4), which by
1141        // the nonce path alone reads as Replaced — but the bump's hash-anchored receipt
1142        // overrides that to a mined outcome.
1143        let store = Arc::new(MockStore::default());
1144        let mut h = handle(4, TxStatus::Sent);
1145        h.broadcasts = vec![h_old, h_new];
1146        store.put_handle(&h).await.unwrap();
1147        Harness::default()
1148            .rpc(Arc::new(MockRpc {
1149                tx_count: 5,
1150                block_number: 20,
1151                canonical: Some(canonical),
1152                receipts: HashMap::from([(h_new, receipt(true, 8, canonical))]),
1153                ..Default::default()
1154            }))
1155            .store(store.clone())
1156            .confirmations(2)
1157            .executor()
1158            .confirm()
1159            .await
1160            .unwrap();
1161        assert_eq!(store.all()[0].status, TxStatus::Confirmed { block: 8 });
1162    }
1163
1164    #[tokio::test]
1165    async fn bump_then_original_mines_bump_receipt_is_ignored_original_wins() {
1166        // RBF doesn't guarantee the bump wins: the newest (bump) broadcast is receiptless,
1167        // so the newest-first scan must `continue` past its Ok(None) to the older mined
1168        // original — not early-return Unknown/Replacing on the first receiptless hash.
1169        use alloy_primitives::TxHash;
1170        use std::collections::HashMap;
1171        let h_orig = TxHash::repeat_byte(0x11);
1172        let h_bump = TxHash::repeat_byte(0x22);
1173        let canonical = B256::repeat_byte(0x88);
1174        let store = Arc::new(MockStore::default());
1175        let mut h = handle(4, TxStatus::Sent);
1176        h.broadcasts = vec![h_orig, h_bump];
1177        store.put_handle(&h).await.unwrap();
1178        Harness::default()
1179            .rpc(Arc::new(MockRpc {
1180                tx_count: 5,
1181                block_number: 10,
1182                canonical: Some(canonical),
1183                receipts: HashMap::from([(h_orig, receipt(true, 8, canonical))]),
1184                ..Default::default()
1185            }))
1186            .store(store.clone())
1187            .confirmations(2)
1188            .executor()
1189            .confirm()
1190            .await
1191            .unwrap();
1192        assert_eq!(store.all()[0].status, TxStatus::Confirmed { block: 8 });
1193    }
1194
1195    #[tokio::test]
1196    async fn receipt_read_error_yields_unknown_holds_state() {
1197        // A transient receipt-RPC error must be a no-op (Unknown), never misread as "not
1198        // mined" — which would rewind a mined handle. The nonce is consumed (tx_count 5 >
1199        // 4), so the only thing preventing a state change is the Err->Unknown short-circuit.
1200        let h1 = B256::repeat_byte(1);
1201        let mined = TxStatus::Mined {
1202            block: 8,
1203            block_hash: h1,
1204        };
1205
1206        let store = Arc::new(MockStore::default());
1207        store.put_handle(&handle(4, mined.clone())).await.unwrap();
1208        Harness::default()
1209            .rpc(Arc::new(MockRpc {
1210                tx_count: 5,
1211                block_number: 20,
1212                receipt_err: true,
1213                ..Default::default()
1214            }))
1215            .store(store.clone())
1216            .confirmations(2)
1217            .executor()
1218            .confirm()
1219            .await
1220            .unwrap();
1221        assert_eq!(store.all()[0].status, mined); // unchanged
1222
1223        // Distinctness: same view, a clean None read instead lets the nonce path apply
1224        // (nonce 4 < 5 -> Replaced), so the Err path is observably different from None.
1225        let store = Arc::new(MockStore::default());
1226        store.put_handle(&handle(4, mined.clone())).await.unwrap();
1227        run_confirm(&store, 5, 20, None, None, 2).await;
1228        assert_eq!(
1229            store.all()[0].status,
1230            TxStatus::Replacing { since_block: 20 }
1231        );
1232    }
1233
1234    #[tokio::test]
1235    async fn stuck_cancel_bumps_via_cancel_request() {
1236        // Real engine, no rules: `Transaction` self-send default-denies, `Cancel` default-
1237        // allows. If `bump_approval` picks by shape, the RBF proceeds; a wrong pick wedges.
1238        use crate::adapters::SystemClock;
1239        use crate::adapters::policy::DefaultPolicyEngine;
1240        use crate::core::wallet::TxIntent;
1241        use alloy_primitives::{TxKind, U256};
1242
1243        let account = Address::ZERO;
1244        let self_send = TxIntent {
1245            chain_id: 1,
1246            account,
1247            to: TxKind::Call(account),
1248            value: U256::ZERO,
1249            input: Bytes::new(),
1250            purpose: None,
1251        };
1252        let intent_hash = self_send.hash();
1253        let mut h = handle(4, TxStatus::Sent);
1254        h.intent = self_send;
1255        h.intent_hash = intent_hash;
1256        h.id = HandleId::new(intent_hash, 4);
1257
1258        let store = Arc::new(MockStore::default());
1259        store.put_handle(&h).await.unwrap();
1260        let exec = Harness::default()
1261            .rpc(Arc::new(MockRpc {
1262                tx_count: 4,
1263                ..Default::default()
1264            }))
1265            .gas(Arc::new(MockGas {
1266                bump: Some(estimation(200, 1)),
1267                ..Default::default()
1268            }))
1269            .policy(Arc::new(DefaultPolicyEngine::new(
1270                vec![],
1271                Arc::new(SystemClock),
1272            )))
1273            .store(store.clone())
1274            .bump_timeout(0)
1275            .executor();
1276        exec.escalate().await.unwrap();
1277
1278        assert_eq!(store.all()[0].broadcasts.len(), 2);
1279    }
1280
1281    #[tokio::test]
1282    async fn receipt_missing_block_anchor_yields_unknown() {
1283        // A receipt with no block anchor (or only one of the two fields) is the
1284        // pending/partial shape: anchor()'s tuple-destructure guard makes it Unknown and
1285        // holds state. `canonical` is set to a hash that would confirm, so only the guard
1286        // prevents a transition.
1287        let mut half = receipt(true, 8, B256::repeat_byte(1));
1288        half.block_hash = None; // block_number Some, block_hash None
1289        for r in [receipt_unanchored(), half] {
1290            let store = Arc::new(MockStore::default());
1291            store.put_handle(&handle(4, TxStatus::Sent)).await.unwrap();
1292            run_confirm(&store, 4, 20, Some(r), Some(B256::repeat_byte(1)), 2).await;
1293            assert_eq!(store.all()[0].status, TxStatus::Sent);
1294        }
1295    }
1296}