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
//! Batch auction mechanism for MEV protection
//!
//! This module implements batch auctions (also called call auctions) where orders are collected
//! during a batch period and executed simultaneously at a uniform clearing price. This prevents
//! front-running and provides fairer price discovery.
//!
//! # How It Works
//!
//! 1. **Collection Phase**: Orders are submitted during the batch period
//! 2. **Price Discovery**: Find the price that maximizes matched volume
//! 3. **Execution**: All matched orders execute at the uniform clearing price
//! 4. **Settlement**: Update balances and create trade records
//!
//! # Benefits
//!
//! - Prevents front-running and sandwich attacks
//! - Fair price discovery (everyone gets same price)
//! - Reduces MEV extraction
//! - Better for large trades (less price impact)

use chrono::{DateTime, Duration, Utc};
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

use crate::error::{CoreError, Result};
use crate::models::Trade;
use crate::trading::order_book::{LimitOrder, OrderSide};

/// Batch auction configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchAuctionConfig {
    /// Duration of each batch period (e.g., 10 seconds, 1 minute)
    pub batch_duration: Duration,
    /// Minimum orders required to execute a batch
    pub min_orders: usize,
    /// Maximum price deviation from reference price (as percentage)
    pub max_price_deviation_pct: Decimal,
    /// Whether to allow partial fills
    pub allow_partial_fills: bool,
}

impl Default for BatchAuctionConfig {
    fn default() -> Self {
        Self {
            batch_duration: Duration::seconds(10),
            min_orders: 2,
            max_price_deviation_pct: dec!(20.0), // 20% max deviation
            allow_partial_fills: true,
        }
    }
}

/// Status of a batch auction
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BatchStatus {
    /// Collecting orders
    Collecting,
    /// Computing clearing price
    Computing,
    /// Executing matched orders
    Executing,
    /// Batch completed
    Completed,
    /// Batch cancelled (e.g., insufficient orders)
    Cancelled,
}

/// A batch auction instance
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchAuction {
    /// Unique batch ID
    pub id: Uuid,
    /// Token being traded
    pub token_id: Uuid,
    /// Batch start time
    pub start_time: DateTime<Utc>,
    /// Batch end time
    pub end_time: DateTime<Utc>,
    /// Current status
    pub status: BatchStatus,
    /// Collected buy orders
    pub buy_orders: Vec<LimitOrder>,
    /// Collected sell orders
    pub sell_orders: Vec<LimitOrder>,
    /// Clearing price (if computed)
    pub clearing_price: Option<Decimal>,
    /// Total volume matched
    pub matched_volume: Decimal,
    /// Configuration
    pub config: BatchAuctionConfig,
}

impl BatchAuction {
    /// Create a new batch auction
    pub fn new(token_id: Uuid, config: BatchAuctionConfig) -> Self {
        let start_time = Utc::now();
        let end_time = start_time + config.batch_duration;

        Self {
            id: Uuid::new_v4(),
            token_id,
            start_time,
            end_time,
            status: BatchStatus::Collecting,
            buy_orders: Vec::new(),
            sell_orders: Vec::new(),
            clearing_price: None,
            matched_volume: dec!(0),
            config,
        }
    }

    /// Check if the batch period has ended
    pub fn is_ended(&self) -> bool {
        Utc::now() >= self.end_time
    }

    /// Get remaining time in the batch period
    pub fn remaining_time(&self) -> Duration {
        if self.is_ended() {
            Duration::zero()
        } else {
            self.end_time - Utc::now()
        }
    }

    /// Add an order to the batch
    pub fn add_order(&mut self, order: LimitOrder) -> Result<()> {
        // Validate batch is collecting
        if self.status != BatchStatus::Collecting {
            return Err(CoreError::InvalidState(format!(
                "Batch is not collecting orders (status: {:?})",
                self.status
            )));
        }

        // Validate token matches
        if order.token_id != self.token_id {
            return Err(CoreError::Validation(format!(
                "Order token {} does not match batch token {}",
                order.token_id, self.token_id
            )));
        }

        // Add to appropriate side
        match order.side {
            OrderSide::Buy => self.buy_orders.push(order),
            OrderSide::Sell => self.sell_orders.push(order),
        }

        Ok(())
    }

