-
Notifications
You must be signed in to change notification settings - Fork 424
Expand file tree
/
Copy pathbid.rs
More file actions
1359 lines (1257 loc) · 55.6 KB
/
Copy pathbid.rs
File metadata and controls
1359 lines (1257 loc) · 55.6 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 core::cmp::Ordering;
use soroban_sdk::{contracttype, symbol_short, Address, BytesN, Env, Symbol, Vec};
use crate::admin::AdminStorage;
use crate::errors::QuickLendXError;
use crate::events::{emit_bid_expired, emit_bid_expiry_grace_updated, emit_bid_ttl_updated};
use crate::storage::{bump_persistent, extend_persistent_ttl};
pub use crate::types::{Bid, BidStatus};
/// Storage keys for the per-invoice bid index.
///
/// Instead of storing a single `Vec<BytesN<32>>` under one key (which causes
/// O(n) read+write on every mutation), we use an indexed layout:
///
/// - `Count(invoice_id)` -> `u32` — number of bid entries for this invoice
/// - `Entry(invoice_id, idx)` -> `BytesN<32>` — individual bid ID at position `idx`
///
/// This makes `add_bid_to_invoice` O(1) (write one entry + increment count)
/// instead of O(n) (read full Vec, append, write full Vec), reducing gas
/// on the hot bidding path.
#[derive(Clone)]
#[contracttype]
pub enum BidIndexKey {
Count(BytesN<32>),
Entry(BytesN<32>, u32),
}
// --- Bid TTL configuration ----------------------------------------------------
//
// TTL is stored in whole days and is admin-configurable within [MIN, MAX].
// A zero TTL is explicitly rejected to prevent bids that expire immediately.
// An extreme TTL (> MAX_BID_TTL_DAYS) is rejected to prevent bids that
// effectively never expire, which would lock investor funds indefinitely.
//
// Default: 7 days | Min: 1 day | Max: 30 days
pub const DEFAULT_BID_TTL_DAYS: u64 = 7;
pub const MIN_BID_TTL_DAYS: u64 = 1;
pub const MAX_BID_TTL_DAYS: u64 = 30;
const BID_TTL_KEY: Symbol = symbol_short!("bid_ttl");
const MAX_ACTIVE_BIDS_PER_INVESTOR_KEY: Symbol = symbol_short!("mx_actbd");
const DEFAULT_MAX_ACTIVE_BIDS_PER_INVESTOR: u32 = 20;
const SECONDS_PER_DAY: u64 = 86400;
// --- Bid expiry grace period -------------------------------------------------
//
// A stale `Placed` bid (one whose `expiration_timestamp` has already passed)
// only becomes eligible for the permissionless cleanup entrypoints
// (`cleanup_expired_bids` / `cleanup_expired_bids_paged`, and the lazy-refresh
// helpers they share) once this additional grace window has also elapsed on
// top of `expiration_timestamp`. The grace period exists purely to give the
// investor (or the wider system) a buffer before a third party can force the
// `Placed -> Expired` transition; it never affects acceptance or active-bid
// counting, which continue to key off the raw `expiration_timestamp` via
// `Bid::is_expired`.
//
// Admin-configurable within [MIN, MAX], mirroring the bid TTL knob above.
// Default: 0 (matches the pre-existing behaviour of cleaning up immediately
// at raw expiry) | Min: 0 | Max: 30 days.
pub const DEFAULT_BID_EXPIRY_GRACE_SECONDS: u64 = 0;
pub const MIN_BID_EXPIRY_GRACE_SECONDS: u64 = 0;
pub const MAX_BID_EXPIRY_GRACE_SECONDS: u64 = 30 * SECONDS_PER_DAY;
const BID_EXPIRY_GRACE_KEY: Symbol = symbol_short!("bid_grace");
/// @notice Maximum number of active bids allowed per invoice.
/// @dev An active bid is one in the `Placed` status. Limiting this prevents unbounded
/// storage growth, keeping state reads and iterations highly efficient and within
/// Soroban compute limits. Bids transitioning to terminal states (like Expired, Cancelled)
/// are excluded from this limit, so new bids can replace old ones.
pub const MAX_BIDS_PER_INVOICE: u32 = 50;
/// Sentinel value meaning the investor active-bid limit is disabled (no cap).
pub const INVESTOR_BID_LIMIT_DISABLED: u32 = 0;
/// Snapshot of the current bid TTL configuration returned by `get_bid_ttl_config`.
///
/// Provides all bounds and the active value in a single call so off-chain
/// clients and tests can assert the full configuration without multiple queries.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BidTtlConfig {
/// Currently active TTL in days (admin-set or compile-time default).
pub current_days: u64,
/// Minimum allowed TTL in days (compile-time constant: 1).
pub min_days: u64,
/// Maximum allowed TTL in days (compile-time constant: 30).
pub max_days: u64,
/// Compile-time default TTL in days (7).
pub default_days: u64,
/// `true` when the admin has explicitly set a TTL; `false` when the
/// compile-time default is in use.
pub is_custom: bool,
}
/// Snapshot of the current bid expiry grace-period configuration returned by
/// `get_bid_expiry_grace_config`.
///
/// The grace period is added on top of a bid's `expiration_timestamp` before
/// `cleanup_stale_bid` is allowed to auto-cancel it. See
/// `docs/BID_EXPIRY_GRACE.md` for the full auto-cancellation flow.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BidExpiryGraceConfig {
/// Currently active grace period in seconds (admin-set or compile-time default).
pub current_seconds: u64,
/// Minimum allowed grace period in seconds (compile-time constant: 0).
pub min_seconds: u64,
/// Maximum allowed grace period in seconds (compile-time constant: 30 days).
pub max_seconds: u64,
/// Compile-time default grace period in seconds (0 — immediate cleanup).
pub default_seconds: u64,
/// `true` when the admin has explicitly set a grace period; `false` when
/// the compile-time default is in use.
pub is_custom: bool,
}
/// Snapshot of the current investor active-bid limit configuration.
///
/// Returned by [`BidStorage::get_bid_limit_config`] so that off-chain clients,
/// dashboards, and tests can inspect the complete policy in a single call.
///
/// ### Interpreting `limit`
///
/// | `limit` value | Meaning |
/// |---------------|------------------------------------------------------------|
/// | `0` | Limit is **disabled** - any number of open bids is allowed |
/// | `n > 0` | At most `n` concurrently `Placed` bids per investor |
///
/// Use [`BidStorage::is_investor_bid_limit_active`] for a simple boolean check.
#[contracttype]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct BidLimitConfig {
/// Active limit value. `0` means enforcement is disabled.
pub limit: u32,
/// Compile-time default (`DEFAULT_MAX_ACTIVE_BIDS_PER_INVESTOR` = 20).
pub default_limit: u32,
/// `true` when `limit == 0` (enforcement disabled).
pub is_disabled: bool,
/// `true` when the admin has explicitly set a value (overriding the default).
pub is_custom: bool,
}
// Removed duplicate BidStatus and Bid definitions.
// Using definitions from crate::types.
impl Bid {
/// @notice Returns whether a bid is expired at `current_timestamp`.
/// @dev Expiration is evaluated with an inclusive comparison:
/// `current_timestamp >= expiration_timestamp`.
/// This means a bid is valid until the second before expiry and
/// becomes expired at the expiry timestamp. All cleanup and acceptance
/// paths rely on this same predicate to avoid off-by-one divergence.
/// @param current_timestamp Current ledger timestamp.
/// @return true when the bid has reached or passed its expiry boundary.
pub fn is_expired(&self, current_timestamp: u64) -> bool {
current_timestamp >= self.expiration_timestamp
}
/// @notice Returns whether a bid is eligible for permissionless cleanup
/// (the `Placed -> Expired` transition performed by
/// `cleanup_expired_bids`/`cleanup_expired_bids_paged` and the
/// lazy-refresh helpers) at `current_timestamp`.
/// @dev A bid is excluded from acceptance and active-bid counting as soon
/// as `is_expired` is true (no change there — see
/// `docs/BID_EXPIRY_GRACE.md`), but the actual storage transition and
/// index pruning are deferred until `grace_seconds` (the
/// admin-configurable `bid_expiry_grace_seconds`) have also elapsed
/// on top of `expiration_timestamp`. This gives the investor a
/// buffer before any third party can force the cleanup.
/// @param current_timestamp Current ledger timestamp.
/// @param grace_seconds Configured grace window, from
/// `BidStorage::get_bid_expiry_grace_seconds`.
/// @return true once `current_timestamp >= expiration_timestamp + grace_seconds`.
pub fn is_cleanup_eligible(&self, current_timestamp: u64, grace_seconds: u64) -> bool {
current_timestamp >= self.expiration_timestamp.saturating_add(grace_seconds)
}
/// Backward-compatible helper used by some tests: uses compile-time default.
pub fn default_expiration(now: u64) -> u64 {
now.saturating_add(DEFAULT_BID_TTL_DAYS.saturating_mul(SECONDS_PER_DAY))
}
/// Compute default expiration using configured TTL (admin-configurable).
pub fn default_expiration_with_env(env: &Env, now: u64) -> u64 {
let days = BidStorage::get_bid_ttl_days(env);
now.saturating_add(days.saturating_mul(SECONDS_PER_DAY))
}
}
pub struct BidStorage;
const ALL_BIDS_KEY: Symbol = symbol_short!("all_bids");
impl BidStorage {
fn all_bids_key() -> Symbol {
ALL_BIDS_KEY
}
pub fn get_all_bids(env: &Env) -> Vec<BytesN<32>> {
let result: Vec<BytesN<32>> = env
.storage()
.persistent()
.get(&Self::all_bids_key())
.unwrap_or_else(|| Vec::new(env));
if !result.is_empty() {
extend_persistent_ttl(env, &Self::all_bids_key());
}
result
}
fn add_to_all_bids(env: &Env, bid_id: &BytesN<32>) {
let mut bids = Self::get_all_bids(env);
let mut exists = false;
for bid in bids.iter() {
if bid == *bid_id {
exists = true;
break;
}
}
if !exists {
bids.push_back(bid_id.clone());
env.storage().persistent().set(&Self::all_bids_key(), &bids);
extend_persistent_ttl(env, &Self::all_bids_key());
}
}
fn invoice_bid_count_key(invoice_id: &BytesN<32>) -> BidIndexKey {
BidIndexKey::Count(invoice_id.clone())
}
fn invoice_bid_entry_key(invoice_id: &BytesN<32>, index: u32) -> BidIndexKey {
BidIndexKey::Entry(invoice_id.clone(), index)
}
fn investor_bids_key(investor: &Address) -> (soroban_sdk::Symbol, Address) {
(symbol_short!("bid_inv"), investor.clone())
}
pub fn get_bids_by_investor_all(env: &Env, investor: &Address) -> Vec<BytesN<32>> {
let key = Self::investor_bids_key(investor);
let result: Vec<BytesN<32>> = env
.storage()
.persistent()
.get(&key)
.unwrap_or_else(|| Vec::new(env));
if !result.is_empty() {
extend_persistent_ttl(env, &key);
}
result
}
fn add_to_investor_bids(env: &Env, investor: &Address, bid_id: &BytesN<32>) {
let key = Self::investor_bids_key(investor);
let mut bids = Self::get_bids_by_investor_all(env, investor);
let mut exists = false;
for bid in bids.iter() {
if bid == *bid_id {
exists = true;
break;
}
}
if !exists {
bids.push_back(bid_id.clone());
env.storage().persistent().set(&key, &bids);
extend_persistent_ttl(env, &key);
}
}
pub fn store_bid(env: &Env, bid: &Bid) {
crate::assert_view_only!(env);
env.storage().persistent().set(&bid.bid_id, bid);
bump_persistent(env, &bid.bid_id);
// Add to investor index
Self::add_to_investor_bids(env, &bid.investor, &bid.bid_id);
// Add to global index
Self::add_to_all_bids(env, &bid.bid_id);
}
pub fn get_bid(env: &Env, bid_id: &BytesN<32>) -> Option<Bid> {
let result = env.storage().persistent().get(bid_id);
if result.is_some() {
bump_persistent(env, &bid_id);
}
result
}
pub fn update_bid(env: &Env, bid: &Bid) {
crate::assert_view_only!(env);
env.storage().persistent().set(&bid.bid_id, bid);
bump_persistent(env, &bid.bid_id);
}
pub fn get_bids_for_invoice(env: &Env, invoice_id: &BytesN<32>) -> Vec<BytesN<32>> {
let count_key = Self::invoice_bid_count_key(invoice_id);
let count: u32 = env.storage().persistent().get(&count_key).unwrap_or(0);
if count > 0 {
bump_persistent(env, &count_key);
}
let mut bids = Vec::new(env);
let mut idx: u32 = 0;
while idx < count {
let entry_key = Self::invoice_bid_entry_key(invoice_id, idx);
if let Some(bid_id) = env.storage().persistent().get(&entry_key) {
bump_persistent(env, &entry_key);
bids.push_back(bid_id);
}
idx += 1;
}
bids
}
pub fn get_active_bid_count(env: &Env, invoice_id: &BytesN<32>) -> u32 {
let _ = Self::refresh_expired_bids(env, invoice_id);
let bid_ids = Self::get_bids_for_invoice(env, invoice_id);
let mut active_count = 0u32;
let mut idx: u32 = 0;
while idx < bid_ids.len() {
let bid_id = bid_ids.get(idx).unwrap();
if let Some(bid) = Self::get_bid(env, &bid_id) {
if bid.status == BidStatus::Placed {
active_count += 1;
}
}
idx += 1;
}
active_count
}
/// Return the currently active bid TTL in days.
///
/// Falls back to `DEFAULT_BID_TTL_DAYS` (7) when no admin override has
/// been stored, ensuring deterministic behaviour even on a fresh contract.
pub fn get_bid_ttl_days(env: &Env) -> u64 {
env.storage()
.instance()
.get(&BID_TTL_KEY)
.unwrap_or(DEFAULT_BID_TTL_DAYS)
}
/// Return the full TTL configuration snapshot.
///
/// Includes the active value, compile-time bounds, the default, and a flag
/// indicating whether the admin has overridden the default.
pub fn get_bid_ttl_config(env: &Env) -> BidTtlConfig {
let stored: Option<u64> = env.storage().instance().get(&BID_TTL_KEY);
BidTtlConfig {
current_days: stored.unwrap_or(DEFAULT_BID_TTL_DAYS),
min_days: MIN_BID_TTL_DAYS,
max_days: MAX_BID_TTL_DAYS,
default_days: DEFAULT_BID_TTL_DAYS,
is_custom: stored.is_some(),
}
}
/// Admin-only: set bid TTL in days.
///
/// ### Bounds
/// - Minimum: `MIN_BID_TTL_DAYS` (1) - prevents zero-TTL bids that expire
/// immediately and can never be accepted.
/// - Maximum: `MAX_BID_TTL_DAYS` (30) - prevents extreme windows that
/// would lock investor funds for unreasonably long periods.
///
/// ### Errors
/// Returns `InvalidBidTtl` (not `InvalidAmount`) for a clear, auditable
/// error signal distinct from monetary validation failures.
///
/// ### Events
/// Emits `ttl_upd` with the old value, new value, admin address, and
/// ledger timestamp so off-chain monitors can track every config change.
pub fn set_bid_ttl_days(env: &Env, admin: &Address, days: u64) -> Result<u64, QuickLendXError> {
admin.require_auth();
AdminStorage::require_admin(env, admin)?;
// Explicit zero check first for a clear error message.
if days == 0 {
return Err(QuickLendXError::InvalidBidTtl);
}
if !(MIN_BID_TTL_DAYS..=MAX_BID_TTL_DAYS).contains(&days) {
return Err(QuickLendXError::InvalidBidTtl);
}
let old_days = Self::get_bid_ttl_days(env);
env.storage().instance().set(&BID_TTL_KEY, &days);
emit_bid_ttl_updated(env, old_days, days, admin);
Ok(days)
}
/// Admin-only: reset bid TTL to the compile-time default (7 days).
///
/// Removes the stored override so `get_bid_ttl_days` returns the default
/// and `get_bid_ttl_config` reports `is_custom = false`.
///
/// ### Events
/// Emits `ttl_upd` with the old value and `DEFAULT_BID_TTL_DAYS` as the
/// new value so the reset is fully auditable.
pub fn reset_bid_ttl_to_default(env: &Env, admin: &Address) -> Result<u64, QuickLendXError> {
admin.require_auth();
AdminStorage::require_admin(env, admin)?;
let old_days = Self::get_bid_ttl_days(env);
env.storage().instance().remove(&BID_TTL_KEY);
emit_bid_ttl_updated(env, old_days, DEFAULT_BID_TTL_DAYS, admin);
Ok(DEFAULT_BID_TTL_DAYS)
}
/// Return the currently active bid expiry grace period, in seconds.
///
/// Falls back to `DEFAULT_BID_EXPIRY_GRACE_SECONDS` (0 — no grace, matching
/// pre-existing behaviour) when no admin override has been stored.
pub fn get_bid_expiry_grace_seconds(env: &Env) -> u64 {
env.storage()
.instance()
.get(&BID_EXPIRY_GRACE_KEY)
.unwrap_or(DEFAULT_BID_EXPIRY_GRACE_SECONDS)
}
/// Return the full bid expiry grace-period configuration snapshot.
pub fn get_bid_expiry_grace_config(env: &Env) -> BidExpiryGraceConfig {
let stored: Option<u64> = env.storage().instance().get(&BID_EXPIRY_GRACE_KEY);
BidExpiryGraceConfig {
current_seconds: stored.unwrap_or(DEFAULT_BID_EXPIRY_GRACE_SECONDS),
min_seconds: MIN_BID_EXPIRY_GRACE_SECONDS,
max_seconds: MAX_BID_EXPIRY_GRACE_SECONDS,
default_seconds: DEFAULT_BID_EXPIRY_GRACE_SECONDS,
is_custom: stored.is_some(),
}
}
/// Admin-only: set the bid expiry grace period, in seconds.
///
/// ### Bounds
/// - Minimum: `MIN_BID_EXPIRY_GRACE_SECONDS` (0) - allows cleanup
/// immediately at expiry when no buffer is desired.
/// - Maximum: `MAX_BID_EXPIRY_GRACE_SECONDS` (30 days) - prevents a grace
/// window so long that stale bids never become cleanable.
///
/// ### Errors
/// Returns `InvalidTimestamp` for an out-of-bounds value, matching the
/// convention used by `defaults::resolve_grace_period` for the analogous
/// invoice grace period.
///
/// ### Events
/// Emits `BidExpiryGraceUpdated` with the old value, new value, admin
/// address, and ledger timestamp so off-chain monitors can track every
/// config change.
pub fn set_bid_expiry_grace_seconds(
env: &Env,
admin: &Address,
seconds: u64,
) -> Result<u64, QuickLendXError> {
admin.require_auth();
AdminStorage::require_admin(env, admin)?;
if seconds > MAX_BID_EXPIRY_GRACE_SECONDS {
return Err(QuickLendXError::InvalidTimestamp);
}
let old_seconds = Self::get_bid_expiry_grace_seconds(env);
env.storage().instance().set(&BID_EXPIRY_GRACE_KEY, &seconds);
emit_bid_expiry_grace_updated(env, old_seconds, seconds, admin);
Ok(seconds)
}
/// Admin-only: reset the bid expiry grace period to the compile-time
/// default (0).
///
/// Removes the stored override so `get_bid_expiry_grace_seconds` returns
/// the default and `get_bid_expiry_grace_config` reports `is_custom = false`.
pub fn reset_bid_expiry_grace_to_default(
env: &Env,
admin: &Address,
) -> Result<u64, QuickLendXError> {
admin.require_auth();
AdminStorage::require_admin(env, admin)?;
let old_seconds = Self::get_bid_expiry_grace_seconds(env);
env.storage().instance().remove(&BID_EXPIRY_GRACE_KEY);
emit_bid_expiry_grace_updated(env, old_seconds, DEFAULT_BID_EXPIRY_GRACE_SECONDS, admin);
Ok(DEFAULT_BID_EXPIRY_GRACE_SECONDS)
}
/// Get configured max number of active (Placed) bids per investor across all invoices.
/// A value of 0 disables this limit.
pub fn get_max_active_bids_per_investor(env: &Env) -> u32 {
env.storage()
.instance()
.get(&MAX_ACTIVE_BIDS_PER_INVESTOR_KEY)
.unwrap_or(DEFAULT_MAX_ACTIVE_BIDS_PER_INVESTOR)
}
/// Return a complete snapshot of the investor active-bid limit policy.
///
/// Analogous to [`BidStorage::get_bid_ttl_config`] for TTL. Intended
/// for off-chain dashboards, admin panels, and test assertions.
///
pub fn get_bid_limit_config(env: &Env) -> BidLimitConfig {
let stored: Option<u32> = env
.storage()
.instance()
.get(&MAX_ACTIVE_BIDS_PER_INVESTOR_KEY);
let limit = stored.unwrap_or(DEFAULT_MAX_ACTIVE_BIDS_PER_INVESTOR);
BidLimitConfig {
limit,
default_limit: DEFAULT_MAX_ACTIVE_BIDS_PER_INVESTOR,
is_disabled: limit == INVESTOR_BID_LIMIT_DISABLED,
is_custom: stored.is_some(),
}
}
/// Returns `true` when the investor active-bid limit is enforced.
///
/// Returns `false` when the limit has been set to `0`
/// (`INVESTOR_BID_LIMIT_DISABLED`), meaning bids will **not** be rejected
/// for having too many open positions.
///
/// ### Usage
///
/// Prefer this over comparing `get_max_active_bids_per_investor() != 0`
/// directly, to keep the zero-is-disabled semantic in one place.
///
/// ```ignore
/// if BidStorage::is_investor_bid_limit_active(&env) {
/// // enforcement is on; check count
/// }
/// ```
pub fn is_investor_bid_limit_active(env: &Env) -> bool {
Self::get_max_active_bids_per_investor(env) != INVESTOR_BID_LIMIT_DISABLED
}
/// This function is **read-only** with respect to the limit policy itself.
/// Setting or changing the limit requires admin authority and goes through
/// [`BidStorage::set_max_active_bids_per_investor`].
pub fn investor_has_reached_bid_limit(env: &Env, investor: &Address) -> bool {
let limit = Self::get_max_active_bids_per_investor(env);
// Limit of 0 means "disabled" - never block a placement.
if limit == INVESTOR_BID_LIMIT_DISABLED {
return false;
}
let active = Self::count_active_placed_bids_for_investor(env, investor);
active >= limit
}
/// Admin-only: set max number of active (Placed) bids per investor across all invoices.
/// A value of 0 disables this limit.
pub fn set_max_active_bids_per_investor(
env: &Env,
admin: &Address,
limit: u32,
) -> Result<u32, QuickLendXError> {
admin.require_auth();
AdminStorage::require_admin(env, admin)?;
env.storage()
.instance()
.set(&MAX_ACTIVE_BIDS_PER_INVESTOR_KEY, &limit);
Ok(limit)
}
/// Admin-only: reset the investor active-bid limit to the compile-time
/// default (`DEFAULT_MAX_ACTIVE_BIDS_PER_INVESTOR` = 20).
///
/// Removes the stored override so `get_bid_limit_config` reports
/// `is_custom = false` and `is_disabled = false`.
///
/// Useful for reverting a previous `set_max_active_bids_per_investor(0)`
/// call when the unrestricted window should end.
pub fn reset_max_active_bids_per_investor(
env: &Env,
admin: &Address,
) -> Result<u32, QuickLendXError> {
admin.require_auth();
AdminStorage::require_admin(env, admin)?;
env.storage()
.instance()
.remove(&MAX_ACTIVE_BIDS_PER_INVESTOR_KEY);
Ok(DEFAULT_MAX_ACTIVE_BIDS_PER_INVESTOR)
}
/// @notice Prunes expired bids from the investor's global index.
///
/// # Purpose
/// Maintains the investor's bid list to prevent unbounded growth with historical expired bids.
/// Ensures that investor active-bid limit checks (e.g., MAX_ACTIVE_BIDS_PER_INVESTOR) operate
/// in O(active_bids) time, not O(all_historical_bids).
///
/// # Invariants
/// - Terminal bids (Accepted, Withdrawn, Cancelled) are kept in the index for historical audit
/// - Expired bids are pruned to keep the list size manageable
/// - Placed (non-expired) bids are preserved
/// - The index after refresh accurately reflects countable active bids for rate-limiting
///
/// # Grace period
/// A `Placed` bid only transitions to `Expired` once it has passed its
/// `expiration_timestamp` by at least the configured
/// `bid_expiry_grace_seconds` (see `BidStorage::get_bid_expiry_grace_seconds`).
/// It is still excluded from acceptance and active-bid counts as soon as
/// its raw TTL passes; the grace period only delays this storage
/// transition and index pruning. See `docs/BID_LIFECYCLE_DIAGRAM.md`.
///
/// # Parameters
/// @param env The Soroban environment
/// @param investor The address of the investor
///
/// @return newly_expired The number of bids that transitioned from Placed to Expired in this call
pub fn refresh_investor_bids(env: &Env, investor: &Address) -> u32 {
let current_timestamp = env.ledger().timestamp();
let grace_seconds = Self::get_bid_expiry_grace_seconds(env);
let bid_ids = Self::get_bids_by_investor_all(env, investor);
let mut active = Vec::new(env);
let mut newly_expired = 0u32;
for bid_id in bid_ids.iter() {
if let Some(mut bid) = Self::get_bid(env, &bid_id) {
// Determine if this bid should remain in the investor's active index.
// We keep terminal states (Accepted, Withdrawn, Cancelled) in the index
// but prune Expired ones to keep the list size manageable.
if bid.status == BidStatus::Placed {
if bid.is_cleanup_eligible(current_timestamp, grace_seconds) {
bid.status = BidStatus::Expired;
Self::update_bid(env, &bid);
emit_bid_expired(env, &bid);
newly_expired = newly_expired.saturating_add(1);
// Do not push to active -> prunes this expired bid
} else {
active.push_back(bid_id);
}
} else if bid.status == BidStatus::Expired {
// Prune already expired bids from the index
} else {
// Keep terminal states: Accepted, Withdrawn, Cancelled
active.push_back(bid_id);
}
}
}
// Only update storage if the list actually shrank
if active.len() < bid_ids.len() {
let key = Self::investor_bids_key(investor);
env.storage().instance().set(&key, &active);
}
newly_expired
}
/// @notice Count currently active (Placed) bids for an investor across all invoices.
///
/// # Purpose
/// Returns the count of non-expired Placed bids for rate limiting and bid management.
/// Used by bidding logic to enforce MAX_ACTIVE_BIDS_PER_INVESTOR.
///
/// # Invariants
/// - Includes only Placed bids that have not yet reached their expiration timestamp
/// - Excludes terminal states (Accepted, Withdrawn, Cancelled) and Expired bids
/// - The count is always <= the investor's active bid limit (if enforced)
///
/// # Side Effects
/// - Calls refresh_investor_bids, which may update the investor's bid index to prune expired bids
/// - Does NOT modify bid statuses (transitions happen within refresh_investor_bids)
///
/// @param env The Soroban environment
/// @param investor The address of the investor
/// @return count The number of non-expired Placed bids across all invoices
pub fn count_active_placed_bids_for_investor(env: &Env, investor: &Address) -> u32 {
let _ = Self::refresh_investor_bids(env, investor);
let current_timestamp = env.ledger().timestamp();
let bid_ids = Self::get_bids_by_investor_all(env, investor);
let mut count = 0u32;
for bid_id in bid_ids.iter() {
if let Some(bid) = Self::get_bid(env, &bid_id) {
if bid.status == BidStatus::Placed && !bid.is_expired(current_timestamp) {
count = count.saturating_add(1);
}
}
}
count
}
pub fn add_bid_to_invoice(env: &Env, invoice_id: &BytesN<32>, bid_id: &BytesN<32>) {
crate::assert_view_only!(env);
let count_key = Self::invoice_bid_count_key(invoice_id);
let count: u32 = env.storage().persistent().get(&count_key).unwrap_or(0);
let entry_key = Self::invoice_bid_entry_key(invoice_id, count);
env.storage().persistent().set(&entry_key, bid_id);
bump_persistent(env, &entry_key);
env.storage().persistent().set(&count_key, &(count + 1));
bump_persistent(env, &count_key);
}
/// @notice Scans and prunes expired bids from an invoice's bid list.
/// @dev Maintains O(N) where N is current bids on invoice. Pruning keeps N small.
///
/// # Invariants
/// - Invariant 1: Terminal bids (Accepted, Withdrawn, Cancelled) are NEVER modified or removed
/// - Invariant 2: Active Placed bids are preserved if not yet expired
/// - Invariant 3: Expired/orphaned bids are removed from the index to prevent unbounded growth
/// - Invariant 4: The operation is idempotent - calling multiple times on same state yields same result
/// - Invariant 5: Cleanup is bounded by O(N) compute and storage changes
///
/// # Security Properties
/// - Cleanup cannot corrupt active bid records; terminal states are always preserved
/// - Cleanup cannot trigger DoS via unbounded iteration (index size capped at MAX_BIDS_PER_INVOICE)
/// - Cleanup is deterministic: same ledger timestamp + bid set -> same result always
///
/// @param env The Soroban environment (for timestamp, storage access).
/// @param invoice_id The unique identifier of the invoice.
/// @return cleaned_count Total number of bids cleaned (transitioned to Expired or already Expired bids removed from index).
///
/// A `Placed` bid transitions to `Expired` only after `expiration_timestamp
/// + bid_expiry_grace_seconds` has elapsed; see `Bid::is_cleanup_eligible`.
pub fn refresh_expired_bids(env: &Env, invoice_id: &BytesN<32>) -> u32 {
let current_timestamp = env.ledger().timestamp();
let grace_seconds = Self::get_bid_expiry_grace_seconds(env);
let count_key = Self::invoice_bid_count_key(invoice_id);
let old_count: u32 = env.storage().persistent().get(&count_key).unwrap_or(0);
if old_count > 0 {
bump_persistent(env, &count_key);
}
let mut cleaned_count = 0u32;
let mut write_idx: u32 = 0;
let mut read_idx: u32 = 0;
while read_idx < old_count {
let entry_key = Self::invoice_bid_entry_key(invoice_id, read_idx);
let should_keep = env
.storage()
.persistent()
.get::<_, BytesN<32>>(&entry_key)
.is_some_and(|bid_id| {
bump_persistent(env, &entry_key);
if let Some(mut bid) = Self::get_bid(env, &bid_id) {
let is_terminal = bid.status == BidStatus::Accepted
|| bid.status == BidStatus::Withdrawn
|| bid.status == BidStatus::Cancelled;
if is_terminal {
true
} else if bid.status == BidStatus::Placed
&& bid.is_cleanup_eligible(current_timestamp, grace_seconds)
{
bid.status = BidStatus::Expired;
Self::update_bid(env, &bid);
emit_bid_expired(env, &bid);
cleaned_count = cleaned_count.saturating_add(1);
false
} else if bid.status == BidStatus::Expired {
cleaned_count = cleaned_count.saturating_add(1);
false
} else {
true
}
} else {
cleaned_count = cleaned_count.saturating_add(1);
false
}
});
if should_keep {
if write_idx != read_idx {
let src = Self::invoice_bid_entry_key(invoice_id, read_idx);
let dst = Self::invoice_bid_entry_key(invoice_id, write_idx);
if let Some(bid_id) = env.storage().persistent().get::<_, BytesN<32>>(&src) {
bump_persistent(env, &src);
env.storage().persistent().set(&dst, &bid_id);
bump_persistent(env, &dst);
}
}
write_idx += 1;
}
read_idx += 1;
}
// Remove stale entries beyond the new write_idx
while write_idx < old_count {
env.storage()
.persistent()
.remove(&Self::invoice_bid_entry_key(invoice_id, write_idx));
write_idx += 1;
}
if cleaned_count > 0 {
let new_count = old_count.saturating_sub(cleaned_count);
env.storage().persistent().set(&count_key, &new_count);
bump_persistent(env, &count_key);
}
cleaned_count
}
/// @notice Public interface to trigger cleanup of expired bids for a specific invoice.
///
/// # Purpose
/// Removes expired bids from an invoice's bid list to prevent storage bloat.
/// Can be called proactively by off-chain indexers or triggered during on-chain operations.
///
/// # Idempotency Guarantee
/// This operation is fully idempotent: calling it multiple times on the same invoice
/// and ledger timestamp will always:
/// - Return 0 on subsequent calls (nothing new to clean)
/// - Leave the index state unchanged
/// - Never corrupt terminal bid records
///
/// # DoS Safety
/// - Cleanup is O(N) where N = number of bids on invoice (capped at MAX_BIDS_PER_INVOICE)
/// - No unbounded allocations or recursive calls
/// - No external calls; purely state transition
/// - Gas cost scales predictably with bid count
///
/// # Terminal Bid Preservation
/// Accepted, Withdrawn, and Cancelled bids are NEVER touched by cleanup,
/// even if they have passed their expiration timestamp. Only Placed bids
/// can transition to Expired and be pruned.
///
/// # Returns
/// The count of bids cleaned (including newly expired and already-expired bids removed).
/// On the second call with unchanged ledger time, returns 0.
///
/// # Example
/// ```ignore
/// let cleaned = BidStorage::cleanup_expired_bids(&env, &invoice_id);
/// // First call: returns 3 (3 expired Placed bids transitioned and removed)
/// // Second call: returns 0 (idempotent; nothing left to clean)
/// ```
pub fn cleanup_expired_bids(env: &Env, invoice_id: &BytesN<32>) -> u32 {
Self::refresh_expired_bids(env, invoice_id)
}
/// @notice Paginated cleanup of expired bids for a specific invoice.
///
/// # Purpose
/// Removes expired bids from an invoice's bid list with pagination support.
/// Allows operators to process large bid lists in multiple transactions to avoid
/// instruction budget exhaustion at maximum capacity (MAX_BIDS_PER_INVOICE = 50).
///
/// # Pagination Parameters
/// - `offset`: Starting position in the bid list (0-indexed)
/// - `limit`: Maximum number of bids to process in this call (capped at MAX_BIDS_PER_INVOICE)
///
/// # Instruction Budget Safety
/// By using pagination, operators can split cleanup of 50 bids across multiple transactions:
/// - Single call with limit=50: ~500-1000 instructions (worst-case)
/// - Two calls with limit=25: ~250-500 instructions each (safe margin)
/// - Five calls with limit=10: ~100-200 instructions each (very safe)
///
/// # Idempotency Guarantee
/// This operation is fully idempotent: calling it multiple times on the same invoice
/// and ledger timestamp will always:
/// - Return 0 on subsequent calls (nothing new to clean)
/// - Leave the index state unchanged
/// - Never corrupt terminal bid records
///
/// # Terminal Bid Preservation
/// Accepted, Withdrawn, and Cancelled bids are NEVER touched by cleanup,
/// even if they have passed their expiration timestamp. Only Placed bids
/// can transition to Expired and be pruned.
///
/// # Returns
/// A tuple (cleaned_count, total_count) where:
/// - `cleaned_count`: Number of bids cleaned in this call
/// - `total_count`: Total number of bids on invoice after cleanup
///
/// # Example
/// ```ignore
/// // Process 50 bids in two transactions
/// let (cleaned1, total1) = BidStorage::cleanup_expired_bids_paged(&env, &invoice_id, 0, 25);
/// // First call: returns (3, 47) - cleaned 3 bids, 47 remain
/// let (cleaned2, total2) = BidStorage::cleanup_expired_bids_paged(&env, &invoice_id, 25, 25);
/// // Second call: returns (0, 47) - no more to clean, 47 remain
/// ```
pub fn cleanup_expired_bids_paged(
env: &Env,
invoice_id: &BytesN<32>,
offset: u32,
limit: u32,
) -> (u32, u32) {
// Validate and cap pagination parameters
let capped_limit = limit.min(MAX_BIDS_PER_INVOICE);
// Prevent overflow: offset + limit must not exceed u32::MAX
if offset > u32::MAX - capped_limit {
return (0, 0);
}
let current_timestamp = env.ledger().timestamp();
let grace_seconds = Self::get_bid_expiry_grace_seconds(env);
let count_key = Self::invoice_bid_count_key(invoice_id);
let old_count: u32 = env.storage().persistent().get(&count_key).unwrap_or(0);
if old_count > 0 {
bump_persistent(env, &count_key);
}
// If offset is beyond the current count, return early
if offset >= old_count {
return (0, old_count);
}
let end_idx = (offset + capped_limit).min(old_count);
let mut cleaned_count = 0u32;
let mut write_idx: u32 = offset;
let mut read_idx: u32 = offset;
// Process only the requested range [offset, end_idx)
while read_idx < end_idx {
let entry_key = Self::invoice_bid_entry_key(invoice_id, read_idx);
let should_keep = env
.storage()
.persistent()
.get::<_, BytesN<32>>(&entry_key)
.is_some_and(|bid_id| {
bump_persistent(env, &entry_key);
if let Some(mut bid) = Self::get_bid(env, &bid_id) {
let is_terminal = bid.status == BidStatus::Accepted
|| bid.status == BidStatus::Withdrawn
|| bid.status == BidStatus::Cancelled;
if is_terminal {
true
} else if bid.status == BidStatus::Placed
&& bid.is_cleanup_eligible(current_timestamp, grace_seconds)
{
bid.status = BidStatus::Expired;
Self::update_bid(env, &bid);
emit_bid_expired(env, &bid);
cleaned_count = cleaned_count.saturating_add(1);
false
} else if bid.status == BidStatus::Expired {
cleaned_count = cleaned_count.saturating_add(1);
false
} else {
true
}
} else {
cleaned_count = cleaned_count.saturating_add(1);
false
}
});
if should_keep {
if write_idx != read_idx {
let src = Self::invoice_bid_entry_key(invoice_id, read_idx);
let dst = Self::invoice_bid_entry_key(invoice_id, write_idx);
if let Some(bid_id) = env.storage().persistent().get::<_, BytesN<32>>(&src) {
bump_persistent(env, &src);
env.storage().persistent().set(&dst, &bid_id);
bump_persistent(env, &dst);
}
}
write_idx += 1;
}
read_idx += 1;
}
// Only update count if we processed the entire list (offset=0 and end_idx=old_count)
// Otherwise, the full cleanup will handle the final count update
if offset == 0 && end_idx == old_count && cleaned_count > 0 {
let new_count = old_count.saturating_sub(cleaned_count);
env.storage().persistent().set(&count_key, &new_count);
bump_persistent(env, &count_key);
(cleaned_count, new_count)
} else {
// For partial cleanup, return the cleaned count and current total
(cleaned_count, old_count.saturating_sub(cleaned_count))
}
}
pub fn get_bid_records_for_invoice(env: &Env, invoice_id: &BytesN<32>) -> Vec<Bid> {
let _ = Self::refresh_expired_bids(env, invoice_id);
let mut bids = Vec::new(env);
for bid_id in Self::get_bids_for_invoice(env, invoice_id).iter() {
if let Some(bid) = Self::get_bid(env, &bid_id) {
bids.push_back(bid);
}
}
bids
}
pub fn get_bids_by_status(env: &Env, invoice_id: &BytesN<32>, status: BidStatus) -> Vec<Bid> {
let mut filtered = Vec::new(env);
let records = Self::get_bid_records_for_invoice(env, invoice_id);
let mut idx: u32 = 0;
while idx < records.len() {
let bid = records.get(idx).unwrap();
if bid.status == status {
filtered.push_back(bid);
}
idx += 1;
}
filtered
}
pub fn get_bids_by_investor(
env: &Env,
invoice_id: &BytesN<32>,
investor: &Address,
) -> Vec<Bid> {
let mut filtered = Vec::new(env);
let records = Self::get_bid_records_for_invoice(env, invoice_id);
let mut idx: u32 = 0;
while idx < records.len() {
let bid = records.get(idx).unwrap();
if &bid.investor == investor {
filtered.push_back(bid);
}
idx += 1;
}
filtered
}