forked from QuickLendX/quicklendx-protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfees.rs
More file actions
1287 lines (1150 loc) · 45.9 KB
/
Copy pathfees.rs
File metadata and controls
1287 lines (1150 loc) · 45.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Fee management module for the QuickLendX protocol.
//!
//! Handles platform fee configuration, revenue tracking, volume-tier discounts,
//! and treasury routing for all fee types supported by the protocol.
use crate::audit::{log_config_change, write_i128_to_buf, write_u64_to_buf, AuditOperation};
use crate::errors::QuickLendXError;
use crate::events;
use soroban_sdk::{contracttype, symbol_short, vec, Address, Env, Map, String, Symbol, Vec};
// Constants
const MAX_FEE_BPS: u32 = 1000; // 10% hard cap for all fees
#[allow(dead_code)]
const MIN_FEE_BPS: u32 = 0;
/// Basis-point denominator for percentage calculations (100% = 10,000 bps).
const BPS_DENOMINATOR: i128 = 10_000;
const DEFAULT_PLATFORM_FEE_BPS: u32 = 200; // 2%
const MAX_PLATFORM_FEE_BPS: u32 = 1000; // 10%
const ROTATION_TTL_SECONDS: u64 = 604_800; // 7 days
/// Minimum delay before a pending rotation can be confirmed (1 day).
/// Prevents same-block finalisation and gives the admin a window to cancel.
pub const MIN_ROTATION_DELAY_SECONDS: u64 = 86_400; // 1 day
const EARLY_PLATFORM_DISCOUNT_BPS: i128 = 1_000; // 10%
const LATE_FEE_SURCHARGE_BPS: i128 = 2_000; // 20%
// Storage keys
const FEE_CONFIG_KEY: Symbol = symbol_short!("fee_cfg");
const REVENUE_KEY: Symbol = symbol_short!("revenue");
const VOLUME_KEY: Symbol = symbol_short!("volume");
#[allow(dead_code)]
const TREASURY_CONFIG_KEY: Symbol = symbol_short!("treasury");
const PLATFORM_FEE_KEY: Symbol = symbol_short!("plt_fee");
const ROTATION_KEY: Symbol = symbol_short!("rotate");
/// Guard key: set to `true` once `initialize` completes to prevent re-initialization.
const FEES_INIT_KEY: Symbol = symbol_short!("fee_init");
/// Fee types supported by the platform
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum FeeType {
Platform,
Processing,
Verification,
EarlyPayment,
LatePayment,
Origination,
}
/// Volume tier for discounted fees
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum VolumeTier {
Standard,
Silver,
Gold,
Platinum,
}
/// Fee structure configuration
#[contracttype]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug))]
pub struct FeeStructure {
pub fee_type: FeeType,
pub base_fee_bps: u32,
pub min_fee: i128,
pub max_fee: i128,
pub is_active: bool,
pub updated_at: u64,
pub updated_by: Address,
}
/// User volume data
#[contracttype]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug))]
pub struct UserVolumeData {
pub user: Address,
pub total_volume: i128,
pub transaction_count: u32,
pub current_tier: VolumeTier,
pub last_updated: u64,
}
/// Treasury configuration for platform fees
#[contracttype]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug))]
pub struct TreasuryConfig {
pub treasury_address: Address,
pub is_active: bool,
pub updated_at: u64,
pub updated_by: Address,
}
/// Platform fee configuration
#[contracttype]
#[derive(Clone, PartialEq)]
#[cfg_attr(test, derive(Debug))]
pub struct PlatformFeeConfig {
pub fee_bps: u32,
pub treasury_address: Option<Address>, // Simplified - just store address directly
pub updated_at: u64,
pub updated_by: Address,
}
/// Revenue configuration
#[contracttype]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug))]
pub struct RevenueConfig {
pub treasury_address: Address,
pub treasury_share_bps: u32,
pub developer_share_bps: u32,
pub platform_share_bps: u32,
pub auto_distribution: bool,
pub min_distribution_amount: i128,
}
/// Pending two-step treasury/fee-recipient rotation request.
///
/// Admin initiates the rotation; the new address must confirm by calling
/// `confirm_treasury_rotation`, proving ownership before the deadline.
/// This prevents accidental misrouting to addresses the team does not control.
#[contracttype]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug))]
pub struct RecipientRotationRequest {
pub new_address: Address,
pub initiated_by: Address,
pub initiated_at: u64,
pub confirmation_deadline: u64,
}
/// Revenue tracking
#[contracttype]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug))]
pub struct RevenueData {
pub period: u64,
pub total_collected: i128,
pub fees_by_type: Map<FeeType, i128>,
pub total_distributed: i128,
pub pending_distribution: i128,
pub transaction_count: u32,
}
/// Fee analytics
#[contracttype]
#[derive(Clone)]
#[cfg_attr(test, derive(Debug))]
pub struct FeeAnalytics {
pub period: u64,
pub total_fees: i128,
pub average_fee_rate: i128,
pub total_transactions: u32,
pub fee_efficiency_score: u32,
}
// ─── Audit serialization helpers ─────────────────────────────────────────────
fn fmt_fee_structure(
env: &Env,
base_fee_bps: u32,
min_fee: i128,
max_fee: i128,
is_active: bool,
) -> String {
// "bps:{u32};min:{i128};max:{i128};active:{bool}" — max ~109 chars
let mut buf = [0u8; 120];
let mut pos = 0usize;
let p = b"bps:";
buf[pos..pos + p.len()].copy_from_slice(p);
pos += p.len();
pos += write_u64_to_buf(&mut buf[pos..], base_fee_bps as u64);
let p = b";min:";
buf[pos..pos + p.len()].copy_from_slice(p);
pos += p.len();
pos += write_i128_to_buf(&mut buf[pos..], min_fee);
let p = b";max:";
buf[pos..pos + p.len()].copy_from_slice(p);
pos += p.len();
pos += write_i128_to_buf(&mut buf[pos..], max_fee);
let p: &[u8] = if is_active {
b";active:true"
} else {
b";active:false"
};
buf[pos..pos + p.len()].copy_from_slice(p);
pos += p.len();
String::from_str(
env,
core::str::from_utf8(&buf[..pos]).unwrap_or("fee_struct"),
)
}
fn fmt_rev_dist(env: &Env, treasury_bps: u32, dev_bps: u32, plt_bps: u32, min_amt: i128) -> String {
// "t:{u32};d:{u32};p:{u32};min:{i128}" — max ~67 chars
let mut buf = [0u8; 80];
let mut pos = 0usize;
let p = b"t:";
buf[pos..pos + p.len()].copy_from_slice(p);
pos += p.len();
pos += write_u64_to_buf(&mut buf[pos..], treasury_bps as u64);
let p = b";d:";
buf[pos..pos + p.len()].copy_from_slice(p);
pos += p.len();
pos += write_u64_to_buf(&mut buf[pos..], dev_bps as u64);
let p = b";p:";
buf[pos..pos + p.len()].copy_from_slice(p);
pos += p.len();
pos += write_u64_to_buf(&mut buf[pos..], plt_bps as u64);
let p = b";min:";
buf[pos..pos + p.len()].copy_from_slice(p);
pos += p.len();
pos += write_i128_to_buf(&mut buf[pos..], min_amt);
String::from_str(env, core::str::from_utf8(&buf[..pos]).unwrap_or("rev_dist"))
}
fn fee_type_label(fee_type: &FeeType) -> &'static str {
match fee_type {
FeeType::Platform => "Platform",
FeeType::Processing => "Processing",
FeeType::Verification => "Verification",
FeeType::EarlyPayment => "EarlyPayment",
FeeType::LatePayment => "LatePayment",
FeeType::Origination => "Origination",
}
}
pub struct FeeManager;
impl FeeManager {
fn checked_mul_div(a: i128, b: i128, denom: i128) -> Result<i128, QuickLendXError> {
a.checked_mul(b)
.and_then(|v| v.checked_div(denom))
.ok_or(QuickLendXError::ArithmeticOverflow)
}
fn checked_add(a: i128, b: i128) -> Result<i128, QuickLendXError> {
a.checked_add(b).ok_or(QuickLendXError::ArithmeticOverflow)
}
pub fn initialize(env: &Env, admin: &Address) -> Result<(), QuickLendXError> {
// Explicit admin authorization: the caller must be the designated admin.
admin.require_auth();
crate::AdminStorage::require_admin(env, admin)?;
// Guard: reject re-initialization to prevent overwriting live fee config.
if env.storage().instance().has(&FEES_INIT_KEY) {
return Err(QuickLendXError::InvalidFeeConfiguration);
}
// Initialize default fee structures
let default_fees = vec![
env,
FeeStructure {
fee_type: FeeType::Platform,
base_fee_bps: DEFAULT_PLATFORM_FEE_BPS,
min_fee: 100,
max_fee: 1_000_000,
is_active: true,
updated_at: env.ledger().timestamp(),
updated_by: admin.clone(),
},
FeeStructure {
fee_type: FeeType::Processing,
base_fee_bps: 50,
min_fee: 50,
max_fee: 500_000,
is_active: true,
updated_at: env.ledger().timestamp(),
updated_by: admin.clone(),
},
FeeStructure {
fee_type: FeeType::Verification,
base_fee_bps: 100,
min_fee: 100,
max_fee: 100_000,
is_active: true,
updated_at: env.ledger().timestamp(),
updated_by: admin.clone(),
},
];
env.storage().instance().set(&FEE_CONFIG_KEY, &default_fees);
// Initialize platform fee configuration
let platform_fee_config = PlatformFeeConfig {
fee_bps: DEFAULT_PLATFORM_FEE_BPS,
treasury_address: None,
updated_at: env.ledger().timestamp(),
updated_by: admin.clone(),
};
env.storage()
.instance()
.set(&PLATFORM_FEE_KEY, &platform_fee_config);
// Mark the fee system as initialized.
env.storage().instance().set(&FEES_INIT_KEY, &true);
Ok(())
}
/// Configure treasury for platform fee routing
pub fn configure_treasury(
env: &Env,
admin: &Address,
treasury_address: Address,
) -> Result<TreasuryConfig, QuickLendXError> {
admin.require_auth();
crate::AdminStorage::require_admin(env, admin)?;
// Reject self-assignment: treasury must not be the contract itself.
if treasury_address == env.current_contract_address() {
return Err(QuickLendXError::InvalidAddress);
}
// Fetch existing config and reject duplicate treasury address.
let mut platform_config = Self::get_platform_fee_config(env)?;
// The first configuration establishes the recipient. Once a live
// recipient exists, all replacements must use the delayed rotation
// flow so no single admin mutation can redirect fees immediately.
if platform_config.treasury_address.is_some() {
return Err(QuickLendXError::OperationNotAllowed);
}
let treasury_config = TreasuryConfig {
treasury_address: treasury_address.clone(),
is_active: true,
updated_at: env.ledger().timestamp(),
updated_by: admin.clone(),
};
platform_config.treasury_address = Some(treasury_address.clone());
platform_config.updated_at = env.ledger().timestamp();
platform_config.updated_by = admin.clone();
env.storage()
.instance()
.set(&PLATFORM_FEE_KEY, &platform_config);
events::emit_treasury_configured(env, &treasury_address, admin);
Ok(treasury_config)
}
/// Update platform fee basis points
pub fn update_platform_fee(
env: &Env,
admin: &Address,
fee_bps: u32,
) -> Result<(), QuickLendXError> {
// Auth is checked by the caller
admin.require_auth();
crate::AdminStorage::require_admin(env, admin)?;
if fee_bps > MAX_PLATFORM_FEE_BPS {
return Err(QuickLendXError::InvalidFeeBasisPoints);
}
let mut config = Self::get_platform_fee_config(env)?;
if config.fee_bps == fee_bps {
return Ok(());
}
let old_fee_bps = config.fee_bps;
config.fee_bps = fee_bps;
config.updated_at = env.ledger().timestamp();
config.updated_by = admin.clone();
env.storage().instance().set(&PLATFORM_FEE_KEY, &config);
events::emit_platform_fee_config_updated(env, old_fee_bps, fee_bps, admin);
Ok(())
}
/// Get platform fee configuration
pub fn get_platform_fee_config(env: &Env) -> Result<PlatformFeeConfig, QuickLendXError> {
env.storage()
.instance()
.get(&PLATFORM_FEE_KEY)
.ok_or(QuickLendXError::StorageKeyNotFound)
}
/// Calculate platform fee for settlement
pub fn calculate_platform_fee(
env: &Env,
investment_amount: i128,
payment_amount: i128,
) -> Result<(i128, i128), QuickLendXError> {
let config = Self::get_platform_fee_config(env)?;
if payment_amount <= investment_amount {
return Ok((payment_amount, 0));
}
let profit = payment_amount.saturating_sub(investment_amount);
let platform_fee = Self::checked_mul_div(profit, config.fee_bps as i128, BPS_DENOMINATOR)?;
let investor_return = payment_amount
.checked_sub(platform_fee)
.ok_or(QuickLendXError::ArithmeticOverflow)?;
Ok((investor_return, platform_fee))
}
/// Get treasury address if configured
pub fn get_treasury_address(env: &Env) -> Option<Address> {
if let Ok(config) = Self::get_platform_fee_config(env) {
config.treasury_address
} else {
None
}
}
pub fn get_fee_schedule(env: &Env) -> Vec<FeeStructure> {
env.storage()
.instance()
.get(&FEE_CONFIG_KEY)
.unwrap_or_else(|| Vec::new(env))
}
pub fn get_fee_structure(
env: &Env,
fee_type: &FeeType,
) -> Result<FeeStructure, QuickLendXError> {
let fee_structures: Vec<FeeStructure> =
env.storage().instance().get(&FEE_CONFIG_KEY).unwrap();
for i in 0..fee_structures.len() {
let structure = fee_structures.get(i).unwrap();
if structure.fee_type == *fee_type {
return Ok(structure);
}
}
Err(QuickLendXError::StorageKeyNotFound)
}
/// Validate min/max fee consistency for a specific fee type.
///
/// # Consistency Rules
/// 1. **Range Validity**: `min_fee <= max_fee`
/// 2. **Non-negative Values**: Both `min_fee` and `max_fee` must be >= 0
/// 3. **Reasonable Bounds**: `max_fee` must not exceed 10x the base fee
/// (calculated as `base_fee_bps / 100` to account for BPS unit)
/// 4. **Minimum Floor**: When base_fee_bps > 0, min_fee should be <= base fee max
///
/// # Security Notes
/// - Prevents fee structures where max_fee could bypass intended limits
/// - Ensures min_fee doesn't force all transactions into floor pricing
/// - Guards against misconfiguration where bounds are inversely related
///
/// # Errors
/// - `InvalidAmount` if min_fee > max_fee or either is negative
/// - `InvalidFeeConfiguration` if bounds exceed reasonable thresholds
pub fn validate_fee_structure_consistency(
fee_type: &FeeType,
base_fee_bps: u32,
min_fee: i128,
max_fee: i128,
) -> Result<(), QuickLendXError> {
// Rule 1: Non-negative constraint
if min_fee < 0 {
return Err(QuickLendXError::InvalidAmount);
}
if max_fee < 0 {
return Err(QuickLendXError::InvalidAmount);
}
// Rule 2: Range ordering constraint
if max_fee < min_fee {
return Err(QuickLendXError::InvalidAmount);
}
// Rule 3: Sanity check on max_fee (shouldn't exceed reasonable bounds)
// For platform/processing fees, max_fee shouldn't be excessively large
// Set a protocol-wide absolute maximum of 10M stroops
const ABSOLUTE_MAX_FEE: i128 = 10_000_000_000_000; // 10M stroops
if max_fee > ABSOLUTE_MAX_FEE {
return Err(QuickLendXError::InvalidFeeConfiguration);
}
// Rule 4: Fee type-specific consistency checks
match fee_type {
FeeType::Platform | FeeType::Processing | FeeType::Verification => {
// For these fee types, ensure max doesn't exceed a reasonable bound
// based on the base rate. A max of 100x base seems reasonable.
let calculated_max_threshold = (base_fee_bps as i128)
.saturating_mul(100)
.saturating_mul(100); // 100x times BPS value * 100
if max_fee > calculated_max_threshold && calculated_max_threshold > 0 {
return Err(QuickLendXError::InvalidFeeConfiguration);
}
}
FeeType::EarlyPayment | FeeType::LatePayment | FeeType::Origination => {
// Early/late/origination payment fees may have different thresholds
// Allow more flexibility but still bounded
let calculated_max_threshold = (base_fee_bps as i128)
.saturating_mul(500)
.saturating_mul(100); // 500x for flexibility
if max_fee > calculated_max_threshold && calculated_max_threshold > 0 {
return Err(QuickLendXError::InvalidFeeConfiguration);
}
}
}
Ok(())
}
/// Validate consistency across all fee structures in the system.
///
/// # Cross-Type Consistency Rules
/// 1. No two fee types can have overlapping responsibility zones
/// 2. Total of all min_fees shouldn't exceed half the protocol's maximum
/// 3. LatePayment fees must have higher or equal max bounds than standard fees
///
/// # Errors
/// - `InvalidFeeConfiguration` if cross-type consistency violations detected
pub fn validate_cross_fee_consistency(
env: &Env,
fee_type: &FeeType,
min_fee: i128,
_max_fee: i128,
) -> Result<(), QuickLendXError> {
let fee_structures: Vec<FeeStructure> = match env.storage().instance().get(&FEE_CONFIG_KEY)
{
Some(structures) => structures,
None => return Ok(()), // No existing structures, skip cross-check
};
// Check rule 1: For LatePayment, ensure it doesn't undercut regular fees
if *fee_type == FeeType::LatePayment {
for i in 0..fee_structures.len() {
let structure = fee_structures.get(i).unwrap();
if structure.fee_type == FeeType::Platform && structure.min_fee > min_fee {
// LatePayment min shouldn't be less than Platform min
// (though LatePayment max should be higher)
if min_fee < structure.min_fee {
return Err(QuickLendXError::InvalidFeeConfiguration);
}
}
}
}
// Check rule 2: Validate total system fee exposure isn't unreasonable
let mut total_active_min_fees: i128 = 0;
for i in 0..fee_structures.len() {
let structure = fee_structures.get(i).unwrap();
// Accumulate total active minimum fees, checking for i128 overflow.
if structure.is_active {
total_active_min_fees = total_active_min_fees
.checked_add(structure.min_fee)
.ok_or(QuickLendXError::ArithmeticOverflow)?;
}
}
// Add the current fee being configured
total_active_min_fees = total_active_min_fees.saturating_add(min_fee);
// Total min fees shouldn't exceed half the protocol max
const PROTOCOL_MAX_SINGLE_TRANSACTION: i128 = 5_000_000_000_000; // 5M stroops
const MAX_TOTAL_MIN_FEES: i128 = PROTOCOL_MAX_SINGLE_TRANSACTION / 2;
if total_active_min_fees > MAX_TOTAL_MIN_FEES {
return Err(QuickLendXError::InvalidFeeConfiguration);
}
Ok(())
}
pub fn update_fee_structure(
env: &Env,
admin: &Address,
fee_type: FeeType,
base_fee_bps: u32,
min_fee: i128,
max_fee: i128,
is_active: bool,
) -> Result<FeeStructure, QuickLendXError> {
admin.require_auth();
if base_fee_bps > MAX_FEE_BPS {
return Err(QuickLendXError::InvalidFeeBasisPoints);
}
// Apply comprehensive consistency checks
Self::validate_fee_structure_consistency(&fee_type, base_fee_bps, min_fee, max_fee)?;
Self::validate_cross_fee_consistency(env, &fee_type, min_fee, max_fee)?;
let mut fee_structures: Vec<FeeStructure> =
env.storage().instance().get(&FEE_CONFIG_KEY).unwrap();
let mut found = false;
let mut old_bps = 0u32;
let mut old_min_fee: i128 = 0;
let mut old_max_fee: i128 = 0;
let mut old_is_active = false;
let updated_structure = FeeStructure {
fee_type: fee_type.clone(),
base_fee_bps,
min_fee,
max_fee,
is_active,
updated_at: env.ledger().timestamp(),
updated_by: admin.clone(),
};
for i in 0..fee_structures.len() {
let structure = fee_structures.get(i).unwrap();
if structure.fee_type == fee_type {
old_bps = structure.base_fee_bps;
old_min_fee = structure.min_fee;
old_max_fee = structure.max_fee;
old_is_active = structure.is_active;
fee_structures.set(i, updated_structure.clone());
found = true;
break;
}
}
if !found {
fee_structures.push_back(updated_structure.clone());
}
env.storage()
.instance()
.set(&FEE_CONFIG_KEY, &fee_structures);
events::emit_fee_structure_updated(env, &fee_type, old_bps, base_fee_bps, admin);
// Tamper-evident audit entry (atomic with storage write above via Soroban tx semantics)
let old_str = if found {
Some(fmt_fee_structure(
env,
old_bps,
old_min_fee,
old_max_fee,
old_is_active,
))
} else {
None
};
log_config_change(
env,
AuditOperation::ConfigFeeStructureChanged,
admin.clone(),
fee_type_label(&fee_type),
old_str,
Some(fmt_fee_structure(
env,
base_fee_bps,
min_fee,
max_fee,
is_active,
)),
);
Ok(updated_structure)
}
/// Calculate deterministic transaction fees for a user and payment-timing context.
///
/// Fee application order is intentionally fixed so the same inputs always produce
/// the same output:
/// 1. Compute each active fee's raw basis-point amount.
/// 2. Clamp the raw fee into that structure's `[min_fee, max_fee]` range.
/// 3. Apply the user's volume-tier discount to every fee except `LatePayment`.
/// 4. Apply the early-payment discount to the `Platform` fee only.
/// 5. Apply the late-payment surcharge to the `LatePayment` fee only.
///
/// # Security notes
/// - Uses checked BPS multiplication to fail safely on overflow.
/// - Uses checked addition for total fee aggregation.
/// - Iterates only over configured fee structures, keeping work deterministic.
/// - Uses integer division throughout, so rounding always truncates toward zero.
pub fn calculate_total_fees(
env: &Env,
user: &Address,
transaction_amount: i128,
is_early_payment: bool,
is_late_payment: bool,
late_payment_penalty_bps: Option<u32>,
) -> Result<i128, QuickLendXError> {
if transaction_amount <= 0 {
return Err(QuickLendXError::InvalidAmount);
}
let fee_structures: Vec<FeeStructure> =
env.storage().instance().get(&FEE_CONFIG_KEY).unwrap();
let user_volume_data = Self::get_user_volume(env, user);
let tier_discount = Self::get_tier_discount(&user_volume_data.current_tier);
let mut total_fees: i128 = 0;
for i in 0..fee_structures.len() {
let structure = fee_structures.get(i).unwrap();
if !structure.is_active {
continue;
}
if structure.fee_type == FeeType::EarlyPayment && !is_early_payment {
continue;
}
if structure.fee_type == FeeType::LatePayment && !is_late_payment {
continue;
}
let mut fee = Self::calculate_base_fee(&structure, transaction_amount)?;
if structure.fee_type != FeeType::LatePayment {
let discount = Self::checked_mul_div(fee, tier_discount as i128, BPS_DENOMINATOR)?;
fee = fee
.checked_sub(discount)
.ok_or(QuickLendXError::ArithmeticOverflow)?;
}
if is_early_payment && structure.fee_type == FeeType::Platform {
let early =
Self::checked_mul_div(fee, EARLY_PLATFORM_DISCOUNT_BPS, BPS_DENOMINATOR)?;
fee = fee
.checked_sub(early)
.ok_or(QuickLendXError::ArithmeticOverflow)?;
}
if is_late_payment && structure.fee_type == FeeType::LatePayment {
let surcharge_bps =
late_payment_penalty_bps.unwrap_or(LATE_FEE_SURCHARGE_BPS as u32) as i128;
let late = Self::checked_mul_div(fee, surcharge_bps, BPS_DENOMINATOR)?;
fee = fee
.checked_add(late)
.ok_or(QuickLendXError::ArithmeticOverflow)?;
}
total_fees = Self::checked_add(total_fees, fee)?;
}
Ok(total_fees)
}
/// Calculate the raw fee for one structure and clamp it to the configured bounds.
///
/// The clamp happens before tier discounts or timing modifiers so that the contract
/// always applies discounts and penalties to a bounded intermediate value.
///
/// Uses checked BPS multiplication to detect overflow and return
/// `QuickLendXError::ArithmeticOverflow` instead of wrapping.
fn calculate_base_fee(structure: &FeeStructure, amount: i128) -> Result<i128, QuickLendXError> {
let fee = Self::checked_mul_div(amount, structure.base_fee_bps as i128, BPS_DENOMINATOR)?;
let fee = if fee < structure.min_fee {
structure.min_fee
} else if fee > structure.max_fee {
structure.max_fee
} else {
fee
};
Ok(fee)
}
/// Return the fixed discount, in basis points, for a user's current volume tier.
fn get_tier_discount(tier: &VolumeTier) -> u32 {
match tier {
VolumeTier::Standard => 0,
VolumeTier::Silver => 500,
VolumeTier::Gold => 1000,
VolumeTier::Platinum => 1500,
}
}
pub fn get_user_volume(env: &Env, user: &Address) -> UserVolumeData {
let key = (VOLUME_KEY, user.clone());
env.storage()
.instance()
.get(&key)
.unwrap_or(UserVolumeData {
user: user.clone(),
total_volume: 0,
transaction_count: 0,
current_tier: VolumeTier::Standard,
last_updated: env.ledger().timestamp(),
})
}
/// Update a user's cumulative transaction volume and derived discount tier.
///
/// Tier thresholds are monotonic and based only on persisted cumulative volume,
/// which keeps the derived tier deterministic for repeated inputs.
///
/// Uses checked volume accumulation so overflow is rejected by
/// `QuickLendXError::ArithmeticOverflow`.
pub fn update_user_volume(
env: &Env,
user: &Address,
transaction_amount: i128,
) -> Result<UserVolumeData, QuickLendXError> {
let mut volume_data = Self::get_user_volume(env, user);
volume_data.total_volume = Self::checked_add(volume_data.total_volume, transaction_amount)?;
volume_data.transaction_count = volume_data.transaction_count.saturating_add(1);
volume_data.last_updated = env.ledger().timestamp();
volume_data.current_tier = if volume_data.total_volume >= 1_000_000_000_000 {
VolumeTier::Platinum
} else if volume_data.total_volume >= 500_000_000_000 {
VolumeTier::Gold
} else if volume_data.total_volume >= 100_000_000_000 {
VolumeTier::Silver
} else {
VolumeTier::Standard
};
let key = (VOLUME_KEY, user.clone());
env.storage().instance().set(&key, &volume_data);
Ok(volume_data)
}
/// Validate a fee collection map before persisting.
fn validate_fee_collection_map(
fees_collected: &Map<FeeType, i128>,
total_amount: i128,
) -> Result<(), QuickLendXError> {
let mut computed_total: i128 = 0;
for fee_type in fees_collected.keys() {
let amount = fees_collected.get(fee_type).unwrap_or(0);
if amount < 0 {
return Err(QuickLendXError::InvalidAmount);
}
computed_total = Self::checked_add(computed_total, amount)?;
}
if computed_total != total_amount {
return Err(QuickLendXError::InvalidFeeConfiguration);
}
Ok(())
}
pub fn collect_fees(
env: &Env,
user: &Address,
fees_collected: Map<FeeType, i128>,
total_amount: i128,
) -> Result<(), QuickLendXError> {
if total_amount <= 0 {
return Err(QuickLendXError::InvalidAmount);
}
// Validate the map: no negatives, sum == total_amount.
// Missing fee types are acceptable (treated as zero).
Self::validate_fee_collection_map(&fees_collected, total_amount)?;
let period = Self::get_current_period(env);
let key = (REVENUE_KEY, period);
let mut revenue_data: RevenueData =
env.storage().instance().get(&key).unwrap_or(RevenueData {
period,
total_collected: 0,
fees_by_type: Map::new(env),
total_distributed: 0,
pending_distribution: 0,
transaction_count: 0,
});
revenue_data.total_collected =
Self::checked_add(revenue_data.total_collected, total_amount)?;
revenue_data.pending_distribution =
Self::checked_add(revenue_data.pending_distribution, total_amount)?;
revenue_data.transaction_count = revenue_data.transaction_count.saturating_add(1);
// Merge incoming fees into existing period map rather than overwriting.
// This preserves fees collected in earlier calls within the same period.
for fee_type in fees_collected.keys() {
let amount = fees_collected.get(fee_type.clone()).unwrap_or(0);
let existing: i128 = revenue_data.fees_by_type.get(fee_type.clone()).unwrap_or(0);
let merged = Self::checked_add(existing, amount)?;
revenue_data.fees_by_type.set(fee_type, merged);
}
env.storage().instance().set(&key, &revenue_data);
Self::update_user_volume(env, user, total_amount)?;
Ok(())
}
fn get_current_period(env: &Env) -> u64 {
env.ledger().timestamp() / 2_592_000
}
/// Configure revenue distribution with comprehensive share validation.
///
/// # Safety invariants
/// - Each individual share must be in [0, 10_000] bps.
/// - The sum of all shares must equal exactly 10_000 bps (100%).
/// - `min_distribution_amount` must be non-negative.
///
/// # Errors
/// - `InvalidFeeConfiguration` if any individual share exceeds 10_000 bps.
/// - `InvalidAmount` if shares do not sum to 10_000 or min_distribution_amount < 0.
pub fn configure_revenue_distribution(
env: &Env,
admin: &Address,
config: RevenueConfig,
) -> Result<(), QuickLendXError> {
admin.require_auth();
// Validate individual share bounds
Self::validate_revenue_shares(
config.treasury_share_bps,
config.developer_share_bps,
config.platform_share_bps,
)?;
// Validate min distribution amount is non-negative
if config.min_distribution_amount < 0 {
return Err(QuickLendXError::InvalidAmount);
}
// Capture old config before write
let old_str = Self::get_revenue_split_config(env).ok().map(|c| {
fmt_rev_dist(
env,
c.treasury_share_bps,
c.developer_share_bps,
c.platform_share_bps,
c.min_distribution_amount,
)
});
let key = symbol_short!("rev_cfg");
env.storage().instance().set(&key, &config);
// Tamper-evident audit entry (atomic with storage write above via Soroban tx semantics)
log_config_change(
env,
AuditOperation::ConfigRevenueDistributionChanged,
admin.clone(),
"rev_dist",
old_str,
Some(fmt_rev_dist(
env,
config.treasury_share_bps,
config.developer_share_bps,
config.platform_share_bps,
config.min_distribution_amount,
)),
);
// Emit configuration event for audit trail
crate::events::emit_platform_fee_config_updated(
env,
0, // Placeholder for old value if not available easily
config.platform_share_bps,
admin,
);
Ok(())
}
/// Validate that revenue shares are individually bounded and sum to 10_000 bps.
///
/// # Invariants enforced
/// - `0 <= each_share <= 10_000`
/// - `treasury + developer + platform == 10_000`
pub fn validate_revenue_shares(
treasury_share_bps: u32,
developer_share_bps: u32,
platform_share_bps: u32,
) -> Result<(), QuickLendXError> {
// Individual share bounds check
if treasury_share_bps > 10_000
|| developer_share_bps > 10_000
|| platform_share_bps > 10_000
{
return Err(QuickLendXError::InvalidFeeConfiguration);
}
// Sum must equal exactly 10_000 bps (use checked arithmetic to prevent overflow)
let total_shares = treasury_share_bps
.checked_add(developer_share_bps)
.and_then(|s| s.checked_add(platform_share_bps))
.ok_or(QuickLendXError::InvalidFeeConfiguration)?;
if total_shares != 10_000 {
return Err(QuickLendXError::InvalidAmount);
}
Ok(())
}
/// Get current revenue split configuration
pub fn get_revenue_split_config(env: &Env) -> Result<RevenueConfig, QuickLendXError> {
let key = symbol_short!("rev_cfg");
env.storage()
.instance()
.get(&key)
.ok_or(QuickLendXError::StorageKeyNotFound)
}
/// Distribute accumulated revenue for a period according to the configured split.
///
/// # Distribution algorithm
/// 1. Treasury and developer amounts are calculated via `floor(pending * share_bps / 10_000)`.
/// 2. Platform receives the remainder: `pending - treasury - developer`.
/// 3. This guarantees `treasury + developer + platform == pending` (no dust loss).
///
/// # Safety invariants enforced
/// - Revenue config must exist and shares must sum to 10_000 bps.
/// - If [`Self::get_treasury_address`] is set and `treasury_share_bps > 0`, the revenue
/// config's `treasury_address` must match that routing target (same on-chain fee treasury).
/// - Uses checked BPS multiplication for revenue shares to avoid overflow when
/// pending distribution and share rates are large.
/// - Idempotency: when `pending_distribution == 0`, the call returns
/// [`QuickLendXError::OperationNotAllowed`] so a period cannot be "re-settled" until new
/// fees are collected (avoids duplicate events / no-op distributions when
/// `min_distribution_amount == 0`).
/// - Pending distribution must meet the minimum threshold when it is positive.
/// - Post-distribution sum must equal the original pending amount (accounting invariant).
/// - Each distributed amount must be non-negative.
pub fn distribute_revenue(