    /// Get total buy volume at a given price
    fn buy_volume_at_price(&self, price: Decimal) -> Decimal {
        self.buy_orders
            .iter()
            .filter(|order| order.price >= price)
            .map(|order| order.amount)
            .sum()
    }

    /// Get total sell volume at a given price
    fn sell_volume_at_price(&self, price: Decimal) -> Decimal {
        self.sell_orders
            .iter()
            .filter(|order| order.price <= price)
            .map(|order| order.amount)
            .sum()
    }

    /// Compute the clearing price that maximizes matched volume
    pub fn compute_clearing_price(&mut self, reference_price: Option<Decimal>) -> Result<Decimal> {
        if self.status != BatchStatus::Collecting {
            return Err(CoreError::InvalidState(
                "Batch must be in Collecting state".to_string(),
            ));
        }

        // Check minimum orders
        let total_orders = self.buy_orders.len() + self.sell_orders.len();
        if total_orders < self.config.min_orders {
            self.status = BatchStatus::Cancelled;
            return Err(CoreError::InsufficientLiquidity(format!(
                "Insufficient orders: {} < {}",
                total_orders, self.config.min_orders
            )));
        }

        self.status = BatchStatus::Computing;

        // Collect all unique prices from orders
        let mut prices: Vec<Decimal> = self
            .buy_orders
            .iter()
            .chain(self.sell_orders.iter())
            .map(|order| order.price)
            .collect();
        prices.sort();
        prices.dedup();

        // If we have a reference price, filter by max deviation
        if let Some(ref_price) = reference_price {
            let max_deviation = (self.config.max_price_deviation_pct / dec!(100)) * ref_price;
            let min_price = ref_price - max_deviation;
            let max_price = ref_price + max_deviation;
            prices.retain(|&p| p >= min_price && p <= max_price);

            if prices.is_empty() {
                self.status = BatchStatus::Cancelled;
                return Err(CoreError::Validation(
                    "No prices within acceptable deviation".to_string(),
                ));
            }
        }

        // Find price that maximizes matched volume
        let mut best_price = dec!(0);
        let mut max_volume = dec!(0);

        for &price in &prices {
            let buy_vol = self.buy_volume_at_price(price);
            let sell_vol = self.sell_volume_at_price(price);
            let matched_vol = buy_vol.min(sell_vol);

            if matched_vol > max_volume {
                max_volume = matched_vol;
                best_price = price;
            }
        }

        if max_volume.is_zero() {
            self.status = BatchStatus::Cancelled;
            return Err(CoreError::InsufficientLiquidity(
                "No overlapping buy/sell orders".to_string(),
            ));
        }

        self.clearing_price = Some(best_price);
        self.matched_volume = max_volume;

        Ok(best_price)
    }

