forked from QuickLendX/quicklendx-protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathverification.rs
More file actions
1968 lines (1731 loc) · 71 KB
/
Copy pathverification.rs
File metadata and controls
1968 lines (1731 loc) · 71 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
use crate::bid::BidStorage;
use crate::errors::QuickLendXError;
use crate::protocol_limits::{
check_string_length, ProtocolLimitsContract, MAX_ADDRESS_LENGTH, MAX_DESCRIPTION_LENGTH,
MAX_DISPUTE_EVIDENCE_LENGTH, MAX_DISPUTE_REASON_LENGTH, MAX_DISPUTE_RESOLUTION_LENGTH,
MAX_KYC_DATA_LENGTH, MAX_NAME_LENGTH, MAX_NOTES_LENGTH, MAX_REJECTION_REASON_LENGTH,
MAX_TAG_LENGTH, MAX_TAX_ID_LENGTH,
};
use crate::types::BidStatus;
use crate::types::{DisputeStatus, Invoice, InvoiceMetadata, InvoiceStatus};
use soroban_sdk::{contracttype, symbol_short, vec, Address, Bytes, Env, String, Vec};
/// Maximum normalized tags allowed on an invoice.
pub const MAX_INVOICE_TAG_COUNT: u32 = 10;
/// Maximum line items allowed in structured invoice metadata.
pub const MAX_METADATA_LINE_ITEMS: u32 = 100;
#[contracttype]
#[derive(Clone, Eq, PartialEq)]
#[cfg_attr(test, derive(Debug))]
pub enum BusinessVerificationStatus {
Pending,
Verified,
Rejected,
}
#[contracttype]
pub struct BusinessVerification {
pub business: Address,
pub status: BusinessVerificationStatus,
pub verified_at: Option<u64>,
pub verified_by: Option<Address>,
pub kyc_data: String, // Encrypted KYC data
pub submitted_at: u64,
pub rejection_reason: Option<String>,
}
#[contracttype]
#[derive(Clone, PartialEq, Debug, PartialOrd, Ord)]
pub enum InvestorTier {
Basic,
Silver,
Gold,
Platinum,
VIP,
}
#[contracttype]
#[derive(Clone, PartialEq, Debug)]
pub enum InvestorRiskLevel {
Low,
Medium,
High,
VeryHigh,
}
#[contracttype]
pub struct InvestorVerification {
pub investor: Address,
pub status: BusinessVerificationStatus,
pub verified_at: Option<u64>,
pub verified_by: Option<Address>,
pub kyc_data: String,
pub investment_limit: i128,
pub submitted_at: u64,
pub tier: InvestorTier,
pub risk_level: InvestorRiskLevel,
pub risk_score: u32,
pub total_invested: i128,
pub total_returns: i128,
pub successful_investments: u32,
pub defaulted_investments: u32,
pub last_activity: u64,
pub rejection_reason: Option<String>,
pub compliance_notes: Option<String>,
}
pub fn validate_risk_score(score: u32) -> Result<(), QuickLendXError> {
if score > 100 {
return Err(QuickLendXError::InvalidAmount);
}
Ok(())
}
pub struct BusinessVerificationStorage;
impl BusinessVerificationStorage {
const VERIFIED_BUSINESSES_KEY: &'static str = "verified_businesses";
const PENDING_BUSINESSES_KEY: &'static str = "pending_businesses";
const REJECTED_BUSINESSES_KEY: &'static str = "rejected_businesses";
const ADMIN_KEY: &'static str = "admin_address";
const DELETED_BUSINESSES_KEY: &'static str = "deleted_businesses";
/// Validates that a state transition is allowed according to KYC lifecycle rules
///
/// Valid transitions:
/// - None -> Pending (new submission)
/// - Pending -> Verified (admin approval)
/// - Pending -> Rejected (admin rejection)
/// - Rejected -> Pending (resubmission after rejection)
///
/// Invalid transitions:
/// - Verified -> *any other state (verified is final)
/// - Pending -> Pending (duplicate submission)
/// - Rejected -> Rejected (duplicate rejection)
/// - Rejected -> Verified (must go through Pending first)
pub fn validate_state_transition(
old_status: Option<BusinessVerificationStatus>,
new_status: BusinessVerificationStatus,
) -> Result<(), QuickLendXError> {
match (old_status, new_status) {
// New submission (no previous status)
(None, BusinessVerificationStatus::Pending) => Ok(()),
// Pending -> Verified (admin approval)
(Some(BusinessVerificationStatus::Pending), BusinessVerificationStatus::Verified) => {
Ok(())
}
// Pending -> Rejected (admin rejection)
(Some(BusinessVerificationStatus::Pending), BusinessVerificationStatus::Rejected) => {
Ok(())
}
// Rejected -> Pending (resubmission after rejection)
(Some(BusinessVerificationStatus::Rejected), BusinessVerificationStatus::Pending) => {
Ok(())
}
// Invalid transitions
(Some(BusinessVerificationStatus::Verified), _) => {
Err(QuickLendXError::InvalidKYCStatus) // Verified is final
}
(Some(BusinessVerificationStatus::Pending), BusinessVerificationStatus::Pending) => {
Err(QuickLendXError::KYCAlreadyPending) // Duplicate submission
}
(Some(BusinessVerificationStatus::Rejected), BusinessVerificationStatus::Rejected) => {
Err(QuickLendXError::InvalidKYCStatus) // Duplicate rejection
}
(Some(BusinessVerificationStatus::Rejected), BusinessVerificationStatus::Verified) => {
Err(QuickLendXError::InvalidKYCStatus) // Must go through Pending first
}
(None, BusinessVerificationStatus::Verified) => {
Err(QuickLendXError::InvalidKYCStatus) // Cannot be verified without submission
}
(None, BusinessVerificationStatus::Rejected) => {
Err(QuickLendXError::InvalidKYCStatus) // Cannot be rejected without submission
}
}
}
/// Validates that rejection reason is immutable once set
/// Once a business has been rejected with a reason, that reason cannot be changed
pub fn validate_rejection_reason_immutability(
old_verification: &Option<BusinessVerification>,
new_rejection_reason: &Option<String>,
) -> Result<(), QuickLendXError> {
if let Some(old_ver) = old_verification {
// If there was an old rejection reason and a new rejection reason is provided, they must match
if let Some(old_reason) = &old_ver.rejection_reason {
if let Some(new_reason) = new_rejection_reason {
if old_reason != new_reason {
return Err(QuickLendXError::InvalidKYCStatus); // Cannot change rejection reason
}
}
}
}
Ok(())
}
/// Verifies index consistency by checking that a business appears in exactly one status list
pub fn verify_index_consistency(env: &Env, business: &Address) -> Result<(), QuickLendXError> {
let verified = Self::get_verified_businesses(env);
let pending = Self::get_pending_businesses(env);
let rejected = Self::get_rejected_businesses(env);
let in_verified = verified.iter().any(|addr| addr == *business);
let in_pending = pending.iter().any(|addr| addr == *business);
let in_rejected = rejected.iter().any(|addr| addr == *business);
// Business should be in exactly one list
let count = [in_verified, in_pending, in_rejected]
.iter()
.filter(|&&x| x)
.count();
if count != 1 {
return Err(QuickLendXError::InvalidKYCStatus);
}
Ok(())
}
pub fn store_verification(env: &Env, verification: &BusinessVerification) {
env.storage()
.instance()
.set(&verification.business, verification);
// Add to status-specific lists
match verification.status {
BusinessVerificationStatus::Verified => {
Self::add_to_verified_businesses(env, &verification.business);
}
BusinessVerificationStatus::Pending => {
Self::add_to_pending_businesses(env, &verification.business);
}
BusinessVerificationStatus::Rejected => {
Self::add_to_rejected_businesses(env, &verification.business);
}
}
}
pub fn get_verification(env: &Env, business: &Address) -> Option<BusinessVerification> {
env.storage().instance().get(business)
}
pub fn update_verification(
env: &Env,
verification: &BusinessVerification,
) -> Result<(), QuickLendXError> {
let old_verification = Self::get_verification(env, &verification.business);
let old_status = old_verification.as_ref().map(|v| v.status.clone());
// Validate state transition
Self::validate_state_transition(old_status.clone(), verification.status.clone())?;
// Validate rejection reason immutability
Self::validate_rejection_reason_immutability(
&old_verification,
&verification.rejection_reason,
)?;
// Remove from old status list
if let Some(old_ver) = old_verification {
match old_ver.status {
BusinessVerificationStatus::Verified => {
Self::remove_from_verified_businesses(env, &verification.business);
}
BusinessVerificationStatus::Pending => {
Self::remove_from_pending_businesses(env, &verification.business);
}
BusinessVerificationStatus::Rejected => {
Self::remove_from_rejected_businesses(env, &verification.business);
}
}
}
// Store new verification
Self::store_verification(env, verification);
// Verify index consistency after update
Self::verify_index_consistency(env, &verification.business)?;
Ok(())
}
pub fn is_business_verified(env: &Env, business: &Address) -> bool {
if let Some(verification) = Self::get_verification(env, business) {
matches!(verification.status, BusinessVerificationStatus::Verified)
} else {
false
}
}
pub fn get_verified_businesses(env: &Env) -> Vec<Address> {
env.storage()
.instance()
.get(&Self::VERIFIED_BUSINESSES_KEY)
.unwrap_or(vec![env])
}
pub fn get_pending_businesses(env: &Env) -> Vec<Address> {
env.storage()
.instance()
.get(&Self::PENDING_BUSINESSES_KEY)
.unwrap_or(vec![env])
}
pub fn get_rejected_businesses(env: &Env) -> Vec<Address> {
env.storage()
.instance()
.get(&Self::REJECTED_BUSINESSES_KEY)
.unwrap_or(vec![env])
}
fn add_to_verified_businesses(env: &Env, business: &Address) {
let mut verified = Self::get_verified_businesses(env);
verified.push_back(business.clone());
env.storage()
.instance()
.set(&Self::VERIFIED_BUSINESSES_KEY, &verified);
}
fn add_to_pending_businesses(env: &Env, business: &Address) {
let mut pending = Self::get_pending_businesses(env);
pending.push_back(business.clone());
env.storage()
.instance()
.set(&Self::PENDING_BUSINESSES_KEY, &pending);
}
fn add_to_rejected_businesses(env: &Env, business: &Address) {
let mut rejected = Self::get_rejected_businesses(env);
rejected.push_back(business.clone());
env.storage()
.instance()
.set(&Self::REJECTED_BUSINESSES_KEY, &rejected);
}
fn remove_from_verified_businesses(env: &Env, business: &Address) {
let verified = Self::get_verified_businesses(env);
let mut new_verified = vec![env];
for addr in verified.iter() {
if addr != *business {
new_verified.push_back(addr);
}
}
env.storage()
.instance()
.set(&Self::VERIFIED_BUSINESSES_KEY, &new_verified);
}
fn remove_from_pending_businesses(env: &Env, business: &Address) {
let pending = Self::get_pending_businesses(env);
let mut new_pending = vec![env];
for addr in pending.iter() {
if addr != *business {
new_pending.push_back(addr);
}
}
env.storage()
.instance()
.set(&Self::PENDING_BUSINESSES_KEY, &new_pending);
}
fn remove_from_rejected_businesses(env: &Env, business: &Address) {
let rejected = Self::get_rejected_businesses(env);
let mut new_rejected = vec![env];
for addr in rejected.iter() {
if addr != *business {
new_rejected.push_back(addr);
}
}
env.storage()
.instance()
.set(&Self::REJECTED_BUSINESSES_KEY, &new_rejected);
}
/// @deprecated Use `admin::AdminStorage::initialize()` or `admin::AdminStorage::set_admin()` instead
/// This function is kept for backward compatibility with existing tests.
/// Returns true if the business is marked as deleted.
pub fn is_deleted(env: &Env, business: &Address) -> bool {
let deleted = Self::get_deleted_businesses(env);
deleted.iter().any(|addr| addr == *business)
}
/// Retrieve list of deleted businesses.
pub fn get_deleted_businesses(env: &Env) -> Vec<Address> {
env.storage()
.instance()
.get(&Self::DELETED_BUSINESSES_KEY)
.unwrap_or(vec![env])
}
fn add_to_deleted_businesses(env: &Env, business: &Address) {
let mut deleted = Self::get_deleted_businesses(env);
deleted.push_back(business.clone());
env.storage()
.instance()
.set(&Self::DELETED_BUSINESSES_KEY, &deleted);
}
fn remove_from_deleted_businesses(env: &Env, business: &Address) {
let deleted = Self::get_deleted_businesses(env);
let mut new_deleted = vec![env];
for addr in deleted.iter() {
if addr != *business {
new_deleted.push_back(addr);
}
}
env.storage()
.instance()
.set(&Self::DELETED_BUSINESSES_KEY, &new_deleted);
}
/// Deletes a business: removes from any status list and marks as deleted.
pub fn delete_business(env: &Env, business: &Address) -> Result<(), QuickLendXError> {
// Remove from verified, pending, rejected lists if present
if Self::is_business_verified(env, business) {
Self::remove_from_verified_businesses(env, business);
}
if Self::is_business_pending(env, business) {
Self::remove_from_pending_businesses(env, business);
}
if Self::is_business_rejected(env, business) {
Self::remove_from_rejected_businesses(env, business);
}
// Add to deleted list
if Self::is_deleted(env, business) {
// Already deleted; no-op
return Ok(());
}
Self::add_to_deleted_businesses(env, business);
Ok(())
}
/// Restores a previously deleted business: removes from the deleted list and
/// re-adds to the appropriate status list based on the existing verification record.
///
/// # Errors
/// - `BusinessNotVerified` if the business has no verification record.
/// - `BusinessDeleted` if the business is not currently deleted (no-op).
pub fn restore_business(env: &Env, business: &Address) -> Result<(), QuickLendXError> {
if !Self::is_deleted(env, business) {
return Err(QuickLendXError::BusinessDeleted);
}
Self::remove_from_deleted_businesses(env, business);
// Re-add to the status list matching the existing verification record.
if let Some(verification) = Self::get_verification(env, business) {
match verification.status {
BusinessVerificationStatus::Verified => {
Self::add_to_verified_businesses(env, business);
}
BusinessVerificationStatus::Pending => {
Self::add_to_pending_businesses(env, business);
}
BusinessVerificationStatus::Rejected => {
Self::add_to_rejected_businesses(env, business);
}
}
}
Ok(())
}
// Helper checks for status presence
fn is_business_pending(env: &Env, business: &Address) -> bool {
let pending = Self::get_pending_businesses(env);
pending.iter().any(|addr| addr == *business)
}
fn is_business_rejected(env: &Env, business: &Address) -> bool {
let rejected = Self::get_rejected_businesses(env);
rejected.iter().any(|addr| addr == *business)
}
/// It syncs with the new AdminStorage system.
pub fn set_admin(env: &Env, admin: &Address) {
// Store in old location for backward compatibility
env.storage().instance().set(&Self::ADMIN_KEY, admin);
// Always sync with new AdminStorage
// This allows tests that call set_admin() multiple times to work
env.storage()
.instance()
.set(&crate::admin::ADMIN_KEY, admin);
env.storage()
.instance()
.set(&crate::admin::ADMIN_INITIALIZED_KEY, &true);
}
/// @deprecated Use `admin::AdminStorage::get_admin()` instead
/// This function is kept for backward compatibility only
pub fn get_admin(env: &Env) -> Option<Address> {
// Try new storage first, fall back to old
crate::admin::AdminStorage::get_admin(env)
.or_else(|| env.storage().instance().get(&Self::ADMIN_KEY))
}
/// @deprecated Use `admin::AdminStorage::is_admin()` instead
/// This function is kept for backward compatibility only
pub fn is_admin(env: &Env, address: &Address) -> bool {
crate::admin::AdminStorage::is_admin(env, address)
}
}
pub struct InvestorVerificationStorage;
// Investor tier promotion and demotion thresholds are deterministic and derived
// from tracked performance counters plus the investor's risk score.
// These constants make the decision rules auditable and stable across runs.
const VIP_RISK_SCORE_MAX: u32 = 10;
const VIP_TOTAL_INVESTED_MIN: i128 = 5_000_000;
const VIP_SUCCESSFUL_INVESTMENTS_MIN: u32 = 50;
const VIP_DEFAULT_RATE_MAX_PCT: u32 = 5;
const PLATINUM_RISK_SCORE_MAX: u32 = 20;
const PLATINUM_TOTAL_INVESTED_MIN: i128 = 1_000_000;
const PLATINUM_SUCCESSFUL_INVESTMENTS_MIN: u32 = 20;
const PLATINUM_DEFAULT_RATE_MAX_PCT: u32 = 10;
const GOLD_RISK_SCORE_MAX: u32 = 40;
const GOLD_TOTAL_INVESTED_MIN: i128 = 100_000;
const GOLD_SUCCESSFUL_INVESTMENTS_MIN: u32 = 10;
const GOLD_DEFAULT_RATE_MAX_PCT: u32 = 15;
const SILVER_RISK_SCORE_MAX: u32 = 60;
const SILVER_TOTAL_INVESTED_MIN: i128 = 10_000;
const SILVER_SUCCESSFUL_INVESTMENTS_MIN: u32 = 3;
const SILVER_DEFAULT_RATE_MAX_PCT: u32 = 25;
impl InvestorVerificationStorage {
const VERIFIED_INVESTORS_KEY: &'static str = "verified_investors";
const PENDING_INVESTORS_KEY: &'static str = "pending_investors";
const REJECTED_INVESTORS_KEY: &'static str = "rejected_investors";
#[cfg(test)]
const INVESTOR_HISTORY_KEY: &'static str = "investor_history";
#[cfg(test)]
const INVESTOR_ANALYTICS_KEY: &'static str = "investor_analytics";
pub fn submit(env: &Env, investor: &Address, kyc_data: String) -> Result<(), QuickLendXError> {
check_string_length(&kyc_data, MAX_KYC_DATA_LENGTH)?;
let mut verification = Self::get(env, investor);
match verification {
Some(ref existing) => match existing.status {
BusinessVerificationStatus::Pending => {
return Err(QuickLendXError::KYCAlreadyPending)
}
BusinessVerificationStatus::Verified => {
return Err(QuickLendXError::KYCAlreadyVerified)
}
BusinessVerificationStatus::Rejected => {
verification = Some(InvestorVerification {
investor: investor.clone(),
status: BusinessVerificationStatus::Pending,
verified_at: None,
verified_by: None,
kyc_data,
investment_limit: existing.investment_limit,
submitted_at: env.ledger().timestamp(),
tier: existing.tier.clone(),
risk_level: existing.risk_level.clone(),
risk_score: existing.risk_score,
total_invested: existing.total_invested,
total_returns: existing.total_returns,
successful_investments: existing.successful_investments,
defaulted_investments: existing.defaulted_investments,
last_activity: existing.last_activity,
rejection_reason: None,
compliance_notes: None,
});
}
},
None => {
verification = Some(InvestorVerification {
investor: investor.clone(),
status: BusinessVerificationStatus::Pending,
verified_at: None,
verified_by: None,
kyc_data,
investment_limit: 0,
submitted_at: env.ledger().timestamp(),
tier: InvestorTier::Basic,
risk_level: InvestorRiskLevel::High, // Default to high risk for new investors
risk_score: 100, // Default high risk score
total_invested: 0,
total_returns: 0,
successful_investments: 0,
defaulted_investments: 0,
last_activity: env.ledger().timestamp(),
rejection_reason: None,
compliance_notes: None,
});
}
}
if let Some(v) = verification {
Self::store(env, &v);
Self::add_to_pending_investors(env, investor);
}
Ok(())
}
pub fn store(env: &Env, verification: &InvestorVerification) {
env.storage()
.instance()
.set(&verification.investor, verification);
}
pub fn get(env: &Env, investor: &Address) -> Option<InvestorVerification> {
env.storage().instance().get(investor)
}
pub fn update(env: &Env, verification: &InvestorVerification) {
let old_verification = Self::get(env, &verification.investor);
// Remove from old status list
if let Some(old_ver) = old_verification {
match old_ver.status {
BusinessVerificationStatus::Verified => {
Self::remove_from_verified_investors(env, &verification.investor);
}
BusinessVerificationStatus::Pending => {
Self::remove_from_pending_investors(env, &verification.investor);
}
BusinessVerificationStatus::Rejected => {
Self::remove_from_rejected_investors(env, &verification.investor);
}
}
}
// Store new verification
Self::store(env, verification);
// Add to new status list
match verification.status {
BusinessVerificationStatus::Verified => {
Self::add_to_verified_investors(env, &verification.investor);
}
BusinessVerificationStatus::Pending => {
Self::add_to_pending_investors(env, &verification.investor);
}
BusinessVerificationStatus::Rejected => {
Self::add_to_rejected_investors(env, &verification.investor);
}
}
}
pub fn is_investor_verified(env: &Env, investor: &Address) -> bool {
if let Some(verification) = Self::get(env, investor) {
matches!(verification.status, BusinessVerificationStatus::Verified)
} else {
false
}
}
pub fn get_verified_investors(env: &Env) -> Vec<Address> {
env.storage()
.instance()
.get(&Self::VERIFIED_INVESTORS_KEY)
.unwrap_or(vec![env])
}
pub fn get_pending_investors(env: &Env) -> Vec<Address> {
env.storage()
.instance()
.get(&Self::PENDING_INVESTORS_KEY)
.unwrap_or(vec![env])
}
pub fn get_rejected_investors(env: &Env) -> Vec<Address> {
env.storage()
.instance()
.get(&Self::REJECTED_INVESTORS_KEY)
.unwrap_or(vec![env])
}
pub fn get_investors_by_tier(env: &Env, tier: InvestorTier) -> Vec<Address> {
let verified_investors = Self::get_verified_investors(env);
let mut tier_investors = Vec::new(env);
for investor in verified_investors.iter() {
if let Some(verification) = Self::get(env, &investor) {
if verification.tier == tier {
tier_investors.push_back(investor);
}
}
}
tier_investors
}
pub fn get_investors_by_risk_level(env: &Env, risk_level: InvestorRiskLevel) -> Vec<Address> {
let verified_investors = Self::get_verified_investors(env);
let mut risk_investors = Vec::new(env);
for investor in verified_investors.iter() {
if let Some(verification) = Self::get(env, &investor) {
if verification.risk_level == risk_level {
risk_investors.push_back(investor);
}
}
}
risk_investors
}
fn add_to_verified_investors(env: &Env, investor: &Address) {
let mut verified = Self::get_verified_investors(env);
verified.push_back(investor.clone());
env.storage()
.instance()
.set(&Self::VERIFIED_INVESTORS_KEY, &verified);
}
fn add_to_pending_investors(env: &Env, investor: &Address) {
let mut pending = Self::get_pending_investors(env);
pending.push_back(investor.clone());
env.storage()
.instance()
.set(&Self::PENDING_INVESTORS_KEY, &pending);
}
fn add_to_rejected_investors(env: &Env, investor: &Address) {
let mut rejected = Self::get_rejected_investors(env);
rejected.push_back(investor.clone());
env.storage()
.instance()
.set(&Self::REJECTED_INVESTORS_KEY, &rejected);
}
fn remove_from_verified_investors(env: &Env, investor: &Address) {
let verified = Self::get_verified_investors(env);
let mut new_verified = vec![env];
for addr in verified.iter() {
if addr != *investor {
new_verified.push_back(addr);
}
}
env.storage()
.instance()
.set(&Self::VERIFIED_INVESTORS_KEY, &new_verified);
}
fn remove_from_pending_investors(env: &Env, investor: &Address) {
let pending = Self::get_pending_investors(env);
let mut new_pending = vec![env];
for addr in pending.iter() {
if addr != *investor {
new_pending.push_back(addr);
}
}
env.storage()
.instance()
.set(&Self::PENDING_INVESTORS_KEY, &new_pending);
}
fn remove_from_rejected_investors(env: &Env, investor: &Address) {
let rejected = Self::get_rejected_investors(env);
let mut new_rejected = vec![env];
for addr in rejected.iter() {
if addr != *investor {
new_rejected.push_back(addr);
}
}
env.storage()
.instance()
.set(&Self::REJECTED_INVESTORS_KEY, &new_rejected);
}
}
/// Normalizes a tag by trimming whitespace and converting to lowercase.
/// Enforces length limits of 1-50 characters.
pub fn normalize_tag(env: &Env, tag: &String) -> Result<String, QuickLendXError> {
if tag.is_empty() || tag.len() > MAX_TAG_LENGTH.saturating_mul(2) {
return Err(QuickLendXError::InvalidTag);
}
let mut buf = [0u8; (MAX_TAG_LENGTH as usize) * 2];
tag.copy_into_slice(&mut buf[..tag.len() as usize]);
let raw_slice = &buf[..tag.len() as usize];
let mut start = 0usize;
let mut end = raw_slice.len();
while start < end && raw_slice[start].is_ascii_whitespace() {
start += 1;
}
while end > start && raw_slice[end - 1].is_ascii_whitespace() {
end -= 1;
}
if start == end {
return Err(QuickLendXError::InvalidTag);
}
let normalized_len = end - start;
if normalized_len > MAX_TAG_LENGTH as usize {
return Err(QuickLendXError::InvalidTag);
}
let mut normalized_bytes = [0u8; MAX_TAG_LENGTH as usize];
for (idx, &b) in raw_slice[start..end].iter().enumerate() {
let lower = if b.is_ascii_uppercase() { b + 32 } else { b };
normalized_bytes[idx] = lower;
}
let normalized_str = String::from_str(
env,
core::str::from_utf8(&normalized_bytes[..normalized_len])
.map_err(|_| QuickLendXError::InvalidTag)?,
);
if normalized_str.is_empty() {
return Err(QuickLendXError::InvalidTag);
}
Ok(normalized_str)
}
/// @notice Validate a bid against protocol rules and business constraints
/// @dev Enforces minimum bid amounts (both absolute and percentage-based),
/// invoice status checks, ownership validation, and investor capacity limits
/// @param env The contract environment
/// @param invoice The invoice being bid on
/// @param bid_amount The amount being bid
/// @param expected_return The expected return amount for the investor
/// @param investor The address of the bidding investor
/// @return Success if bid passes all validation rules
/// @error InvalidAmount if bid amount is below minimum or exceeds invoice amount
/// @error InvalidStatus if invoice is not in Verified state or is past due date
/// @error Unauthorized if business tries to bid on own invoice
/// @error OperationNotAllowed if investor already has an active bid on this invoice
/// @error InsufficientCapacity if bid exceeds investor's remaining investment capacity
pub fn validate_bid(
env: &Env,
invoice: &Invoice,
bid_amount: i128,
expected_return: i128,
investor: &Address,
) -> Result<(), QuickLendXError> {
// 1. Basic amount validation
if bid_amount <= 0 {
return Err(QuickLendXError::InvalidAmount);
}
// 2. Invoice state and stale check
if invoice.status != InvoiceStatus::Verified {
return Err(QuickLendXError::InvalidStatus);
}
// Pre-maturity check: prevent bidding on invoices that have already reached their due date
if env.ledger().timestamp() >= invoice.due_date {
return Err(QuickLendXError::InvalidStatus);
}
// 3. Ownership check: Business cannot bid on its own invoice
if &invoice.business == investor {
return Err(QuickLendXError::Unauthorized);
}
// 4. Protocol limits and bid size validation
let limits = ProtocolLimitsContract::get_protocol_limits(env.clone());
// Calculate minimum bid amount using both absolute minimum and percentage-based minimum
let percent_min = invoice
.amount
.saturating_mul(limits.min_bid_bps as i128)
.saturating_div(10_000);
let effective_min_bid = if percent_min > limits.min_bid_amount {
percent_min
} else {
limits.min_bid_amount
};
if bid_amount < effective_min_bid {
return Err(QuickLendXError::InvalidAmount);
}
if bid_amount > invoice.amount {
return Err(QuickLendXError::InvoiceAmountInvalid);
}
// Expected return must exceed the original bid to avoid negative payoff.
if expected_return <= bid_amount {
return Err(QuickLendXError::InvalidAmount);
}
// 5. Investor Eligibility and Capacity
// This checks both verification status AND individual/risk-based investment limits
validate_investor_investment(env, investor, bid_amount)?;
// 6. Existing Bid Protection
BidStorage::cleanup_expired_bids(env, &invoice.id);
let existing_bids = BidStorage::get_bids_for_invoice(env, &invoice.id);
for bid_id in existing_bids.iter() {
if let Some(existing_bid) = BidStorage::get_bid(env, &bid_id) {
// Prevent multiple active bids from the same investor on one invoice
if existing_bid.investor == *investor && existing_bid.status == BidStatus::Placed {
return Err(QuickLendXError::OperationNotAllowed);
}
}
}
Ok(())
}
pub fn submit_kyc_application(
env: &Env,
business: &Address,
kyc_data: String,
) -> Result<(), QuickLendXError> {
check_string_length(&kyc_data, MAX_KYC_DATA_LENGTH)?;
// Only the business can submit their own KYC
business.require_auth();
// Get existing verification record
let existing_verification = BusinessVerificationStorage::get_verification(env, business);
let old_status = existing_verification.as_ref().map(|v| v.status.clone());
// Validate state transition to Pending
BusinessVerificationStorage::validate_state_transition(
old_status.clone(),
BusinessVerificationStatus::Pending,
)?;
let verification = BusinessVerification {
business: business.clone(),
status: BusinessVerificationStatus::Pending,
verified_at: None,
verified_by: None,
kyc_data,
submitted_at: env.ledger().timestamp(),
rejection_reason: None, // Clear rejection reason on resubmission
};
BusinessVerificationStorage::update_verification(env, &verification)?;
// Emit appropriate event based on whether this is a resubmission
if matches!(old_status, Some(BusinessVerificationStatus::Rejected)) {
emit_kyc_resubmitted(env, business);
} else {
emit_kyc_submitted(env, business);
}
Ok(())
}
pub fn verify_business(
env: &Env,
admin: &Address,
business: &Address,
) -> Result<(), QuickLendXError> {
// Only admin can verify businesses
admin.require_auth();
if !BusinessVerificationStorage::is_admin(env, admin) {
return Err(QuickLendXError::NotAdmin);
}
let mut verification = BusinessVerificationStorage::get_verification(env, business)
.ok_or(QuickLendXError::KYCNotFound)?;
// Validate state transition to Verified
BusinessVerificationStorage::validate_state_transition(
Some(verification.status.clone()),
BusinessVerificationStatus::Verified,
)?;
verification.status = BusinessVerificationStatus::Verified;
verification.verified_at = Some(env.ledger().timestamp());
verification.verified_by = Some(admin.clone());
// Clear rejection reason when verified
verification.rejection_reason = None;
BusinessVerificationStorage::update_verification(env, &verification)?;
emit_business_verified(env, business, admin);
Ok(())
}
/// Reject a pending business KYC record with an auditable reason.
///
/// # Errors
/// - `NotAdmin` if `admin` is not a contract admin
/// - `KYCNotFound` if the business has no KYC record
/// - `InvalidKYCStatus` if the business is not currently `Pending`
/// - `InvalidDescription` if `reason` exceeds `MAX_REJECTION_REASON_LENGTH`
pub fn reject_business(
env: &Env,
admin: &Address,
business: &Address,
reason: String,
) -> Result<(), QuickLendXError> {
check_string_length(&reason, MAX_REJECTION_REASON_LENGTH)?;
// Only admin can reject businesses
admin.require_auth();
if !BusinessVerificationStorage::is_admin(env, admin) {
return Err(QuickLendXError::NotAdmin);
}
let mut verification = BusinessVerificationStorage::get_verification(env, business)
.ok_or(QuickLendXError::KYCNotFound)?;
// Validate state transition to Rejected
BusinessVerificationStorage::validate_state_transition(
Some(verification.status.clone()),
BusinessVerificationStatus::Rejected,
)?;
verification.status = BusinessVerificationStatus::Rejected;
verification.rejection_reason = Some(reason.clone());
BusinessVerificationStorage::update_verification(env, &verification)?;
emit_business_rejected(env, business, admin, &reason);
Ok(())
}
pub fn get_business_verification_status(
env: &Env,
business: &Address,
) -> Option<BusinessVerification> {
BusinessVerificationStorage::get_verification(env, business)
}
pub fn require_business_verification(env: &Env, business: &Address) -> Result<(), QuickLendXError> {
if !BusinessVerificationStorage::is_business_verified(env, business) {
return Err(QuickLendXError::BusinessNotVerified);
}
Ok(())
}
/// Enforce that a business is not in KYC-pending state before allowing a sensitive operation.
///
/// Pending businesses have submitted KYC but have not yet been approved or rejected.
/// They must not be allowed to perform privileged actions (e.g. upload invoices, cancel
/// invoices, accept bids) until their identity has been confirmed by an admin.
///
/// # Errors