openzeppelin_relayer/repositories/
transaction.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
//! This module defines an in-memory transaction repository for managing
//! transaction data. It provides asynchronous methods for creating, retrieving,
//! updating, and deleting transactions, as well as querying transactions by
//! various criteria such as relayer ID, status, and nonce. The repository
//! is implemented using a `Mutex`-protected `HashMap` to store transaction
//! data, ensuring thread-safe access in an asynchronous context.
use crate::{
    models::{
        NetworkTransactionData, TransactionRepoModel, TransactionStatus, TransactionUpdateRequest,
    },
    repositories::*,
};
use async_trait::async_trait;
use eyre::Result;
use itertools::Itertools;
use std::collections::HashMap;
use tokio::sync::{Mutex, MutexGuard};

/// A trait defining transaction repository operations
#[async_trait]
pub trait TransactionRepository: Repository<TransactionRepoModel, String> {
    /// Find transactions by relayer ID with pagination
    async fn find_by_relayer_id(
        &self,
        relayer_id: &str,
        query: PaginationQuery,
    ) -> Result<PaginatedResult<TransactionRepoModel>, RepositoryError>;

    /// Find transactions by status
    async fn find_by_status(
        &self,
        status: TransactionStatus,
    ) -> Result<Vec<TransactionRepoModel>, RepositoryError>;

    /// Find a transaction by relayer ID and nonce
    async fn find_by_nonce(
        &self,
        relayer_id: &str,
        nonce: u64,
    ) -> Result<Option<TransactionRepoModel>, RepositoryError>;

    /// Update the status of a transaction
    async fn update_status(
        &self,
        tx_id: String,
        status: TransactionStatus,
    ) -> Result<TransactionRepoModel, RepositoryError>;

    /// Partially update a transaction
    async fn partial_update(
        &self,
        tx_id: String,
        update: TransactionUpdateRequest,
    ) -> Result<TransactionRepoModel, RepositoryError>;

    /// Update the network data of a transaction
    async fn update_network_data(
        &self,
        tx_id: String,
        network_data: NetworkTransactionData,
    ) -> Result<TransactionRepoModel, RepositoryError>;

    /// Set the sent_at timestamp of a transaction
    async fn set_sent_at(
        &self,
        tx_id: String,
        sent_at: String,
    ) -> Result<TransactionRepoModel, RepositoryError>;

    /// Set the confirmed_at timestamp of a transaction
    async fn set_confirmed_at(
        &self,
        tx_id: String,
        confirmed_at: String,
    ) -> Result<TransactionRepoModel, RepositoryError>;
}

#[cfg(test)]
mockall::mock! {
    pub TransactionRepository {}

    #[async_trait]
    impl Repository<TransactionRepoModel, String> for TransactionRepository {
        async fn create(&self, entity: TransactionRepoModel) -> Result<TransactionRepoModel, RepositoryError>;
        async fn get_by_id(&self, id: String) -> Result<TransactionRepoModel, RepositoryError>;
        async fn list_all(&self) -> Result<Vec<TransactionRepoModel>, RepositoryError>;
        async fn list_paginated(&self, query: PaginationQuery) -> Result<PaginatedResult<TransactionRepoModel>, RepositoryError>;
        async fn update(&self, id: String, entity: TransactionRepoModel) -> Result<TransactionRepoModel, RepositoryError>;
        async fn delete_by_id(&self, id: String) -> Result<(), RepositoryError>;
        async fn count(&self) -> Result<usize, RepositoryError>;
    }

    #[async_trait]
    impl TransactionRepository for TransactionRepository {
        async fn find_by_relayer_id(&self, relayer_id: &str, query: PaginationQuery) -> Result<PaginatedResult<TransactionRepoModel>, RepositoryError>;
        async fn find_by_status(&self, status: TransactionStatus) -> Result<Vec<TransactionRepoModel>, RepositoryError>;
        async fn find_by_nonce(&self, relayer_id: &str, nonce: u64) -> Result<Option<TransactionRepoModel>, RepositoryError>;
        async fn update_status(&self, tx_id: String, status: TransactionStatus) -> Result<TransactionRepoModel, RepositoryError>;
        async fn partial_update(&self, tx_id: String, update: TransactionUpdateRequest) -> Result<TransactionRepoModel, RepositoryError>;
        async fn update_network_data(&self, tx_id: String, network_data: NetworkTransactionData) -> Result<TransactionRepoModel, RepositoryError>;
        async fn set_sent_at(&self, tx_id: String, sent_at: String) -> Result<TransactionRepoModel, RepositoryError>;
        async fn set_confirmed_at(&self, tx_id: String, confirmed_at: String) -> Result<TransactionRepoModel, RepositoryError>;
    }
}

