forked from MettaChain/PropChain-contract
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
2759 lines (2499 loc) · 98.5 KB
/
Copy pathlib.rs
File metadata and controls
2759 lines (2499 loc) · 98.5 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
#![cfg_attr(not(feature = "std"), no_std, no_main)]
#![allow(
clippy::arithmetic_side_effects,
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::needless_borrows_for_generic_args
)]
use ink::storage::Mapping;
mod status_packing;
#[ink::contract]
mod propchain_lending {
use ink::prelude::string::String;
use ink::prelude::vec::Vec;
use super::*;
#[derive(Debug, PartialEq, Eq, scale::Encode, scale::Decode)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum LendingError {
Unauthorized,
PropertyNotFound,
InsufficientCollateral,
LoanNotFound,
LoanNotActive,
PoolNotFound,
InsufficientLiquidity,
PositionNotFound,
LiquidationThresholdNotMet,
InvalidParameters,
ProposalNotFound,
RestructuringNotFound,
InsufficientVotes,
ServicerNotFound,
PaymentScheduleNotFound,
ReentrantCall,
// Admin key rotation (Issue #496)
KeyRotationCooldown,
KeyRotationExpired,
NoPendingRotation,
RotationUnauthorized,
RequestExpired,
}
impl From<propchain_traits::ReentrancyError> for LendingError {
fn from(_: propchain_traits::ReentrancyError) -> Self {
LendingError::ReentrantCall
}
}
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct CollateralRecord {
pub property_id: u64,
pub assessed_value: u128,
pub ltv_ratio: u32,
pub liquidation_threshold: u32,
}
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct LendingPool {
pub pool_id: u64,
pub total_deposits: u128,
pub total_borrows: u128,
pub base_rate: u32,
}
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct MarginPosition {
pub position_id: u64,
pub owner: AccountId,
pub collateral: u128,
pub leverage: u32,
pub is_short: bool,
pub entry_price: u128,
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
scale::Encode,
scale::Decode,
ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum LoanStatus {
Pending,
Active,
Repaid,
Defaulted,
RestructuringProposed,
Restructured,
Liquidated,
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
scale::Encode,
scale::Decode,
ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum CollateralKind {
Unsecured,
PropertyTokenized,
}
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
scale::Encode,
scale::Decode,
ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum LoanType {
Variable,
FixedRate,
}
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct LoanApplication {
pub loan_id: u64,
pub applicant: AccountId,
pub property_id: u64,
pub requested_amount: u128,
pub collateral_value: u128,
pub credit_score: u32,
pub approved: bool,
pub servicer_id: Option<u64>,
pub servicing_reference: String,
pub servicing_status: String,
pub collateral_kind: CollateralKind,
pub term_months: u32,
pub interest_rate_bps: u32,
pub loan_type: LoanType,
pub start_block: Option<u64>,
pub status: LoanStatus,
pub accrued_interest: u128,
pub last_interest_timestamp: u64,
}
/// SCALE-footprint-compact representation of `LoanApplication` (Issue #738).
///
/// `bool approved`, the two `String` fields, and the two `Option<u64>`
/// fields are folded into a single `u32 status_flags` plus packed payload
/// fields. The two enum-valued fields `LoanType` and `CollateralKind`
/// collapse to single bytes. The two `String`s become `Vec<u8>`, which
/// has the same SCALE width as `String` (compact-length prefix + bytes)
/// but is a no_std-friendly representation that does not require UTF-8
/// validity enforcement on round-trip.
#[derive(scale::Encode, scale::Decode)]
#[cfg_attr(
feature = "std",
derive(scale_info::TypeInfo, Debug, Clone, PartialEq, Eq)
)]
pub struct PackedLoanApplication {
pub loan_id: u64,
pub applicant: AccountId,
pub property_id: u64,
pub requested_amount: u128,
pub collateral_value: u128,
pub credit_score: u32,
pub accrued_interest: u128,
pub last_interest_timestamp: u64,
pub term_months: u32,
pub interest_rate_bps: u32,
pub status_flags: u32,
pub servicer_id_packed: u64,
pub start_block_packed: u64,
pub status_tag: u8,
pub servicing_reference: Vec<u8>,
pub servicing_status: Vec<u8>,
}
impl From<LoanApplication> for PackedLoanApplication {
fn from(src: LoanApplication) -> Self {
use super::status_packing::*;
let mut flags: u32 = 0;
if src.approved {
flags |= FLAG_APPROVED;
}
if src.servicer_id.is_some() {
flags |= FLAG_HAS_SERVICER_ID;
}
if src.start_block.is_some() {
flags |= FLAG_HAS_START_BLOCK;
}
if matches!(src.loan_type, LoanType::FixedRate) {
flags |= FLAG_LOAN_TYPE_FIXED_RATE;
}
if matches!(src.collateral_kind, CollateralKind::PropertyTokenized) {
flags |= FLAG_COLLATERAL_PROPERTY_TOKENIZED;
}
let status_tag = match src.status {
LoanStatus::Pending => STATUS_PENDING,
LoanStatus::Active => STATUS_ACTIVE,
LoanStatus::Repaid => STATUS_REPAID,
LoanStatus::Defaulted => STATUS_DEFAULTED,
LoanStatus::RestructuringProposed => STATUS_RESTRUCTURING_PROPOSED,
LoanStatus::Restructured => STATUS_RESTRUCTURED,
LoanStatus::Liquidated => STATUS_LIQUIDATED,
};
PackedLoanApplication {
loan_id: src.loan_id,
applicant: src.applicant,
property_id: src.property_id,
requested_amount: src.requested_amount,
collateral_value: src.collateral_value,
credit_score: src.credit_score,
accrued_interest: src.accrued_interest,
last_interest_timestamp: src.last_interest_timestamp,
term_months: src.term_months,
interest_rate_bps: src.interest_rate_bps,
status_flags: flags,
servicer_id_packed: src.servicer_id.unwrap_or(0),
start_block_packed: src.start_block.unwrap_or(0),
status_tag,
servicing_reference: src.servicing_reference.into_bytes(),
servicing_status: src.servicing_status.into_bytes(),
}
}
}
impl From<PackedLoanApplication> for LoanApplication {
fn from(src: PackedLoanApplication) -> Self {
use super::status_packing::*;
LoanApplication {
loan_id: src.loan_id,
applicant: src.applicant,
property_id: src.property_id,
requested_amount: src.requested_amount,
collateral_value: src.collateral_value,
credit_score: src.credit_score,
approved: (src.status_flags & FLAG_APPROVED) != 0,
servicer_id: if (src.status_flags & FLAG_HAS_SERVICER_ID) != 0 {
Some(src.servicer_id_packed)
} else {
None
},
servicing_reference: String::from_utf8(src.servicing_reference).unwrap_or_default(),
servicing_status: String::from_utf8(src.servicing_status).unwrap_or_default(),
collateral_kind: if (src.status_flags & FLAG_COLLATERAL_PROPERTY_TOKENIZED) != 0 {
CollateralKind::PropertyTokenized
} else {
CollateralKind::Unsecured
},
term_months: src.term_months,
interest_rate_bps: src.interest_rate_bps,
loan_type: if (src.status_flags & FLAG_LOAN_TYPE_FIXED_RATE) != 0 {
LoanType::FixedRate
} else {
LoanType::Variable
},
start_block: if (src.status_flags & FLAG_HAS_START_BLOCK) != 0 {
Some(src.start_block_packed)
} else {
None
},
status: match src.status_tag {
STATUS_PENDING => LoanStatus::Pending,
STATUS_ACTIVE => LoanStatus::Active,
STATUS_REPAID => LoanStatus::Repaid,
STATUS_DEFAULTED => LoanStatus::Defaulted,
STATUS_RESTRUCTURING_PROPOSED => LoanStatus::RestructuringProposed,
STATUS_RESTRUCTURED => LoanStatus::Restructured,
_ => LoanStatus::Liquidated,
},
accrued_interest: src.accrued_interest,
last_interest_timestamp: src.last_interest_timestamp,
}
}
}
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct LoanServicer {
pub servicer_id: u64,
pub account: AccountId,
pub name: String,
pub active: bool,
pub collateral_kind: CollateralKind,
pub term_months: u32,
pub interest_rate_bps: u32,
pub status: LoanStatus,
pub loan_type: LoanType,
pub start_block: Option<u64>,
}
// ── #829: Variable amortization schedules ────────────────────────────────
/// The repayment schedule type for a loan.
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
scale::Encode,
scale::Decode,
ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum Schedule {
/// Single lump-sum repayment at maturity (principal + all interest).
Bullet,
/// Equal total payments each period (principal portion grows over time).
Annuity,
/// Equal principal payments each period (descending total outlay).
Linear,
/// User-defined custom schedule parameters.
Custom {
/// Custom number of installments.
num_installments: u32,
/// Custom interval between payments (blocks).
interval_blocks: u64,
/// Custom principal per installment (0 = computed from total).
principal_per_payment: u128,
},
}
impl Schedule {
/// Compute the per-period installment amount given total principal,
/// interest rate (bps), term months, and blocks per period.
pub fn installment(
&self,
principal: u128,
rate_bps: u32,
term_months: u32,
interval_blocks: u64,
) -> u128 {
match self {
Schedule::Bullet => principal, // full principal at end
Schedule::Annuity => {
// Simplified annuity: equal total payments each period.
// per_period_rate = rate_bps * interval_blocks / (5_256_000 * 10_000)
let n = (term_months as u64 * 432_000u64)
.checked_div(interval_blocks.max(1))
.unwrap_or(1) as u128;
if n == 0 {
return principal;
}
let per_period_rate_numer =
(rate_bps as u128).saturating_mul(interval_blocks as u128);
let per_period_rate_denom = 52_560_000_000u128; // 5_256_000 * 10_000
let interest = principal
.saturating_mul(per_period_rate_numer)
.checked_div(per_period_rate_denom)
.unwrap_or(0);
let base = principal / n;
base.saturating_add(interest)
}
Schedule::Linear => {
let n = (term_months as u64 * 432_000u64)
.checked_div(interval_blocks.max(1))
.unwrap_or(1) as u128;
if n == 0 {
return principal;
}
// Equal principal + declining interest
let per_period_principal = principal / n;
let per_period_rate_numer =
(rate_bps as u128).saturating_mul(interval_blocks as u128);
let per_period_rate_denom = 52_560_000_000u128; // 5_256_000 * 10_000
let interest_first = principal
.saturating_mul(per_period_rate_numer)
.checked_div(per_period_rate_denom)
.unwrap_or(0);
per_period_principal.saturating_add(interest_first)
}
Schedule::Custom {
principal_per_payment,
..
} => {
if *principal_per_payment > 0 {
*principal_per_payment
} else {
let n = (term_months as u64 * 432_000u64)
.checked_div(interval_blocks.max(1))
.unwrap_or(1) as u128;
principal.checked_div(n).unwrap_or(principal)
}
}
}
}
}
#[derive(
Debug,
Clone,
PartialEq,
Eq,
scale::Encode,
scale::Decode,
ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum PaymentScheduleStatus {
Active,
Completed,
Defaulted,
}
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct PaymentSchedule {
pub schedule_id: u64,
pub loan_id: u64,
pub borrower: AccountId,
pub schedule_type: Schedule,
pub principal_due: u128,
pub interest_due: u128,
pub installment_amount: u128,
pub total_installments: u32,
pub installments_paid: u32,
pub first_due_block: u64,
pub interval_blocks: u64,
pub next_due_block: u64,
pub total_paid: u128,
pub status: PaymentScheduleStatus,
}
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct LoanRestructuring {
pub loan_id: u64,
pub proposed_by: AccountId,
pub proposed_term_months: u32,
pub proposed_interest_rate_bps: u32,
pub borrower_approved: bool,
pub lender_approved: bool,
}
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct YieldPosition {
pub owner: AccountId,
pub staked: u128,
pub reward_debt: u128,
pub accumulated_rewards: u128,
}
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct Proposal {
pub proposal_id: u64,
pub description: String,
pub votes_for: u64,
pub votes_against: u64,
pub executed: bool,
}
/// On-chain credit history for a borrower.
///
/// Score formula (0–1000):
/// base 500
/// + repayments_on_time * 20 (capped at +300)
/// - defaults * 150 (capped at -450)
/// - active_loans * 10 (capped at -100)
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct CreditProfile {
pub repayments_on_time: u32,
pub defaults: u32,
pub active_loans: u32,
pub total_borrowed: u128,
}
// ── #304: Loan Marketplace types ─────────────────────────────────────────
/// Status of a loan marketplace listing.
#[derive(
Debug,
Clone,
Copy,
PartialEq,
Eq,
scale::Encode,
scale::Decode,
ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub enum ListingStatus {
/// Awaiting bids from lenders.
Open,
/// An offer has been accepted; origination in progress.
OfferAccepted,
/// Loan originated successfully.
Originated,
/// Listing withdrawn by the borrower.
Cancelled,
}
pub type TokenId = u64;
/// A borrower's public loan request listed on the marketplace (#304).
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct LoanListing {
pub listing_id: u64,
pub borrower: AccountId,
pub property_id: u64,
pub requested_amount: u128,
/// Maximum interest rate the borrower is willing to pay (basis points).
pub max_rate_bps: u32,
pub term_months: u32,
pub collateral_kind: CollateralKind,
/// Multi-token collateral basket: (token_id, amount) pairs (#827).
pub collateral_basket: Vec<(TokenId, u128)>,
pub status: ListingStatus,
pub created_at: u64,
/// ID of the accepted offer, if any.
pub accepted_offer_id: Option<u64>,
}
/// A lender's counter-offer in response to a marketplace listing (#304).
#[derive(
Debug, Clone, PartialEq, scale::Encode, scale::Decode, ink::storage::traits::StorageLayout,
)]
#[cfg_attr(feature = "std", derive(scale_info::TypeInfo))]
pub struct LoanOffer {
pub offer_id: u64,
pub listing_id: u64,
pub lender: AccountId,
pub offered_amount: u128,
/// Interest rate offered by the lender (basis points).
pub rate_bps: u32,
pub term_months: u32,
pub is_accepted: bool,
pub created_at: u64,
}
#[ink(storage)]
pub struct PropertyLending {
admin: AccountId,
collateral_records: Mapping<u64, CollateralRecord>,
pools: Mapping<u64, LendingPool>,
pool_count: u64,
margin_positions: Mapping<u64, MarginPosition>,
position_count: u64,
loan_applications: Mapping<u64, LoanApplication>,
borrower_loans: Mapping<AccountId, Vec<u64>>,
loan_restructurings: Mapping<u64, LoanRestructuring>,
loan_count: u64,
loan_servicers: Mapping<u64, LoanServicer>,
servicer_count: u64,
payment_schedules: Mapping<u64, PaymentSchedule>,
loan_payment_schedule: Mapping<u64, u64>,
schedule_count: u64,
yield_positions: Mapping<AccountId, YieldPosition>,
total_staked: u128,
reward_per_block: u128,
proposals: Mapping<u64, Proposal>,
proposal_count: u64,
credit_profiles: Mapping<AccountId, CreditProfile>,
reentrancy_guard: propchain_traits::ReentrancyGuard,
// #304: Loan Marketplace
marketplace_listings: Mapping<u64, LoanListing>,
marketplace_offers: Mapping<u64, LoanOffer>,
listing_count: u64,
offer_count: u64,
// #588: Multi-collateral portfolio mapping loan_id -> property_ids
pub loan_collaterals: Mapping<u64, Vec<u64>>,
// Admin Key Rotation (Issue #496)
pending_admin_rotation: Option<propchain_traits::KeyRotationRequest>,
}
#[ink(event)]
pub struct CollateralAssessed {
#[ink(topic)]
property_id: u64,
assessed_value: u128,
ltv_ratio: u32,
}
#[ink(event)]
pub struct PoolCreated {
#[ink(topic)]
pool_id: u64,
base_rate: u32,
}
#[ink(event)]
pub struct PositionOpened {
#[ink(topic)]
position_id: u64,
#[ink(topic)]
owner: AccountId,
collateral: u128,
}
#[ink(event)]
pub struct LoanApproved {
#[ink(topic)]
loan_id: u64,
#[ink(topic)]
applicant: AccountId,
amount: u128,
}
#[ink(event)]
pub struct LoanServicerRegistered {
#[ink(topic)]
servicer_id: u64,
#[ink(topic)]
account: AccountId,
name: String,
}
#[ink(event)]
pub struct LoanServicerAssigned {
#[ink(topic)]
loan_id: u64,
#[ink(topic)]
servicer_id: u64,
external_reference: String,
}
#[ink(event)]
pub struct LoanServicingStatusUpdated {
#[ink(topic)]
loan_id: u64,
status: String,
}
#[ink(event)]
pub struct LoanRestructuringProposed {
#[ink(topic)]
loan_id: u64,
#[ink(topic)]
proposer: AccountId,
new_term_months: u32,
new_interest_rate_bps: u32,
}
#[ink(event)]
pub struct LoanRestructured {
#[ink(topic)]
loan_id: u64,
new_term_months: u32,
new_interest_rate_bps: u32,
}
#[ink(event)]
pub struct LoanLiquidated {
#[ink(topic)]
loan_id: u64,
#[ink(topic)]
borrower: AccountId,
collateral_seized: u128,
}
#[ink(event)]
pub struct ProposalCreated {
#[ink(topic)]
proposal_id: u64,
description: String,
}
// ── #304: Loan Marketplace events ────────────────────────────────────────
#[ink(event)]
pub struct LoanListingCreated {
#[ink(topic)]
pub listing_id: u64,
#[ink(topic)]
pub borrower: AccountId,
pub requested_amount: u128,
pub max_rate_bps: u32,
}
#[ink(event)]
pub struct LoanOfferSubmitted {
#[ink(topic)]
pub offer_id: u64,
#[ink(topic)]
pub listing_id: u64,
#[ink(topic)]
pub lender: AccountId,
pub rate_bps: u32,
}
#[ink(event)]
pub struct LoanOfferAccepted {
#[ink(topic)]
pub listing_id: u64,
#[ink(topic)]
pub offer_id: u64,
pub loan_id: u64,
}
#[ink(event)]
pub struct LoanListingCancelled {
#[ink(topic)]
pub listing_id: u64,
#[ink(topic)]
pub borrower: AccountId,
}
// ── Admin Key Rotation Events (Issue #496) ────────────────────────────────
#[ink(event)]
pub struct AdminRotationRequested {
#[ink(topic)]
old_admin: AccountId,
#[ink(topic)]
new_admin: AccountId,
effective_at_block: u32,
}
#[ink(event)]
pub struct AdminRotationConfirmed {
#[ink(topic)]
old_admin: AccountId,
#[ink(topic)]
new_admin: AccountId,
}
#[ink(event)]
pub struct AdminRotationCancelled {
#[ink(topic)]
old_admin: AccountId,
cancelled_by: AccountId,
}
impl PropertyLending {
#[ink(constructor)]
pub fn new(admin: AccountId) -> Self {
Self {
admin,
collateral_records: Mapping::default(),
pools: Mapping::default(),
pool_count: 0,
margin_positions: Mapping::default(),
position_count: 0,
loan_applications: Mapping::default(),
borrower_loans: Mapping::default(),
loan_restructurings: Mapping::default(),
loan_count: 0,
loan_servicers: Mapping::default(),
servicer_count: 0,
payment_schedules: Mapping::default(),
loan_payment_schedule: Mapping::default(),
schedule_count: 0,
yield_positions: Mapping::default(),
total_staked: 0,
reward_per_block: 100,
proposals: Mapping::default(),
proposal_count: 0,
credit_profiles: Mapping::default(),
reentrancy_guard: propchain_traits::ReentrancyGuard::new(),
// #304: Loan Marketplace
marketplace_listings: Mapping::default(),
marketplace_offers: Mapping::default(),
listing_count: 0,
offer_count: 0,
loan_collaterals: Mapping::default(),
// Admin Key Rotation (Issue #496)
pending_admin_rotation: None,
}
}
#[ink(message)]
pub fn assess_collateral(
&mut self,
property_id: u64,
value: u128,
ltv: u32,
liq_threshold: u32,
) -> Result<(), LendingError> {
if self.env().caller() != self.admin {
return Err(LendingError::Unauthorized);
}
let record = CollateralRecord {
property_id,
assessed_value: value,
ltv_ratio: ltv,
liquidation_threshold: liq_threshold,
};
self.collateral_records.insert(property_id, &record);
self.env().emit_event(CollateralAssessed {
property_id,
assessed_value: value,
ltv_ratio: ltv,
});
Ok(())
}
#[ink(message)]
pub fn should_liquidate(&self, property_id: u64, current_value: u128) -> bool {
if let Some(r) = self.collateral_records.get(property_id) {
let ratio = (r.assessed_value * 10000) / current_value.max(1);
ratio > r.liquidation_threshold as u128
} else {
false
}
}
#[ink(message)]
pub fn should_liquidate_loan(
&self,
loan_id: u64,
current_collateral_values: Vec<(u64, u128)>,
) -> Result<bool, LendingError> {
let app = self
.loan_applications
.get(loan_id)
.ok_or(LendingError::LoanNotFound)?;
if app.status != LoanStatus::Active {
return Ok(false);
}
let collaterals = self.loan_collaterals.get(loan_id).unwrap_or_default();
if collaterals.is_empty() {
if let Some(record) = self.collateral_records.get(app.property_id) {
let current = current_collateral_values
.iter()
.find(|(id, _)| *id == app.property_id)
.map(|(_, v)| *v)
.unwrap_or(record.assessed_value);
let ratio = (record.assessed_value * 10000) / current.max(1);
return Ok(ratio > record.liquidation_threshold as u128);
}
return Ok(false);
}
let total_debt = app.requested_amount.saturating_add(app.accrued_interest);
let mut total_current_value: u128 = 0;
let mut weighted_threshold_sum: u128 = 0;
let mut total_assessed: u128 = 0;
for &pid in &collaterals {
let record = self
.collateral_records
.get(pid)
.ok_or(LendingError::PropertyNotFound)?;
total_assessed = total_assessed.saturating_add(record.assessed_value);
weighted_threshold_sum = weighted_threshold_sum.saturating_add(
record
.assessed_value
.saturating_mul(record.liquidation_threshold as u128),
);
let current_val = current_collateral_values
.iter()
.find(|(id, _)| *id == pid)
.map(|(_, v)| *v)
.unwrap_or(record.assessed_value);
total_current_value = total_current_value.saturating_add(current_val);
}
let effective_threshold = weighted_threshold_sum
.checked_div(total_assessed)
.unwrap_or(0);
let current_ltv = (total_debt * 10000) / total_current_value.max(1);
Ok(current_ltv > effective_threshold)
}
#[ink(message)]
pub fn create_pool(&mut self, base_rate: u32) -> Result<u64, LendingError> {
if self.env().caller() != self.admin {
return Err(LendingError::Unauthorized);
}
self.pool_count += 1;
let pool = LendingPool {
pool_id: self.pool_count,
total_deposits: 0,
total_borrows: 0,
base_rate,
};
self.pools.insert(self.pool_count, &pool);
self.env().emit_event(PoolCreated {
pool_id: self.pool_count,
base_rate,
});
Ok(self.pool_count)
}
#[ink(message)]
pub fn deposit(&mut self, pool_id: u64, amount: u128) -> Result<(), LendingError> {
propchain_traits::non_reentrant!(self, {
let mut pool = self.pools.get(pool_id).ok_or(LendingError::PoolNotFound)?;
pool.total_deposits += amount;
self.pools.insert(pool_id, &pool);
Ok(())
})
}
#[ink(message)]
pub fn borrow(&mut self, pool_id: u64, amount: u128) -> Result<(), LendingError> {
propchain_traits::non_reentrant!(self, {
let mut pool = self.pools.get(pool_id).ok_or(LendingError::PoolNotFound)?;
if pool.total_deposits < pool.total_borrows + amount {
return Err(LendingError::InsufficientLiquidity);
}
pool.total_borrows += amount;
self.pools.insert(pool_id, &pool);
Ok(())
})
}
#[ink(message)]
pub fn borrow_rate(&self, pool_id: u64) -> Result<u32, LendingError> {
let pool = self.pools.get(pool_id).ok_or(LendingError::PoolNotFound)?;
let utilisation = (pool.total_borrows * 10000)
.checked_div(pool.total_deposits)
.unwrap_or(0);
Ok(pool.base_rate + (utilisation / 50) as u32)
}
#[ink(message)]
pub fn open_position(
&mut self,
collateral: u128,
leverage: u32,
short: bool,
price: u128,
) -> Result<u64, LendingError> {
self.position_count += 1;
let pos = MarginPosition {
position_id: self.position_count,
owner: self.env().caller(),
collateral,
leverage,
is_short: short,
entry_price: price,
};
self.margin_positions.insert(self.position_count, &pos);
self.env().emit_event(PositionOpened {
position_id: self.position_count,
owner: self.env().caller(),
collateral,
});
Ok(self.position_count)
}
#[ink(message)]
pub fn position_pnl(
&self,
position_id: u64,
current_price: u128,
) -> Result<i128, LendingError> {
let pos = self
.margin_positions
.get(position_id)
.ok_or(LendingError::PositionNotFound)?;
let delta = current_price as i128 - pos.entry_price as i128;
let signed = if pos.is_short { -delta } else { delta };
Ok((signed * pos.leverage as i128) / 100)
}
#[ink(message)]
pub fn apply_for_loan(
&mut self,
property_id: u64,
requested_amount: u128,
collateral_value: u128,
credit_score: u32,
) -> Result<u64, LendingError> {
self.apply_for_loan_with_terms(
property_id,
requested_amount,
collateral_value,
credit_score,