allsource-core 0.19.1

High-performance event store core built in Rust
Documentation
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
use crate::{
    application::dto::{
        BlockchainDto, ConfirmTransactionRequest, ConfirmTransactionResponse,
        InitiatePaymentRequest, InitiatePaymentResponse, ListTransactionsResponse,
        RefundTransactionRequest, RefundTransactionResponse, TransactionDto,
    },
    domain::{
        entities::{AccessToken, Transaction},
        repositories::{
            AccessTokenRepository, ArticleRepository, CreatorRepository, TransactionRepository,
        },
        value_objects::{ArticleId, Money, TenantId, TransactionId, WalletAddress},
    },
    error::Result,
};
use sha2::{Digest, Sha256};
use std::sync::Arc;

/// Use Case: Initiate Payment
///
/// Initiates a payment transaction for article access.
/// This creates a pending transaction that will be confirmed after on-chain verification.
///
/// Responsibilities:
/// - Validate input (DTO validation)
/// - Verify article exists and is purchasable
/// - Verify creator can receive payments
/// - Check for duplicate transaction signature (prevent replay attacks)
/// - Create domain Transaction entity
/// - Persist via repository
/// - Return response DTO
pub struct InitiatePaymentUseCase {
    transaction_repository: Arc<dyn TransactionRepository>,
    article_repository: Arc<dyn ArticleRepository>,
    creator_repository: Arc<dyn CreatorRepository>,
}

impl InitiatePaymentUseCase {
    pub fn new(
        transaction_repository: Arc<dyn TransactionRepository>,
        article_repository: Arc<dyn ArticleRepository>,
        creator_repository: Arc<dyn CreatorRepository>,
    ) -> Self {
        Self {
            transaction_repository,
            article_repository,
            creator_repository,
        }
    }

    pub async fn execute(
        &self,
        request: InitiatePaymentRequest,
    ) -> Result<InitiatePaymentResponse> {
        // Check for duplicate signature (replay attack prevention)
        if self
            .transaction_repository
            .signature_exists(&request.tx_signature)
            .await?
        {
            return Err(crate::error::AllSourceError::ValidationError(
                "Transaction signature already exists".to_string(),
            ));
        }

        // Parse IDs
        let tenant_id = TenantId::new(request.tenant_id)?;
        let article_id = ArticleId::new(request.article_id)?;
        let reader_wallet = WalletAddress::new(request.reader_wallet)?;

        // Verify article exists and is purchasable
        let article = self
            .article_repository
            .find_by_id(&article_id)
            .await?
            .ok_or_else(|| {
                crate::error::AllSourceError::EntityNotFound("Article not found".to_string())
            })?;

        if !article.is_purchasable() {
            return Err(crate::error::AllSourceError::ValidationError(
                "Article is not available for purchase".to_string(),
            ));
        }

        // Verify creator can receive payments
        let creator = self
            .creator_repository
            .find_by_id(article.creator_id())
            .await?
            .ok_or_else(|| {
                crate::error::AllSourceError::EntityNotFound("Creator not found".to_string())
            })?;

        creator.can_receive_payments()?;

        // Determine blockchain
        let blockchain = request.blockchain.unwrap_or(BlockchainDto::Solana).into();

        // Create transaction
        let transaction = Transaction::new(
            tenant_id,
            article_id,
            *article.creator_id(),
            reader_wallet,
            Money::usd_cents(article.price_cents()),
            creator.fee_percentage(),
            blockchain,
            request.tx_signature,
        )?;

        // Persist transaction
        self.transaction_repository.save(&transaction).await?;

        Ok(InitiatePaymentResponse {
            transaction: TransactionDto::from(&transaction),
        })
    }
}

/// Use Case: Confirm Transaction
///
/// Confirms a transaction after on-chain verification.
/// This creates an access token for the reader.
pub struct ConfirmTransactionUseCase {
    transaction_repository: Arc<dyn TransactionRepository>,
    access_token_repository: Arc<dyn AccessTokenRepository>,
    article_repository: Arc<dyn ArticleRepository>,
    creator_repository: Arc<dyn CreatorRepository>,
}

impl ConfirmTransactionUseCase {
    pub fn new(
        transaction_repository: Arc<dyn TransactionRepository>,
        access_token_repository: Arc<dyn AccessTokenRepository>,
        article_repository: Arc<dyn ArticleRepository>,
        creator_repository: Arc<dyn CreatorRepository>,
    ) -> Self {
        Self {
            transaction_repository,
            access_token_repository,
            article_repository,
            creator_repository,
        }
    }

