-
Notifications
You must be signed in to change notification settings - Fork 117
/
fee_reserve.rs
749 lines (642 loc) · 25 KB
/
fee_reserve.rs
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
use super::FeeReserveFinalizationSummary;
use crate::{
errors::CanBeAbortion,
transaction::{AbortReason, CostingParameters},
types::*,
};
use radix_engine_interface::blueprints::resource::LiquidFungibleResource;
use sbor::rust::cmp::min;
use transaction::prelude::TransactionCostingParameters;
#[derive(Debug, Clone, PartialEq, Eq, ScryptoSbor)]
pub enum FeeReserveError {
InsufficientBalance {
required: Decimal,
remaining: Decimal,
},
Overflow,
LimitExceeded {
limit: u32,
committed: u32,
new: u32,
},
LoanRepaymentFailed {
xrd_owed: Decimal,
},
Abort(AbortReason),
}
#[derive(Copy, Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord, ScryptoSbor)]
pub enum StorageType {
State,
Archive,
}
impl CanBeAbortion for FeeReserveError {
fn abortion(&self) -> Option<&AbortReason> {
match self {
Self::Abort(reason) => Some(reason),
_ => None,
}
}
}
/// This is only allowed before a transaction properly begins.
/// After any other methods are called, this cannot be called again.
pub trait PreExecutionFeeReserve {
fn consume_deferred_execution(&mut self, cost_units: u32) -> Result<(), FeeReserveError>;
fn consume_deferred_storage(
&mut self,
storage_type: StorageType,
size_increase: usize,
) -> Result<(), FeeReserveError>;
}
pub trait ExecutionFeeReserve {
fn consume_execution(&mut self, cost_units: u32) -> Result<(), FeeReserveError>;
fn consume_finalization(&mut self, cost_units: u32) -> Result<(), FeeReserveError>;
fn consume_storage(
&mut self,
storage_type: StorageType,
size_increase: usize,
) -> Result<(), FeeReserveError>;
fn consume_royalty(
&mut self,
royalty_amount: RoyaltyAmount,
recipient: RoyaltyRecipient,
) -> Result<(), FeeReserveError>;
fn lock_fee(&mut self, vault_id: NodeId, fee: LiquidFungibleResource, contingent: bool);
}
pub trait FinalizingFeeReserve {
fn finalize(self) -> FeeReserveFinalizationSummary;
}
pub trait FeeReserve: PreExecutionFeeReserve + ExecutionFeeReserve + FinalizingFeeReserve {}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, ScryptoSbor)]
pub enum RoyaltyRecipient {
Package(PackageAddress, NodeId),
Component(ComponentAddress, NodeId),
}
impl RoyaltyRecipient {
pub fn vault_id(&self) -> NodeId {
match self {
RoyaltyRecipient::Package(_, v) | RoyaltyRecipient::Component(_, v) => *v,
}
}
}
#[derive(Debug, Clone, ScryptoSbor)]
pub struct SystemLoanFeeReserve {
execution_cost_unit_price: Decimal,
execution_cost_unit_limit: u32,
execution_cost_unit_loan: u32,
finalization_cost_unit_price: Decimal,
finalization_cost_unit_limit: u32,
usd_price: Decimal,
state_storage_price: Decimal,
archive_storage_price: Decimal,
tip_percentage: u16,
/// Whether to abort the transaction run when the loan is repaid.
/// This is used when test-executing pending transactions.
abort_when_loan_repaid: bool,
/// (Cache) The effective execution cost unit price, with tips considered
effective_execution_cost_unit_price: Decimal,
/// (Cache) The effective finalization cost unit price, with tips considered
effective_finalization_cost_unit_price: Decimal,
/// The XRD balance
xrd_balance: Decimal,
/// The amount of XRD owed to the system
xrd_owed: Decimal,
/// Execution costs
execution_cost_units_committed: u32,
execution_cost_units_deferred: u32,
// Finalization costs
finalization_cost_units_committed: u32,
/// Royalty costs
royalty_cost_committed: Decimal,
royalty_cost_breakdown: IndexMap<RoyaltyRecipient, Decimal>,
/// Storage Costs
storage_cost_committed: Decimal,
storage_cost_deferred: IndexMap<StorageType, usize>,
/// Payments made during the execution of a transaction.
locked_fees: Vec<(NodeId, LiquidFungibleResource, bool)>,
}
impl Default for SystemLoanFeeReserve {
fn default() -> Self {
Self::new(
&CostingParameters::default(),
&TransactionCostingParameters::default(),
false,
)
}
}
#[inline]
fn checked_add(a: u32, b: u32) -> Result<u32, FeeReserveError> {
a.checked_add(b).ok_or(FeeReserveError::Overflow)
}
#[inline]
fn checked_add_assign(value: &mut u32, summand: u32) -> Result<(), FeeReserveError> {
*value = checked_add(*value, summand)?;
Ok(())
}
impl SystemLoanFeeReserve {
pub fn new(
costing_parameters: &CostingParameters,
transaction_costing_parameters: &TransactionCostingParameters,
abort_when_loan_repaid: bool,
) -> Self {
// Sanity checks
assert!(!costing_parameters.execution_cost_unit_price.is_negative());
assert!(!costing_parameters
.finalization_cost_unit_price
.is_negative());
assert!(!costing_parameters.usd_price.is_negative());
assert!(!costing_parameters.state_storage_price.is_negative());
assert!(!costing_parameters.archive_storage_price.is_negative());
assert!(!transaction_costing_parameters
.free_credit_in_xrd
.is_negative());
let tip_percentage = Decimal::ONE
.checked_add(
Decimal::ONE_HUNDREDTH
.checked_mul(transaction_costing_parameters.tip_percentage)
.unwrap(),
)
.unwrap();
let effective_execution_cost_unit_price = costing_parameters
.execution_cost_unit_price
.checked_mul(tip_percentage)
.unwrap();
let effective_finalization_cost_unit_price = costing_parameters
.finalization_cost_unit_price
.checked_mul(tip_percentage)
.unwrap();
let system_loan_in_xrd = effective_execution_cost_unit_price
.checked_mul(costing_parameters.execution_cost_unit_loan)
.unwrap();
Self {
// Execution costing parameters
execution_cost_unit_price: costing_parameters.execution_cost_unit_price,
execution_cost_unit_limit: costing_parameters.execution_cost_unit_limit,
execution_cost_unit_loan: costing_parameters.execution_cost_unit_loan,
// Finalization costing parameters
finalization_cost_unit_price: costing_parameters.finalization_cost_unit_price,
finalization_cost_unit_limit: costing_parameters.finalization_cost_unit_limit,
// USD and storage price
usd_price: costing_parameters.usd_price,
state_storage_price: costing_parameters.state_storage_price,
archive_storage_price: costing_parameters.archive_storage_price,
// Tipping percentage
tip_percentage: transaction_costing_parameters.tip_percentage,
// Aborting support
abort_when_loan_repaid,
// Cache
effective_execution_cost_unit_price: effective_execution_cost_unit_price,
effective_finalization_cost_unit_price: effective_finalization_cost_unit_price,
// Running balance
xrd_balance: system_loan_in_xrd
.checked_add(transaction_costing_parameters.free_credit_in_xrd)
.expect("Invalid system loan or free credit amount"),
xrd_owed: system_loan_in_xrd,
// Internal states
execution_cost_units_committed: 0,
execution_cost_units_deferred: 0,
finalization_cost_units_committed: 0,
royalty_cost_breakdown: index_map_new(),
royalty_cost_committed: Decimal::ZERO,
storage_cost_committed: Decimal::ZERO,
storage_cost_deferred: index_map_new(),
locked_fees: Vec::new(),
}
}
pub fn execution_cost_unit_limit(&self) -> u32 {
self.execution_cost_unit_limit
}
pub fn execution_cost_unit_price(&self) -> Decimal {
self.execution_cost_unit_price
}
pub fn finalization_cost_unit_limit(&self) -> u32 {
self.finalization_cost_unit_limit
}
pub fn finalization_cost_unit_price(&self) -> Decimal {
self.finalization_cost_unit_price
}
pub fn usd_price(&self) -> Decimal {
self.usd_price
}
pub fn tip_percentage(&self) -> u32 {
self.tip_percentage.into()
}
pub fn fee_balance(&self) -> Decimal {
self.xrd_balance
}
pub fn royalty_cost_breakdown(&self) -> &IndexMap<RoyaltyRecipient, Decimal> {
&self.royalty_cost_breakdown
}
fn check_execution_cost_unit_limit(&self, cost_units: u32) -> Result<(), FeeReserveError> {
if checked_add(self.execution_cost_units_committed, cost_units)?
> self.execution_cost_unit_limit
{
return Err(FeeReserveError::LimitExceeded {
limit: self.execution_cost_unit_limit,
committed: self.execution_cost_units_committed,
new: cost_units,
});
}
Ok(())
}
fn check_finalization_cost_unit_limit(&self, cost_units: u32) -> Result<(), FeeReserveError> {
if checked_add(self.finalization_cost_units_committed, cost_units)?
> self.finalization_cost_unit_limit
{
return Err(FeeReserveError::LimitExceeded {
limit: self.finalization_cost_unit_limit,
committed: self.finalization_cost_units_committed,
new: cost_units,
});
}
Ok(())
}
fn consume_execution_internal(&mut self, cost_units: u32) -> Result<(), FeeReserveError> {
self.check_execution_cost_unit_limit(cost_units)?;
let amount = self
.effective_execution_cost_unit_price
.checked_mul(cost_units)
.ok_or(FeeReserveError::Overflow)?;
if self.xrd_balance < amount {
return Err(FeeReserveError::InsufficientBalance {
required: amount,
remaining: self.xrd_balance,
});
} else {
self.xrd_balance -= amount;
self.execution_cost_units_committed += cost_units;
Ok(())
}
}
fn consume_finalization_internal(&mut self, cost_units: u32) -> Result<(), FeeReserveError> {
self.check_finalization_cost_unit_limit(cost_units)?;
let amount = self
.effective_finalization_cost_unit_price
.checked_mul(cost_units)
.ok_or(FeeReserveError::Overflow)?;
if self.xrd_balance < amount {
return Err(FeeReserveError::InsufficientBalance {
required: amount,
remaining: self.xrd_balance,
});
} else {
self.xrd_balance -= amount;
self.finalization_cost_units_committed += cost_units;
Ok(())
}
}
fn consume_royalty_internal(
&mut self,
royalty_amount: RoyaltyAmount,
recipient: RoyaltyRecipient,
) -> Result<(), FeeReserveError> {
let amount = match royalty_amount {
RoyaltyAmount::Xrd(xrd_amount) => xrd_amount,
RoyaltyAmount::Usd(usd_amount) => usd_amount
.checked_mul(self.usd_price)
.ok_or(FeeReserveError::Overflow)?,
RoyaltyAmount::Free => Decimal::ZERO,
};
if self.xrd_balance < amount {
return Err(FeeReserveError::InsufficientBalance {
required: amount,
remaining: self.xrd_balance,
});
} else {
self.xrd_balance -= amount;
self.royalty_cost_breakdown
.entry(recipient)
.or_default()
.add_assign(amount);
self.royalty_cost_committed += amount;
Ok(())
}
}
pub fn repay_all(&mut self) -> Result<(), FeeReserveError> {
// Apply deferred execution cost
self.consume_execution_internal(self.execution_cost_units_deferred)?;
self.execution_cost_units_deferred = 0;
// Apply deferred storage cost
let types: Vec<StorageType> = self.storage_cost_deferred.keys().cloned().collect();
for t in types {
self.consume_storage(t, self.storage_cost_deferred.get(&t).cloned().unwrap())?;
self.storage_cost_deferred.remove(&t);
}
// Repay owed with balance
let amount = min(self.xrd_balance, self.xrd_owed);
self.xrd_owed -= amount;
self.xrd_balance -= amount; // not used afterwards
// Check outstanding loan
if !self.xrd_owed.is_zero() {
return Err(FeeReserveError::LoanRepaymentFailed {
xrd_owed: self.xrd_owed,
});
}
if self.abort_when_loan_repaid {
return Err(FeeReserveError::Abort(
AbortReason::ConfiguredAbortTriggeredOnFeeLoanRepayment,
));
}
Ok(())
}
pub fn revert_royalty(&mut self) {
self.xrd_balance += self.royalty_cost_committed;
self.royalty_cost_breakdown.clear();
self.royalty_cost_committed = Decimal::ZERO;
}
#[inline]
pub fn fully_repaid(&self) -> bool {
// The xrd_owed state is not reset before all deferred costs are applied.
// Thus, not checking the deferred balance
self.xrd_owed == Decimal::ZERO
}
}
impl PreExecutionFeeReserve for SystemLoanFeeReserve {
fn consume_deferred_execution(&mut self, cost_units: u32) -> Result<(), FeeReserveError> {
checked_add_assign(&mut self.execution_cost_units_deferred, cost_units)?;
Ok(())
}
fn consume_deferred_storage(
&mut self,
storage_type: StorageType,
size_increase: usize,
) -> Result<(), FeeReserveError> {
self.storage_cost_deferred
.entry(storage_type)
.or_default()
.add_assign(size_increase);
Ok(())
}
}
impl ExecutionFeeReserve for SystemLoanFeeReserve {
fn consume_execution(&mut self, cost_units: u32) -> Result<(), FeeReserveError> {
if cost_units == 0 {
return Ok(());
}
self.consume_execution_internal(cost_units)?;
if !self.fully_repaid()
&& self.execution_cost_units_committed >= self.execution_cost_unit_loan
{
self.repay_all()?;
}
Ok(())
}
fn consume_finalization(&mut self, cost_units: u32) -> Result<(), FeeReserveError> {
if cost_units == 0 {
return Ok(());
}
self.consume_finalization_internal(cost_units)?;
Ok(())
}
fn consume_royalty(
&mut self,
royalty_amount: RoyaltyAmount,
recipient: RoyaltyRecipient,
) -> Result<(), FeeReserveError> {
if royalty_amount.is_zero() {
return Ok(());
}
if royalty_amount.is_negative() {
panic!("System invariant broken: Encountered negative royalty amount")
}
self.consume_royalty_internal(royalty_amount, recipient)?;
Ok(())
}
fn consume_storage(
&mut self,
storage_type: StorageType,
size_increase: usize,
) -> Result<(), FeeReserveError> {
let amount = match storage_type {
StorageType::State => self.state_storage_price,
StorageType::Archive => self.archive_storage_price,
}
.checked_mul(size_increase)
.ok_or(FeeReserveError::Overflow)?;
if self.xrd_balance < amount {
return Err(FeeReserveError::InsufficientBalance {
required: amount,
remaining: self.xrd_balance,
});
} else {
self.xrd_balance -= amount;
self.storage_cost_committed += amount;
Ok(())
}
}
fn lock_fee(&mut self, vault_id: NodeId, mut fee: LiquidFungibleResource, contingent: bool) {
// Update balance
if !contingent {
self.xrd_balance = self
.xrd_balance
.checked_add(fee.amount())
.expect("No overflow due to limited XRD supply");
}
// Move resource
self.locked_fees
.push((vault_id, fee.take_all(), contingent));
}
}
impl FinalizingFeeReserve for SystemLoanFeeReserve {
fn finalize(self) -> FeeReserveFinalizationSummary {
let total_execution_cost_in_xrd = self
.execution_cost_unit_price
.checked_mul(Decimal::from(self.execution_cost_units_committed))
.unwrap();
let total_finalization_cost_in_xrd = self
.finalization_cost_unit_price
.checked_mul(Decimal::from(self.finalization_cost_units_committed))
.unwrap();
let tip_percentage = Decimal::from(self.tip_percentage)
.checked_div(dec!(100))
.unwrap();
let total_tipping_cost_in_xrd = total_execution_cost_in_xrd
.checked_mul(tip_percentage)
.unwrap()
.checked_add(
total_finalization_cost_in_xrd
.checked_mul(tip_percentage)
.unwrap(),
)
.unwrap();
FeeReserveFinalizationSummary {
total_execution_cost_units_consumed: self.execution_cost_units_committed,
total_finalization_cost_units_consumed: self.finalization_cost_units_committed,
total_execution_cost_in_xrd,
total_finalization_cost_in_xrd,
total_tipping_cost_in_xrd,
total_royalty_cost_in_xrd: self.royalty_cost_committed,
total_storage_cost_in_xrd: self.storage_cost_committed,
total_bad_debt_in_xrd: self.xrd_owed,
locked_fees: self.locked_fees,
royalty_cost_breakdown: self.royalty_cost_breakdown,
}
}
}
impl FeeReserve for SystemLoanFeeReserve {}
#[cfg(test)]
mod tests {
use super::*;
const TEST_COMPONENT: ComponentAddress =
component_address(EntityType::GlobalGenericComponent, 5);
const TEST_VAULT_ID: NodeId = NodeId([0u8; NodeId::LENGTH]);
const TEST_VAULT_ID_2: NodeId = NodeId([1u8; NodeId::LENGTH]);
fn xrd<T: Into<Decimal>>(amount: T) -> LiquidFungibleResource {
LiquidFungibleResource::new(amount.into())
}
fn create_test_fee_reserve(
execution_cost_unit_price: Decimal,
usd_price: Decimal,
state_storage_price: Decimal,
tip_percentage: u16,
execution_cost_unit_limit: u32,
execution_cost_unit_loan: u32,
abort_when_loan_repaid: bool,
) -> SystemLoanFeeReserve {
let mut costing_parameters = CostingParameters::default();
costing_parameters.execution_cost_unit_price = execution_cost_unit_price;
costing_parameters.execution_cost_unit_limit = execution_cost_unit_limit;
costing_parameters.execution_cost_unit_loan = execution_cost_unit_loan;
costing_parameters.usd_price = usd_price;
costing_parameters.state_storage_price = state_storage_price;
let mut transaction_costing_parameters = TransactionCostingParameters::default();
transaction_costing_parameters.tip_percentage = tip_percentage;
SystemLoanFeeReserve::new(
&costing_parameters,
&transaction_costing_parameters,
abort_when_loan_repaid,
)
}
#[test]
fn test_consume_and_repay() {
let mut fee_reserve = create_test_fee_reserve(dec!(1), dec!(1), dec!(0), 2, 100, 5, false);
fee_reserve.consume_execution(2).unwrap();
fee_reserve.lock_fee(TEST_VAULT_ID, xrd(3), false);
fee_reserve.repay_all().unwrap();
let summary = fee_reserve.finalize();
assert_eq!(summary.loan_fully_repaid(), true);
assert_eq!(summary.total_execution_cost_units_consumed, 2);
assert_eq!(summary.total_execution_cost_in_xrd, dec!("2"));
assert_eq!(summary.total_tipping_cost_in_xrd, dec!("0.04"));
assert_eq!(summary.total_royalty_cost_in_xrd, dec!("0"));
assert_eq!(summary.total_bad_debt_in_xrd, dec!("0"));
}
#[test]
fn test_out_of_cost_unit() {
let mut fee_reserve = create_test_fee_reserve(dec!(1), dec!(1), dec!(0), 2, 100, 5, false);
assert_eq!(
fee_reserve.consume_execution(6),
Err(FeeReserveError::InsufficientBalance {
required: dec!("6.12"),
remaining: dec!("5.1"),
}),
);
fee_reserve.repay_all().unwrap();
let summary = fee_reserve.finalize();
assert_eq!(summary.loan_fully_repaid(), true);
assert_eq!(summary.total_execution_cost_units_consumed, 0);
assert_eq!(summary.total_execution_cost_in_xrd, dec!("0"));
assert_eq!(summary.total_royalty_cost_in_xrd, dec!("0"));
assert_eq!(summary.total_bad_debt_in_xrd, dec!("0"));
}
#[test]
fn test_lock_fee() {
let mut fee_reserve =
create_test_fee_reserve(dec!(1), dec!(1), dec!(0), 2, 100, 500, false);
fee_reserve.lock_fee(TEST_VAULT_ID, xrd(100), false);
fee_reserve.repay_all().unwrap();
let summary = fee_reserve.finalize();
assert_eq!(summary.loan_fully_repaid(), true);
assert_eq!(summary.total_execution_cost_units_consumed, 0);
assert_eq!(summary.total_execution_cost_in_xrd, dec!("0"));
assert_eq!(summary.total_royalty_cost_in_xrd, dec!("0"));
assert_eq!(summary.total_bad_debt_in_xrd, dec!("0"));
}
#[test]
fn test_xrd_cost_unit_conversion() {
let mut fee_reserve =
create_test_fee_reserve(dec!(5), dec!(1), dec!(0), 0, 100, 500, false);
fee_reserve.lock_fee(TEST_VAULT_ID, xrd(100), false);
fee_reserve.repay_all().unwrap();
let summary = fee_reserve.finalize();
assert_eq!(summary.loan_fully_repaid(), true);
assert_eq!(summary.total_execution_cost_units_consumed, 0);
assert_eq!(summary.total_execution_cost_in_xrd, dec!("0"));
assert_eq!(summary.total_royalty_cost_in_xrd, dec!("0"));
assert_eq!(summary.total_bad_debt_in_xrd, dec!("0"));
assert_eq!(summary.locked_fees, vec![(TEST_VAULT_ID, xrd(100), false)],);
}
#[test]
fn test_bad_debt() {
let mut fee_reserve = create_test_fee_reserve(dec!(5), dec!(1), dec!(0), 1, 100, 50, false);
fee_reserve.consume_execution(2).unwrap();
assert_eq!(
fee_reserve.repay_all(),
Err(FeeReserveError::LoanRepaymentFailed {
xrd_owed: dec!("10.1")
})
);
let summary = fee_reserve.finalize();
assert_eq!(summary.loan_fully_repaid(), false);
assert_eq!(summary.total_execution_cost_units_consumed, 2);
assert_eq!(summary.total_execution_cost_in_xrd, dec!("10"));
assert_eq!(summary.total_tipping_cost_in_xrd, dec!("0.1"));
assert_eq!(summary.total_royalty_cost_in_xrd, dec!("0"));
assert_eq!(summary.total_bad_debt_in_xrd, dec!("10.1"));
assert_eq!(summary.locked_fees, vec![],);
}
#[test]
fn test_royalty_execution_mix() {
let mut fee_reserve = create_test_fee_reserve(dec!(5), dec!(2), dec!(0), 1, 100, 50, false);
fee_reserve.consume_execution(2).unwrap();
fee_reserve
.consume_royalty(
RoyaltyAmount::Xrd(2.into()),
RoyaltyRecipient::Package(PACKAGE_PACKAGE, TEST_VAULT_ID),
)
.unwrap();
fee_reserve
.consume_royalty(
RoyaltyAmount::Usd(7.into()),
RoyaltyRecipient::Package(PACKAGE_PACKAGE, TEST_VAULT_ID),
)
.unwrap();
fee_reserve.lock_fee(TEST_VAULT_ID, xrd(100), false);
fee_reserve.repay_all().unwrap();
let summary = fee_reserve.finalize();
assert_eq!(summary.loan_fully_repaid(), true);
assert_eq!(summary.total_execution_cost_in_xrd, dec!("10"));
assert_eq!(summary.total_tipping_cost_in_xrd, dec!("0.1"));
assert_eq!(summary.total_royalty_cost_in_xrd, dec!("16"));
assert_eq!(summary.total_bad_debt_in_xrd, dec!("0"));
assert_eq!(summary.locked_fees, vec![(TEST_VAULT_ID, xrd(100), false)]);
assert_eq!(summary.total_execution_cost_units_consumed, 2);
assert_eq!(
summary.royalty_cost_breakdown,
indexmap!(
RoyaltyRecipient::Package(PACKAGE_PACKAGE, TEST_VAULT_ID) => dec!("16")
)
);
}
#[test]
fn test_royalty_insufficient_balance() {
let mut fee_reserve =
create_test_fee_reserve(dec!(1), dec!(1), dec!(0), 0, 1000, 50, false);
fee_reserve.lock_fee(TEST_VAULT_ID, xrd(100), false);
fee_reserve
.consume_royalty(
RoyaltyAmount::Xrd(90.into()),
RoyaltyRecipient::Package(PACKAGE_PACKAGE, TEST_VAULT_ID),
)
.unwrap();
assert_eq!(
fee_reserve.consume_royalty(
RoyaltyAmount::Xrd(80.into()),
RoyaltyRecipient::Component(TEST_COMPONENT, TEST_VAULT_ID_2),
),
Err(FeeReserveError::InsufficientBalance {
required: dec!("80"),
remaining: dec!("60"),
}),
);
}
}