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
//! NFT integration for gated access and trading benefits
use crate::error::CoreError;
use rust_decimal::Decimal;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

/// NFT rarity tiers
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum NftRarity {
    /// Most abundant rarity tier
    Common,
    /// Second rarity tier
    Uncommon,
    /// Third rarity tier
    Rare,
    /// Fourth rarity tier
    Epic,
    /// Fifth rarity tier with significant benefits
    Legendary,
    /// Highest and rarest tier with maximum benefits
    Mythic,
}

impl NftRarity {
    /// Get the fee discount percentage for this rarity
    pub fn fee_discount(&self) -> Decimal {
        match self {
            NftRarity::Common => Decimal::new(5, 2),     // 0.05 (5%)
            NftRarity::Uncommon => Decimal::new(10, 2),  // 0.10 (10%)
            NftRarity::Rare => Decimal::new(15, 2),      // 0.15 (15%)
            NftRarity::Epic => Decimal::new(20, 2),      // 0.20 (20%)
            NftRarity::Legendary => Decimal::new(30, 2), // 0.30 (30%)
            NftRarity::Mythic => Decimal::new(50, 2),    // 0.50 (50%)
        }
    }

    /// Get the priority level for this rarity (higher = better)
    pub fn priority_level(&self) -> u8 {
        match self {
            NftRarity::Common => 1,
            NftRarity::Uncommon => 2,
            NftRarity::Rare => 3,
            NftRarity::Epic => 4,
            NftRarity::Legendary => 5,
            NftRarity::Mythic => 6,
        }
    }
}

/// NFT collection metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NftCollection {
    /// Unique identifier of this collection
    pub id: Uuid,
    /// Human-readable collection name
    pub name: String,
    /// Short ticker symbol for the collection
    pub symbol: String,
    /// On-chain smart contract address
    pub contract_address: String,
    /// Blockchain on which this collection is deployed
    pub chain: String,
    /// Maximum number of tokens in the collection
    pub total_supply: u64,
    /// Whether the collection has been platform-verified
    pub verified: bool,
    /// When this collection record was created
    pub created_at: chrono::DateTime<chrono::Utc>,
}

impl NftCollection {
    /// Create a new NFT collection
    pub fn new(
        name: String,
        symbol: String,
        contract_address: String,
        chain: String,
        total_supply: u64,
    ) -> Self {
        Self {
            id: Uuid::new_v4(),
            name,
            symbol,
            contract_address,
            chain,
            total_supply,
            verified: false,
            created_at: chrono::Utc::now(),
        }
    }

    /// Verify the collection
    pub fn verify(&mut self) {
        self.verified = true;
    }
}

/// NFT ownership record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NftOwnership {
    /// Unique identifier of this ownership record
    pub id: Uuid,
    /// User who owns the token
    pub user_id: Uuid,
    /// Collection this token belongs to
    pub collection_id: Uuid,
    /// On-chain token identifier within the collection
    pub token_id: String,
    /// Rarity tier of the token
    pub rarity: NftRarity,
    /// When ownership was recorded
    pub acquired_at: chrono::DateTime<chrono::Utc>,
    /// Whether on-chain ownership has been verified
    pub verified: bool,
}

impl NftOwnership {
    /// Create a new NFT ownership record
    pub fn new(user_id: Uuid, collection_id: Uuid, token_id: String, rarity: NftRarity) -> Self {
        Self {
            id: Uuid::new_v4(),
            user_id,
            collection_id,
            token_id,
            rarity,
            acquired_at: chrono::Utc::now(),
            verified: false,
        }
    }

    /// Verify NFT ownership
    pub fn verify(&mut self) {
        self.verified = true;
    }
}

/// NFT-gated access levels
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NftAccessLevel {
    /// Collection that gates this access
    pub collection_id: Uuid,
    /// Minimum rarity required to unlock this access level
    pub required_rarity: NftRarity,
    /// Category of access being gated
    pub access_type: AccessType,
    /// Concrete benefits that come with this access level
    pub benefits: Vec<AccessBenefit>,
}

/// Types of gated access
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum AccessType {
    /// Access to exclusive liquidity pools
    PrivatePool,
    /// Early access to new token launches
    EarlyTokenAccess,
    /// Access to premium platform features
    PremiumFeatures,
    /// Access to exclusive events and airdrops
    ExclusiveEvents,
    /// Reduced trading fees
    ReducedFees,
    /// Priority customer support
    PrioritySupport,
    /// Advanced analytics and market data
    AdvancedAnalytics,
}

