kaccy-core 0.2.0

Core business logic for Kaccy Protocol - batching, fee optimization, and transaction management
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
//! Trade execution logic

use crate::error::{CoreError, Result};
use crate::models::{Balance, Order, OrderType, Trade};
use crate::pricing::{FeeBreakdown, FeeSchedule};
use chrono::Utc;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use sqlx::PgPool;
use uuid::Uuid;

/// Trade executor handles atomic trade execution with ACID guarantees
pub struct TradeExecutor {
    pool: PgPool,
    fee_schedule: FeeSchedule,
}

impl TradeExecutor {
    /// Creates a new `TradeExecutor` with the default fee schedule.
    pub fn new(pool: PgPool) -> Self {
        Self {
            pool,
            fee_schedule: FeeSchedule::default(),
        }
    }

    /// Creates a new `TradeExecutor` with the specified fee schedule.
    pub fn with_fee_schedule(pool: PgPool, fee_schedule: FeeSchedule) -> Self {
        Self { pool, fee_schedule }
    }

    /// Calculate fees for a trade
    pub fn calculate_fees(&self, amount_btc: Decimal) -> FeeBreakdown {
        self.fee_schedule.calculate(amount_btc)
    }

    /// Execute a buy order after payment is confirmed
    pub async fn execute_buy_order(&self, order_id: Uuid) -> Result<Trade> {
        let mut tx = self.pool.begin().await?;

        // 1. Get and lock the order
        let order: Order = sqlx::query_as(
            r#"
            SELECT * FROM orders
            WHERE order_id = $1 AND status = 'pending'
            FOR UPDATE
            "#,
        )
        .bind(order_id)
        .fetch_optional(&mut *tx)
        .await?
        .ok_or_else(|| CoreError::NotFound("Order not found".to_string()))?;

        if order.order_type != OrderType::Buy {
            return Err(CoreError::Validation(
                "Order is not a buy order".to_string(),
            ));
        }

        // 2. Get and lock the token, also get issuer_user_id for royalty
        let (circulating_supply, total_supply, issuer_user_id): (Decimal, Decimal, Uuid) =
            sqlx::query_as(
                r#"
            SELECT circulating_supply, total_supply, issuer_user_id FROM tokens
            WHERE token_id = $1
            FOR UPDATE
            "#,
            )
            .bind(order.token_id)
            .fetch_one(&mut *tx)
            .await?;

        // Check supply limit
        if circulating_supply + order.amount > total_supply {
            return Err(CoreError::Validation(
                "Would exceed total supply".to_string(),
            ));
        }

        // 3. Calculate fees
        let fees = self.calculate_fees(order.total_btc);

        // 4. Update token circulating supply
        sqlx::query(
            r#"
            UPDATE tokens
            SET circulating_supply = circulating_supply + $1
            WHERE token_id = $2
            "#,
        )
        .bind(order.amount)
        .bind(order.token_id)
        .execute(&mut *tx)
        .await?;

        // 5. Update or insert user balance
        sqlx::query(
            r#"
            INSERT INTO balances (balance_id, user_id, token_id, amount, locked_amount, updated_at)
            VALUES ($1, $2, $3, $4, 0, NOW())
            ON CONFLICT (user_id, token_id)
            DO UPDATE SET amount = balances.amount + $4, updated_at = NOW()
            "#,
        )
        .bind(Uuid::new_v4())
        .bind(order.user_id)
        .bind(order.token_id)
        .bind(order.amount)
        .execute(&mut *tx)
        .await?;

        // 6. Create trade record
        let trade_id = Uuid::new_v4();
        let trade = Trade {
            trade_id,
            buyer_user_id: order.user_id,
            seller_user_id: None, // Bonding curve buy
            token_id: order.token_id,
            amount: order.amount,
            price_btc: order.price_btc,
            total_btc: order.total_btc,
            platform_fee_btc: fees.platform_fee_btc,
            issuer_royalty_btc: fees.issuer_royalty_btc,
            executed_at: Utc::now(),
        };

        sqlx::query(
            r#"
            INSERT INTO trades (trade_id, buyer_user_id, seller_user_id, token_id, amount, price_btc, total_btc, platform_fee_btc, issuer_royalty_btc, executed_at)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
            "#,
        )
        .bind(trade.trade_id)
        .bind(trade.buyer_user_id)
        .bind(trade.seller_user_id)
        .bind(trade.token_id)
        .bind(trade.amount)
        .bind(trade.price_btc)
        .bind(trade.total_btc)
        .bind(trade.platform_fee_btc)
        .bind(trade.issuer_royalty_btc)
        .bind(trade.executed_at)
        .execute(&mut *tx)
        .await?;

        // 7. Update order status
        sqlx::query(
            r#"
            UPDATE orders
            SET status = 'completed', completed_at = NOW()
            WHERE order_id = $1
            "#,
        )
        .bind(order_id)
        .execute(&mut *tx)
        .await?;

        // 8. Record issuer royalty (credit to issuer's BTC balance)
        if fees.issuer_royalty_btc > dec!(0) {
            sqlx::query(
                r#"
                INSERT INTO issuer_earnings (earning_id, user_id, token_id, trade_id, amount_btc, created_at)
                VALUES ($1, $2, $3, $4, $5, NOW())
                "#,
            )
            .bind(Uuid::new_v4())
            .bind(issuer_user_id)
            .bind(order.token_id)
            .bind(trade.trade_id)
            .bind(fees.issuer_royalty_btc)
            .execute(&mut *tx)
            .await
            .ok(); // Don't fail if table doesn't exist yet
        }

        tx.commit().await?;

        tracing::info!(
            order_id = %order_id,
            trade_id = %trade_id,
            amount = %order.amount,
            fees = %fees.total_fees_btc,
            "Buy order executed successfully"
        );

        Ok(trade)
    }

