1use 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
23const DEFAULT_GAS_BUFFER_PCT: u128 = 25;
29
30const CANCEL_GAS_LIMIT: u64 = 21_000;
33
34pub 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 #[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 pub fn with_gas_buffer_pct(mut self, pct: u128) -> Self {
77 self.gas_buffer_pct = pct;
78 self
79 }
80
81 #[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 #[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 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 #[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 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 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 self.build_sign_submit(intent, gas_limit, fees, nonce, approval)
194 .await
195 }
196
197 #[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 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 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 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 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 envelope: approval.gas_envelope(),
335 signed: signed.rlp.clone(),
336 broadcasts: vec![signed.hash],
337 last_broadcast_at: now,
338 cancelled: false,
339 };
340 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 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 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 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
385fn 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#[derive(Debug, thiserror::Error)]
395#[non_exhaustive]
396pub enum TransactionManagerError {
397 #[error("signer {signer} does not control the intent account {intent}")]
399 AccountMismatch {
400 intent: Address,
402 signer: Address,
404 },
405 #[error("simulation rejected: {reason}")]
407 SimulationRejected {
408 reason: String,
410 },
411 #[error("no tracked transaction for this handle id")]
413 UnknownHandle,
414 #[error("the transaction already settled — nothing to cancel")]
416 CancelTerminal,
417 #[error(transparent)]
419 Denied(PolicyRejection),
420 #[error(transparent)]
422 Rpc(#[from] RpcError),
423 #[error(transparent)]
425 Gas(#[from] GasOracleError),
426 #[error(transparent)]
428 Policy(#[from] PolicyEngineError),
429 #[error(transparent)]
431 Nonce(#[from] NonceManagerError),
432 #[error(transparent)]
434 Signer(#[from] SignerError),
435 #[error(transparent)]
437 Store(#[from] StateStoreError),
438 #[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 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", "submit",
509 "persist", ]
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); 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()); }
549
550 #[tokio::test]
551 async fn transient_submit_failure_assumes_sent_and_keeps_the_nonce() {
552 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 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 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 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 let failed = build(false).send(&intent()).await;
607 assert!(matches!(failed, Err(TransactionManagerError::Signer(_))));
608
609 let recovered = build(true).send(&intent()).await.unwrap();
611 assert_eq!(recovered.nonce, 5);
612 }
613
614 #[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}