#[derive(Debug)]
pub struct InMemoryTransactionRepository {
    store: Mutex<HashMap<String, TransactionRepoModel>>,
}

impl InMemoryTransactionRepository {
    pub fn new() -> Self {
        Self {
            store: Mutex::new(HashMap::new()),
        }
    }

    async fn acquire_lock<T>(lock: &Mutex<T>) -> Result<MutexGuard<T>, RepositoryError> {
        Ok(lock.lock().await)
    }
}

// Implement both traits for InMemoryTransactionRepository

#[async_trait]
impl Repository<TransactionRepoModel, String> for InMemoryTransactionRepository {
    async fn create(
        &self,
        tx: TransactionRepoModel,
    ) -> Result<TransactionRepoModel, RepositoryError> {
        let mut store = Self::acquire_lock(&self.store).await?;
        if store.contains_key(&tx.id) {
            return Err(RepositoryError::ConstraintViolation(format!(
                "Transaction with ID {} already exists",
                tx.id
            )));
        }
        store.insert(tx.id.clone(), tx.clone());
        Ok(tx)
    }

    async fn get_by_id(&self, id: String) -> Result<TransactionRepoModel, RepositoryError> {
        let store = Self::acquire_lock(&self.store).await?;
        store.get(&id).cloned().ok_or_else(|| {
            RepositoryError::NotFound(format!("Transaction with ID {} not found", id))
        })
    }

    #[allow(clippy::map_entry)]
    async fn update(
        &self,
        id: String,
        tx: TransactionRepoModel,
    ) -> Result<TransactionRepoModel, RepositoryError> {
        let mut store = Self::acquire_lock(&self.store).await?;
        if store.contains_key(&id) {
            let mut updated_tx = tx;
            updated_tx.id = id.clone();
            store.insert(id, updated_tx.clone());
            Ok(updated_tx)
        } else {
            Err(RepositoryError::NotFound(format!(
                "Transaction with ID {} not found",
                id
            )))
        }
    }

    async fn delete_by_id(&self, id: String) -> Result<(), RepositoryError> {
        let mut store = Self::acquire_lock(&self.store).await?;
        if store.remove(&id).is_some() {
            Ok(())
        } else {
            Err(RepositoryError::NotFound(format!(
                "Transaction with ID {} not found",
                id
            )))
        }
    }

    async fn list_all(&self) -> Result<Vec<TransactionRepoModel>, RepositoryError> {
        let store = Self::acquire_lock(&self.store).await?;
        Ok(store.values().cloned().collect())
    }

    async fn list_paginated(
        &self,
        query: PaginationQuery,
    ) -> Result<PaginatedResult<TransactionRepoModel>, RepositoryError> {
        let total = self.count().await?;
        let start = ((query.page - 1) * query.per_page) as usize;
        let store = Self::acquire_lock(&self.store).await?;
        let items: Vec<TransactionRepoModel> = store
            .values()
            .skip(start)
            .take(query.per_page as usize)
            .cloned()
            .collect();

        Ok(PaginatedResult {
            items,
            total: total as u64,
            page: query.page,
            per_page: query.per_page,
        })
    }

    async fn count(&self) -> Result<usize, RepositoryError> {
        let store = Self::acquire_lock(&self.store).await?;
        Ok(store.len())
    }
}

