-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathlib.rs
1275 lines (1099 loc) · 36.7 KB
/
lib.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
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
// Copyright 2023 Centrifuge Foundation (centrifuge.io).
// This file is part of Centrifuge chain project.
// Centrifuge is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version (see http://www.gnu.org/licenses).
// Centrifuge is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
#![cfg_attr(not(feature = "std"), no_std)]
//! This pallet offers extrinsics to handle loans.
//!
//! The following actions are performed over a loan:
//!
//! | Extrinsics | Role |
//! |-------------------------------------|-----------|
//! | [`Pallet::create()`] | Borrower |
//! | [`Pallet::borrow()`] | Borrower |
//! | [`Pallet::repay()`] | Borrower |
//! | [`Pallet::write_off()`] | |
//! | [`Pallet::admin_write_off()`] | LoanAdmin |
//! | [`Pallet::propose_loan_mutation()`] | LoanAdmin |
//! | [`Pallet::apply_loan_mutation()`] | |
//! | [`Pallet::propose_transfer_debt()`] | Borrower |
//! | [`Pallet::apply_transfer_debt()`] | |
//! | [`Pallet::close()`] | Borrower |
//!
//! The following actions are performed over an entire pool of loans:
//!
//! | Extrinsics | Role |
//! |------------------------------------------|-----------|
//! | [`Pallet::propose_write_off_policy()`] | PoolAdmin |
//! | [`Pallet::apply_write_off_policy()`] | |
//! | [`Pallet::update_portfolio_valuation()`] | |
//!
//! The whole pallet is optimized for the more expensive extrinsic that is
//! [`Pallet::update_portfolio_valuation()`] that should go through all active
//! loans.
/// High level types that uses `pallet::Config`
pub mod entities {
pub mod changes;
pub mod input;
pub mod interest;
pub mod loans;
pub mod pricing;
}
/// Low level types that doesn't know about what a pallet is
pub mod types;
/// Utility types for configure the pallet from a runtime
pub mod util;
mod weights;
#[cfg(test)]
mod tests;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
pub use pallet::*;
pub use weights::WeightInfo;
#[frame_support::pallet]
pub mod pallet {
use cfg_traits::{
self,
changes::ChangeGuard,
data::{DataCollection, DataRegistry},
interest::InterestAccrual,
IntoSeconds, Permissions, PoolInspect, PoolNAV, PoolReserve, PoolWriteOffPolicyMutate,
Seconds, TimeAsSecs,
};
use cfg_types::{
adjustments::Adjustment,
permissions::{PermissionScope, PoolRole, Role},
portfolio::{self, InitialPortfolioValuation, PortfolioValuationUpdateType},
};
use entities::{
changes::{Change, LoanMutation},
input::{PriceCollectionInput, PrincipalInput, RepaidInput},
loans::{self, ActiveLoan, ActiveLoanInfo, LoanInfo},
};
use frame_support::{
pallet_prelude::*,
storage::transactional,
traits::tokens::{
self,
nonfungibles::{Inspect, Transfer},
},
};
use frame_system::pallet_prelude::*;
use parity_scale_codec::HasCompact;
use scale_info::TypeInfo;
use sp_arithmetic::{FixedPointNumber, PerThing};
use sp_runtime::{
traits::{BadOrigin, EnsureAdd, EnsureAddAssign, EnsureInto, One, Zero},
ArithmeticError, FixedPointOperand, TransactionOutcome,
};
use sp_std::{collections::btree_map::BTreeMap, vec, vec::Vec};
use types::{
self,
cashflow::CashflowPayment,
policy::{self, WriteOffRule, WriteOffStatus},
BorrowLoanError, CloseLoanError, CreateLoanError, MutationError, RepayLoanError,
WrittenOffError,
};
use super::*;
pub type PortfolioInfoOf<T> = Vec<(<T as Config>::LoanId, ActiveLoanInfo<T>)>;
pub type AssetOf<T> = (<T as Config>::CollectionId, <T as Config>::ItemId);
pub type PriceOf<T> = (<T as Config>::Balance, <T as Config>::Moment);
const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Represent a runtime change
type RuntimeChange: From<Change<Self>> + TryInto<Change<Self>>;
/// Identify a currency.
type CurrencyId: Parameter + Copy + MaxEncodedLen;
/// Identify a non fungible collection
type CollectionId: Parameter + Member + Default + TypeInfo + Copy + MaxEncodedLen;
/// Identify a non fungible item
type ItemId: Parameter + Member + Default + TypeInfo + Copy + MaxEncodedLen;
/// Identify a loan in the pallet
type LoanId: Parameter
+ Member
+ Default
+ TypeInfo
+ MaxEncodedLen
+ Copy
+ EnsureAdd
+ One;
/// Identify a loan in the pallet
type PriceId: Parameter + Member + TypeInfo + Copy + MaxEncodedLen + Ord;
/// Defines the rate type used for math computations
type Rate: Parameter + Member + FixedPointNumber + TypeInfo + MaxEncodedLen;
/// Defines the balance type used for math computations
type Balance: tokens::Balance + FixedPointOperand;
/// Type to represent different quantities
type Quantity: Parameter + Member + FixedPointNumber + TypeInfo + MaxEncodedLen;
/// Defines the perthing type used where values can not overpass 100%
type PerThing: Parameter + Member + PerThing + TypeInfo + MaxEncodedLen;
/// Fetching method for the time of the current block
type Time: TimeAsSecs;
/// Generic time type
type Moment: Parameter + Member + IntoSeconds;
/// Used to mint, transfer, and inspect assets.
type NonFungible: Transfer<Self::AccountId>
+ Inspect<Self::AccountId, CollectionId = Self::CollectionId, ItemId = Self::ItemId>;
/// The PoolId type
type PoolId: Member + Parameter + Default + Copy + HasCompact + MaxEncodedLen;
/// Access to the pool
type Pool: PoolReserve<
Self::AccountId,
Self::CurrencyId,
Balance = Self::Balance,
PoolId = Self::PoolId,
>;
/// Used to verify permissions of users
type Permissions: Permissions<
Self::AccountId,
Scope = PermissionScope<Self::PoolId, Self::CurrencyId>,
Role = Role,
Error = DispatchError,
>;
/// Used to fetch and update Oracle prices
type PriceRegistry: DataRegistry<Self::PriceId, Self::PoolId, Data = PriceOf<Self>>;
/// Used to calculate interest accrual for debt.
type InterestAccrual: InterestAccrual<
Self::Rate,
Self::Balance,
Adjustment<Self::Balance>,
NormalizedDebt = Self::Balance,
>;
/// Used to notify the runtime about changes that require special
/// treatment.
type ChangeGuard: ChangeGuard<
PoolId = Self::PoolId,
ChangeId = Self::Hash,
Change = Self::RuntimeChange,
>;
/// Max number of active loans per pool.
#[pallet::constant]
type MaxActiveLoansPerPool: Get<u32>;
/// Max number of write-off groups per pool.
#[pallet::constant]
type MaxWriteOffPolicySize: Get<u32> + Parameter;
/// Information of runtime weights
type WeightInfo: WeightInfo;
}
/// Contains the last loan id generated
#[pallet::storage]
pub(crate) type LastLoanId<T: Config> =
StorageMap<_, Blake2_128Concat, T::PoolId, T::LoanId, ValueQuery>;
/// Storage for loans that has been created but are not still active.
#[pallet::storage]
pub(crate) type CreatedLoan<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
T::PoolId,
Blake2_128Concat,
T::LoanId,
loans::CreatedLoan<T>,
OptionQuery,
>;
/// Storage for active loans.
/// The indexation of this storage differs from `CreatedLoan` or
/// `ClosedLoan` because here we try to minimize the iteration speed over
/// all active loans in a pool.
#[pallet::storage]
pub type ActiveLoans<T: Config> = StorageMap<
_,
Blake2_128Concat,
T::PoolId,
BoundedVec<(T::LoanId, ActiveLoan<T>), T::MaxActiveLoansPerPool>,
ValueQuery,
>;
/// Storage for closed loans.
/// No mutations are expected in this storage.
/// Loans are stored here for historical purposes.
#[pallet::storage]
pub(crate) type ClosedLoan<T: Config> = StorageDoubleMap<
_,
Blake2_128Concat,
T::PoolId,
Blake2_128Concat,
T::LoanId,
loans::ClosedLoan<T>,
OptionQuery,
>;
/// Stores write off policy used in each pool
#[pallet::storage]
pub(crate) type WriteOffPolicy<T: Config> = StorageMap<
_,
Blake2_128Concat,
T::PoolId,
BoundedVec<WriteOffRule<T::Rate>, T::MaxWriteOffPolicySize>,
ValueQuery,
>;
/// Stores the portfolio valuation associated to each pool
#[pallet::storage]
#[pallet::getter(fn portfolio_valuation)]
pub(crate) type PortfolioValuation<T: Config> = StorageMap<
_,
Blake2_128Concat,
T::PoolId,
portfolio::PortfolioValuation<T::Balance, T::LoanId, T::MaxActiveLoansPerPool>,
ValueQuery,
InitialPortfolioValuation<T::Time>,
>;
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// A loan was created
Created {
pool_id: T::PoolId,
loan_id: T::LoanId,
loan_info: LoanInfo<T>,
},
/// An amount was borrowed for a loan
Borrowed {
pool_id: T::PoolId,
loan_id: T::LoanId,
amount: PrincipalInput<T>,
},
/// An amount was repaid for a loan
Repaid {
pool_id: T::PoolId,
loan_id: T::LoanId,
amount: RepaidInput<T>,
},
/// A loan was written off
WrittenOff {
pool_id: T::PoolId,
loan_id: T::LoanId,
status: WriteOffStatus<T::Rate>,
},
/// An active loan was mutated
Mutated {
pool_id: T::PoolId,
loan_id: T::LoanId,
mutation: LoanMutation<T::Rate>,
},
/// A loan was closed
Closed {
pool_id: T::PoolId,
loan_id: T::LoanId,
collateral: AssetOf<T>,
},
/// The portfolio valuation for a pool was updated.
PortfolioValuationUpdated {
pool_id: T::PoolId,
valuation: T::Balance,
update_type: PortfolioValuationUpdateType,
},
/// The write off policy for a pool was updated.
WriteOffPolicyUpdated {
pool_id: T::PoolId,
policy: BoundedVec<WriteOffRule<T::Rate>, T::MaxWriteOffPolicySize>,
},
/// Debt has been transfered between loans
DebtTransferred {
pool_id: T::PoolId,
from_loan_id: T::LoanId,
to_loan_id: T::LoanId,
repaid_amount: RepaidInput<T>,
borrow_amount: PrincipalInput<T>,
},
/// Debt of a loan has been increased
DebtIncreased {
pool_id: T::PoolId,
loan_id: T::LoanId,
amount: PrincipalInput<T>,
},
}
#[pallet::error]
pub enum Error<T> {
/// Emits when pool doesn't exist
PoolNotFound,
/// Emits when loan doesn't exist or it's not active yet.
LoanNotActiveOrNotFound,
/// Emits when a write-off rule is not found in a policy for a specific
/// loan. It happens when there is no policy or the loan is not overdue.
NoValidWriteOffRule,
/// Emits when the NFT owner is not found
NFTOwnerNotFound,
/// Emits when NFT owner doesn't match the expected owner
NotNFTOwner,
/// Emits when the applicant account is not the borrower of the loan
NotLoanBorrower,
/// Emits when the max number of active loans was reached
MaxActiveLoansReached,
/// The Change Id does not belong to a loan change
NoLoanChangeId,
/// The Change Id exists but it's not releated with the expected change
UnrelatedChangeId,
/// Emits when the pricing method is not compatible with the input
MismatchedPricingMethod,
/// Emits when settlement price is exceeds the configured variation.
SettlementPriceExceedsVariation,
/// Emits when the loan is incorrectly specified and can not be created
CreateLoanError(CreateLoanError),
/// Emits when the loan can not be borrowed from
BorrowLoanError(BorrowLoanError),
/// Emits when the loan can not be repaid from
RepayLoanError(RepayLoanError),
/// Emits when the loan can not be written off
WrittenOffError(WrittenOffError),
/// Emits when the loan can not be closed
CloseLoanError(CloseLoanError),
/// Emits when the loan can not be mutated
MutationError(MutationError),
/// Emits when debt is transfered to the same loan
TransferDebtToSameLoan,
/// Emits when debt is transfered with different repaid/borrow amounts
TransferDebtAmountMismatched,
}
impl<T> From<CreateLoanError> for Error<T> {
fn from(error: CreateLoanError) -> Self {
Error::<T>::CreateLoanError(error)
}
}
impl<T> From<BorrowLoanError> for Error<T> {
fn from(error: BorrowLoanError) -> Self {
Error::<T>::BorrowLoanError(error)
}
}
impl<T> From<RepayLoanError> for Error<T> {
fn from(error: RepayLoanError) -> Self {
Error::<T>::RepayLoanError(error)
}
}
impl<T> From<WrittenOffError> for Error<T> {
fn from(error: WrittenOffError) -> Self {
Error::<T>::WrittenOffError(error)
}
}
impl<T> From<CloseLoanError> for Error<T> {
fn from(error: CloseLoanError) -> Self {
Error::<T>::CloseLoanError(error)
}
}
impl<T> From<MutationError> for Error<T> {
fn from(error: MutationError) -> Self {
Error::<T>::MutationError(error)
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Creates a new loan against the collateral provided
///
/// The origin must be the owner of the collateral.
/// This collateral will be transferred to the existing pool.
#[pallet::weight(T::WeightInfo::create())]
#[pallet::call_index(0)]
pub fn create(
origin: OriginFor<T>,
pool_id: T::PoolId,
info: LoanInfo<T>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::ensure_role(pool_id, &who, PoolRole::Borrower)?;
Self::ensure_collateral_owner(&who, info.collateral())?;
Self::ensure_pool_exists(pool_id)?;
info.validate(T::Time::now())?;
let collateral = info.collateral();
T::NonFungible::transfer(&collateral.0, &collateral.1, &T::Pool::account_for(pool_id))?;
let loan_id = Self::generate_loan_id(pool_id)?;
CreatedLoan::<T>::insert(pool_id, loan_id, loans::CreatedLoan::new(info.clone(), who));
Self::deposit_event(Event::<T>::Created {
pool_id,
loan_id,
loan_info: info,
});
Ok(())
}
/// Transfers borrow amount to the borrower.
///
/// The origin must be the borrower of the loan.
/// The borrow action should fulfill the borrow restrictions configured
/// at [`types::LoanRestrictions`]. The `amount` will be transferred
/// from pool reserve to borrower. The portfolio valuation of the pool
/// is updated to reflect the new present value of the loan.
#[pallet::weight(T::WeightInfo::borrow(T::MaxActiveLoansPerPool::get()))]
#[pallet::call_index(1)]
pub fn borrow(
origin: OriginFor<T>,
pool_id: T::PoolId,
loan_id: T::LoanId,
amount: PrincipalInput<T>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let _count = Self::borrow_action(&who, pool_id, loan_id, &amount, false)?;
T::Pool::withdraw(pool_id, who, amount.balance()?)?;
Self::deposit_event(Event::<T>::Borrowed {
pool_id,
loan_id,
amount,
});
Ok(())
}
/// Transfers amount borrowed to the pool reserve.
///
/// The origin must be the borrower of the loan.
/// The repay action should fulfill the repay restrictions
/// configured at [`types::RepayRestrictions`].
/// If the repaying `amount` is more than current debt, only current
/// debt is transferred. This does not apply to `unscheduled_amount`,
/// which can be used to repay more than the outstanding debt.
/// The portfolio valuation of the pool is updated to reflect the new
/// present value of the loan.
#[pallet::weight(T::WeightInfo::repay(T::MaxActiveLoansPerPool::get()))]
#[pallet::call_index(2)]
pub fn repay(
origin: OriginFor<T>,
pool_id: T::PoolId,
loan_id: T::LoanId,
amount: RepaidInput<T>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let (amount, _count) = Self::repay_action(&who, pool_id, loan_id, &amount, false)?;
T::Pool::deposit(pool_id, who, amount.repaid_amount()?.total()?)?;
Self::deposit_event(Event::<T>::Repaid {
pool_id,
loan_id,
amount,
});
Ok(())
}
/// Writes off an overdue loan.
///
/// This action will write off based on the configured write off policy.
/// The write off action will only take effect if it writes down more
/// (percentage or penalty) than the current write off status of the
/// loan. This action will never writes up. i.e:
/// - Write off by admin with percentage 0.5 and penalty 0.2
/// - Time passes and the policy can be applied.
/// - Write of with a policy that says: percentage 0.3, penaly 0.4
/// - The loan is written off with the maximum between the policy and
/// the current rule: percentage 0.5, penalty 0.4
///
/// No special permisions are required to this call.
/// The portfolio valuation of the pool is updated to reflect the new
/// present value of the loan.
#[pallet::weight(T::WeightInfo::write_off(T::MaxActiveLoansPerPool::get()))]
#[pallet::call_index(3)]
pub fn write_off(
origin: OriginFor<T>,
pool_id: T::PoolId,
loan_id: T::LoanId,
) -> DispatchResult {
ensure_signed(origin)?;
let (status, _count) = Self::update_active_loan(pool_id, loan_id, |loan| {
let rule = Self::find_write_off_rule(pool_id, loan)?
.ok_or(Error::<T>::NoValidWriteOffRule)?;
let status = rule.status.compose_max(&loan.write_off_status());
loan.write_off(&status)?;
Ok(status)
})?;
Self::deposit_event(Event::<T>::WrittenOff {
pool_id,
loan_id,
status,
});
Ok(())
}
/// Writes off a loan from admin origin.
///
/// Forces a writing off of a loan if the `percentage` and `penalty`
/// parameters respecting the policy values as the maximum.
/// This action can write down/up the current write off status of the
/// loan. If there is no active policy, an admin write off action can
/// write up the write off status. But if there is a policy applied, the
/// admin can only write up until the policy. Write down more than the
/// policy is always allowed. The portfolio valuation of the pool is
/// updated to reflect the new present value of the loan.
#[pallet::weight(T::WeightInfo::admin_write_off(T::MaxActiveLoansPerPool::get()))]
#[pallet::call_index(4)]
pub fn admin_write_off(
origin: OriginFor<T>,
pool_id: T::PoolId,
loan_id: T::LoanId,
percentage: T::Rate,
penalty: T::Rate,
) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::ensure_role(pool_id, &who, PoolRole::LoanAdmin)?;
let status = WriteOffStatus {
percentage,
penalty,
};
let (_, _count) = Self::update_active_loan(pool_id, loan_id, |loan| {
let rule = Self::find_write_off_rule(pool_id, loan)?;
Self::ensure_admin_write_off(&status, rule)?;
loan.write_off(&status)?;
Ok(())
})?;
Self::deposit_event(Event::<T>::WrittenOff {
pool_id,
loan_id,
status,
});
Ok(())
}
/// Propose a change.
/// The change is not performed until you call
/// [`Pallet::apply_loan_mutation()`].
#[pallet::weight(T::WeightInfo::propose_loan_mutation(T::MaxActiveLoansPerPool::get()))]
#[pallet::call_index(5)]
pub fn propose_loan_mutation(
origin: OriginFor<T>,
pool_id: T::PoolId,
loan_id: T::LoanId,
mutation: LoanMutation<T::Rate>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::ensure_role(pool_id, &who, PoolRole::LoanAdmin)?;
let (mut loan, _count) = Self::get_active_loan(pool_id, loan_id)?;
transactional::with_transaction(|| {
let result = loan.mutate_with(mutation.clone());
// We do not want to apply the mutation,
// only check if there is no error in applying it
TransactionOutcome::Rollback(result)
})?;
T::ChangeGuard::note(pool_id, Change::Loan(loan_id, mutation).into())?;
Ok(())
}
/// Apply a proposed change identified by a change id.
/// It will only perform the change if the requirements for it
/// are fulfilled.
#[pallet::weight(T::WeightInfo::apply_loan_mutation(T::MaxActiveLoansPerPool::get()))]
#[pallet::call_index(6)]
pub fn apply_loan_mutation(
origin: OriginFor<T>,
pool_id: T::PoolId,
change_id: T::Hash,
) -> DispatchResult {
ensure_signed(origin)?;
let Change::Loan(loan_id, mutation) = Self::get_released_change(pool_id, change_id)?
else {
Err(Error::<T>::UnrelatedChangeId)?
};
let (_, _count) = Self::update_active_loan(pool_id, loan_id, |loan| {
loan.mutate_with(mutation.clone())
})?;
Self::deposit_event(Event::<T>::Mutated {
pool_id,
loan_id,
mutation,
});
Ok(())
}
/// Closes a given loan
///
/// A loan only can be closed if it's fully repaid by the loan borrower.
/// Closing a loan gives back the collateral used for the loan to the
/// borrower .
#[pallet::weight(T::WeightInfo::close(T::MaxActiveLoansPerPool::get()))]
#[pallet::call_index(7)]
pub fn close(
origin: OriginFor<T>,
pool_id: T::PoolId,
loan_id: T::LoanId,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let ((closed_loan, borrower), _count) = match CreatedLoan::<T>::take(pool_id, loan_id) {
Some(created_loan) => (created_loan.close()?, Zero::zero()),
None => {
let (active_loan, count) = Self::take_active_loan(pool_id, loan_id)?;
(active_loan.close(pool_id)?, count)
}
};
Self::ensure_loan_borrower(&who, &borrower)?;
let collateral = closed_loan.collateral();
T::NonFungible::transfer(&collateral.0, &collateral.1, &who)?;
ClosedLoan::<T>::insert(pool_id, loan_id, closed_loan);
Self::deposit_event(Event::<T>::Closed {
pool_id,
loan_id,
collateral,
});
Ok(())
}
/// Updates the write off policy with write off rules.
///
/// The write off policy is used to automatically set a write off
/// minimum value to the loan.
#[pallet::weight(T::WeightInfo::propose_write_off_policy())]
#[pallet::call_index(8)]
pub fn propose_write_off_policy(
origin: OriginFor<T>,
pool_id: T::PoolId,
policy: BoundedVec<WriteOffRule<T::Rate>, T::MaxWriteOffPolicySize>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
Self::ensure_role(pool_id, &who, PoolRole::PoolAdmin)?;
Self::ensure_pool_exists(pool_id)?;
T::ChangeGuard::note(pool_id, Change::Policy(policy).into())?;
Ok(())
}
/// Apply a proposed change identified by a change id.
/// It will only perform the change if the requirements for it
/// are fulfilled.
#[pallet::weight(T::WeightInfo::apply_write_off_policy())]
#[pallet::call_index(9)]
pub fn apply_write_off_policy(
origin: OriginFor<T>,
pool_id: T::PoolId,
change_id: T::Hash,
) -> DispatchResult {
ensure_signed(origin)?;
let Change::Policy(policy) = Self::get_released_change(pool_id, change_id)? else {
Err(Error::<T>::UnrelatedChangeId)?
};
Self::update_write_off_policy(pool_id, policy)?;
Ok(())
}
/// Updates the porfolio valuation for the given pool
#[pallet::weight(T::WeightInfo::update_portfolio_valuation(
T::MaxActiveLoansPerPool::get()
))]
#[pallet::call_index(10)]
pub fn update_portfolio_valuation(
origin: OriginFor<T>,
pool_id: T::PoolId,
) -> DispatchResultWithPostInfo {
ensure_signed(origin)?;
Self::ensure_pool_exists(pool_id)?;
let (_, count) = Self::update_portfolio_valuation_for_pool(
pool_id,
PriceCollectionInput::FromRegistry,
)?;
Ok(Some(T::WeightInfo::update_portfolio_valuation(count)).into())
}
/// Transfer debt from one loan to another loan,
/// repaying from the first loan and borrowing the same amount from the
/// second loan. `from_loan_id` is the loan used to repay.
/// `to_loan_id` is the loan used to borrow.
/// The repaid and borrow amount must match.
#[pallet::weight(T::WeightInfo::propose_transfer_debt(T::MaxActiveLoansPerPool::get()))]
#[pallet::call_index(11)]
pub fn propose_transfer_debt(
origin: OriginFor<T>,
pool_id: T::PoolId,
from_loan_id: T::LoanId,
to_loan_id: T::LoanId,
repaid_amount: RepaidInput<T>,
borrow_amount: PrincipalInput<T>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
transactional::with_transaction(|| {
let result = Self::transfer_debt_action(
&who,
pool_id,
from_loan_id,
to_loan_id,
repaid_amount.clone(),
borrow_amount.clone(),
false,
);
// We do not want to apply the mutation,
// only check if there is no error in applying it
TransactionOutcome::Rollback(result)
})?;
T::ChangeGuard::note(
pool_id,
Change::TransferDebt(from_loan_id, to_loan_id, repaid_amount, borrow_amount).into(),
)?;
Ok(())
}
/// Transfer debt from one loan to another loan,
/// repaying from the first loan and borrowing the same amount from the
/// second loan. `from_loan_id` is the loan used to repay.
/// `to_loan_id` is the loan used to borrow.
/// The repaid and borrow amount must match.
#[pallet::weight(T::WeightInfo::apply_transfer_debt(T::MaxActiveLoansPerPool::get()))]
#[pallet::call_index(12)]
pub fn apply_transfer_debt(
origin: OriginFor<T>,
pool_id: T::PoolId,
change_id: T::Hash,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let Change::TransferDebt(from_loan_id, to_loan_id, repaid_amount, borrow_amount) =
Self::get_released_change(pool_id, change_id)?
else {
Err(Error::<T>::UnrelatedChangeId)?
};
let (_, _count) = Self::transfer_debt_action(
&who,
pool_id,
from_loan_id,
to_loan_id,
repaid_amount.clone(),
borrow_amount.clone(),
true,
)?;
Self::deposit_event(Event::<T>::DebtTransferred {
pool_id,
from_loan_id,
to_loan_id,
repaid_amount,
borrow_amount,
});
Ok(())
}
/// Increase debt for a loan. Similar to [`Pallet::borrow()`] but
/// without transferring from the pool.
///
/// The origin must be the borrower of the loan.
/// The increase debt action should fulfill the borrow restrictions
/// configured at [`types::LoanRestrictions`]. The portfolio valuation
/// of the pool is updated to reflect the new present value of the loan.
#[pallet::weight(T::WeightInfo::increase_debt(T::MaxActiveLoansPerPool::get()))]
#[pallet::call_index(13)]
pub fn increase_debt(
origin: OriginFor<T>,
pool_id: T::PoolId,
loan_id: T::LoanId,
amount: PrincipalInput<T>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let _count = Self::borrow_action(&who, pool_id, loan_id, &amount, false)?;
Self::deposit_event(Event::<T>::DebtIncreased {
pool_id,
loan_id,
amount,
});
Ok(())
}
}
// Loan actions
impl<T: Config> Pallet<T> {
fn borrow_action(
who: &T::AccountId,
pool_id: T::PoolId,
loan_id: T::LoanId,
amount: &PrincipalInput<T>,
permissionless: bool,
) -> Result<u32, DispatchError> {
Ok(match CreatedLoan::<T>::take(pool_id, loan_id) {
Some(created_loan) => {
if !permissionless {
Self::ensure_loan_borrower(who, created_loan.borrower())?;
}
let mut active_loan = created_loan.activate(pool_id, amount.clone())?;
active_loan.borrow(amount, pool_id)?;
Self::insert_active_loan(pool_id, loan_id, active_loan)?
}
None => {
Self::update_active_loan(pool_id, loan_id, |loan| {
if !permissionless {
Self::ensure_loan_borrower(who, loan.borrower())?;
}
loan.borrow(amount, pool_id)
})?
.1
}
})
}
fn repay_action(
who: &T::AccountId,
pool_id: T::PoolId,
loan_id: T::LoanId,
amount: &RepaidInput<T>,
permissionless: bool,
) -> Result<(RepaidInput<T>, u32), DispatchError> {
Self::update_active_loan(pool_id, loan_id, |loan| {
if !permissionless {
Self::ensure_loan_borrower(who, loan.borrower())?;
}
loan.repay(amount.clone(), pool_id)
})
}
fn transfer_debt_action(
who: &T::AccountId,
pool_id: T::PoolId,
from_loan_id: T::LoanId,
to_loan_id: T::LoanId,
repaid_amount: RepaidInput<T>,
borrow_amount: PrincipalInput<T>,
permissionless: bool,
) -> Result<(T::Balance, u32), DispatchError> {
ensure!(
from_loan_id != to_loan_id,
Error::<T>::TransferDebtToSameLoan
);
let repaid_amount =
Self::repay_action(who, pool_id, from_loan_id, &repaid_amount, permissionless)?.0;
ensure!(
borrow_amount.balance()? == repaid_amount.repaid_amount()?.total()?,
Error::<T>::TransferDebtAmountMismatched
);
let count =
Self::borrow_action(who, pool_id, to_loan_id, &borrow_amount, permissionless)?;
Ok((repaid_amount.repaid_amount()?.total()?, count))
}
/// Set the maturity date of the loan to this instant.
#[cfg(feature = "runtime-benchmarks")]
pub fn expire_action(pool_id: T::PoolId, loan_id: T::LoanId) -> DispatchResult {
Self::update_active_loan(pool_id, loan_id, |loan| {
loan.set_maturity(T::Time::now());
Ok(())
})?;
Ok(())
}
}
/// Utility methods
impl<T: Config> Pallet<T> {
fn ensure_role(pool_id: T::PoolId, who: &T::AccountId, role: PoolRole) -> DispatchResult {
T::Permissions::has(
PermissionScope::Pool(pool_id),
who.clone(),
Role::PoolRole(role),
)
.then_some(())
.ok_or_else(|| BadOrigin.into())
}
fn ensure_collateral_owner(
owner: &T::AccountId,
(collection_id, item_id): AssetOf<T>,
) -> DispatchResult {
T::NonFungible::owner(&collection_id, &item_id)
.ok_or(Error::<T>::NFTOwnerNotFound)?
.eq(owner)
.then_some(())
.ok_or_else(|| Error::<T>::NotNFTOwner.into())