    /// Execute the batch at the clearing price
    pub fn execute(&mut self) -> Result<Vec<BatchMatch>> {
        let clearing_price = self
            .clearing_price
            .ok_or_else(|| CoreError::InvalidState("Clearing price not computed".to_string()))?;

        if self.status != BatchStatus::Computing {
            return Err(CoreError::InvalidState(
                "Batch must be in Computing state".to_string(),
            ));
        }

        self.status = BatchStatus::Executing;

        // Get eligible buy orders (price >= clearing price)
        let mut eligible_buys: Vec<&LimitOrder> = self
            .buy_orders
            .iter()
            .filter(|order| order.price >= clearing_price)
            .collect();

        // Get eligible sell orders (price <= clearing price)
        let mut eligible_sells: Vec<&LimitOrder> = self
            .sell_orders
            .iter()
            .filter(|order| order.price <= clearing_price)
            .collect();

        // Sort by price-time priority
        eligible_buys.sort_by(|a, b| {
            b.price
                .cmp(&a.price)
                .then_with(|| a.timestamp.cmp(&b.timestamp))
        });
        eligible_sells.sort_by(|a, b| {
            a.price
                .cmp(&b.price)
                .then_with(|| a.timestamp.cmp(&b.timestamp))
        });

        let mut matches = Vec::new();
        let mut buy_idx = 0;
        let mut sell_idx = 0;
        let mut buy_filled = dec!(0);
        let mut sell_filled = dec!(0);

        // Match orders
        while buy_idx < eligible_buys.len() && sell_idx < eligible_sells.len() {
            let buy_order = eligible_buys[buy_idx];
            let sell_order = eligible_sells[sell_idx];

            let buy_remaining = buy_order.amount - buy_filled;
            let sell_remaining = sell_order.amount - sell_filled;

            if buy_remaining.is_zero() {
                buy_idx += 1;
                buy_filled = dec!(0);
                continue;
            }

            if sell_remaining.is_zero() {
                sell_idx += 1;
                sell_filled = dec!(0);
                continue;
            }

            let match_amount = buy_remaining.min(sell_remaining);

            matches.push(BatchMatch {
                buy_order_id: buy_order.order_id,
                sell_order_id: sell_order.order_id,
                buyer_id: buy_order.user_id,
                seller_id: sell_order.user_id,
                amount: match_amount,
                price: clearing_price,
                timestamp: Utc::now(),
            });

            buy_filled += match_amount;
            sell_filled += match_amount;

            if buy_filled >= buy_order.amount {
                buy_idx += 1;
                buy_filled = dec!(0);
            }

            if sell_filled >= sell_order.amount {
                sell_idx += 1;
                sell_filled = dec!(0);
            }
        }

        self.status = BatchStatus::Completed;

        Ok(matches)
    }

    /// Get statistics about the batch
    pub fn stats(&self) -> BatchStats {
        BatchStats {
            batch_id: self.id,
            token_id: self.token_id,
            total_buy_orders: self.buy_orders.len(),
            total_sell_orders: self.sell_orders.len(),
            total_buy_volume: self.buy_orders.iter().map(|o| o.amount).sum(),
            total_sell_volume: self.sell_orders.iter().map(|o| o.amount).sum(),
            clearing_price: self.clearing_price,
            matched_volume: self.matched_volume,
            status: self.status,
            start_time: self.start_time,
            end_time: self.end_time,
        }
    }
}

/// A matched trade from a batch auction
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchMatch {
    /// Buy order ID
    pub buy_order_id: Uuid,
    /// Sell order ID
    pub sell_order_id: Uuid,
    /// Buyer user ID
    pub buyer_id: Uuid,
    /// Seller user ID
    pub seller_id: Uuid,
    /// Matched amount
    pub amount: Decimal,
    /// Clearing price
    pub price: Decimal,
    /// Match timestamp
    pub timestamp: DateTime<Utc>,
}

impl BatchMatch {
    /// Convert to a Trade record
    pub fn to_trade(&self, token_id: Uuid) -> Trade {
        Trade {
            trade_id: Uuid::new_v4(),
            buyer_user_id: self.buyer_id,
            seller_user_id: Some(self.seller_id),
            token_id,
            amount: self.amount,
            price_btc: self.price,
            total_btc: self.amount * self.price,
            platform_fee_btc: dec!(0), // Fees calculated separately
            issuer_royalty_btc: dec!(0),
            executed_at: self.timestamp,
        }
    }
}

/// Batch auction statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BatchStats {
    /// Batch ID
    pub batch_id: Uuid,
    /// Token ID
    pub token_id: Uuid,
    /// Total buy orders submitted
    pub total_buy_orders: usize,
    /// Total sell orders submitted
    pub total_sell_orders: usize,
    /// Total buy volume
    pub total_buy_volume: Decimal,
    /// Total sell volume
    pub total_sell_volume: Decimal,
    /// Clearing price (if computed)
    pub clearing_price: Option<Decimal>,
    /// Matched volume
    pub matched_volume: Decimal,
    /// Batch status
    pub status: BatchStatus,
    /// Start time
    pub start_time: DateTime<Utc>,
    /// End time
    pub end_time: DateTime<Utc>,
}

impl BatchStats {
    /// Get match rate (matched volume / total volume)
    pub fn match_rate(&self) -> Decimal {
        let total_volume = self.total_buy_volume.min(self.total_sell_volume);
        if total_volume.is_zero() {
            dec!(0)
        } else {
            (self.matched_volume / total_volume) * dec!(100)
        }
    }