/// Specific benefit provided by NFT access
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccessBenefit {
    /// Machine-readable benefit type identifier
    pub benefit_type: String,
    /// Human-readable description of the benefit
    pub description: String,
    /// Quantified benefit value (e.g. fee discount %, priority level)
    pub value: Decimal,
}

impl NftAccessLevel {
    /// Create a new NFT access level
    pub fn new(collection_id: Uuid, required_rarity: NftRarity, access_type: AccessType) -> Self {
        let benefits = match access_type {
            AccessType::ReducedFees => vec![AccessBenefit {
                benefit_type: "fee_discount".to_string(),
                description: "Trading fee discount".to_string(),
                value: required_rarity.fee_discount(),
            }],
            AccessType::PrioritySupport => vec![AccessBenefit {
                benefit_type: "priority_level".to_string(),
                description: "Support priority level".to_string(),
                value: Decimal::from(required_rarity.priority_level()),
            }],
            _ => vec![],
        };

        Self {
            collection_id,
            required_rarity,
            access_type,
            benefits,
        }
    }

    /// Check if a user has the required NFT
    pub fn has_access(&self, user_nfts: &[NftOwnership]) -> bool {
        user_nfts.iter().any(|nft| {
            nft.collection_id == self.collection_id
                && nft.rarity.priority_level() >= self.required_rarity.priority_level()
                && nft.verified
        })
    }
}

/// NFT verification system
#[derive(Debug, Clone)]
pub struct NftVerifier {
    /// Platform-verified collections that can be checked for ownership
    verified_collections: HashMap<Uuid, NftCollection>,
}

impl NftVerifier {
    /// Create a new NFT verifier
    pub fn new() -> Self {
        Self {
            verified_collections: HashMap::new(),
        }
    }

    /// Add a verified collection
    pub fn add_verified_collection(&mut self, collection: NftCollection) {
        if collection.verified {
            self.verified_collections.insert(collection.id, collection);
        }
    }

    /// Verify NFT ownership
    pub async fn verify_ownership(
        &self,
        collection_id: Uuid,
        token_id: &str,
        owner_address: &str,
    ) -> Result<bool, CoreError> {
        // In a real implementation, this would:
        // 1. Check if collection is verified
        // 2. Query the blockchain to verify ownership
        // 3. Return the verification result

        if !self.verified_collections.contains_key(&collection_id) {
            return Err(CoreError::Validation("Collection not verified".to_string()));
        }

        // Simplified verification for demonstration
        // In production, this would make actual blockchain queries
        Ok(!owner_address.is_empty() && !token_id.is_empty())
    }

    /// Get collection by ID
    pub fn get_collection(&self, collection_id: &Uuid) -> Option<&NftCollection> {
        self.verified_collections.get(collection_id)
    }
}

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