    pub async fn execute(
        &self,
        request: ConfirmTransactionRequest,
    ) -> Result<ConfirmTransactionResponse> {
        // Parse transaction ID
        let transaction_id = TransactionId::parse(&request.transaction_id)?;

        // Find transaction
        let mut transaction = self
            .transaction_repository
            .find_by_id(&transaction_id)
            .await?
            .ok_or_else(|| {
                crate::error::AllSourceError::EntityNotFound("Transaction not found".to_string())
            })?;

        // Confirm transaction
        transaction.confirm()?;

        // Save updated transaction
        self.transaction_repository.save(&transaction).await?;

        // Generate access token
        let token_hash = generate_token_hash(&transaction);

        let access_token = AccessToken::new_paid(
            transaction.tenant_id().clone(),
            transaction.article_id().clone(),
            *transaction.creator_id(),
            transaction.reader_wallet().clone(),
            *transaction.id(),
            token_hash.clone(),
        )?;

        // Save access token
        self.access_token_repository.save(&access_token).await?;

        // Update article stats
        if let Some(mut article) = self
            .article_repository
            .find_by_id(transaction.article_id())
            .await?
        {
            article.record_purchase(transaction.amount_cents());
            self.article_repository.save(&article).await?;
        }

        // Update creator revenue
        if let Some(mut creator) = self
            .creator_repository
            .find_by_id(transaction.creator_id())
            .await?
        {
            creator.record_revenue(transaction.creator_amount_cents());
            self.creator_repository.save(&creator).await?;
        }

        Ok(ConfirmTransactionResponse {
            transaction: TransactionDto::from(&transaction),
            access_token: Some(token_hash),
        })
    }
}

/// Use Case: Fail Transaction
///
/// Marks a transaction as failed after on-chain verification fails.
pub struct FailTransactionUseCase;

impl FailTransactionUseCase {
    pub fn execute(mut transaction: Transaction, reason: &str) -> Result<TransactionDto> {
        transaction.fail(reason)?;
        Ok(TransactionDto::from(&transaction))
    }
}

/// Use Case: Refund Transaction
///
/// Processes a refund for a confirmed transaction.
/// This revokes the associated access token.
pub struct RefundTransactionUseCase {
    transaction_repository: Arc<dyn TransactionRepository>,
    access_token_repository: Arc<dyn AccessTokenRepository>,
}

impl RefundTransactionUseCase {
    pub fn new(
        transaction_repository: Arc<dyn TransactionRepository>,
        access_token_repository: Arc<dyn AccessTokenRepository>,
    ) -> Self {
        Self {
            transaction_repository,
            access_token_repository,
        }
    }

    pub async fn execute(
        &self,
        request: RefundTransactionRequest,
    ) -> Result<RefundTransactionResponse> {
        // Parse transaction ID
        let transaction_id = TransactionId::parse(&request.transaction_id)?;

        // Find transaction
        let mut transaction = self
            .transaction_repository
            .find_by_id(&transaction_id)
            .await?
            .ok_or_else(|| {
                crate::error::AllSourceError::EntityNotFound("Transaction not found".to_string())
            })?;

        // Process refund
        transaction.refund(&request.refund_tx_signature)?;

        // Save updated transaction
        self.transaction_repository.save(&transaction).await?;

        // Revoke access token
        let reason = request
            .reason
            .unwrap_or_else(|| "Refund processed".to_string());
        self.access_token_repository
            .revoke_by_transaction(&transaction_id, &reason)
            .await?;

        Ok(RefundTransactionResponse {
            transaction: TransactionDto::from(&transaction),
        })
    }
}

/// Use Case: Dispute Transaction
///
/// Marks a transaction as disputed.
pub struct DisputeTransactionUseCase;

impl DisputeTransactionUseCase {
    pub fn execute(mut transaction: Transaction, reason: &str) -> Result<TransactionDto> {
        transaction.dispute(reason)?;
        Ok(TransactionDto::from(&transaction))
    }
}

/// Use Case: Resolve Dispute
///
/// Resolves a disputed transaction.
pub struct ResolveDisputeUseCase;

impl ResolveDisputeUseCase {
    pub fn execute(mut transaction: Transaction, resolution: &str) -> Result<TransactionDto> {
        transaction.resolve_dispute(resolution)?;
        Ok(TransactionDto::from(&transaction))
    }
}

/// Use Case: List Transactions
///
/// Returns a list of transactions.
pub struct ListTransactionsUseCase;