#[async_trait]
impl TransactionRepository for InMemoryTransactionRepository {
    async fn find_by_relayer_id(
        &self,
        relayer_id: &str,
        query: PaginationQuery,
    ) -> Result<PaginatedResult<TransactionRepoModel>, RepositoryError> {
        let store = Self::acquire_lock(&self.store).await?;
        let filtered: Vec<TransactionRepoModel> = store
            .values()
            .filter(|tx| tx.relayer_id == relayer_id)
            .cloned()
            .collect();

        let total = filtered.len() as u64;

        if total == 0 {
            return Ok(PaginatedResult::<TransactionRepoModel> {
                items: vec![],
                total: 0,
                page: query.page,
                per_page: query.per_page,
            });
        }

        let start = ((query.page - 1) * query.per_page) as usize;

        // Sort and paginate
        let items = filtered
            .into_iter()
            .sorted_by(|a, b| a.created_at.cmp(&b.created_at)) // Sort by created_at
            .skip(start)
            .take(query.per_page as usize)
            .collect();

        Ok(PaginatedResult {
            items,
            total,
            page: query.page,
            per_page: query.per_page,
        })
    }

    async fn find_by_status(
        &self,
        status: TransactionStatus,
    ) -> Result<Vec<TransactionRepoModel>, RepositoryError> {
        let store = Self::acquire_lock(&self.store).await?;
        Ok(store
            .values()
            .filter(|tx| tx.status == status)
            .cloned()
            .collect())
    }

    async fn find_by_nonce(
        &self,
        relayer_id: &str,
        nonce: u64,
    ) -> Result<Option<TransactionRepoModel>, RepositoryError> {
        let store = Self::acquire_lock(&self.store).await?;
        let filtered: Vec<TransactionRepoModel> = store
            .values()
            .filter(|tx| {
                tx.relayer_id == relayer_id
                    && match &tx.network_data {
                        NetworkTransactionData::Evm(data) => data.nonce == Some(nonce),
                        _ => false,
                    }
            })
            .cloned()
            .collect();

        Ok(filtered.into_iter().next())
    }

    async fn update_status(
        &self,
        tx_id: String,
        status: TransactionStatus,
    ) -> Result<TransactionRepoModel, RepositoryError> {
        let mut tx = self.get_by_id(tx_id.clone()).await?;
        tx.status = status;
        self.update(tx_id, tx).await
    }

    async fn partial_update(
        &self,
        tx_id: String,
        update: TransactionUpdateRequest,
    ) -> Result<TransactionRepoModel, RepositoryError> {
        let mut store = Self::acquire_lock(&self.store).await?;

        if let Some(tx) = store.get_mut(&tx_id) {
            if let Some(status) = update.status {
                tx.status = status;
            }
            if let Some(sent_at) = update.sent_at {
                tx.sent_at = Some(sent_at);
            }
            if let Some(confirmed_at) = update.confirmed_at {
                tx.confirmed_at = Some(confirmed_at);
            }
            if let Some(network_data) = update.network_data {
                tx.network_data = network_data;
            }
            if let Some(hashes) = update.hashes {
                tx.hashes = hashes;
            }
            if let Some(is_canceled) = update.is_canceled {
                tx.is_canceled = Some(is_canceled);
            }
            Ok(tx.clone())
        } else {
            Err(RepositoryError::NotFound(format!(
                "Transaction with ID {} not found",
                tx_id
            )))
        }
    }

    async fn update_network_data(
        &self,
        tx_id: String,
        network_data: NetworkTransactionData,
    ) -> Result<TransactionRepoModel, RepositoryError> {
        let mut tx = self.get_by_id(tx_id.clone()).await?;
        tx.network_data = network_data;
        self.update(tx_id, tx).await
    }

    async fn set_sent_at(
        &self,
        tx_id: String,
        sent_at: String,
    ) -> Result<TransactionRepoModel, RepositoryError> {
        let mut tx = self.get_by_id(tx_id.clone()).await?;
        tx.sent_at = Some(sent_at);
        self.update(tx_id, tx).await
    }

    async fn set_confirmed_at(
        &self,
        tx_id: String,
        confirmed_at: String,
    ) -> Result<TransactionRepoModel, RepositoryError> {
        let mut tx = self.get_by_id(tx_id.clone()).await?;
        tx.confirmed_at = Some(confirmed_at);
        self.update(tx_id, tx).await
    }
}

impl Default for InMemoryTransactionRepository {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use crate::models::{evm::Speed, EvmTransactionData, NetworkType};
    use std::str::FromStr;

    use crate::models::U256;

    use super::*;