    /// Execute a sell order (immediate execution against bonding curve)
    pub async fn execute_sell_order(&self, order_id: Uuid) -> Result<Trade> {
        let mut tx = self.pool.begin().await?;

        // 1. Get and lock the order
        let order: Order = sqlx::query_as(
            r#"
            SELECT * FROM orders
            WHERE order_id = $1 AND status = 'pending'
            FOR UPDATE
            "#,
        )
        .bind(order_id)
        .fetch_optional(&mut *tx)
        .await?
        .ok_or_else(|| CoreError::NotFound("Order not found".to_string()))?;

        if order.order_type != OrderType::Sell {
            return Err(CoreError::Validation(
                "Order is not a sell order".to_string(),
            ));
        }

        // 2. Get and lock user balance
        let balance: Balance = sqlx::query_as(
            r#"
            SELECT * FROM balances
            WHERE user_id = $1 AND token_id = $2
            FOR UPDATE
            "#,
        )
        .bind(order.user_id)
        .bind(order.token_id)
        .fetch_optional(&mut *tx)
        .await?
        .ok_or_else(|| CoreError::InsufficientBalance {
            required: order.amount,
            available: dec!(0),
        })?;

        // Check sufficient balance
        if balance.available() < order.amount {
            return Err(CoreError::InsufficientBalance {
                required: order.amount,
                available: balance.available(),
            });
        }

        // 3. Get and lock the token
        let (circulating_supply, issuer_user_id): (Decimal, Uuid) = sqlx::query_as(
            r#"
            SELECT circulating_supply, issuer_user_id FROM tokens
            WHERE token_id = $1
            FOR UPDATE
            "#,
        )
        .bind(order.token_id)
        .fetch_one(&mut *tx)
        .await?;

        // Check we're not selling more than circulating
        if order.amount > circulating_supply {
            return Err(CoreError::Validation(
                "Cannot sell more than circulating supply".to_string(),
            ));
        }

        // 4. Calculate fees on proceeds
        let fees = self.calculate_fees(order.total_btc);

        // 5. Deduct from user balance
        sqlx::query(
            r#"
            UPDATE balances
            SET amount = amount - $1, updated_at = NOW()
            WHERE user_id = $2 AND token_id = $3
            "#,
        )
        .bind(order.amount)
        .bind(order.user_id)
        .bind(order.token_id)
        .execute(&mut *tx)
        .await?;

        // 6. Update token circulating supply
        sqlx::query(
            r#"
            UPDATE tokens
            SET circulating_supply = circulating_supply - $1
            WHERE token_id = $2
            "#,
        )
        .bind(order.amount)
        .bind(order.token_id)
        .execute(&mut *tx)
        .await?;

        // 7. Create trade record
        let trade_id = Uuid::new_v4();
        let trade = Trade {
            trade_id,
            buyer_user_id: Uuid::nil(), // Bonding curve is the "buyer"
            seller_user_id: Some(order.user_id),
            token_id: order.token_id,
            amount: order.amount,
            price_btc: order.price_btc,
            total_btc: order.total_btc,
            platform_fee_btc: fees.platform_fee_btc,
            issuer_royalty_btc: fees.issuer_royalty_btc,
            executed_at: Utc::now(),
        };

        sqlx::query(
            r#"
            INSERT INTO trades (trade_id, buyer_user_id, seller_user_id, token_id, amount, price_btc, total_btc, platform_fee_btc, issuer_royalty_btc, executed_at)
            VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
            "#,
        )
        .bind(trade.trade_id)
        .bind(trade.buyer_user_id)
        .bind(trade.seller_user_id)
        .bind(trade.token_id)
        .bind(trade.amount)
        .bind(trade.price_btc)
        .bind(trade.total_btc)
        .bind(trade.platform_fee_btc)
        .bind(trade.issuer_royalty_btc)
        .bind(trade.executed_at)
        .execute(&mut *tx)
        .await?;

        // 8. Update order status
        sqlx::query(
            r#"
            UPDATE orders
            SET status = 'completed', completed_at = NOW()
            WHERE order_id = $1
            "#,
        )
        .bind(order_id)
        .execute(&mut *tx)
        .await?;

        // 9. Record pending BTC payout to seller
        let net_proceeds = fees.net_amount_btc;
        sqlx::query(
            r#"
            INSERT INTO pending_payouts (payout_id, user_id, trade_id, amount_btc, status, created_at)
            VALUES ($1, $2, $3, $4, 'pending', NOW())
            "#,
        )
        .bind(Uuid::new_v4())
        .bind(order.user_id)
        .bind(trade.trade_id)
        .bind(net_proceeds)
        .execute(&mut *tx)
        .await
        .ok(); // Don't fail if table doesn't exist yet

        // 10. Record issuer royalty
        if fees.issuer_royalty_btc > dec!(0) {
            sqlx::query(
                r#"
                INSERT INTO issuer_earnings (earning_id, user_id, token_id, trade_id, amount_btc, created_at)
                VALUES ($1, $2, $3, $4, $5, NOW())
                "#,
            )
            .bind(Uuid::new_v4())
            .bind(issuer_user_id)
            .bind(order.token_id)
            .bind(trade.trade_id)
            .bind(fees.issuer_royalty_btc)
            .execute(&mut *tx)
            .await
            .ok();
        }

        tx.commit().await?;

        tracing::info!(
            order_id = %order_id,
            trade_id = %trade_id,
            amount = %order.amount,
            net_proceeds = %net_proceeds,
            "Sell order executed successfully"
        );

        Ok(trade)
    }