impl ListTransactionsUseCase {
    pub fn execute(transactions: &[Transaction]) -> ListTransactionsResponse {
        let transaction_dtos: Vec<TransactionDto> =
            transactions.iter().map(TransactionDto::from).collect();
        let count = transaction_dtos.len();

        ListTransactionsResponse {
            transactions: transaction_dtos,
            count,
        }
    }
}

/// Generate a secure token hash from transaction data
fn generate_token_hash(transaction: &Transaction) -> String {
    let mut hasher = Sha256::new();
    hasher.update(transaction.id().as_uuid().to_string().as_bytes());
    hasher.update(transaction.tx_signature().as_bytes());
    hasher.update(transaction.reader_wallet().to_string().as_bytes());
    hasher.update(transaction.article_id().to_string().as_bytes());
    format!("{:x}", hasher.finalize())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::domain::{
        entities::{
            AccessTokenId, Blockchain, Creator, CreatorStatus, PaywallArticle, TransactionStatus,
        },
        repositories::{
            AccessTokenQuery, ArticleQuery, CreatorQuery, RevenueDataPoint, RevenueGranularity,
            TransactionQuery,
        },
        value_objects::CreatorId,
    };
    use async_trait::async_trait;
    use chrono::{DateTime, Utc};
    use std::sync::Mutex;

    const VALID_WALLET: &str = "9WzDXwBbmkg8ZTbNMqUxvQRAyrZzDsGYdLVL9zYtAWWM";
    const VALID_SIGNATURE: &str =
        "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9g8eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9g";

    struct MockTransactionRepository {
        transactions: Mutex<Vec<Transaction>>,
    }

    impl MockTransactionRepository {
        fn new() -> Self {
            Self {
                transactions: Mutex::new(Vec::new()),
            }
        }
    }

    #[async_trait]
    impl TransactionRepository for MockTransactionRepository {
        async fn save(&self, transaction: &Transaction) -> Result<()> {
            let mut transactions = self.transactions.lock().unwrap();
            if let Some(pos) = transactions.iter().position(|t| t.id() == transaction.id()) {
                transactions[pos] = transaction.clone();
            } else {
                transactions.push(transaction.clone());
            }
            Ok(())
        }

        async fn find_by_id(&self, id: &TransactionId) -> Result<Option<Transaction>> {
            let transactions = self.transactions.lock().unwrap();
            Ok(transactions.iter().find(|t| t.id() == id).cloned())
        }

        async fn find_by_signature(&self, signature: &str) -> Result<Option<Transaction>> {
            let transactions = self.transactions.lock().unwrap();
            Ok(transactions
                .iter()
                .find(|t| t.tx_signature() == signature)
                .cloned())
        }

        async fn find_by_article(
            &self,
            _article_id: &ArticleId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<Transaction>> {
            Ok(Vec::new())
        }

        async fn find_by_creator(
            &self,
            _creator_id: &CreatorId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<Transaction>> {
            Ok(Vec::new())
        }

        async fn find_by_reader(
            &self,
            _wallet: &WalletAddress,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<Transaction>> {
            Ok(Vec::new())
        }

        async fn find_by_status(
            &self,
            _status: TransactionStatus,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<Transaction>> {
            Ok(Vec::new())
        }

        async fn count(&self) -> Result<usize> {
            Ok(self.transactions.lock().unwrap().len())
        }

        async fn count_by_status(&self, _status: TransactionStatus) -> Result<usize> {
            Ok(0)
        }

        async fn get_creator_revenue(&self, _creator_id: &CreatorId) -> Result<u64> {
            Ok(0)
        }

        async fn get_article_revenue(&self, _article_id: &ArticleId) -> Result<u64> {
            Ok(0)
        }

        async fn query(&self, _query: &TransactionQuery) -> Result<Vec<Transaction>> {
            Ok(Vec::new())
        }

        async fn get_revenue_by_period(
            &self,
            _creator_id: &CreatorId,
            _start_date: DateTime<Utc>,
            _end_date: DateTime<Utc>,
            _granularity: RevenueGranularity,
        ) -> Result<Vec<RevenueDataPoint>> {
            Ok(Vec::new())
        }
    }

    struct MockArticleRepository {
        articles: Mutex<Vec<PaywallArticle>>,
    }

    impl MockArticleRepository {
        fn new() -> Self {
            Self {
                articles: Mutex::new(Vec::new()),
            }
        }

        fn add_article(&self, article: PaywallArticle) {
            self.articles.lock().unwrap().push(article);
        }
    }

    #[async_trait]
    impl ArticleRepository for MockArticleRepository {
        async fn save(&self, article: &PaywallArticle) -> Result<()> {
            let mut articles = self.articles.lock().unwrap();
            if let Some(pos) = articles.iter().position(|a| a.id() == article.id()) {
                articles[pos] = article.clone();
            } else {
                articles.push(article.clone());
            }
            Ok(())
        }

        async fn find_by_id(&self, id: &ArticleId) -> Result<Option<PaywallArticle>> {
            let articles = self.articles.lock().unwrap();
            Ok(articles.iter().find(|a| a.id() == id).cloned())
        }

        async fn find_by_url(&self, _url: &str) -> Result<Option<PaywallArticle>> {
            Ok(None)
        }

        async fn find_by_creator(
            &self,
            _creator_id: &CreatorId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn find_by_tenant(
            &self,
            _tenant_id: &TenantId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn find_active_by_creator(
            &self,
            _creator_id: &CreatorId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn find_by_status(
            &self,
            _status: crate::domain::entities::ArticleStatus,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn count(&self) -> Result<usize> {
            Ok(0)
        }

        async fn count_by_creator(&self, _creator_id: &CreatorId) -> Result<usize> {
            Ok(0)
        }

        async fn count_by_status(
            &self,
            _status: crate::domain::entities::ArticleStatus,
        ) -> Result<usize> {
            Ok(0)
        }

        async fn delete(&self, _id: &ArticleId) -> Result<bool> {
            Ok(false)
        }

        async fn query(&self, _query: &ArticleQuery) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn find_top_by_revenue(
            &self,
            _creator_id: Option<&CreatorId>,
            _limit: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }

        async fn find_recent(
            &self,
            _creator_id: Option<&CreatorId>,
            _limit: usize,
        ) -> Result<Vec<PaywallArticle>> {
            Ok(Vec::new())
        }
    }

    struct MockCreatorRepository {
        creators: Mutex<Vec<Creator>>,
    }

    impl MockCreatorRepository {
        fn new() -> Self {
            Self {
                creators: Mutex::new(Vec::new()),
            }
        }

        fn add_creator(&self, creator: Creator) {
            self.creators.lock().unwrap().push(creator);
        }
    }

    #[async_trait]
    impl CreatorRepository for MockCreatorRepository {
        async fn create(&self, creator: Creator) -> Result<Creator> {
            let mut creators = self.creators.lock().unwrap();
            creators.push(creator.clone());
            Ok(creator)
        }

        async fn save(&self, creator: &Creator) -> Result<()> {
            let mut creators = self.creators.lock().unwrap();
            if let Some(pos) = creators.iter().position(|c| c.id() == creator.id()) {
                creators[pos] = creator.clone();
            }
            Ok(())
        }

        async fn find_by_id(&self, id: &CreatorId) -> Result<Option<Creator>> {
            let creators = self.creators.lock().unwrap();
            Ok(creators.iter().find(|c| c.id() == id).cloned())
        }

        async fn find_by_email(&self, _email: &str) -> Result<Option<Creator>> {
            Ok(None)
        }

        async fn find_by_wallet(&self, _wallet: &WalletAddress) -> Result<Option<Creator>> {
            Ok(None)
        }

        async fn find_by_tenant(
            &self,
            _tenant_id: &TenantId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<Creator>> {
            Ok(Vec::new())
        }

        async fn find_active(&self, _limit: usize, _offset: usize) -> Result<Vec<Creator>> {
            Ok(Vec::new())
        }

        async fn count(&self) -> Result<usize> {
            Ok(0)
        }

        async fn count_by_status(&self, _status: CreatorStatus) -> Result<usize> {
            Ok(0)
        }

        async fn delete(&self, _id: &CreatorId) -> Result<bool> {
            Ok(false)
        }

        async fn query(&self, _query: &CreatorQuery) -> Result<Vec<Creator>> {
            Ok(Vec::new())
        }
    }

    struct MockAccessTokenRepository {
        tokens: Mutex<Vec<AccessToken>>,
    }

    impl MockAccessTokenRepository {
        fn new() -> Self {
            Self {
                tokens: Mutex::new(Vec::new()),
            }
        }
    }

    #[async_trait]
    impl AccessTokenRepository for MockAccessTokenRepository {
        async fn save(&self, token: &AccessToken) -> Result<()> {
            self.tokens.lock().unwrap().push(token.clone());
            Ok(())
        }

        async fn find_by_id(&self, _id: &AccessTokenId) -> Result<Option<AccessToken>> {
            Ok(None)
        }

        async fn find_by_hash(&self, _token_hash: &str) -> Result<Option<AccessToken>> {
            Ok(None)
        }

        async fn find_by_transaction(
            &self,
            _transaction_id: &TransactionId,
        ) -> Result<Option<AccessToken>> {
            Ok(None)
        }

        async fn find_by_article_and_wallet(
            &self,
            _article_id: &ArticleId,
            _wallet: &WalletAddress,
        ) -> Result<Vec<AccessToken>> {
            Ok(Vec::new())
        }

        async fn find_valid_token(
            &self,
            _article_id: &ArticleId,
            _wallet: &WalletAddress,
        ) -> Result<Option<AccessToken>> {
            Ok(None)
        }

        async fn find_by_reader(
            &self,
            _wallet: &WalletAddress,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<AccessToken>> {
            Ok(Vec::new())
        }

        async fn find_by_article(
            &self,
            _article_id: &ArticleId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<AccessToken>> {
            Ok(Vec::new())
        }

        async fn find_by_creator(
            &self,
            _creator_id: &CreatorId,
            _limit: usize,
            _offset: usize,
        ) -> Result<Vec<AccessToken>> {
            Ok(Vec::new())
        }

        async fn count(&self) -> Result<usize> {
            Ok(0)
        }

        async fn count_valid(&self) -> Result<usize> {
            Ok(0)
        }

        async fn count_by_article(&self, _article_id: &ArticleId) -> Result<usize> {
            Ok(0)
        }

        async fn revoke(&self, _id: &AccessTokenId, _reason: &str) -> Result<bool> {
            Ok(true)
        }

        async fn revoke_by_transaction(
            &self,
            _transaction_id: &TransactionId,
            _reason: &str,
        ) -> Result<usize> {
            Ok(1)
        }

        async fn delete_expired(&self, _before: DateTime<Utc>) -> Result<usize> {
            Ok(0)
        }

        async fn query(&self, _query: &AccessTokenQuery) -> Result<Vec<AccessToken>> {
            Ok(Vec::new())
        }
    }

    #[tokio::test]
    async fn test_initiate_payment() {
        let tx_repo = Arc::new(MockTransactionRepository::new());
        let article_repo = Arc::new(MockArticleRepository::new());
        let creator_repo = Arc::new(MockCreatorRepository::new());

        // Create and add creator
        let tenant_id = TenantId::new("test-tenant".to_string()).unwrap();
        let wallet = WalletAddress::new(VALID_WALLET.to_string()).unwrap();
        let mut creator = Creator::new(
            tenant_id.clone(),
            "creator@example.com".to_string(),
            wallet,
            None,
        )
        .unwrap();
        creator.verify_email();
        let creator_id = *creator.id();
        creator_repo.add_creator(creator);

        // Create and add article
        let article_id = ArticleId::new("test-article".to_string()).unwrap();
        let article = PaywallArticle::new(
            article_id.clone(),
            tenant_id.clone(),
            creator_id,
            "Test Article".to_string(),
            "https://example.com/article".to_string(),
            50,
        )
        .unwrap();
        article_repo.add_article(article);

        let use_case =
            InitiatePaymentUseCase::new(tx_repo.clone(), article_repo.clone(), creator_repo);

        let request = InitiatePaymentRequest {
            tenant_id: "test-tenant".to_string(),
            article_id: "test-article".to_string(),
            reader_wallet: "11111111111111111111111111111111".to_string(),
            tx_signature: VALID_SIGNATURE.to_string(),
            blockchain: None,
        };

        let response = use_case.execute(request).await;
        assert!(response.is_ok());

        let response = response.unwrap();
        assert_eq!(response.transaction.amount_cents, 50);
        assert_eq!(
            response.transaction.status,
            crate::application::dto::TransactionStatusDto::Pending
        );
    }

    #[test]
    fn test_list_transactions() {
        let tenant_id = TenantId::new("test-tenant".to_string()).unwrap();
        let article_id = ArticleId::new("test-article".to_string()).unwrap();
        let creator_id = CreatorId::new();
        let wallet = WalletAddress::new(VALID_WALLET.to_string()).unwrap();

        let transactions = vec![
            Transaction::new(
                tenant_id,
                article_id,
                creator_id,
                wallet,
                Money::usd_cents(50),
                10,
                Blockchain::Solana,
                VALID_SIGNATURE.to_string(),
            )
            .unwrap(),
        ];

        let response = ListTransactionsUseCase::execute(&transactions);
        assert_eq!(response.count, 1);
        assert_eq!(response.transactions.len(), 1);
    }
}