/// NFT marketplace integration models
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NftListing {
    /// Unique identifier of the listing
    pub id: Uuid,
    /// Collection the listed token belongs to
    pub collection_id: Uuid,
    /// Token being listed for sale
    pub token_id: String,
    /// User selling the token
    pub seller_id: Uuid,
    /// Asking price
    pub price: Decimal,
    /// Currency denomination of the price
    pub currency: String,
    /// Current lifecycle status of the listing
    pub status: ListingStatus,
    /// When the listing was created
    pub created_at: chrono::DateTime<chrono::Utc>,
    /// When the listing expires (None = no expiry)
    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// Status of an NFT marketplace listing
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ListingStatus {
    /// Listing is live and available for purchase
    Active,
    /// Token has been sold
    Sold,
    /// Seller cancelled the listing
    Cancelled,
    /// Listing has passed its expiry time
    Expired,
}

impl NftListing {
    /// Create a new NFT listing
    pub fn new(
        collection_id: Uuid,
        token_id: String,
        seller_id: Uuid,
        price: Decimal,
        currency: String,
        duration_hours: Option<u64>,
    ) -> Self {
        let expires_at =
            duration_hours.map(|hours| chrono::Utc::now() + chrono::Duration::hours(hours as i64));

        Self {
            id: Uuid::new_v4(),
            collection_id,
            token_id,
            seller_id,
            price,
            currency,
            status: ListingStatus::Active,
            created_at: chrono::Utc::now(),
            expires_at,
        }
    }

    /// Check if listing is still active
    pub fn is_active(&self) -> bool {
        if self.status != ListingStatus::Active {
            return false;
        }

        if let Some(expires_at) = self.expires_at {
            chrono::Utc::now() < expires_at
        } else {
            true
        }
    }

    /// Mark listing as sold
    pub fn mark_sold(&mut self) {
        self.status = ListingStatus::Sold;
    }

    /// Cancel listing
    pub fn cancel(&mut self) {
        self.status = ListingStatus::Cancelled;
    }
}

/// NFT-based fee discount calculator
#[derive(Debug, Clone)]
pub struct NftFeeDiscountCalculator {
    /// Access levels that may grant fee discounts
    access_levels: Vec<NftAccessLevel>,
}

impl NftFeeDiscountCalculator {
    /// Create a new calculator
    pub fn new() -> Self {
        Self {
            access_levels: Vec::new(),
        }
    }

    /// Add an access level
    pub fn add_access_level(&mut self, access_level: NftAccessLevel) {
        self.access_levels.push(access_level);
    }

    /// Calculate total fee discount for a user
    pub fn calculate_discount(&self, user_nfts: &[NftOwnership]) -> Decimal {
        let mut max_discount = Decimal::ZERO;

        for access_level in &self.access_levels {
            if access_level.access_type == AccessType::ReducedFees
                && access_level.has_access(user_nfts)
            {
                for benefit in &access_level.benefits {
                    if benefit.benefit_type == "fee_discount" {
                        max_discount = max_discount.max(benefit.value);
                    }
                }
            }
        }

        max_discount
    }

    /// Get all benefits available to a user
    pub fn get_user_benefits(&self, user_nfts: &[NftOwnership]) -> Vec<AccessBenefit> {
        let mut benefits = Vec::new();

        for access_level in &self.access_levels {
            if access_level.has_access(user_nfts) {
                benefits.extend(access_level.benefits.clone());
            }
        }

        // Deduplicate and keep highest values
        let mut unique_benefits: HashMap<String, AccessBenefit> = HashMap::new();
        for benefit in benefits {
            unique_benefits
                .entry(benefit.benefit_type.clone())
                .and_modify(|existing| {
                    if benefit.value > existing.value {
                        *existing = benefit.clone();
                    }
                })
                .or_insert(benefit);
        }

        unique_benefits.into_values().collect()
    }
}

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

/// Exclusive trading pool for NFT holders
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NftGatedPool {
    /// Unique identifier of the pool
    pub id: Uuid,
    /// Human-readable name
    pub name: String,
    /// NFT collection required for entry
    pub required_collection: Uuid,
    /// Minimum rarity level required for entry
    pub required_rarity: NftRarity,
    /// Trading pairs available in this pool
    pub token_pairs: Vec<(Uuid, Uuid)>,
    /// Total liquidity deposited
    pub total_liquidity: Decimal,
    /// When the pool was created
    pub created_at: chrono::DateTime<chrono::Utc>,
}

impl NftGatedPool {
    /// Create a new NFT-gated pool
    pub fn new(name: String, required_collection: Uuid, required_rarity: NftRarity) -> Self {
        Self {
            id: Uuid::new_v4(),
            name,
            required_collection,
            required_rarity,
            token_pairs: Vec::new(),
            total_liquidity: Decimal::ZERO,
            created_at: chrono::Utc::now(),
        }
    }

    /// Add a token pair to the pool
    pub fn add_token_pair(&mut self, token_a: Uuid, token_b: Uuid) {
        self.token_pairs.push((token_a, token_b));
    }

    /// Check if user can access this pool
    pub fn can_access(&self, user_nfts: &[NftOwnership]) -> bool {
        user_nfts.iter().any(|nft| {
            nft.collection_id == self.required_collection
                && nft.rarity.priority_level() >= self.required_rarity.priority_level()
                && nft.verified
        })
    }
}

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

    #[test]
    fn test_nft_rarity_discounts() {
        assert_eq!(NftRarity::Common.fee_discount(), Decimal::new(5, 2));
        assert_eq!(NftRarity::Legendary.fee_discount(), Decimal::new(30, 2));
        assert_eq!(NftRarity::Mythic.fee_discount(), Decimal::new(50, 2));
    }

    #[test]
    fn test_nft_rarity_priority() {
        assert!(NftRarity::Legendary.priority_level() > NftRarity::Rare.priority_level());
        assert_eq!(NftRarity::Mythic.priority_level(), 6);
    }

    #[test]
    fn test_nft_collection_creation() {
        let collection = NftCollection::new(
            "Test Collection".to_string(),
            "TEST".to_string(),
            "0x123".to_string(),
            "Ethereum".to_string(),
            10000,
        );

        assert_eq!(collection.name, "Test Collection");
        assert!(!collection.verified);
    }

    #[test]
    fn test_nft_collection_verification() {
        let mut collection = NftCollection::new(
            "Test".to_string(),
            "TEST".to_string(),
            "0x123".to_string(),
            "Ethereum".to_string(),
            1000,
        );

        assert!(!collection.verified);
        collection.verify();
        assert!(collection.verified);
    }

    #[test]
    fn test_nft_ownership() {
        let ownership = NftOwnership::new(
            Uuid::new_v4(),
            Uuid::new_v4(),
            "1".to_string(),
            NftRarity::Rare,
        );

        assert_eq!(ownership.rarity, NftRarity::Rare);
        assert!(!ownership.verified);
    }

    #[test]
    fn test_access_level_benefits() {
        let collection_id = Uuid::new_v4();
        let access_level =
            NftAccessLevel::new(collection_id, NftRarity::Epic, AccessType::ReducedFees);

        assert_eq!(access_level.access_type, AccessType::ReducedFees);
        assert!(!access_level.benefits.is_empty());
    }

    #[test]
    fn test_has_access() {
        let collection_id = Uuid::new_v4();
        let user_id = Uuid::new_v4();

        let access_level =
            NftAccessLevel::new(collection_id, NftRarity::Rare, AccessType::PrivatePool);

        let mut nft = NftOwnership::new(user_id, collection_id, "1".to_string(), NftRarity::Epic);
        nft.verify();

        assert!(access_level.has_access(&[nft.clone()]));

        // Lower rarity should not grant access
        let mut nft_common =
            NftOwnership::new(user_id, collection_id, "2".to_string(), NftRarity::Common);
        nft_common.verify();
        assert!(!access_level.has_access(&[nft_common]));
    }

    #[test]
    fn test_nft_listing() {
        let listing = NftListing::new(
            Uuid::new_v4(),
            "1".to_string(),
            Uuid::new_v4(),
            Decimal::from(100),
            "BTC".to_string(),
            Some(24),
        );

        assert!(listing.is_active());
        assert_eq!(listing.status, ListingStatus::Active);
    }

    #[test]
    fn test_listing_expiration() {
        let mut listing = NftListing::new(
            Uuid::new_v4(),
            "1".to_string(),
            Uuid::new_v4(),
            Decimal::from(100),
            "BTC".to_string(),
            Some(0), // Expires immediately
        );

        // Should be expired
        assert!(!listing.is_active());

        listing.status = ListingStatus::Expired;
        assert!(!listing.is_active());
    }

    #[test]
    fn test_fee_discount_calculator() {
        let collection_id = Uuid::new_v4();
        let user_id = Uuid::new_v4();

        let mut calculator = NftFeeDiscountCalculator::new();
        let access_level =
            NftAccessLevel::new(collection_id, NftRarity::Epic, AccessType::ReducedFees);
        calculator.add_access_level(access_level);

        let mut nft = NftOwnership::new(user_id, collection_id, "1".to_string(), NftRarity::Epic);
        nft.verify();

        let discount = calculator.calculate_discount(&[nft]);
        assert_eq!(discount, NftRarity::Epic.fee_discount());
    }

    #[test]
    fn test_nft_gated_pool() {
        let collection_id = Uuid::new_v4();
        let user_id = Uuid::new_v4();

        let mut pool = NftGatedPool::new(
            "Exclusive Pool".to_string(),
            collection_id,
            NftRarity::Legendary,
        );

        pool.add_token_pair(Uuid::new_v4(), Uuid::new_v4());
        assert_eq!(pool.token_pairs.len(), 1);

        let mut nft = NftOwnership::new(
            user_id,
            collection_id,
            "1".to_string(),
            NftRarity::Legendary,
        );
        nft.verify();

        assert!(pool.can_access(&[nft]));
    }

    #[tokio::test]
    async fn test_nft_verifier() {
        let mut verifier = NftVerifier::new();
        let mut collection = NftCollection::new(
            "Test".to_string(),
            "TEST".to_string(),
            "0x123".to_string(),
            "Ethereum".to_string(),
            1000,
        );
        collection.verify();

        let collection_id = collection.id;
        verifier.add_verified_collection(collection);

        let result = verifier.verify_ownership(collection_id, "1", "0xabc").await;
        assert!(result.is_ok());
        assert!(result.unwrap());
    }
}