    // Helper function to create test transactions
    fn create_test_transaction(id: &str) -> TransactionRepoModel {
        TransactionRepoModel {
            id: id.to_string(),
            relayer_id: "relayer-1".to_string(),
            status: TransactionStatus::Pending,
            created_at: "2025-01-27T15:31:10.777083+00:00".to_string(),
            sent_at: Some("2025-01-27T15:31:10.777083+00:00".to_string()),
            confirmed_at: Some("2025-01-27T15:31:10.777083+00:00".to_string()),
            valid_until: None,
            network_type: NetworkType::Evm,
            priced_at: None,
            hashes: vec![],
            network_data: NetworkTransactionData::Evm(EvmTransactionData {
                gas_price: Some(1000000000),
                gas_limit: 21000,
                nonce: Some(1),
                value: U256::from_str("1000000000000000000").unwrap(),
                data: Some("0x".to_string()),
                from: "0xSender".to_string(),
                to: Some("0xRecipient".to_string()),
                chain_id: 1,
                signature: None,
                hash: Some(format!("0x{}", id)),
                speed: Some(Speed::Fast),
                max_fee_per_gas: None,
                max_priority_fee_per_gas: None,
                raw: None,
            }),
            noop_count: None,
            is_canceled: Some(false),
        }
    }

    fn create_test_transaction_pending_state(id: &str) -> TransactionRepoModel {
        TransactionRepoModel {
            id: id.to_string(),
            relayer_id: "relayer-1".to_string(),
            status: TransactionStatus::Pending,
            created_at: "2025-01-27T15:31:10.777083+00:00".to_string(),
            sent_at: None,
            confirmed_at: None,
            valid_until: None,
            network_type: NetworkType::Evm,
            priced_at: None,
            hashes: vec![],
            network_data: NetworkTransactionData::Evm(EvmTransactionData {
                gas_price: Some(1000000000),
                gas_limit: 21000,
                nonce: Some(1),
                value: U256::from_str("1000000000000000000").unwrap(),
                data: Some("0x".to_string()),
                from: "0xSender".to_string(),
                to: Some("0xRecipient".to_string()),
                chain_id: 1,
                signature: None,
                hash: Some(format!("0x{}", id)),
                speed: Some(Speed::Fast),
                max_fee_per_gas: None,
                max_priority_fee_per_gas: None,
                raw: None,
            }),
            noop_count: None,
            is_canceled: Some(false),
        }
    }

    #[tokio::test]
    async fn test_create_transaction() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction("test-1");