    /// Cancel a pending order
    pub async fn cancel_order(&self, order_id: Uuid, user_id: Uuid) -> Result<()> {
        let result = sqlx::query(
            r#"
            UPDATE orders
            SET status = 'cancelled', completed_at = NOW()
            WHERE order_id = $1 AND user_id = $2 AND status = 'pending'
            "#,
        )
        .bind(order_id)
        .bind(user_id)
        .execute(&self.pool)
        .await?;

        if result.rows_affected() == 0 {
            return Err(CoreError::NotFound(
                "Order not found or already processed".to_string(),
            ));
        }

        tracing::info!(order_id = %order_id, "Order cancelled");
        Ok(())
    }

    /// Expire old pending orders
    pub async fn expire_stale_orders(&self, max_age_hours: i64) -> Result<u64> {
        let result = sqlx::query(
            r#"
            UPDATE orders
            SET status = 'expired', completed_at = NOW()
            WHERE status = 'pending'
            AND created_at < NOW() - INTERVAL '1 hour' * $1
            "#,
        )
        .bind(max_age_hours)
        .execute(&self.pool)
        .await?;

        let count = result.rows_affected();
        if count > 0 {
            tracing::info!(count = count, "Expired stale orders");
        }
        Ok(count)
    }

    /// Execute multiple buy orders in a single transaction
    /// Returns successful trades and failed order IDs
    pub async fn execute_buy_orders_batch(
        &self,
        order_ids: Vec<Uuid>,
    ) -> Result<BatchExecutionResult> {
        let mut successful_trades = Vec::new();
        let mut failed_orders = Vec::new();

        for order_id in order_ids {
            match self.execute_buy_order(order_id).await {
                Ok(trade) => successful_trades.push(trade),
                Err(e) => {
                    tracing::warn!(order_id = %order_id, error = %e, "Failed to execute buy order in batch");
                    failed_orders.push((order_id, e.to_string()));
                }
            }
        }

        tracing::info!(
            successful = successful_trades.len(),
            failed = failed_orders.len(),
            "Batch buy order execution completed"
        );

        Ok(BatchExecutionResult {
            successful_trades,
            failed_orders,
        })
    }

