1use std::sync::Arc;
30
31use indexmap::IndexMap;
32use moonproof_macros::async_trait;
33use moonproof_utils::EventBus;
34use serde::{Deserialize, Serialize};
35use tokio::sync::{broadcast, RwLock};
36
37use crate::abstractions::ProtocolVersion;
38use crate::error::{Result, WalletError};
39
40pub type TransactionHash = String;
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
46#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
47pub enum TransactionHistoryStatus {
48 Success,
49 Failure,
50 PartialSuccess,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct TransactionHistoryEntry {
61 pub hash: TransactionHash,
63 pub protocol_version: ProtocolVersion,
68 pub status: TransactionHistoryStatus,
69 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub identifiers: Option<Vec<String>>,
73 #[serde(default, skip_serializing_if = "Option::is_none")]
75 pub timestamp_ms: Option<i64>,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub fees: Option<u128>,
81 #[serde(default, skip_serializing_if = "Option::is_none")]
84 pub shielded: Option<serde_json::Value>,
85 #[serde(default, skip_serializing_if = "Option::is_none")]
87 pub unshielded: Option<serde_json::Value>,
88 #[serde(default, skip_serializing_if = "Option::is_none")]
90 pub dust: Option<serde_json::Value>,
91 #[serde(default, skip_serializing_if = "serde_json::Value::is_null")]
95 pub extra: serde_json::Value,
96}
97
98impl TransactionHistoryEntry {
99 pub fn merge(&mut self, incoming: Self) {
107 debug_assert_eq!(self.hash, incoming.hash);
110 self.protocol_version = incoming.protocol_version;
111 self.status = incoming.status;
112 if incoming.identifiers.is_some() {
113 self.identifiers = incoming.identifiers;
114 }
115 if incoming.timestamp_ms.is_some() {
116 self.timestamp_ms = incoming.timestamp_ms;
117 }
118 if incoming.fees.is_some() {
119 self.fees = incoming.fees;
120 }
121 if incoming.shielded.is_some() {
122 self.shielded = incoming.shielded;
123 }
124 if incoming.unshielded.is_some() {
125 self.unshielded = incoming.unshielded;
126 }
127 if incoming.dust.is_some() {
128 self.dust = incoming.dust;
129 }
130 match (&mut self.extra, incoming.extra) {
131 (serde_json::Value::Object(existing_map), serde_json::Value::Object(incoming_map)) => {
132 for (k, v) in incoming_map {
133 existing_map.insert(k, v);
134 }
135 }
136 (slot, incoming) if !incoming.is_null() => {
137 *slot = incoming;
138 }
139 _ => {}
140 }
141 }
142}
143
144#[async_trait]
148pub trait TransactionHistoryStorage: Send + Sync + std::fmt::Debug {
149 async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()>;
150 async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>>;
151 async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>>;
152 async fn remove(&self, hash: &str) -> Result<()>;
153 async fn clear(&self) -> Result<()>;
154 async fn serialize(&self) -> Result<String> {
158 let all = self.get_all().await?;
159 serde_json::to_string(&all)
160 .map_err(|e| WalletError::Serialization(format!("encode tx history: {e}")))
161 }
162}
163
164#[async_trait]
165impl<T: TransactionHistoryStorage + ?Sized> TransactionHistoryStorage for Arc<T> {
166 async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()> {
167 (**self).upsert(entry).await
168 }
169 async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>> {
170 (**self).get(hash).await
171 }
172 async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
173 (**self).get_all().await
174 }
175 async fn remove(&self, hash: &str) -> Result<()> {
176 (**self).remove(hash).await
177 }
178 async fn clear(&self) -> Result<()> {
179 (**self).clear().await
180 }
181}
182
183#[derive(Debug, Clone, Default)]
189pub struct InMemoryTransactionHistoryStorage {
190 inner: Arc<RwLock<IndexMap<TransactionHash, TransactionHistoryEntry>>>,
191}
192
193impl InMemoryTransactionHistoryStorage {
194 #[must_use]
195 pub fn new() -> Self {
196 Self::default()
197 }
198
199 pub fn restore(serialized: &str) -> Result<Self> {
203 let entries: Vec<TransactionHistoryEntry> = serde_json::from_str(serialized)
204 .map_err(|e| WalletError::Serialization(format!("decode tx history: {e}")))?;
205 let mut map = IndexMap::with_capacity(entries.len());
206 for e in entries {
207 map.insert(e.hash.clone(), e);
208 }
209 Ok(Self {
210 inner: Arc::new(RwLock::new(map)),
211 })
212 }
213}
214
215#[async_trait]
216impl TransactionHistoryStorage for InMemoryTransactionHistoryStorage {
217 async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()> {
218 let mut map = self.inner.write().await;
219 match map.get_mut(&entry.hash) {
220 Some(existing) => existing.merge(entry),
221 None => {
222 map.insert(entry.hash.clone(), entry);
223 }
224 }
225 Ok(())
226 }
227
228 async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>> {
229 Ok(self.inner.read().await.get(hash).cloned())
230 }
231
232 async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
233 Ok(self.inner.read().await.values().cloned().collect())
234 }
235
236 async fn remove(&self, hash: &str) -> Result<()> {
237 self.inner.write().await.shift_remove(hash);
238 Ok(())
239 }
240
241 async fn clear(&self) -> Result<()> {
242 self.inner.write().await.clear();
243 Ok(())
244 }
245}
246
247#[derive(Debug, Clone)]
252pub enum TxHistoryEvent {
253 Upserted(Box<TransactionHistoryEntry>),
255 Removed(TransactionHash),
257 Cleared,
259}
260
261#[derive(Debug)]
276pub struct WatchedTransactionHistoryStorage<S>
277where
278 S: TransactionHistoryStorage,
279{
280 inner: Arc<S>,
281 events: EventBus<TxHistoryEvent>,
282}
283
284impl<S: TransactionHistoryStorage> Clone for WatchedTransactionHistoryStorage<S> {
285 fn clone(&self) -> Self {
286 Self {
287 inner: Arc::clone(&self.inner),
288 events: self.events.clone(),
289 }
290 }
291}
292
293impl<S: TransactionHistoryStorage> WatchedTransactionHistoryStorage<S> {
294 pub fn new(inner: S) -> Self {
296 Self {
297 inner: Arc::new(inner),
298 events: EventBus::new(),
299 }
300 }
301
302 pub fn with_capacity(inner: S, capacity: usize) -> Self {
304 Self {
305 inner: Arc::new(inner),
306 events: EventBus::with_capacity(capacity),
307 }
308 }
309
310 pub fn subscribe(&self) -> broadcast::Receiver<TxHistoryEvent> {
314 self.events.subscribe()
315 }
316
317 pub fn subscriber_count(&self) -> usize {
320 self.events.subscriber_count()
321 }
322}
323
324#[async_trait]
325impl<S: TransactionHistoryStorage> TransactionHistoryStorage
326 for WatchedTransactionHistoryStorage<S>
327{
328 async fn upsert(&self, entry: TransactionHistoryEntry) -> Result<()> {
329 self.inner.upsert(entry.clone()).await?;
330 self.events
331 .publish(TxHistoryEvent::Upserted(Box::new(entry)));
332 Ok(())
333 }
334
335 async fn get(&self, hash: &str) -> Result<Option<TransactionHistoryEntry>> {
336 self.inner.get(hash).await
337 }
338
339 async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
340 self.inner.get_all().await
341 }
342
343 async fn remove(&self, hash: &str) -> Result<()> {
344 self.inner.remove(hash).await?;
345 self.events
346 .publish(TxHistoryEvent::Removed(hash.to_owned()));
347 Ok(())
348 }
349
350 async fn clear(&self) -> Result<()> {
351 self.inner.clear().await?;
352 self.events.publish(TxHistoryEvent::Cleared);
353 Ok(())
354 }
355}
356
357#[derive(Debug, Clone, Default)]
361pub struct NoOpTransactionHistoryStorage;
362
363#[async_trait]
364impl TransactionHistoryStorage for NoOpTransactionHistoryStorage {
365 async fn upsert(&self, _entry: TransactionHistoryEntry) -> Result<()> {
366 Ok(())
367 }
368 async fn get(&self, _hash: &str) -> Result<Option<TransactionHistoryEntry>> {
369 Ok(None)
370 }
371 async fn get_all(&self) -> Result<Vec<TransactionHistoryEntry>> {
372 Ok(Vec::new())
373 }
374 async fn remove(&self, _hash: &str) -> Result<()> {
375 Ok(())
376 }
377 async fn clear(&self) -> Result<()> {
378 Ok(())
379 }
380}
381
382#[cfg(test)]
383mod tests {
384 use super::*;
385
386 fn entry(hash: &str, status: TransactionHistoryStatus) -> TransactionHistoryEntry {
387 TransactionHistoryEntry {
388 hash: hash.to_owned(),
389 protocol_version: ProtocolVersion(8),
390 status,
391 identifiers: None,
392 timestamp_ms: None,
393 fees: None,
394 shielded: None,
395 unshielded: None,
396 dust: None,
397 extra: serde_json::Value::Null,
398 }
399 }
400
401 fn matches_upsert_event(ev: &TxHistoryEvent, hash: &str) -> bool {
402 matches!(ev, TxHistoryEvent::Upserted(e) if e.hash == hash)
403 }
404
405 fn matches_remove_event(ev: &TxHistoryEvent, hash: &str) -> bool {
406 matches!(ev, TxHistoryEvent::Removed(h) if h == hash)
407 }
408
409 #[tokio::test]
410 async fn watched_storage_broadcasts_upsert() {
411 let watched =
412 WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
413 let mut rx = watched.subscribe();
414 watched
415 .upsert(entry("aa", TransactionHistoryStatus::Success))
416 .await
417 .unwrap();
418 let ev = rx.recv().await.unwrap();
419 assert!(matches_upsert_event(&ev, "aa"));
420 }
421
422 #[tokio::test]
423 async fn watched_storage_broadcasts_remove_and_clear() {
424 let watched =
425 WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
426 watched
427 .upsert(entry("aa", TransactionHistoryStatus::Success))
428 .await
429 .unwrap();
430 let mut rx = watched.subscribe();
431 watched.remove("aa").await.unwrap();
432 let ev = rx.recv().await.unwrap();
433 assert!(matches_remove_event(&ev, "aa"));
434 watched.clear().await.unwrap();
435 let ev = rx.recv().await.unwrap();
436 assert!(matches!(ev, TxHistoryEvent::Cleared));
437 }
438
439 #[tokio::test]
440 async fn watched_storage_get_all_passes_through() {
441 let watched =
442 WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
443 watched
444 .upsert(entry("aa", TransactionHistoryStatus::Success))
445 .await
446 .unwrap();
447 watched
448 .upsert(entry("bb", TransactionHistoryStatus::Failure))
449 .await
450 .unwrap();
451 let all = watched.get_all().await.unwrap();
452 assert_eq!(all.len(), 2);
453 }
454
455 #[tokio::test]
456 async fn watched_storage_subscriber_count_tracks_receivers() {
457 let watched =
458 WatchedTransactionHistoryStorage::new(InMemoryTransactionHistoryStorage::new());
459 assert_eq!(watched.subscriber_count(), 0);
460 let _rx1 = watched.subscribe();
461 let _rx2 = watched.subscribe();
462 assert_eq!(watched.subscriber_count(), 2);
463 }
464
465 #[tokio::test]
466 async fn upsert_inserts_new_entry() {
467 let store = InMemoryTransactionHistoryStorage::new();
468 store
469 .upsert(entry("aa", TransactionHistoryStatus::Success))
470 .await
471 .unwrap();
472 let got = store.get("aa").await.unwrap().unwrap();
473 assert_eq!(got.status, TransactionHistoryStatus::Success);
474 }
475
476 #[tokio::test]
477 async fn upsert_merges_existing_entry_field_aware() {
478 let store = InMemoryTransactionHistoryStorage::new();
479 let mut a = entry("aa", TransactionHistoryStatus::Success);
480 a.fees = Some(100);
481 store.upsert(a).await.unwrap();
482 let mut b = entry("aa", TransactionHistoryStatus::Success);
483 b.timestamp_ms = Some(1234);
484 store.upsert(b).await.unwrap();
487 let got = store.get("aa").await.unwrap().unwrap();
488 assert_eq!(got.fees, Some(100));
489 assert_eq!(got.timestamp_ms, Some(1234));
490 }
491
492 #[tokio::test]
493 async fn get_all_preserves_insertion_order() {
494 let store = InMemoryTransactionHistoryStorage::new();
495 store
496 .upsert(entry("aa", TransactionHistoryStatus::Success))
497 .await
498 .unwrap();
499 store
500 .upsert(entry("bb", TransactionHistoryStatus::Failure))
501 .await
502 .unwrap();
503 store
504 .upsert(entry("cc", TransactionHistoryStatus::PartialSuccess))
505 .await
506 .unwrap();
507 let all = store.get_all().await.unwrap();
508 let hashes: Vec<&str> = all.iter().map(|e| e.hash.as_str()).collect();
509 assert_eq!(hashes, vec!["aa", "bb", "cc"]);
510 }
511
512 #[tokio::test]
513 async fn remove_drops_entry_only() {
514 let store = InMemoryTransactionHistoryStorage::new();
515 store
516 .upsert(entry("aa", TransactionHistoryStatus::Success))
517 .await
518 .unwrap();
519 store
520 .upsert(entry("bb", TransactionHistoryStatus::Success))
521 .await
522 .unwrap();
523 store.remove("aa").await.unwrap();
524 assert!(store.get("aa").await.unwrap().is_none());
525 assert!(store.get("bb").await.unwrap().is_some());
526 }
527
528 #[tokio::test]
529 async fn serialize_and_restore_round_trip() {
530 let store = InMemoryTransactionHistoryStorage::new();
531 let mut a = entry("aa", TransactionHistoryStatus::Success);
532 a.fees = Some(7);
533 store.upsert(a).await.unwrap();
534 store
535 .upsert(entry("bb", TransactionHistoryStatus::Failure))
536 .await
537 .unwrap();
538 let json = store.serialize().await.unwrap();
539 let restored = InMemoryTransactionHistoryStorage::restore(&json).unwrap();
540 let all = restored.get_all().await.unwrap();
541 assert_eq!(all.len(), 2);
542 assert_eq!(all[0].hash, "aa");
543 assert_eq!(all[0].fees, Some(7));
544 }
545
546 #[tokio::test]
547 async fn noop_returns_empty_for_every_query() {
548 let store = NoOpTransactionHistoryStorage;
549 store
550 .upsert(entry("aa", TransactionHistoryStatus::Success))
551 .await
552 .unwrap();
553 assert!(store.get("aa").await.unwrap().is_none());
554 assert!(store.get_all().await.unwrap().is_empty());
555 }
556}