        let result = repo.create(tx.clone()).await.unwrap();
        assert_eq!(result.id, tx.id);
        assert_eq!(repo.count().await.unwrap(), 1);
    }

    #[tokio::test]
    async fn test_get_transaction() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction("test-1");

        repo.create(tx.clone()).await.unwrap();
        let stored = repo.get_by_id("test-1".to_string()).await.unwrap();
        if let NetworkTransactionData::Evm(stored_data) = &stored.network_data {
            if let NetworkTransactionData::Evm(tx_data) = &tx.network_data {
                assert_eq!(stored_data.hash, tx_data.hash);
            }
        }
    }

    #[tokio::test]
    async fn test_update_transaction() {
        let repo = InMemoryTransactionRepository::new();
        let mut tx = create_test_transaction("test-1");

        repo.create(tx.clone()).await.unwrap();
        tx.status = TransactionStatus::Confirmed;

        let updated = repo.update("test-1".to_string(), tx).await.unwrap();
        assert!(matches!(updated.status, TransactionStatus::Confirmed));
    }

    #[tokio::test]
    async fn test_delete_transaction() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction("test-1");

        repo.create(tx).await.unwrap();
        repo.delete_by_id("test-1".to_string()).await.unwrap();

        let result = repo.get_by_id("test-1".to_string()).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_list_all_transactions() {
        let repo = InMemoryTransactionRepository::new();
        let tx1 = create_test_transaction("test-1");
        let tx2 = create_test_transaction("test-2");

        repo.create(tx1).await.unwrap();
        repo.create(tx2).await.unwrap();

        let transactions = repo.list_all().await.unwrap();
        assert_eq!(transactions.len(), 2);
    }

    #[tokio::test]
    async fn test_count_transactions() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction("test-1");

        assert_eq!(repo.count().await.unwrap(), 0);
        repo.create(tx).await.unwrap();
        assert_eq!(repo.count().await.unwrap(), 1);
    }

    #[tokio::test]
    async fn test_get_nonexistent_transaction() {
        let repo = InMemoryTransactionRepository::new();
        let result = repo.get_by_id("nonexistent".to_string()).await;
        assert!(matches!(result, Err(RepositoryError::NotFound(_))));
    }

    #[tokio::test]
    async fn test_duplicate_transaction_creation() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction("test-1");

        repo.create(tx.clone()).await.unwrap();
        let result = repo.create(tx).await;

        assert!(matches!(
            result,
            Err(RepositoryError::ConstraintViolation(_))
        ));
    }

    #[tokio::test]
    async fn test_update_nonexistent_transaction() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction("test-1");

        let result = repo.update("nonexistent".to_string(), tx).await;
        assert!(matches!(result, Err(RepositoryError::NotFound(_))));
    }

    #[tokio::test]
    async fn test_partial_update() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction_pending_state("test-tx-id");
        repo.create(tx.clone()).await.unwrap();

        // Test updating only status
        let update1 = TransactionUpdateRequest {
            status: Some(TransactionStatus::Sent),
            sent_at: None,
            confirmed_at: None,
            network_data: None,
            hashes: None,
            priced_at: None,
            noop_count: None,
            is_canceled: None,
        };
        let updated_tx1 = repo
            .partial_update("test-tx-id".to_string(), update1)
            .await
            .unwrap();
        assert_eq!(updated_tx1.status, TransactionStatus::Sent);
        assert_eq!(updated_tx1.sent_at, None);

        // Test updating multiple fields
        let update2 = TransactionUpdateRequest {
            status: Some(TransactionStatus::Confirmed),
            sent_at: Some("2023-01-01T12:00:00Z".to_string()),
            confirmed_at: Some("2023-01-01T12:05:00Z".to_string()),
            network_data: None,
            hashes: None,
            priced_at: None,
            noop_count: None,
            is_canceled: None,
        };
        let updated_tx2 = repo
            .partial_update("test-tx-id".to_string(), update2)
            .await
            .unwrap();
        assert_eq!(updated_tx2.status, TransactionStatus::Confirmed);
        assert_eq!(
            updated_tx2.sent_at,
            Some("2023-01-01T12:00:00Z".to_string())
        );
        assert_eq!(
            updated_tx2.confirmed_at,
            Some("2023-01-01T12:05:00Z".to_string())
        );

        // Test updating non-existent transaction
        let update3 = TransactionUpdateRequest {
            status: Some(TransactionStatus::Failed),
            sent_at: None,
            confirmed_at: None,
            network_data: None,
            hashes: None,
            priced_at: None,
            noop_count: None,
            is_canceled: None,
        };
        let result = repo
            .partial_update("non-existent-id".to_string(), update3)
            .await;
        assert!(result.is_err());
        assert!(matches!(result.unwrap_err(), RepositoryError::NotFound(_)));
    }

    #[tokio::test]
    async fn test_update_status() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction("test-1");

        repo.create(tx).await.unwrap();

        // Update status to Confirmed
        let updated = repo
            .update_status("test-1".to_string(), TransactionStatus::Confirmed)
            .await
            .unwrap();

        // Verify the status was updated in the returned transaction
        assert_eq!(updated.status, TransactionStatus::Confirmed);

        // Also verify by getting the transaction directly
        let stored = repo.get_by_id("test-1".to_string()).await.unwrap();
        assert_eq!(stored.status, TransactionStatus::Confirmed);

        // Update status to Failed
        let updated = repo
            .update_status("test-1".to_string(), TransactionStatus::Failed)
            .await
            .unwrap();

        // Verify the status was updated
        assert_eq!(updated.status, TransactionStatus::Failed);

        // Verify updating a non-existent transaction
        let result = repo
            .update_status("non-existent".to_string(), TransactionStatus::Confirmed)
            .await;
        assert!(matches!(result, Err(RepositoryError::NotFound(_))));
    }

    #[tokio::test]
    async fn test_list_paginated() {
        let repo = InMemoryTransactionRepository::new();

        // Create multiple transactions
        for i in 1..=10 {
            let tx = create_test_transaction(&format!("test-{}", i));
            repo.create(tx).await.unwrap();
        }

        // Test first page with 3 items per page
        let query = PaginationQuery {
            page: 1,
            per_page: 3,
        };
        let result = repo.list_paginated(query).await.unwrap();
        assert_eq!(result.items.len(), 3);
        assert_eq!(result.total, 10);
        assert_eq!(result.page, 1);
        assert_eq!(result.per_page, 3);

        // Test second page with 3 items per page
        let query = PaginationQuery {
            page: 2,
            per_page: 3,
        };
        let result = repo.list_paginated(query).await.unwrap();
        assert_eq!(result.items.len(), 3);
        assert_eq!(result.total, 10);
        assert_eq!(result.page, 2);
        assert_eq!(result.per_page, 3);

        // Test page with fewer items than per_page
        let query = PaginationQuery {
            page: 4,
            per_page: 3,
        };
        let result = repo.list_paginated(query).await.unwrap();
        assert_eq!(result.items.len(), 1);
        assert_eq!(result.total, 10);
        assert_eq!(result.page, 4);
        assert_eq!(result.per_page, 3);

        // Test empty page (beyond total items)
        let query = PaginationQuery {
            page: 5,
            per_page: 3,
        };
        let result = repo.list_paginated(query).await.unwrap();
        assert_eq!(result.items.len(), 0);
        assert_eq!(result.total, 10);
    }

    #[tokio::test]
    async fn test_find_by_nonce() {
        let repo = InMemoryTransactionRepository::new();

        // Create transactions with different nonces
        let tx1 = create_test_transaction("test-1");

        let mut tx2 = create_test_transaction("test-2");
        if let NetworkTransactionData::Evm(ref mut data) = tx2.network_data {
            data.nonce = Some(2);
        }

        let mut tx3 = create_test_transaction("test-3");
        tx3.relayer_id = "relayer-2".to_string();
        if let NetworkTransactionData::Evm(ref mut data) = tx3.network_data {
            data.nonce = Some(1);
        }

        repo.create(tx1).await.unwrap();
        repo.create(tx2).await.unwrap();
        repo.create(tx3).await.unwrap();

        // Test finding transaction with specific relayer_id and nonce
        let result = repo.find_by_nonce("relayer-1", 1).await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().id, "test-1");

        // Test finding transaction with a different nonce
        let result = repo.find_by_nonce("relayer-1", 2).await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().id, "test-2");

        // Test finding transaction from a different relayer
        let result = repo.find_by_nonce("relayer-2", 1).await.unwrap();
        assert!(result.is_some());
        assert_eq!(result.as_ref().unwrap().id, "test-3");

        // Test finding transaction that doesn't exist
        let result = repo.find_by_nonce("relayer-1", 99).await.unwrap();
        assert!(result.is_none());
    }

    #[tokio::test]
    async fn test_update_network_data() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction("test-1");

        repo.create(tx.clone()).await.unwrap();

        // Create new network data with updated values
        let updated_network_data = NetworkTransactionData::Evm(EvmTransactionData {
            gas_price: Some(2000000000),
            gas_limit: 30000,
            nonce: Some(2),
            value: U256::from_str("2000000000000000000").unwrap(),
            data: Some("0xUpdated".to_string()),
            from: "0xSender".to_string(),
            to: Some("0xRecipient".to_string()),
            chain_id: 1,
            signature: None,
            hash: Some("0xUpdated".to_string()),
            raw: None,
            speed: None,
            max_fee_per_gas: None,
            max_priority_fee_per_gas: None,
        });

        let updated = repo
            .update_network_data("test-1".to_string(), updated_network_data)
            .await
            .unwrap();

        // Verify the network data was updated
        if let NetworkTransactionData::Evm(data) = &updated.network_data {
            assert_eq!(data.gas_price, Some(2000000000));
            assert_eq!(data.gas_limit, 30000);
            assert_eq!(data.nonce, Some(2));
            assert_eq!(data.hash, Some("0xUpdated".to_string()));
            assert_eq!(data.data, Some("0xUpdated".to_string()));
        } else {
            panic!("Expected EVM network data");
        }
    }

    #[tokio::test]
    async fn test_set_sent_at() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction("test-1");

        repo.create(tx).await.unwrap();

        // Updated sent_at timestamp
        let new_sent_at = "2025-02-01T10:00:00.000000+00:00".to_string();

        let updated = repo
            .set_sent_at("test-1".to_string(), new_sent_at.clone())
            .await
            .unwrap();

        // Verify the sent_at timestamp was updated
        assert_eq!(updated.sent_at, Some(new_sent_at.clone()));

        // Also verify by getting the transaction directly
        let stored = repo.get_by_id("test-1".to_string()).await.unwrap();
        assert_eq!(stored.sent_at, Some(new_sent_at.clone()));
    }

    #[tokio::test]
    async fn test_set_confirmed_at() {
        let repo = InMemoryTransactionRepository::new();
        let tx = create_test_transaction("test-1");

        repo.create(tx).await.unwrap();

        // Updated confirmed_at timestamp
        let new_confirmed_at = "2025-02-01T11:30:45.123456+00:00".to_string();

        let updated = repo
            .set_confirmed_at("test-1".to_string(), new_confirmed_at.clone())
            .await
            .unwrap();

        // Verify the confirmed_at timestamp was updated
        assert_eq!(updated.confirmed_at, Some(new_confirmed_at.clone()));

        // Also verify by getting the transaction directly
        let stored = repo.get_by_id("test-1".to_string()).await.unwrap();
        assert_eq!(stored.confirmed_at, Some(new_confirmed_at.clone()));
    }

    #[tokio::test]
    async fn test_find_by_relayer_id() {
        let repo = InMemoryTransactionRepository::new();
        let tx1 = create_test_transaction("test-1");
        let tx2 = create_test_transaction("test-2");

        // Create a transaction with a different relayer_id
        let mut tx3 = create_test_transaction("test-3");
        tx3.relayer_id = "relayer-2".to_string();

        repo.create(tx1).await.unwrap();
        repo.create(tx2).await.unwrap();
        repo.create(tx3).await.unwrap();

        // Test finding transactions for relayer-1
        let query = PaginationQuery {
            page: 1,
            per_page: 10,
        };
        let result = repo
            .find_by_relayer_id("relayer-1", query.clone())
            .await
            .unwrap();
        assert_eq!(result.total, 2);
        assert_eq!(result.items.len(), 2);
        assert!(result.items.iter().all(|tx| tx.relayer_id == "relayer-1"));

        // Test finding transactions for relayer-2
        let result = repo
            .find_by_relayer_id("relayer-2", query.clone())
            .await
            .unwrap();
        assert_eq!(result.total, 1);
        assert_eq!(result.items.len(), 1);
        assert!(result.items.iter().all(|tx| tx.relayer_id == "relayer-2"));

        // Test finding transactions for non-existent relayer
        let result = repo
            .find_by_relayer_id("non-existent", query.clone())
            .await
            .unwrap();
        assert_eq!(result.total, 0);
        assert_eq!(result.items.len(), 0);
    }

    #[tokio::test]
    async fn test_find_by_status() {
        let repo = InMemoryTransactionRepository::new();
        let tx1 = create_test_transaction("test-1");

        // Create a transaction with a different status
        let mut tx2 = create_test_transaction("test-2");
        tx2.status = TransactionStatus::Confirmed;

        let mut tx3 = create_test_transaction("test-3");
        tx3.status = TransactionStatus::Failed;

        repo.create(tx1).await.unwrap();
        repo.create(tx2).await.unwrap();
        repo.create(tx3).await.unwrap();

        // Test finding transactions with Pending status
        let result = repo
            .find_by_status(TransactionStatus::Pending)
            .await
            .unwrap();
        assert_eq!(result.len(), 1);
        assert!(result
            .iter()
            .all(|tx| tx.status == TransactionStatus::Pending));

        // Test finding transactions with Confirmed status
        let result = repo
            .find_by_status(TransactionStatus::Confirmed)
            .await
            .unwrap();
        assert_eq!(result.len(), 1);
        assert!(result
            .iter()
            .all(|tx| tx.status == TransactionStatus::Confirmed));

        // Test finding transactions with Failed status
        let result = repo
            .find_by_status(TransactionStatus::Failed)
            .await
            .unwrap();
        assert_eq!(result.len(), 1);
        assert!(result
            .iter()
            .all(|tx| tx.status == TransactionStatus::Failed));
    }
}