    /// Execute multiple sell orders in a single transaction
    /// Returns successful trades and failed order IDs
    pub async fn execute_sell_orders_batch(
        &self,
        order_ids: Vec<Uuid>,
    ) -> Result<BatchExecutionResult> {
        let mut successful_trades = Vec::new();
        let mut failed_orders = Vec::new();

        for order_id in order_ids {
            match self.execute_sell_order(order_id).await {
                Ok(trade) => successful_trades.push(trade),
                Err(e) => {
                    tracing::warn!(order_id = %order_id, error = %e, "Failed to execute sell order in batch");
                    failed_orders.push((order_id, e.to_string()));
                }
            }
        }

        tracing::info!(
            successful = successful_trades.len(),
            failed = failed_orders.len(),
            "Batch sell order execution completed"
        );

        Ok(BatchExecutionResult {
            successful_trades,
            failed_orders,
        })
    }

    /// Get pending orders for a specific token
    pub async fn get_pending_orders_by_token(&self, token_id: Uuid) -> Result<Vec<Order>> {
        let orders = sqlx::query_as::<_, Order>(
            r#"
            SELECT * FROM orders
            WHERE token_id = $1 AND status = 'pending'
            ORDER BY created_at ASC
            "#,
        )
        .bind(token_id)
        .fetch_all(&self.pool)
        .await?;

        Ok(orders)
    }

    /// Get pending orders for a specific user
    pub async fn get_pending_orders_by_user(&self, user_id: Uuid) -> Result<Vec<Order>> {
        let orders = sqlx::query_as::<_, Order>(
            r#"
            SELECT * FROM orders
            WHERE user_id = $1 AND status = 'pending'
            ORDER BY created_at ASC
            "#,
        )
        .bind(user_id)
        .fetch_all(&self.pool)
        .await?;

        Ok(orders)
    }
}

/// Result of batch order execution
#[derive(Debug)]
pub struct BatchExecutionResult {
    /// Trades that were executed successfully.
    pub successful_trades: Vec<Trade>,
    /// Orders that failed, paired with their error messages.
    pub failed_orders: Vec<(Uuid, String)>,
}

impl BatchExecutionResult {
    /// Get total number of orders processed
    pub fn total_processed(&self) -> usize {
        self.successful_trades.len() + self.failed_orders.len()
    }

    /// Get success rate as percentage
    pub fn success_rate(&self) -> Decimal {
        if self.total_processed() == 0 {
            return dec!(0);
        }
        let successful = Decimal::from(self.successful_trades.len());
        let total = Decimal::from(self.total_processed());
        (successful / total) * dec!(100)
    }

