1mod 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
29const DEFAULT_REQUIRED_CONFIRMATIONS: u64 = 12;
32
33const DEFAULT_BUMP_TIMEOUT_SECS: u64 = 30;
36
37struct Cycle {
40 view: ChainView,
41 finality: FinalityConfig,
42 mined_nonce: u64,
43}
44
45pub 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 refill: Option<Arc<TransactionManager>>,
64 approvals: Mutex<HashMap<HandleId, PolicyApproval>>,
68 last_latest: AtomicU64,
71}
72
73impl AccountExecutor {
74 #[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 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 pub fn with_confirmations(mut self, depth: u64) -> Self {
114 self.required_confirmations = depth;
115 self
116 }
117
118 pub fn with_bump_timeout(mut self, secs: u64) -> Self {
120 self.bump_timeout = secs;
121 self
122 }
123
124 pub fn with_refill(mut self, manager: Arc<TransactionManager>) -> Self {
127 self.refill = Some(manager);
128 self
129 }
130
131 pub fn track(&self, handle: HandleId, approval: PolicyApproval) {
135 self.approvals.lock().insert(handle, approval);
136 }
137
138 #[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 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 pub async fn confirm(&self) -> Result<(), ExecutorError> {
168 let Some(cycle) = self.read_cycle().await? else {
169 return Ok(()); };
171 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 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 if self.state_store.put_handle(&handle).await.is_ok() && handle.status.is_terminal() {
198 self.approvals.lock().remove(&handle.id);
199 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 async fn refill_intent(&self, manager: &TransactionManager, handle: &TxHandle) {
215 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 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 async fn event_for(&self, handle: &TxHandle, mined: u64) -> ChainEvent {
256 for hash in handle.broadcasts.iter().rev() {
258 match self.rpc.receipt(*hash).await {
259 Ok(None) => continue, Ok(Some(receipt)) => return self.anchor(receipt).await,
261 Err(_) => return ChainEvent::Unknown,
262 }
263 }
264 match handle.nonce < mined {
265 true => ChainEvent::Replaced, false => ChainEvent::Pending, }
268 }
269
270 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 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 if handle.nonce < self.rpc.tx_count(self.account).await? {
318 return Ok(());
319 }
320 let Some(current) = signing::decode_fees(&handle.signed) else {
322 return Ok(()); };
324 let bumped = match self.gas_oracle.bump(current.fees).await {
325 Ok(fees) => fees,
326 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 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(()); };
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 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 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 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#[derive(Debug, thiserror::Error)]
405#[non_exhaustive]
406pub enum ExecutorError {
407 #[error(transparent)]
409 Rpc(#[from] RpcError),
410 #[error(transparent)]
412 Gas(#[from] GasOracleError),
413 #[error(transparent)]
415 Policy(#[from] PolicyEngineError),
416 #[error(transparent)]
418 Nonce(#[from] NonceManagerError),
419 #[error(transparent)]
421 Signer(#[from] SignerError),
422 #[error(transparent)]
424 Store(#[from] StateStoreError),
425 #[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 #[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 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); 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 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()); let seen = submit.seen.lock();
514 assert_eq!(seen.len(), 2); 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 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 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 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 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); }
618
619 #[tokio::test]
620 async fn freed_nonce_un_mines_a_tentative_handle() {
621 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 run_confirm(&store, 5, 10, None, None, 3).await;
644 assert_eq!(
645 store.all()[0].status,
646 TxStatus::Replacing { since_block: 10 } );
648 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 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 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 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 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 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, 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); let resets = log.lock().iter().filter(|e| **e == "reset").count();
737 assert_eq!(resets, 1); }
739
740 #[tokio::test]
741 async fn inconsistent_view_skips_the_cycle() {
742 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), 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); }
763
764 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 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 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; exec.escalate().await.unwrap();
857 assert_eq!(store.all()[0].broadcasts.len(), 2); assert_eq!(*policy.calls.lock(), 0); }
860
861 #[tokio::test]
862 async fn bump_beyond_approved_envelope_stops() {
863 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; 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 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); assert_eq!(*policy.calls.lock(), 1); }
891
892 #[tokio::test]
893 async fn bump_stops_at_gas_ceiling() {
894 let (exec, store, policy) = send_setup(None); seed_and_track(&exec, &store, GasEnvelope::DEFAULT).await;
896 exec.escalate().await.unwrap();
897 assert_eq!(store.all()[0].broadcasts.len(), 1); 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 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 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 let store = Arc::new(MockStore::default());
946 let exec = Harness::default()
947 .rpc(Arc::new(MockRpc {
948 tx_count: 5, ..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); }
968
969 #[tokio::test]
970 async fn bump_denied_by_fresh_policy_leaves_the_tx() {
971 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 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 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 assert_eq!(*policy.calls.lock(), 1);
1005 }
1006
1007 #[tokio::test]
1008 async fn bump_exactly_at_envelope_ceiling_is_admitted() {
1009 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); assert_eq!(*policy.calls.lock(), 0); }
1022
1023 #[tokio::test]
1024 async fn decode_fees_leaves_a_non_1559_signed_tx_unbumped() {
1025 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); assert_eq!(h.status, TxStatus::Sent);
1034 assert_eq!(*policy.calls.lock(), 0); }
1036
1037 #[tokio::test]
1038 async fn decode_fees_leaves_a_handle_with_undecodable_signed_bytes() {
1039 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 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); 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 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); assert_eq!(h.nonce, 4);
1101 assert_eq!(h.id, handle(4, TxStatus::Sent).id); assert_eq!(h.status, TxStatus::Sent);
1103 assert_eq!(*policy.calls.lock(), 0); }
1105
1106 #[tokio::test]
1107 async fn newest_broadcast_receipt_wins_over_stale_older_hash() {
1108 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 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 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 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 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); 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 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 let mut half = receipt(true, 8, B256::repeat_byte(1));
1288 half.block_hash = None; 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}