    /// Check if batch was successful
    pub fn is_successful(&self) -> bool {
        self.status == BatchStatus::Completed && !self.matched_volume.is_zero()
    }
}

/// Manager for running batch auctions
pub struct BatchAuctionManager {
    /// Active batches by token
    active_batches: HashMap<Uuid, BatchAuction>,
    /// Completed batches (kept for history)
    completed_batches: Vec<BatchAuction>,
    /// Default configuration
    default_config: BatchAuctionConfig,
}

impl BatchAuctionManager {
    /// Create a new batch auction manager
    pub fn new(config: BatchAuctionConfig) -> Self {
        Self {
            active_batches: HashMap::new(),
            completed_batches: Vec::new(),
            default_config: config,
        }
    }

    /// Start a new batch for a token
    pub fn start_batch(&mut self, token_id: Uuid) -> Result<Uuid> {
        if self.active_batches.contains_key(&token_id) {
            return Err(CoreError::AlreadyExists(format!(
                "Batch already active for token {}",
                token_id
            )));
        }

        let batch = BatchAuction::new(token_id, self.default_config.clone());
        let batch_id = batch.id;
        self.active_batches.insert(token_id, batch);

        Ok(batch_id)
    }

    /// Add an order to the active batch for a token
    pub fn add_order(&mut self, order: LimitOrder) -> Result<()> {
        let batch = self
            .active_batches
            .get_mut(&order.token_id)
            .ok_or_else(|| {
                CoreError::NotFound(format!("No active batch for token {}", order.token_id))
            })?;

        batch.add_order(order)
    }

    /// Execute a batch for a token
    pub fn execute_batch(
        &mut self,
        token_id: Uuid,
        reference_price: Option<Decimal>,
    ) -> Result<Vec<BatchMatch>> {
        let mut batch = self.active_batches.remove(&token_id).ok_or_else(|| {
            CoreError::NotFound(format!("No active batch for token {}", token_id))
        })?;

        batch.compute_clearing_price(reference_price)?;
        let matches = batch.execute()?;

        self.completed_batches.push(batch);

        Ok(matches)
    }

    /// Get active batch for a token
    pub fn get_active_batch(&self, token_id: &Uuid) -> Option<&BatchAuction> {
        self.active_batches.get(token_id)
    }

    /// Get statistics for all completed batches
    pub fn get_completed_stats(&self) -> Vec<BatchStats> {
        self.completed_batches.iter().map(|b| b.stats()).collect()
    }