    /// Check if all orders succeeded
    pub fn all_successful(&self) -> bool {
        self.failed_orders.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::pricing::FeeSchedule;
    use chrono::Utc;
    use rust_decimal_macros::dec;

    /// Build a minimal valid `Trade` for use in test fixtures.
    fn make_trade() -> Trade {
        Trade {
            trade_id: Uuid::new_v4(),
            buyer_user_id: Uuid::new_v4(),
            seller_user_id: None,
            token_id: Uuid::new_v4(),
            amount: dec!(10),
            price_btc: dec!(0.001),
            total_btc: dec!(0.01),
            platform_fee_btc: dec!(0.00025),
            issuer_royalty_btc: dec!(0.00005),
            executed_at: Utc::now(),
        }
    }

    // ----------------------------------------------------------------
    // BatchExecutionResult — total_processed
    // ----------------------------------------------------------------

    #[test]
    fn test_total_processed_empty_batch() {
        let result = BatchExecutionResult {
            successful_trades: vec![],
            failed_orders: vec![],
        };
        assert_eq!(
            result.total_processed(),
            0,
            "Empty batch must report zero total processed"
        );
    }

    #[test]
    fn test_total_processed_all_successful() {
        let result = BatchExecutionResult {
            successful_trades: vec![make_trade(), make_trade(), make_trade()],
            failed_orders: vec![],
        };
        assert_eq!(
            result.total_processed(),
            3,
            "All-successful batch must count only the successful trades"
        );
    }

    #[test]
    fn test_total_processed_all_failed() {
        let result = BatchExecutionResult {
            successful_trades: vec![],
            failed_orders: vec![
                (Uuid::new_v4(), "supply exceeded".to_string()),
                (Uuid::new_v4(), "order not found".to_string()),
            ],
        };
        assert_eq!(
            result.total_processed(),
            2,
            "All-failed batch must count only the failed orders"
        );
    }

    #[test]
    fn test_total_processed_mixed_batch() {
        let result = BatchExecutionResult {
            successful_trades: vec![make_trade(), make_trade()],
            failed_orders: vec![(Uuid::new_v4(), "validation error".to_string())],
        };
        assert_eq!(
            result.total_processed(),
            3,
            "Mixed batch must sum successful and failed counts"
        );
    }

    // ----------------------------------------------------------------
    // BatchExecutionResult — success_rate
    // ----------------------------------------------------------------

    #[test]
    fn test_success_rate_empty_batch_returns_zero() {
        let result = BatchExecutionResult {
            successful_trades: vec![],
            failed_orders: vec![],
        };
        assert_eq!(
            result.success_rate(),
            dec!(0),
            "Empty batch must return success_rate of 0"
        );
    }

    #[test]
    fn test_success_rate_all_successful_is_100() {
        let result = BatchExecutionResult {
            successful_trades: vec![make_trade(), make_trade()],
            failed_orders: vec![],
        };
        assert_eq!(
            result.success_rate(),
            dec!(100),
            "All-successful batch must return success_rate of 100"
        );
    }

    #[test]
    fn test_success_rate_all_failed_is_zero() {
        let result = BatchExecutionResult {
            successful_trades: vec![],
            failed_orders: vec![
                (Uuid::new_v4(), "err".to_string()),
                (Uuid::new_v4(), "err".to_string()),
            ],
        };
        assert_eq!(
            result.success_rate(),
            dec!(0),
            "All-failed batch must return success_rate of 0"
        );
    }

    #[test]
    fn test_success_rate_fifty_percent() {
        let result = BatchExecutionResult {
            successful_trades: vec![make_trade()],
            failed_orders: vec![(Uuid::new_v4(), "err".to_string())],
        };
        assert_eq!(
            result.success_rate(),
            dec!(50),
            "One success out of two total must return success_rate of 50"
        );
    }

    #[test]
    fn test_success_rate_one_in_four_is_25() {
        let result = BatchExecutionResult {
            successful_trades: vec![make_trade()],
            failed_orders: vec![
                (Uuid::new_v4(), "e".to_string()),
                (Uuid::new_v4(), "e".to_string()),
                (Uuid::new_v4(), "e".to_string()),
            ],
        };
        assert_eq!(
            result.success_rate(),
            dec!(25),
            "One success out of four total must return success_rate of 25"
        );
    }

    // ----------------------------------------------------------------
    // BatchExecutionResult — all_successful
    // ----------------------------------------------------------------

    #[test]
    fn test_all_successful_true_when_no_failures() {
        let result = BatchExecutionResult {
            successful_trades: vec![make_trade()],
            failed_orders: vec![],
        };
        assert!(
            result.all_successful(),
            "all_successful must be true when failed_orders is empty"
        );
    }

    #[test]
    fn test_all_successful_false_when_any_failure() {
        let result = BatchExecutionResult {
            successful_trades: vec![make_trade()],
            failed_orders: vec![(Uuid::new_v4(), "one failure".to_string())],
        };
        assert!(
            !result.all_successful(),
            "all_successful must be false when there is at least one failure"
        );
    }

    #[test]
    fn test_all_successful_true_for_empty_batch() {
        // Empty batch has no failures, so all_successful is vacuously true
        let result = BatchExecutionResult {
            successful_trades: vec![],
            failed_orders: vec![],
        };
        assert!(
            result.all_successful(),
            "all_successful must be true for an empty batch (no failures)"
        );
    }

    // ----------------------------------------------------------------
    // FeeSchedule::calculate (pure logic used by TradeExecutor)
    // ----------------------------------------------------------------

    #[test]
    fn test_fee_calculation_default_schedule() {
        let schedule = FeeSchedule::default();
        let breakdown = schedule.calculate(dec!(1.0));

        // platform fee: 1.0 * 0.025 = 0.025
        assert_eq!(
            breakdown.platform_fee_btc,
            dec!(0.025),
            "Default platform fee must be 2.5% of trade amount"
        );
        // issuer royalty: 1.0 * 0.005 = 0.005
        assert_eq!(
            breakdown.issuer_royalty_btc,
            dec!(0.005),
            "Default issuer royalty must be 0.5% of trade amount"
        );
        // net: 1.0 - 0.025 - 0.005 = 0.97
        assert_eq!(
            breakdown.net_amount_btc,
            dec!(0.97),
            "Net amount must be trade amount minus all fees"
        );
        assert_eq!(
            breakdown.total_fees_btc,
            dec!(0.03),
            "Total fees must be 3% of trade amount"
        );
    }

    #[test]
    fn test_fee_calculation_zero_amount() {
        let schedule = FeeSchedule::default();
        let breakdown = schedule.calculate(dec!(0));

        assert_eq!(breakdown.platform_fee_btc, dec!(0));
        assert_eq!(breakdown.issuer_royalty_btc, dec!(0));
        assert_eq!(breakdown.total_fees_btc, dec!(0));
        assert_eq!(breakdown.net_amount_btc, dec!(0));
    }

    #[test]
    fn test_fee_schedule_with_discount() {
        let schedule = FeeSchedule::default();
        let discounted = schedule.with_discount(dec!(50)); // 50% off platform fee

        // Platform fee halved: 0.025 * 0.5 = 0.0125
        assert_eq!(discounted.platform_fee_rate, dec!(0.0125));
        // Issuer royalty unchanged
        assert_eq!(
            discounted.issuer_royalty_rate, schedule.issuer_royalty_rate,
            "Royalty rate must not change with discount"
        );
    }

    #[test]
    fn test_fee_schedule_discount_capped_at_50pct() {
        let schedule = FeeSchedule::default();
        // Apply 100% discount — must be capped at 50%
        let discounted = schedule.with_discount(dec!(100));
        let capped = schedule.with_discount(dec!(50));

        assert_eq!(
            discounted.platform_fee_rate, capped.platform_fee_rate,
            "Discount must be capped at 50% of the platform fee rate"
        );
    }
}