Skip to main content

walletkit/core/wallet/
transaction_manager.rs

1//! `TransactionManager` — the one-shot send pipeline: it turns a [`TxIntent`] into
2//! a broadcast transaction plus a persisted, queryable [`TxHandle`]. Tracking,
3//! bumping, and reorg handling are the executor's job; this is the fixed-order build
4//! path, reusing alloy for all tx mechanics.
5
6use super::signing;
7use crate::core::deps::{
8    Clock, GasOracle, GasOracleError, NonceManager, NonceManagerError, PolicyEngine,
9    PolicyEngineError, Rpc, RpcError, Signer, SignerError, StateStore, StateStoreError,
10    SubmissionError, SubmissionStrategy,
11};
12use crate::core::wallet::{
13    Decision, HandleId, IntentHash, PolicyApproval, PolicyRejection, SignatureEnvelope,
14    SigningRequest, TxHandle, TxIntent, TxStatus,
15};
16use crate::obs::{debug, error, info, warn};
17use alloy_dyn_abi::TypedData;
18use alloy_eips::eip1559::Eip1559Estimation;
19use alloy_primitives::{Address, Bytes, TxKind, U256};
20use alloy_rpc_types_eth::{TransactionInput, TransactionRequest};
21use std::sync::Arc;
22
23/// Gas-limit buffer over `eth_estimateGas`. viem/ethers trust the raw estimate, but it
24/// can underestimate for gas-forwarding / failure-swallowing contracts (geth #21746,
25/// the 63/64 rule) and state drifts before inclusion; over-provisioning is ~free
26/// (EIP-1559 refunds unused gas) while underestimating burns a reverted tx. Tunable
27/// via [`TransactionManager::with_gas_buffer_pct`]. Percent.
28const DEFAULT_GAS_BUFFER_PCT: u128 = 25;
29
30/// Gas for a cancel self-send — the exact base tx cost (0-value, empty calldata), so it
31/// needs no estimation (Yellow Paper G_transaction).
32const CANCEL_GAS_LIMIT: u64 = 21_000;
33
34/// Staged send pipeline: policy → nonce → gas → sign → submit → persist, plus cancel
35/// and bump. Wraps the ports; the [`Wallet`](crate::Wallet) facade drives it.
36pub struct TransactionManager {
37    rpc: Arc<dyn Rpc>,
38    gas_oracle: Arc<dyn GasOracle>,
39    policy: Arc<dyn PolicyEngine>,
40    nonce_manager: Arc<dyn NonceManager>,
41    signer: Arc<dyn Signer>,
42    submission: Arc<dyn SubmissionStrategy>,
43    state_store: Arc<dyn StateStore>,
44    clock: Arc<dyn Clock>,
45    gas_buffer_pct: u128,
46}
47
48impl TransactionManager {
49    /// Wire the pipeline from its ports (`gas_buffer_pct` pads the estimated gas limit).
50    #[allow(clippy::too_many_arguments)]
51    pub fn new(
52        rpc: Arc<dyn Rpc>,
53        gas_oracle: Arc<dyn GasOracle>,
54        policy: Arc<dyn PolicyEngine>,
55        nonce_manager: Arc<dyn NonceManager>,
56        signer: Arc<dyn Signer>,
57        submission: Arc<dyn SubmissionStrategy>,
58        state_store: Arc<dyn StateStore>,
59        clock: Arc<dyn Clock>,
60    ) -> Self {
61        Self {
62            rpc,
63            gas_oracle,
64            policy,
65            nonce_manager,
66            signer,
67            submission,
68            state_store,
69            clock,
70            gas_buffer_pct: DEFAULT_GAS_BUFFER_PCT,
71        }
72    }
73
74    /// Override the gas-limit buffer (percent). Lower it for cost-sensitive,
75    /// well-estimated txs; raise it for gas-forwarding contracts (see the const).
76    pub fn with_gas_buffer_pct(mut self, pct: u128) -> Self {
77        self.gas_buffer_pct = pct;
78        self
79    }
80
81    /// Sign an EIP-191 `personal_sign` message through the policy gate. Blind signing is
82    /// impossible: the message is `0x19`-prefixed and default-denied unless a rule allows it.
83    /// `skip_all` is mandatory — only the safe `payload_hash` is recorded, never the message.
84    #[cfg_attr(
85        feature = "tracing",
86        tracing::instrument(
87            name = "sign_message",
88            level = "debug",
89            skip_all,
90            fields(payload_hash = %alloy_primitives::eip191_hash_message(message))
91        )
92    )]
93    pub async fn sign_message(
94        &self,
95        message: &[u8],
96    ) -> Result<SignatureEnvelope, TransactionManagerError> {
97        let request = SigningRequest::Message(Bytes::copy_from_slice(message));
98        let approval = self.authorize(&request).await?;
99        Ok(self
100            .signer
101            .sign_message(message, &approval, self.clock.now_unix())
102            .await?)
103    }
104
105    /// Sign EIP-712 typed data through the policy gate (domain `chainId` validated in the
106    /// signer). A domain not on an allowlisted `verifyingContract` is default-denied.
107    /// `skip_all` keeps the typed-data content out of telemetry; only the hash is recorded.
108    #[cfg_attr(
109        feature = "tracing",
110        tracing::instrument(
111            name = "sign_typed_data",
112            level = "debug",
113            skip_all,
114            fields(payload_hash = ?typed.eip712_signing_hash().ok())
115        )
116    )]
117    pub async fn sign_typed_data(
118        &self,
119        typed: &TypedData,
120    ) -> Result<SignatureEnvelope, TransactionManagerError> {
121        let request = SigningRequest::TypedData(Box::new(typed.clone()));
122        let approval = self.authorize(&request).await?;
123        Ok(self
124            .signer
125            .sign_typed_data(typed, &approval, self.clock.now_unix())
126            .await?)
127    }
128
129    /// Run the policy gate for a signing request, returning the minted approval or a denial.
130    async fn authorize(
131        &self,
132        request: &SigningRequest,
133    ) -> Result<PolicyApproval, TransactionManagerError> {
134        match self.policy.evaluate(request).await? {
135            Decision::Allow(approval) => Ok(approval),
136            Decision::Deny(rejection) => Err(TransactionManagerError::Denied(rejection)),
137        }
138    }
139
140    /// Estimate (also the pre-sign revert gate) → fees → policy → allocate → build →
141    /// sign → persist → submit. A nonce is allocated only after policy Allow and
142    /// released if any later step fails, so a denied or failed send never leaves a gap.
143    #[cfg_attr(
144        feature = "tracing",
145        tracing::instrument(
146            name = "wallet.send",
147            level = "info",
148            skip_all,
149            fields(intent_hash = ?intent.hash(), account = %intent.account, chain_id = intent.chain_id)
150        )
151    )]
152    pub async fn send(&self, intent: &TxIntent) -> Result<TxHandle, TransactionManagerError> {
153        let account = intent.account;
154        // The nonce is allocated for `account`; signing with a different key would put
155        // it on the wrong sender. Fail before touching the chain or a nonce.
156        let signer = self.signer.address();
157        if signer != account {
158            return Err(TransactionManagerError::AccountMismatch {
159                intent: account,
160                signer,
161            });
162        }
163        let request = TransactionRequest {
164            from: Some(account),
165            to: Some(intent.to),
166            value: Some(intent.value),
167            input: TransactionInput::new(intent.input.clone()),
168            ..Default::default()
169        };
170
171        // estimate_gas executes the tx, so it doubles as the pre-sign revert gate: a
172        // deterministic failure means it would revert (a transient one is retryable).
173        let gas_limit = match self.rpc.estimate_gas(&request).await {
174            Ok(gas) => self.buffered_gas(gas),
175            Err(RpcError::Call {
176                transient: false,
177                message,
178            }) => return Err(TransactionManagerError::SimulationRejected { reason: message }),
179            Err(e) => return Err(e.into()),
180        };
181        let fees = self.gas_oracle.estimate().await?;
182
183        let request = SigningRequest::Transaction(intent.clone());
184        let approval = match self.policy.evaluate(&request).await? {
185            Decision::Allow(approval) => approval,
186            Decision::Deny(rejection) => return Err(TransactionManagerError::Denied(rejection)),
187        };
188
189        let nonce = self.nonce_manager.allocate(account).await?;
190        debug!(nonce, "nonce allocated");
191        // `build_sign_submit` owns the nonce lifecycle: it recycles the nonce only when
192        // nothing was broadcast, so a live tx's nonce is never freed for reuse.
193        self.build_sign_submit(intent, gas_limit, fees, nonce, approval)
194            .await
195    }
196
197    /// Cancel a pending tx: a policy-gated 0-value self-send at its nonce (RBF). Errors if
198    /// the tx already settled; the original settles as `Dropped` once the cancel mines.
199    #[cfg_attr(
200        feature = "tracing",
201        tracing::instrument(name = "wallet.cancel", level = "info", skip_all, fields(id = ?id))
202    )]
203    pub async fn cancel(&self, id: HandleId) -> Result<TxHandle, TransactionManagerError> {
204        let mut target = self
205            .state_store
206            .handle(id)
207            .await?
208            .ok_or(TransactionManagerError::UnknownHandle)?;
209        if target.status.is_terminal() {
210            return Err(TransactionManagerError::CancelTerminal);
211        }
212        let account = target.account;
213        let intent = TxIntent {
214            chain_id: target.intent.chain_id,
215            account,
216            to: TxKind::Call(account),
217            value: U256::ZERO,
218            input: Bytes::new(),
219            purpose: None,
220        };
221        let intent_hash = intent.hash();
222        let approval = self
223            .authorize(&SigningRequest::Cancel(intent.clone()))
224            .await?;
225
226        // Persist cancelled=true before broadcasting: any consumption of this nonce settles
227        // the original Dropped, regardless of what the submit does.
228        target.cancelled = true;
229        self.state_store.put_handle(&target).await?;
230
231        let now = self.clock.now_unix();
232        let basis = fee_basis(&target.signed)?;
233        let signed = match self
234            .broadcast_cancel_with_repricing(&target, &intent, intent_hash, basis, &approval, now)
235            .await
236        {
237            Ok(signed) => signed,
238            // The cancel never broadcast — un-poison the target so a later foreign displacement
239            // settles it `Replaced` (refillable), not a spurious `Dropped`.
240            Err(e) => {
241                target.cancelled = false;
242                let _ = self.state_store.put_handle(&target).await;
243                return Err(e);
244            }
245        };
246
247        let cancel = TxHandle {
248            id: HandleId::new(intent_hash, target.nonce),
249            account,
250            intent,
251            intent_hash,
252            nonce: target.nonce,
253            status: TxStatus::Sent,
254            envelope: approval.gas_envelope(),
255            signed: signed.rlp,
256            broadcasts: vec![signed.hash],
257            last_broadcast_at: now,
258            cancelled: false,
259        };
260        self.state_store.put_handle(&cancel).await?;
261        info!(nonce = target.nonce, "cancel submitted");
262        Ok(cancel)
263    }
264
265    /// Sign and submit the cancel at `basis`; on `replacement transaction underpriced`
266    /// (target re-priced concurrently) re-fetch its fees and resend once. `already known`
267    /// / `nonce too low` count as success (the tx is already in the pool).
268    async fn broadcast_cancel_with_repricing(
269        &self,
270        target: &TxHandle,
271        intent: &TxIntent,
272        intent_hash: IntentHash,
273        mut basis: Eip1559Estimation,
274        approval: &PolicyApproval,
275        now: u64,
276    ) -> Result<signing::SignedTx, TransactionManagerError> {
277        let mut attempts = 0u8;
278        loop {
279            let fees = self.gas_oracle.bump(basis).await?;
280            let tx = signing::build_tx(intent, target.nonce, CANCEL_GAS_LIMIT, fees);
281            let signed =
282                signing::sign_encode(&*self.signer, tx, intent_hash, approval, now).await?;
283            match self.submission.submit(signed.rlp.clone()).await {
284                Ok(_) => return Ok(signed),
285                Err(e) if e.is_already_accepted() => return Ok(signed),
286                Err(e) if e.is_underpriced() && attempts == 0 => {
287                    attempts += 1;
288                    let fresh = self
289                        .state_store
290                        .handle(target.id)
291                        .await?
292                        .ok_or(TransactionManagerError::UnknownHandle)?;
293                    basis = fee_basis(&fresh.signed)?;
294                    warn!(
295                        nonce = target.nonce,
296                        "cancel underpriced; re-basing over the target"
297                    );
298                }
299                Err(e) => return Err(e.into()),
300            }
301        }
302    }
303
304    async fn build_sign_submit(
305        &self,
306        intent: &TxIntent,
307        gas_limit: u64,
308        fees: Eip1559Estimation,
309        nonce: u64,
310        approval: PolicyApproval,
311    ) -> Result<TxHandle, TransactionManagerError> {
312        let account = intent.account;
313        let intent_hash = intent.hash();
314        let now = self.clock.now_unix();
315        let tx = signing::build_tx(intent, nonce, gas_limit, fees);
316        // Pre-broadcast failure (sign): nothing was sent, so recycle the nonce.
317        let signed =
318            match signing::sign_encode(&*self.signer, tx, intent_hash, &approval, now).await {
319                Ok(out) => out,
320                Err(e) => {
321                    let _ = self.nonce_manager.release(account, nonce).await;
322                    return Err(e.into());
323                }
324            };
325
326        let mut handle = TxHandle {
327            id: HandleId::new(intent_hash, nonce),
328            account,
329            intent: intent.clone(),
330            intent_hash,
331            nonce,
332            status: TxStatus::Pending,
333            // The originally-approved ceiling; a later bump must never exceed it.
334            envelope: approval.gas_envelope(),
335            signed: signed.rlp.clone(),
336            broadcasts: vec![signed.hash],
337            last_broadcast_at: now,
338            cancelled: false,
339        };
340        // Persist the signed tx before broadcast (WAL). A pre-broadcast persist failure
341        // means nothing was sent -> recycle the nonce.
342        if let Err(e) = self.state_store.put_handle(&handle).await {
343            let _ = self.nonce_manager.release(account, nonce).await;
344            return Err(e.into());
345        }
346
347        match self.submission.submit(signed.rlp).await {
348            Ok(_) => {}
349            // Transient (may be in flight) or already-accepted ("already known"/"nonce
350            // too low" -> already sent/mined): assume sent — keep the nonce reserved
351            // (releasing could reuse a live nonce -> double spend) and let recover()/
352            // confirm() settle it.
353            Err(e) if e.is_transient() || e.is_already_accepted() => {
354                handle.status = TxStatus::Sent;
355                let _ = self.state_store.put_handle(&handle).await;
356                warn!(nonce, "submission indeterminate; assuming sent");
357                return Ok(handle);
358            }
359            // Deterministic reject: definitely not broadcast -> terminalize + recycle.
360            Err(e) => {
361                handle.status = TxStatus::Failed {
362                    reason: e.to_string(),
363                };
364                let _ = self.state_store.put_handle(&handle).await;
365                let _ = self.nonce_manager.release(account, nonce).await;
366                error!(error = %e, nonce, "submission rejected; nonce recycled");
367                return Err(e.into());
368            }
369        }
370
371        // Broadcast confirmed. Reflect Sent; a persist failure here must NOT release the
372        // nonce — the tx is live, and freeing its nonce would enable reuse.
373        handle.status = TxStatus::Sent;
374        let _ = self.state_store.put_handle(&handle).await;
375        info!(tx_hash = ?signed.hash, nonce, "transaction submitted");
376        Ok(handle)
377    }
378
379    fn buffered_gas(&self, estimate: u64) -> u64 {
380        let buffered = (estimate as u128).saturating_mul(100 + self.gas_buffer_pct) / 100;
381        buffered.min(u64::MAX as u128) as u64
382    }
383}
384
385/// The target's own fees, so `gas_oracle.bump` clears geth's +10% RBF floor. `None` from
386/// `decode_fees` (non-1559 or undecodable) is terminal — nothing to bump against.
387fn fee_basis(signed: &Bytes) -> Result<Eip1559Estimation, TransactionManagerError> {
388    signing::decode_fees(signed)
389        .map(|f| f.fees)
390        .ok_or(TransactionManagerError::CancelTerminal)
391}
392
393/// Why a send/cancel/bump through the pipeline failed.
394#[derive(Debug, thiserror::Error)]
395#[non_exhaustive]
396pub enum TransactionManagerError {
397    /// The signer's address does not control the intent's account.
398    #[error("signer {signer} does not control the intent account {intent}")]
399    AccountMismatch {
400        /// The intent's declared account.
401        intent: Address,
402        /// The signer's actual address.
403        signer: Address,
404    },
405    /// Pre-send simulation rejected the intent (it would revert).
406    #[error("simulation rejected: {reason}")]
407    SimulationRejected {
408        /// The decoded revert/rejection reason.
409        reason: String,
410    },
411    /// No tracked transaction matches the given handle id.
412    #[error("no tracked transaction for this handle id")]
413    UnknownHandle,
414    /// The transaction already reached a terminal state — nothing to cancel.
415    #[error("the transaction already settled — nothing to cancel")]
416    CancelTerminal,
417    /// Policy denied the intent.
418    #[error(transparent)]
419    Denied(PolicyRejection),
420    /// An RPC call failed.
421    #[error(transparent)]
422    Rpc(#[from] RpcError),
423    /// Fee estimation/bumping failed.
424    #[error(transparent)]
425    Gas(#[from] GasOracleError),
426    /// Policy evaluation failed operationally.
427    #[error(transparent)]
428    Policy(#[from] PolicyEngineError),
429    /// Nonce allocation/reconciliation failed.
430    #[error(transparent)]
431    Nonce(#[from] NonceManagerError),
432    /// Signing failed.
433    #[error(transparent)]
434    Signer(#[from] SignerError),
435    /// A durable-store operation failed.
436    #[error(transparent)]
437    Store(#[from] StateStoreError),
438    /// Broadcasting failed.
439    #[error(transparent)]
440    Submission(#[from] SubmissionError),
441}
442
443#[cfg(test)]
444mod tests {
445    use super::*;
446    use crate::testutils::{
447        CallLog, Harness, MockGas, MockNonce, MockPolicy, MockRpc, MockSigner, MockStore,
448        MockSubmit, Submit, intent, shared_log,
449    };
450    use alloy_primitives::address;
451
452    /// Wires the pipeline sharing one call log across the mocks so a test can assert
453    /// the exact stage order.
454    fn manager(
455        allow: bool,
456        estimate_ok: bool,
457        sign_ok: bool,
458        submit: Submit,
459    ) -> (TransactionManager, CallLog) {
460        let l = shared_log();
461        let tm = Harness::default()
462            .rpc(Arc::new(MockRpc {
463                gas_reverts: !estimate_ok,
464                log: l.clone(),
465                ..Default::default()
466            }))
467            .gas(Arc::new(MockGas {
468                log: l.clone(),
469                ..Default::default()
470            }))
471            .policy(Arc::new(MockPolicy {
472                allow,
473                log: l.clone(),
474                ..Default::default()
475            }))
476            .nonce(Arc::new(MockNonce {
477                next: 7,
478                log: l.clone(),
479            }))
480            .signer(Arc::new(MockSigner {
481                ok: sign_ok,
482                log: l.clone(),
483                ..Default::default()
484            }))
485            .submit(Arc::new(MockSubmit {
486                outcome: submit,
487                log: l.clone(),
488                ..Default::default()
489            }))
490            .store(Arc::new(MockStore::logged(l.clone())))
491            .manager();
492        (tm, l)
493    }
494
495    #[tokio::test]
496    async fn happy_path_runs_stages_in_order_and_returns_a_handle() {
497        let (tm, l) = manager(true, true, true, Submit::Ok);
498        let handle = tm.send(&intent()).await.unwrap();
499        assert_eq!(
500            *l.lock(),
501            [
502                "estimate_gas",
503                "fees",
504                "policy",
505                "allocate",
506                "sign",
507                "persist", // WAL before broadcast
508                "submit",
509                "persist", // status -> Sent after broadcast
510            ]
511        );
512        assert_eq!(handle.status, TxStatus::Sent);
513        assert_eq!(handle.nonce, 7);
514        assert_eq!(handle.broadcasts.len(), 1);
515    }
516
517    #[tokio::test]
518    async fn policy_deny_aborts_before_allocating_a_nonce() {
519        let (tm, l) = manager(false, true, true, Submit::Ok);
520        assert!(matches!(
521            tm.send(&intent()).await,
522            Err(TransactionManagerError::Denied(_))
523        ));
524        assert!(!l.lock().contains(&"allocate"));
525    }
526
527    #[tokio::test]
528    async fn estimate_revert_aborts_before_signing() {
529        let (tm, l) = manager(true, false, true, Submit::Ok);
530        assert!(matches!(
531            tm.send(&intent()).await,
532            Err(TransactionManagerError::SimulationRejected { .. })
533        ));
534        let seen = l.lock();
535        assert!(!seen.contains(&"sign") && !seen.contains(&"allocate"));
536    }
537
538    #[tokio::test]
539    async fn send_rejects_when_signer_does_not_control_the_account() {
540        let (tm, l) = manager(true, true, true, Submit::Ok); // signer address is ZERO
541        let mut mismatched = intent();
542        mismatched.account = address!("0x00000000000000000000000000000000000000bb");
543        assert!(matches!(
544            tm.send(&mismatched).await,
545            Err(TransactionManagerError::AccountMismatch { .. })
546        ));
547        assert!(l.lock().is_empty()); // aborts before any RPC
548    }
549
550    #[tokio::test]
551    async fn transient_submit_failure_assumes_sent_and_keeps_the_nonce() {
552        // Indeterminate submit (may be in-flight) -> assume sent: Ok, Sent, nonce NOT released.
553        let (tm, l) = manager(true, true, true, Submit::Transient);
554        let handle = tm.send(&intent()).await.unwrap();
555        assert_eq!(handle.status, TxStatus::Sent);
556        assert!(!l.lock().contains(&"release"));
557    }
558
559    #[tokio::test]
560    async fn deterministic_submit_reject_releases_the_nonce() {
561        // Definitely not broadcast -> terminalize + recycle the nonce.
562        let (tm, l) = manager(true, true, true, Submit::Deterministic);
563        assert!(matches!(
564            tm.send(&intent()).await,
565            Err(TransactionManagerError::Submission(_))
566        ));
567        let seen = l.lock();
568        assert!(seen.contains(&"allocate") && seen.contains(&"release"));
569    }
570
571    #[tokio::test]
572    async fn already_known_submit_assumes_sent_and_keeps_the_nonce() {
573        // "already known"/"nonce too low" == already accepted -> Sent, nonce NOT released.
574        let (tm, l) = manager(true, true, true, Submit::AlreadyKnown);
575        let handle = tm.send(&intent()).await.unwrap();
576        assert_eq!(handle.status, TxStatus::Sent);
577        assert!(!l.lock().contains(&"release"));
578    }
579
580    #[tokio::test]
581    async fn sign_failure_recycles_the_nonce_so_the_next_send_reuses_it() {
582        // A pre-broadcast sign failure must release the allocated nonce, so the next send
583        // reuses it with no gap. Proven end-to-end against the real allocator + a shared
584        // store (only the signer differs): without the release branch the retry would
585        // allocate 6, not 5.
586        use crate::adapters::{InMemoryStateStore, LocalNonceManager};
587        let store = Arc::new(InMemoryStateStore::default());
588        let rpc = Arc::new(MockRpc {
589            pending_nonce: 5,
590            ..Default::default()
591        });
592        let nonce = Arc::new(LocalNonceManager::new(store.clone(), rpc.clone()));
593        let build = |sign_ok: bool| {
594            Harness::default()
595                .rpc(rpc.clone())
596                .nonce(nonce.clone())
597                .store(store.clone())
598                .signer(Arc::new(MockSigner {
599                    ok: sign_ok,
600                    ..Default::default()
601                }))
602                .manager()
603        };
604
605        // First send: sign fails after allocating nonce 5 -> release it.
606        let failed = build(false).send(&intent()).await;
607        assert!(matches!(failed, Err(TransactionManagerError::Signer(_))));
608
609        // Second send: the freed nonce 5 is reused (no gap), not 6.
610        let recovered = build(true).send(&intent()).await.unwrap();
611        assert_eq!(recovered.nonce, 5);
612    }
613
614    // --- cancel(id) ---
615
616    #[tokio::test]
617    async fn cancel_on_terminal_handle_errors() {
618        use crate::testutils::handle;
619        let store = Arc::new(MockStore::default());
620        let done = handle(5, TxStatus::Confirmed { block: 12 });
621        store.put_handle(&done).await.unwrap();
622        let tm = Harness::default().store(store).manager();
623
624        assert!(matches!(
625            tm.cancel(done.id).await,
626            Err(TransactionManagerError::CancelTerminal)
627        ));
628    }
629}