forked from QuickLendX/quicklendx-protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontract.rs
More file actions
529 lines (461 loc) · 20.5 KB
/
Copy pathcontract.rs
File metadata and controls
529 lines (461 loc) · 20.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
use soroban_sdk::{contract, contractimpl, Address, BytesN, Env, Vec, Bytes, xdr::ToXdr};
use crate::admin::AdminStorage;
use crate::errors::QuickLendXError;
use crate::types::{
Invoice, InvoiceStatus, InvoiceCategory, InvoiceMetadata, Bid, BidStatus,
DisputeStatus, PaymentRecord, InvoiceRating, Escrow, EscrowStatus
};
use crate::storage::InvoiceStorage;
use crate::init::{ProtocolInitializer, InitializationParams};
use crate::protocol_limits::ProtocolLimitsContract;
use crate::verification::{BusinessVerificationStorage, InvestorVerificationStorage, submit_kyc_application, verify_business};
use crate::bid::BidStorage;
use crate::payments::EscrowStorage;
use crate::backup::{Backup, BackupStorage, BackupStatus, BackupRetentionPolicy};
#[contract]
pub struct QuickLendXContract;
#[contractimpl]
impl QuickLendXContract {
/// Initialize the protocol with comprehensive parameters.
pub fn initialize(
env: Env,
admin: Address,
treasury: Address,
fee_bps: u32,
min_invoice_amount: i128,
max_due_date_days: u64,
grace_period_seconds: u64,
initial_currencies: Vec<Address>,
) -> Result<(), QuickLendXError> {
let params = InitializationParams {
admin,
treasury,
fee_bps,
min_invoice_amount,
max_due_date_days,
grace_period_seconds,
initial_currencies,
};
ProtocolInitializer::initialize(&env, ¶ms)
}
pub fn set_admin(env: Env, admin: Address, new_admin: Address) -> Result<(), QuickLendXError> {
AdminStorage::set_admin(&env, &admin, &new_admin)?;
Ok(())
}
/// Initialize the protocol admin only.
pub fn initialize_admin(env: Env, admin: Address) -> Result<(), QuickLendXError> {
AdminStorage::initialize(&env, &admin)
}
pub fn get_admin(env: Env) -> Result<Address, QuickLendXError> {
AdminStorage::get_admin(&env).ok_or(QuickLendXError::StorageKeyNotFound)
}
/// Admin-gated, read-only protocol invariant self-check ("heartbeat").
///
/// Aggregates the cross-module integrity checks (orphan investments, audit
/// chain integrity, solvency, and storage-index coherence) into a single
/// [`InvariantReport`] of `(check_name, passed, evidence)` rows for incident
/// response. Authenticates `admin` before running; the checks never mutate
/// state, so an unauthorized or failing call leaves the ledger unchanged.
pub fn invariant_self_check(
env: Env,
admin: Address,
) -> Result<crate::invariants::InvariantReport, QuickLendXError> {
crate::invariants::invariant_self_check(&env, &admin)
}
/// Initialize protocol limits.
pub fn initialize_protocol_limits(
env: Env,
admin: Address,
) -> Result<(), QuickLendXError> {
ProtocolLimitsContract::initialize(env, admin)
}
/// Store a new invoice on behalf of a KYC-verified business.
///
/// # Authentication & KYC Policy (Issue #790)
///
/// This function enforces a **two-layer authentication policy** to prevent
/// unauthorized invoice creation and storage-based denial-of-service attacks:
///
/// 1. **Business signature** - `business.require_auth()` is called first.
/// Only the business address itself may submit an invoice; no third party
/// (including the admin) can create invoices on behalf of a business.
///
/// 2. **Verified KYC** - the business must have a `Verified` KYC record.
/// - `BusinessNotVerified` (1600) is returned if the business has no KYC
/// record or was rejected.
/// - `KYCAlreadyPending` (1601) is returned if the KYC application is
/// still awaiting admin review, preventing spam from unvetted entities.
///
/// # Security Invariants
/// - An unverified or pending business **cannot** create invoices.
/// - Admin cannot bypass the business signature requirement.
/// - Prevents storage DoS: only KYC-gated addresses can write invoice data.
///
/// # Arguments
/// * `env` - The contract environment.
/// * `business` - The address of the invoice-issuing business (must sign).
/// * `amount` - Invoice face value in the smallest currency unit.
/// * `currency` - Token contract address for the invoice currency.
/// * `due_date` - Unix timestamp by which the invoice must be settled.
/// * `description` - Human-readable invoice description.
/// * `category` - Invoice category (Services, Products, etc.).
/// * `tags` - Optional searchable tags (max 10, each 1-50 bytes).
///
/// # Errors
/// * `BusinessNotVerified` (1600) - business has no KYC record or is rejected.
/// * `KYCAlreadyPending` (1601) - business KYC is pending admin review.
pub fn store_invoice(
env: Env,
business: Address,
amount: i128,
currency: Address,
due_date: u64,
description: soroban_sdk::Bytes,
category: InvoiceCategory,
tags: Vec<soroban_sdk::Bytes>,
) -> Result<BytesN<32>, QuickLendXError> {
// POLICY LAYER 1: Require explicit authorization from the business address.
// This ensures only the business itself can create invoices - not the admin,
// not a third party. Prevents impersonation and unauthorized storage writes.
business.require_auth();
// POLICY LAYER 2: Enforce KYC gating.
// Pending businesses are explicitly rejected with KYCAlreadyPending so
// callers can distinguish "not yet approved" from "rejected/unknown".
// This is the primary anti-spam control: only vetted businesses may write
// invoice data to on-chain storage.
crate::verification::require_business_not_pending(&env, &business)?;
// Enforce per-business invoice cap.
ProtocolLimitsContract::check_invoice_limit(&env, &business)?;
let invoice_id: BytesN<32> = env
.crypto()
.sha256(&env.ledger().timestamp().to_xdr(&env))
.into();
let invoice = Invoice {
invoice_id: invoice_id.clone(),
business,
amount,
currency,
due_date,
description,
category,
tags,
status: InvoiceStatus::Pending,
metadata: None,
metadata_customer_name: None,
metadata_tax_id: None,
total_paid: 0,
funded_amount: 0,
funded_at: None,
average_rating: None,
total_ratings: 0,
investor: None,
dispute_status: DisputeStatus::None,
dispute: None,
payment_history: Vec::new(&env),
ratings: Vec::new(&env),
created_at: env.ledger().timestamp(),
updated_at: env.ledger().timestamp(),
settled_at: None,
};
InvoiceStorage::store_invoice(&env, &invoice);
Ok(invoice_id)
}
pub fn get_invoice(env: Env, invoice_id: BytesN<32>) -> Result<Invoice, QuickLendXError> {
InvoiceStorage::get(&env, &invoice_id).ok_or(QuickLendXError::InvoiceNotFound)
}
pub fn update_invoice_status(env: Env, invoice_id: BytesN<32>, status: InvoiceStatus) -> Result<(), QuickLendXError> {
let mut invoice = InvoiceStorage::get(&env, &invoice_id).ok_or(QuickLendXError::InvoiceNotFound)?;
invoice.status = status;
InvoiceStorage::update_invoice(&env, &invoice);
Ok(())
}
pub fn verify_invoice(env: Env, invoice_id: BytesN<32>) -> Result<(), QuickLendXError> {
let mut invoice = InvoiceStorage::get(&env, &invoice_id).ok_or(QuickLendXError::InvoiceNotFound)?;
invoice.status = InvoiceStatus::Verified;
InvoiceStorage::update_invoice(&env, &invoice);
Ok(())
}
pub fn place_bid(
env: Env,
investor: Address,
invoice_id: BytesN<32>,
bid_amount: i128,
expected_return: i128,
salt: BytesN<32>,
) -> Result<BytesN<32>, QuickLendXError> {
// Idempotency check
let idem_key = idempotency_key(&invoice_id, &investor, &salt, &env);
if idempotency_exists(&env, &idem_key) {
return Err(QuickLendXError::DuplicateBid);
}
if InvoiceStorage::is_frozen(&env, &invoice_id) {
return Err(QuickLendXError::InvoiceFrozen);
}
// Store idempotency marker
store_idempotency(&env, &idem_key);
let bid_id = BidStorage::generate_unique_bid_id(&env);
let bid = Bid {
bid_id: bid_id.clone(),
invoice_id,
investor,
bid_amount,
expected_return,
status: BidStatus::Placed,
timestamp: env.ledger().timestamp(),
expiration_timestamp: env.ledger().timestamp() + 86400,
};
BidStorage::store_bid(&env, &bid);
Ok(bid_id)
}
pub fn accept_bid(env: Env, invoice_id: BytesN<32>, bid_id: BytesN<32>) -> Result<(), QuickLendXError> {
if InvoiceStorage::is_frozen(&env, &invoice_id) {
return Err(QuickLendXError::InvoiceFrozen);
}
let mut invoice = InvoiceStorage::get(&env, &invoice_id).ok_or(QuickLendXError::InvoiceNotFound)?;
let bid = BidStorage::get_bid(&env, &bid_id).unwrap();
invoice.mark_as_funded(&env, bid.investor.clone(), bid.bid_amount, env.ledger().timestamp());
InvoiceStorage::update_invoice(&env, &invoice);
let mut bid = bid;
bid.status = BidStatus::Accepted;
BidStorage::store_bid(&env, &bid);
let escrow_id = crate::payments::EscrowStorage::generate_unique_escrow_id(&env);
let escrow = Escrow {
escrow_id,
invoice_id,
investor: bid.investor,
business: invoice.business,
amount: bid.bid_amount,
currency: invoice.currency,
created_at: env.ledger().timestamp(),
released_at: None,
refunded_at: None,
status: EscrowStatus::Held,
};
crate::payments::EscrowStorage::store_escrow(&env, &escrow);
Ok(())
}
pub fn get_bid(env: Env, bid_id: BytesN<32>) -> Option<Bid> {
BidStorage::get_bid(&env, &bid_id)
}
pub fn get_bids_for_invoice(env: Env, invoice_id: BytesN<32>) -> Vec<Bid> {
let ids = BidStorage::get_bids_for_invoice(&env, &invoice_id);
let mut bids = Vec::new(&env);
for id in ids.iter() {
if let Some(bid) = BidStorage::get_bid(&env, &id) {
bids.push_back(bid);
}
}
bids
}
pub fn withdraw_bid(env: Env, bid_id: BytesN<32>) -> Result<(), QuickLendXError> {
let mut bid = BidStorage::get_bid(&env, &bid_id).unwrap();
bid.status = BidStatus::Withdrawn;
BidStorage::store_bid(&env, &bid);
Ok(())
}
pub fn cleanup_expired_bids(env: Env, invoice_id: BytesN<32>) -> u32 {
BidStorage::cleanup_expired_bids(&env, &invoice_id)
}
pub fn get_ranked_bids(env: Env, invoice_id: BytesN<32>) -> Vec<Bid> {
BidStorage::rank_bids(&env, &invoice_id)
}
pub fn get_best_bid(env: Env, invoice_id: BytesN<32>) -> Option<Bid> {
BidStorage::get_best_bid(&env, &invoice_id)
}
pub fn get_bids_by_status(env: Env, invoice_id: BytesN<32>, status: BidStatus) -> Vec<Bid> {
BidStorage::get_bids_by_status(&env, &invoice_id, status)
}
pub fn get_bids_by_investor(env: Env, invoice_id: BytesN<32>, investor: Address) -> Vec<Bid> {
BidStorage::get_bids_by_investor(&env, &invoice_id, &investor)
}
pub fn submit_kyc_application(env: Env, business: Address, kyc_data: soroban_sdk::Bytes) -> Result<(), QuickLendXError> {
submit_kyc_application(&env, &business, kyc_data)
}
pub fn freeze_invoice(env: Env, admin: Address, invoice_id: BytesN<32>) -> Result<(), QuickLendXError> {
crate::admin::AdminStorage::require_admin(&env, &admin)?;
InvoiceStorage::set_frozen(&env, &invoice_id, true);
Ok(())
}
pub fn verify_business(env: Env, admin: Address, business: Address) -> Result<(), QuickLendXError> {
verify_business(&env, &admin, &business)
}
/// Delete a business, removing it from any status list and marking as deleted.
pub fn delete_business(env: Env, business: Address) -> Result<(), QuickLendXError> {
BusinessVerificationStorage::delete_business(&env, &business)
}
pub fn submit_investor_kyc(env: Env, investor: Address, kyc_data: soroban_sdk::Bytes) -> Result<(), QuickLendXError> {
InvestorVerificationStorage::submit(&env, &investor, kyc_data)
}
pub fn verify_investor(env: Env, investor: Address, limit: i128) {
InvestorVerificationStorage::verify_investor(&env, &investor, limit);
}
pub fn get_available_invoices(env: Env) -> Vec<BytesN<32>> {
InvoiceStorage::get_invoices_by_status(&env, InvoiceStatus::Verified)
}
pub fn get_business_invoices(env: Env, business: Address) -> Vec<BytesN<32>> {
InvoiceStorage::get_business_invoices(&env, &business)
}
pub fn get_total_invoice_count(env: Env) -> u32 {
InvoiceStorage::get_total_count(&env)
}
pub fn get_invoice_count_by_status(env: Env, status: InvoiceStatus) -> u32 {
InvoiceStorage::get_count_by_status(&env, status)
}
pub fn update_invoice_metadata(env: Env, invoice_id: BytesN<32>, metadata: InvoiceMetadata) -> Result<(), QuickLendXError> {
let mut invoice = InvoiceStorage::get(&env, &invoice_id).ok_or(QuickLendXError::InvoiceNotFound)?;
invoice.update_metadata(metadata);
InvoiceStorage::update_invoice(&env, &invoice);
Ok(())
}
pub fn clear_invoice_metadata(env: Env, invoice_id: BytesN<32>) -> Result<(), QuickLendXError> {
let mut invoice = InvoiceStorage::get(&env, &invoice_id).ok_or(QuickLendXError::InvoiceNotFound)?;
invoice.clear_metadata();
InvoiceStorage::update_invoice(&env, &invoice);
Ok(())
}
pub fn get_invoices_by_customer(env: Env, customer_name: soroban_sdk::Bytes) -> Vec<BytesN<32>> {
InvoiceStorage::get_by_customer(&env, &customer_name)
}
pub fn get_invoices_by_tax_id(env: Env, tax_id: soroban_sdk::Bytes) -> Vec<BytesN<32>> {
InvoiceStorage::get_by_tax_id(&env, &tax_id)
}
pub fn get_invoices_by_status_batch(env: Env, ids: Vec<BytesN<32>>) -> Vec<Option<InvoiceStatus>> {
let mut results = Vec::new(&env);
for id in ids.iter() {
if results.len() >= 50 { break; }
let status = InvoiceStorage::get(&env, &id).map(|i| i.status);
results.push_back(status);
}
results
}
pub fn add_invoice_rating(
env: Env,
invoice_id: BytesN<32>,
rating: u32,
comment: soroban_sdk::Bytes,
investor: Address,
) -> Result<(), QuickLendXError> {
let mut invoice = InvoiceStorage::get(&env, &invoice_id).ok_or(QuickLendXError::InvoiceNotFound)?;
invoice.add_rating(rating, comment, investor, env.ledger().timestamp())?;
InvoiceStorage::update_invoice(&env, &invoice);
Ok(())
}
pub fn get_escrow_details(env: Env, invoice_id: BytesN<32>) -> Result<Escrow, QuickLendXError> {
EscrowStorage::get_escrow_by_invoice(&env, &invoice_id).ok_or(QuickLendXError::StorageKeyNotFound)
}
pub fn get_escrow_status(env: Env, invoice_id: BytesN<32>) -> Result<EscrowStatus, QuickLendXError> {
EscrowStorage::get_escrow_status(&env, &invoice_id).ok_or(QuickLendXError::StorageKeyNotFound)
}
pub fn release_escrow_funds(env: Env, invoice_id: BytesN<32>) -> Result<(), QuickLendXError> {
let mut escrow = EscrowStorage::get_escrow_by_invoice(&env, &invoice_id).unwrap();
escrow.status = EscrowStatus::Released;
escrow.released_at = Some(env.ledger().timestamp());
EscrowStorage::update_escrow(&env, &escrow);
Ok(())
}
pub fn refund_escrow_funds(env: Env, invoice_id: BytesN<32>, admin: Address) -> Result<(), QuickLendXError> {
AdminStorage::require_admin(&env, &admin)?;
let mut escrow = EscrowStorage::get_escrow_by_invoice(&env, &invoice_id).unwrap();
escrow.status = EscrowStatus::Refunded;
escrow.refunded_at = Some(env.ledger().timestamp());
EscrowStorage::update_escrow(&env, &escrow);
Ok(())
}
// Backup & Restore
pub fn create_backup(env: Env, admin: Address) -> Result<BytesN<32>, QuickLendXError> {
AdminStorage::require_admin(&env, &admin)?;
let mut all_invoices = Vec::new(&env);
for status in [
InvoiceStatus::Pending,
InvoiceStatus::Verified,
InvoiceStatus::Funded,
InvoiceStatus::Paid,
InvoiceStatus::Defaulted,
] {
let ids = InvoiceStorage::get_invoices_by_status(&env, status);
for id in ids.iter() {
if let Some(invoice) = InvoiceStorage::get(&env, &id) {
all_invoices.push_back(invoice);
}
}
}
let backup_id = BackupStorage::generate_backup_id(&env);
let backup = Backup {
backup_id: backup_id.clone(),
timestamp: env.ledger().timestamp(),
description: soroban_sdk::Bytes::from_slice(&env, "Automatic Backup".as_bytes()),
invoice_count: all_invoices.len(),
status: BackupStatus::Active,
};
BackupStorage::store_backup(&env, &backup, Some(&all_invoices))?;
BackupStorage::store_backup_data(&env, &backup_id, &all_invoices);
BackupStorage::add_to_backup_list(&env, &backup_id);
BackupStorage::cleanup_old_backups(&env)?;
Ok(backup_id)
}
pub fn restore_backup(env: Env, admin: Address, backup_id: BytesN<32>) -> Result<(), QuickLendXError> {
AdminStorage::require_admin(&env, &admin)?;
BackupStorage::restore_from_backup(&env, &backup_id).map(|_| ())
}
pub fn get_backups(env: Env) -> Vec<BytesN<32>> {
BackupStorage::get_all_backups(&env)
}
pub fn validate_backup(env: Env, backup_id: BytesN<32>) -> bool {
BackupStorage::validate_backup(&env, &backup_id).is_ok()
}
pub fn get_backup_details(env: Env, backup_id: BytesN<32>) -> Option<Backup> {
BackupStorage::get_backup(&env, &backup_id)
}
pub fn set_backup_retention_policy(
env: Env,
admin: Address,
max_backups: u32,
max_age_seconds: u64,
enabled: bool,
) -> Result<(), QuickLendXError> {
AdminStorage::require_admin(&env, &admin)?;
let policy = BackupRetentionPolicy {
max_backups,
max_age_seconds,
auto_cleanup_enabled: enabled,
};
BackupStorage::set_retention_policy(&env, &policy);
Ok(())
}
pub fn archive_backup(env: Env, admin: Address, backup_id: BytesN<32>) -> Result<(), QuickLendXError> {
AdminStorage::require_admin(&env, &admin)?;
let mut backup = BackupStorage::get_backup(&env, &backup_id).ok_or(QuickLendXError::OperationNotAllowed)?;
backup.status = BackupStatus::Archived;
BackupStorage::update_backup(&env, &backup)?;
BackupStorage::remove_from_backup_list(&env, &backup_id);
Ok(())
}
/// Rebuild customer, tax_id, and tag secondary indexes from the canonical invoice list.
/// Admin-only. Returns the number of invoices processed.
pub fn admin_reindex_invoices(env: Env, admin: Address) -> Result<u32, QuickLendXError> {
AdminStorage::require_admin(&env, &admin)?;
admin.require_auth();
let all_ids = InvoiceStorage::get_all_invoice_ids(&env);
let mut count: u32 = 0;
for invoice_id in all_ids.iter() {
let invoice = match InvoiceStorage::get(&env, &invoice_id) {
Some(inv) => inv,
None => continue,
};
// Rebuild customer index
if let Some(ref name) = invoice.metadata_customer_name {
InvoiceStorage::add_to_customer_index(&env, name, &invoice_id);
}
// Rebuild tax_id index
if let Some(ref tax_id) = invoice.metadata_tax_id {
InvoiceStorage::add_to_tax_id_index(&env, tax_id, &invoice_id);
}
// Rebuild tag indexes
for tag in invoice.tags.iter() {
InvoiceStorage::add_tag_index(&env, &tag, &invoice_id);
}
count += 1;
}
Ok(count)
}
}