    /// Clean up old completed batches (keep last N)
    pub fn cleanup_old_batches(&mut self, keep_last: usize) {
        if self.completed_batches.len() > keep_last {
            self.completed_batches
                .drain(0..self.completed_batches.len() - keep_last);
        }
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_order(
        token_id: Uuid,
        user_id: Uuid,
        side: OrderSide,
        price: Decimal,
        amount: Decimal,
    ) -> LimitOrder {
        LimitOrder {
            order_id: Uuid::new_v4(),
            token_id,
            user_id,
            side,
            price,
            amount,
            filled_amount: dec!(0),
            timestamp: Utc::now().timestamp_millis(),
        }
    }

    #[test]
    fn test_batch_auction_creation() {
        let token_id = Uuid::new_v4();
        let config = BatchAuctionConfig::default();
        let batch = BatchAuction::new(token_id, config);

        assert_eq!(batch.token_id, token_id);
        assert_eq!(batch.status, BatchStatus::Collecting);
        assert!(batch.buy_orders.is_empty());
        assert!(batch.sell_orders.is_empty());
    }

    #[test]
    fn test_add_order() {
        let token_id = Uuid::new_v4();
        let user_id = Uuid::new_v4();
        let mut batch = BatchAuction::new(token_id, BatchAuctionConfig::default());

        let buy_order = create_test_order(token_id, user_id, OrderSide::Buy, dec!(100), dec!(10));
        let sell_order = create_test_order(token_id, user_id, OrderSide::Sell, dec!(105), dec!(5));

        batch.add_order(buy_order).unwrap();
        batch.add_order(sell_order).unwrap();

        assert_eq!(batch.buy_orders.len(), 1);
        assert_eq!(batch.sell_orders.len(), 1);
    }

    #[test]
    fn test_clearing_price_computation() {
        let token_id = Uuid::new_v4();
        let mut batch = BatchAuction::new(token_id, BatchAuctionConfig::default());

        // Add buy orders
        batch
            .add_order(create_test_order(
                token_id,
                Uuid::new_v4(),
                OrderSide::Buy,
                dec!(105),
                dec!(10),
            ))
            .unwrap();
        batch
            .add_order(create_test_order(
                token_id,
                Uuid::new_v4(),
                OrderSide::Buy,
                dec!(100),
                dec!(15),
            ))
            .unwrap();

        // Add sell orders
        batch
            .add_order(create_test_order(
                token_id,
                Uuid::new_v4(),
                OrderSide::Sell,
                dec!(95),
                dec!(8),
            ))
            .unwrap();
        batch
            .add_order(create_test_order(
                token_id,
                Uuid::new_v4(),
                OrderSide::Sell,
                dec!(102),
                dec!(12),
            ))
            .unwrap();

        let clearing_price = batch.compute_clearing_price(None).unwrap();
        assert!(clearing_price >= dec!(95) && clearing_price <= dec!(105));
        assert!(batch.matched_volume > dec!(0));
    }

    #[test]
    fn test_batch_execution() {
        let token_id = Uuid::new_v4();
        let mut batch = BatchAuction::new(token_id, BatchAuctionConfig::default());

        // Add overlapping orders
        batch
            .add_order(create_test_order(
                token_id,
                Uuid::new_v4(),
                OrderSide::Buy,
                dec!(100),
                dec!(10),
            ))
            .unwrap();
        batch
            .add_order(create_test_order(
                token_id,
                Uuid::new_v4(),
                OrderSide::Sell,
                dec!(100),
                dec!(10),
            ))
            .unwrap();

        batch.compute_clearing_price(None).unwrap();
        let matches = batch.execute().unwrap();

        assert!(!matches.is_empty());
        assert_eq!(batch.status, BatchStatus::Completed);
    }

    #[test]
    fn test_batch_manager() {
        let mut manager = BatchAuctionManager::default();
        let token_id = Uuid::new_v4();

        // Start batch
        let batch_id = manager.start_batch(token_id).unwrap();
        assert!(batch_id != Uuid::nil());

        // Add orders
        let order = create_test_order(
            token_id,
            Uuid::new_v4(),
            OrderSide::Buy,
            dec!(100),
            dec!(10),
        );
        manager.add_order(order).unwrap();

        // Check active batch
        assert!(manager.get_active_batch(&token_id).is_some());
    }

    #[test]
    fn test_insufficient_orders() {
        let token_id = Uuid::new_v4();
        let mut batch = BatchAuction::new(token_id, BatchAuctionConfig::default());

        // Only one order
        batch
            .add_order(create_test_order(
                token_id,
                Uuid::new_v4(),
                OrderSide::Buy,
                dec!(100),
                dec!(10),
            ))
            .unwrap();

        let result = batch.compute_clearing_price(None);
        assert!(result.is_err());
        assert_eq!(batch.status, BatchStatus::Cancelled);
    }

    #[test]
    fn test_batch_stats() {
        let token_id = Uuid::new_v4();
        let mut batch = BatchAuction::new(token_id, BatchAuctionConfig::default());

        batch
            .add_order(create_test_order(
                token_id,
                Uuid::new_v4(),
                OrderSide::Buy,
                dec!(100),
                dec!(10),
            ))
            .unwrap();
        batch
            .add_order(create_test_order(
                token_id,
                Uuid::new_v4(),
                OrderSide::Sell,
                dec!(100),
                dec!(5),
            ))
            .unwrap();

        let stats = batch.stats();
        assert_eq!(stats.total_buy_orders, 1);
        assert_eq!(stats.total_sell_orders, 1);
        assert_eq!(stats.total_buy_volume, dec!(10));
        assert_eq!(stats.total_sell_volume, dec!(5));
    }
}