-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathlib.rs
More file actions
1246 lines (1150 loc) · 47.3 KB
/
Copy pathlib.rs
File metadata and controls
1246 lines (1150 loc) · 47.3 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
#![no_std]
use soroban_sdk::{
contract, contractimpl, panic_with_error, token, Address, BytesN, Env, IntoVal, Symbol, Vec,
};
mod constants;
mod errors;
mod events;
mod test;
mod types;
pub use constants::*;
pub use errors::*;
pub use types::*;
/// Default maximum utilization cap (in basis points) written at
/// `initialize()` time. 8500 bps = 85%. This is the single source of truth for
/// the default: `totals()`'s fallback reads the same constant, so the two call
/// sites can never silently desync if the default is ever changed.
pub const DEFAULT_MAX_UTILIZATION_BPS: u32 = 8500;
#[contract]
pub struct PoolContract;
#[derive(Clone, Copy)]
struct PoolTotals {
shares: u128,
deposits: u128,
funded: u128,
yield_distributed: u128,
loss_realised: u128,
active_invoices: u32,
max_utilization_bps: u32,
}
#[contractimpl]
impl PoolContract {
/// Initializes the pool contract with admin and external contract references.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `admin` - The admin address for this contract.
/// * `invoice_contract` - The invoice contract address.
/// * `escrow_contract` - The escrow contract address.
/// * `usdc_asset` - The USDC asset address.
/// * `registry_contract` - The registry contract address, consulted by
/// `fund_invoice` to re-verify the issuer and buyer are still verified
/// before pool capital is committed.
///
/// # Auth
/// Requires authorization from `admin`.
///
/// # Wiring order
/// `escrow_contract` must already be initialized before this call, since
/// `initialize` cross-checks `escrow_contract.get_usdc_asset()` against
/// its own `usdc_asset` to catch a misconfigured deploy where escrow was
/// wired up with a different token.
///
/// # Panics
/// * `AlreadyInitialized` if the contract has already been initialized.
/// * `InvalidConfiguration` if any two of `admin`, `invoice_contract`,
/// `escrow_contract`, `usdc_asset`, and `registry_contract` are the
/// same address.
/// * `EscrowAssetMismatch` if `escrow_contract`'s configured USDC asset
/// does not match `usdc_asset`.
///
/// # Returns
/// * `()` - No value is returned.
///
/// # Example
/// ```ignore
/// escrow_client.initialize(&admin, &pool, &invoice, &usdc); // escrow first
/// client.initialize(&admin, &invoice, &escrow, &usdc, ®istry);
/// ```
pub fn initialize(
env: Env,
admin: Address,
invoice_contract: Address,
escrow_contract: Address,
usdc_asset: Address,
registry_contract: Address,
) {
if Self::admin(&env).is_some() {
panic_with_error!(&env, PoolError::AlreadyInitialized);
}
if admin == invoice_contract
|| admin == escrow_contract
|| admin == usdc_asset
|| admin == registry_contract
|| invoice_contract == escrow_contract
|| invoice_contract == usdc_asset
|| invoice_contract == registry_contract
|| escrow_contract == usdc_asset
|| escrow_contract == registry_contract
|| usdc_asset == registry_contract
{
panic_with_error!(&env, PoolError::InvalidConfiguration);
}
// Cross-check that the escrow contract being wired in was itself
// initialized with the same usdc_asset. A mismatch here would only
// otherwise surface later as a failed token transfer inside
// fund_invoice's escrow.lock call, since escrow.lock pulls funds
// using escrow's own configured token client. This requires
// escrow_contract to already be initialized at the time pool.initialize
// is called.
let args = Vec::new(&env);
let escrow_usdc_asset: Address =
env.invoke_contract(&escrow_contract, &Symbol::new(&env, "get_usdc_asset"), args);
if escrow_usdc_asset != usdc_asset {
panic_with_error!(&env, PoolError::EscrowAssetMismatch);
}
admin.require_auth();
env.storage().instance().set(&DataKey::Admin, &admin);
env.storage()
.instance()
.set(&DataKey::InvoiceContract, &invoice_contract);
env.storage()
.instance()
.set(&DataKey::EscrowContract, &escrow_contract);
env.storage()
.instance()
.set(&DataKey::UsdcAsset, &usdc_asset);
env.storage()
.instance()
.set(&DataKey::RegistryContract, ®istry_contract);
env.storage().instance().set(&DataKey::TotalShares, &0u128);
env.storage()
.instance()
.set(&DataKey::TotalDeposits, &0u128);
env.storage().instance().set(&DataKey::TotalFunded, &0u128);
env.storage()
.instance()
.set(&DataKey::TotalYieldDistributed, &0u128);
env.storage()
.instance()
.set(&DataKey::ActiveInvoiceCount, &0u32);
env.storage()
.instance()
.set(&DataKey::MaxUtilizationBps, &DEFAULT_MAX_UTILIZATION_BPS);
env.storage()
.instance()
.set(&DataKey::TotalLossRealised, &0u128);
Self::extend_instance_ttl(&env);
events::pool_initialized(
&env,
&admin,
&invoice_contract,
&escrow_contract,
&usdc_asset,
);
}
/// Returns the USDC asset used by the pool.
///
/// # Arguments
/// * `env` - The Soroban environment.
///
/// # Auth
/// No authorization is required.
///
/// # Panics
/// * Panics if the contract has not been initialized (missing `UsdcAsset`).
///
/// # Returns
/// * `Address` - The USDC asset address.
///
/// # Example
/// ```ignore
/// let asset = client.get_usdc_asset();
/// ```
pub fn get_usdc_asset(env: Env) -> Address {
Self::usdc(&env)
}
/// Returns the admin address for the pool.
///
/// # Arguments
/// * `env` - The Soroban environment.
///
/// # Auth
/// No authorization is required.
///
/// # Panics
/// * Panics if the contract has not been initialized (missing `Admin`).
///
/// # Returns
/// * `Address` - The admin address.
///
/// # Example
/// ```ignore
/// let admin = client.get_admin();
/// ```
pub fn get_admin(env: Env) -> Address {
Self::admin(&env).expect("pool is not initialized: admin missing")
}
/// Returns the invoice contract address configured for the pool.
///
/// # Arguments
/// * `env` - The Soroban environment.
///
/// # Auth
/// No authorization is required.
///
/// # Panics
/// * Panics if the contract has not been initialized (missing `InvoiceContract`).
///
/// # Returns
/// * `Address` - The invoice contract address.
///
/// # Example
/// ```ignore
/// let invoice = client.get_invoice_contract();
/// ```
pub fn get_invoice_contract(env: Env) -> Address {
Self::invoice_contract(&env).expect("pool is not initialized: invoice contract missing")
}
/// Returns the escrow contract address configured for the pool.
///
/// # Arguments
/// * `env` - The Soroban environment.
///
/// # Auth
/// No authorization is required.
///
/// # Panics
/// * Panics if the contract has not been initialized (missing `EscrowContract`).
///
/// # Returns
/// * `Address` - The escrow contract address.
///
/// # Example
/// ```ignore
/// let escrow = client.get_escrow_contract();
/// ```
pub fn get_escrow_contract(env: Env) -> Address {
Self::escrow_contract(&env).expect("pool is not initialized: escrow contract missing")
}
/// Deposits USDC from an LP and issues pool shares.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `lp` - The liquidity provider address.
/// * `usdc_amount` - The amount of USDC to deposit.
///
/// # Auth
/// Requires self-authorization from `lp` (via `lp.require_auth()`).
///
/// # Panics
/// * `InvalidAmount` if `usdc_amount` is zero or if initial deposit is below `MIN_INITIAL_DEPOSIT`.
/// * `MinimumDeposit` if the deposit is too small to mint at least 1 share
/// at the current share price (prevents 0-share dust deposits).
/// * `Overflow` if `usdc_amount * total_shares` would overflow `u128`
/// while computing the proportional share price.
///
/// # Returns
/// * `u128` - The number of shares issued.
///
/// # Example
/// ```ignore
/// let shares = client.deposit(&lp, 10_000_000);
/// ```
pub fn deposit(env: Env, lp: Address, usdc_amount: u128) -> u128 {
Self::require_initialized(&env);
lp.require_auth();
if usdc_amount == 0 {
panic_with_error!(&env, PoolError::InvalidAmount);
}
let totals = Self::totals(&env);
let total_shares = totals.shares;
let total_deposits = totals.deposits;
if (total_shares == 0 || total_deposits == 0) && usdc_amount < MIN_INITIAL_DEPOSIT {
panic_with_error!(&env, PoolError::InvalidAmount);
}
let shares_to_issue = if total_shares == 0 || total_deposits == 0 {
usdc_amount
} else {
let scaled = usdc_amount
.checked_mul(total_shares)
.unwrap_or_else(|| panic_with_error!(&env, PoolError::Overflow));
scaled / total_deposits
};
// Dust-attack guard: once the pool accrues yield, the share price
// (total_deposits / total_shares) rises above 1.0, so a sufficiently
// small deposit can round down to 0 shares while its USDC is still
// pulled into total_deposits, silently donating the deposit to existing
// LPs. Reject any deposit that would mint 0 shares so the caller keeps
// their funds. This check runs before the token transfer, so no USDC
// leaves the depositor on the rejection path.
if shares_to_issue == 0 {
panic_with_error!(&env, PoolError::MinimumDeposit);
}
let usdc_id = Self::usdc(&env);
let usdc = token::Client::new(&env, &usdc_id);
usdc.transfer(&lp, &env.current_contract_address(), &(usdc_amount as i128));
env.storage()
.instance()
.set(&DataKey::TotalShares, &(total_shares + shares_to_issue));
env.storage()
.instance()
.set(&DataKey::TotalDeposits, &(total_deposits + usdc_amount));
let lp_shares_key = DataKey::LPShares(lp.clone());
let lp_shares: u128 = env.storage().persistent().get(&lp_shares_key).unwrap_or(0);
env.storage()
.persistent()
.set(&lp_shares_key, &(lp_shares + shares_to_issue));
env.storage()
.persistent()
.extend_ttl(&lp_shares_key, TTL_THRESHOLD, TTL_EXTEND_TO);
let lp_deposit_count_key = DataKey::LPDepositCount(lp.clone());
let count: u32 = env
.storage()
.persistent()
.get(&lp_deposit_count_key)
.unwrap_or(0);
env.storage()
.persistent()
.set(&lp_deposit_count_key, &(count + 1));
env.storage()
.persistent()
.extend_ttl(&lp_deposit_count_key, TTL_THRESHOLD, TTL_EXTEND_TO);
let lp_init_key = DataKey::LPInitialDeposit(lp.clone());
let init_dep: u128 = env.storage().persistent().get(&lp_init_key).unwrap_or(0);
env.storage()
.persistent()
.set(&lp_init_key, &(init_dep + usdc_amount));
env.storage()
.persistent()
.extend_ttl(&lp_init_key, TTL_THRESHOLD, TTL_EXTEND_TO);
events::lp_deposited(&env, &lp, usdc_amount, shares_to_issue);
Self::extend_instance_ttl(&env);
shares_to_issue
}
/// Withdraws shares from the pool and transfers USDC to the LP.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `lp` - The liquidity provider address.
/// * `shares` - The number of shares to withdraw.
///
/// # Auth
/// Requires self-authorization from `lp` (via `lp.require_auth()`).
///
/// # Panics
/// * `InvalidAmount` if `shares` is zero.
/// * `NoShares` if the LP has no shares.
/// * `InsufficientShares` if the LP does not own enough shares.
/// * `InsufficientLiquidity` if the pool lacks enough available USDC.
/// * `Overflow` if `shares * total_deposits` (or `shares * lp_initial_deposit`)
/// would overflow `u128` while computing the redemption amount.
///
/// # Notes
/// On full withdrawal (remaining shares reach zero), `LPInitialDeposit`
/// and `LPDepositCount` are removed from storage. This ensures a
/// subsequent re-deposit starts with a fresh initial-deposit basis
/// and an accurate deposit count.
///
/// # Returns
/// * `u128` - The amount of USDC returned.
///
/// # Example
/// ```ignore
/// let returned = client.withdraw(&lp, 500);
/// ```
pub fn withdraw(env: Env, lp: Address, shares: u128) -> u128 {
Self::require_initialized(&env);
lp.require_auth();
if shares == 0 {
panic_with_error!(&env, PoolError::InvalidAmount);
}
let lp_shares_key = DataKey::LPShares(lp.clone());
let lp_shares: u128 = env
.storage()
.persistent()
.get(&lp_shares_key)
.unwrap_or_else(|| panic_with_error!(&env, PoolError::NoShares));
if shares > lp_shares {
panic_with_error!(&env, PoolError::InsufficientShares);
}
let totals = Self::totals(&env);
let total_shares = totals.shares;
let total_deposits = totals.deposits;
let total_funded = totals.funded;
let available = total_deposits - total_funded;
let scaled = shares
.checked_mul(total_deposits)
.unwrap_or_else(|| panic_with_error!(&env, PoolError::Overflow));
let usdc_to_return = scaled / total_shares;
if usdc_to_return > available {
panic_with_error!(&env, PoolError::InsufficientLiquidity);
}
let usdc_id = Self::usdc(&env);
let usdc = token::Client::new(&env, &usdc_id);
usdc.transfer(
&env.current_contract_address(),
&lp,
&(usdc_to_return as i128),
);
env.storage()
.instance()
.set(&DataKey::TotalShares, &(total_shares - shares));
env.storage()
.instance()
.set(&DataKey::TotalDeposits, &(total_deposits - usdc_to_return));
let remaining_shares = lp_shares - shares;
env.storage()
.persistent()
.set(&lp_shares_key, &remaining_shares);
env.storage()
.persistent()
.extend_ttl(&lp_shares_key, TTL_THRESHOLD, TTL_EXTEND_TO);
if remaining_shares == 0 {
// Full withdrawal: reset LP-scoped storage to prevent stale state
// on re-deposit. LPInitialDeposit is zeroed below via the
// principal_portion calculation; LPDepositCount must be removed too.
let dep_count_key = DataKey::LPDepositCount(lp.clone());
env.storage().persistent().remove(&dep_count_key);
}
let init_dep_key = DataKey::LPInitialDeposit(lp.clone());
let init_dep: u128 = env.storage().persistent().get(&init_dep_key).unwrap_or(0);
let principal_scaled = shares
.checked_mul(init_dep)
.unwrap_or_else(|| panic_with_error!(&env, PoolError::Overflow));
let principal_portion = principal_scaled / (lp_shares);
let yield_earned = usdc_to_return.saturating_sub(principal_portion);
let new_init_dep = init_dep.saturating_sub(principal_portion);
if new_init_dep > 0 {
env.storage().persistent().set(&init_dep_key, &new_init_dep);
env.storage()
.persistent()
.extend_ttl(&init_dep_key, TTL_THRESHOLD, TTL_EXTEND_TO);
} else {
env.storage().persistent().remove(&init_dep_key);
}
let yield_key = DataKey::LPYieldEarned(lp.clone());
let prev_yield: u128 = env.storage().persistent().get(&yield_key).unwrap_or(0);
env.storage()
.persistent()
.set(&yield_key, &(prev_yield + yield_earned));
env.storage()
.persistent()
.extend_ttl(&yield_key, TTL_THRESHOLD, TTL_EXTEND_TO);
events::lp_withdrawn(&env, &lp, usdc_to_return, shares);
Self::extend_instance_ttl(&env);
usdc_to_return
}
/// Funds a listed invoice by moving USDC through escrow and invoice contracts.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `invoice_id` - The invoice to fund.
///
/// # Auth
/// **Permissionless.** Any caller can trigger funding for an invoice, provided
/// the invoice passes all on-chain eligibility checks:
/// 1. Invoice status must be `Listed` (status 1)
/// 2. Invoice funding asset must match the pool's asset (USDC)
/// 3. Pool must have sufficient available liquidity
/// 4. Funding would not cause pool utilization to exceed the `max_utilization_bps` cap
///
/// See README §"Known Centralization Risks & Roadmap" for the longer-term
/// governance design that will let LPs signal approval on funding decisions.
///
/// # Registry re-verification
/// The issuer and buyer's registry verification is re-checked here, in
/// addition to the checks already performed by `invoice.create()` and
/// `invoice.list_for_financing()`. This is the point where pool capital
/// is actually committed, so a revocation that happened after listing
/// must still block new funding. Once funding succeeds, verification is
/// **not** re-checked again at any later step (`mark_shipped`,
/// `confirm_delivery`, `repay`, `trigger_default`) — see
/// `InvoiceContract::list_for_financing` for the rationale.
///
/// # Panics
/// * `InvoiceNotListed` if the invoice is not in listed status.
/// * `AlreadyFunded` if a `FundedInvoice` entry already exists for this invoice id.
/// * `IssuerNotVerified` if the invoice issuer's registry verification has
/// since been revoked.
/// * `BuyerNotVerified` if the invoice buyer's registry verification has
/// since been revoked.
/// * `AssetMismatch` if the invoice funding asset does not match pool USDC.
/// * `InvalidAmount` if the computed funded amount is zero.
/// * `InsufficientLiquidity` if the pool does not have enough funds.
/// * `UtilizationCapExceeded` if funding would push utilization above the cap.
/// * `Overflow` if `face_value * (10000 - discount_bps)` or the resulting
/// utilization calculation overflows `u128`.
///
/// # Returns
/// * `bool` - `true` when the invoice is funded.
///
/// # Example
/// ```ignore
/// client.fund_invoice(&invoice_id);
/// ```
pub fn fund_invoice(env: Env, invoice_id: BytesN<32>) -> bool {
Self::require_initialized(&env);
let invoice_contract = Self::invoice_contract(&env)
.expect("pool is not initialized: invoice contract missing");
let mut args = Vec::new(&env);
args.push_back(invoice_id.clone().into_val(&env));
let invoice_status: u32 =
env.invoke_contract(&invoice_contract, &Symbol::new(&env, "get_status"), args);
if invoice_status != 1 {
panic_with_error!(&env, PoolError::InvoiceNotListed);
}
let funded_key = DataKey::FundedInvoice(invoice_id.clone());
if env.storage().persistent().has(&funded_key) {
panic_with_error!(&env, PoolError::AlreadyFunded);
}
let registry_id = Self::registry_contract(&env);
let mut args = Vec::new(&env);
args.push_back(invoice_id.clone().into_val(&env));
let issuer: Address =
env.invoke_contract(&invoice_contract, &Symbol::new(&env, "get_issuer"), args);
let mut args = Vec::new(&env);
args.push_back(issuer.into_val(&env));
let issuer_verified: bool =
env.invoke_contract(®istry_id, &Symbol::new(&env, "is_verified"), args);
if !issuer_verified {
panic_with_error!(&env, PoolError::IssuerNotVerified);
}
let mut args = Vec::new(&env);
args.push_back(invoice_id.clone().into_val(&env));
let buyer: Address =
env.invoke_contract(&invoice_contract, &Symbol::new(&env, "get_buyer"), args);
let mut args = Vec::new(&env);
args.push_back(buyer.into_val(&env));
let buyer_verified: bool =
env.invoke_contract(®istry_id, &Symbol::new(&env, "is_verified"), args);
if !buyer_verified {
panic_with_error!(&env, PoolError::BuyerNotVerified);
}
let mut args = Vec::new(&env);
args.push_back(invoice_id.clone().into_val(&env));
let invoice_asset: Address = env.invoke_contract(
&invoice_contract,
&Symbol::new(&env, "get_funding_asset"),
args,
);
let usdc_id = Self::usdc(&env);
if invoice_asset != usdc_id {
panic_with_error!(&env, PoolError::AssetMismatch);
}
let mut args = Vec::new(&env);
args.push_back(invoice_id.clone().into_val(&env));
let face_value: u128 = env.invoke_contract(
&invoice_contract,
&Symbol::new(&env, "get_face_value"),
args,
);
let mut args = Vec::new(&env);
args.push_back(invoice_id.clone().into_val(&env));
let discount_bps: u32 = env.invoke_contract(
&invoice_contract,
&Symbol::new(&env, "get_discount_bps"),
args,
);
// `face_value` is read from the invoice contract via a cross-contract
// call and is not bounded by this pool, so the scaling multiplication
// must be guarded just like the utilization check below (#585).
let funded_amount = face_value
.checked_mul(10000 - discount_bps as u128)
.unwrap_or_else(|| panic_with_error!(&env, PoolError::Overflow))
/ 10000;
if funded_amount == 0 {
panic_with_error!(&env, PoolError::InvalidAmount);
}
let totals = Self::totals(&env);
let total_deposits = totals.deposits;
let total_funded = totals.funded;
let available = total_deposits - total_funded;
if funded_amount > available {
panic_with_error!(&env, PoolError::InsufficientLiquidity);
}
let max_utilization_bps = totals.max_utilization_bps;
let new_total_funded = total_funded + funded_amount;
let utilization_after =
Self::utilization_bps_or_panic(&env, new_total_funded, total_deposits);
if utilization_after > max_utilization_bps {
panic_with_error!(&env, PoolError::UtilizationCapExceeded);
}
// --- Checks-effects-interactions: commit pool state BEFORE any
// cross-contract calls so a reentrant callback into this contract
// always sees the updated TotalFunded / ActiveInvoiceCount /
// FundedInvoice, preventing double-funding via stale state.
env.storage()
.instance()
.set(&DataKey::TotalFunded, &(total_funded + funded_amount));
let active_count = totals.active_invoices;
env.storage()
.instance()
.set(&DataKey::ActiveInvoiceCount, &(active_count + 1));
env.storage().persistent().set(&funded_key, &funded_amount);
env.storage()
.persistent()
.extend_ttl(&funded_key, TTL_THRESHOLD, TTL_EXTEND_TO);
// --- Interactions: cross-contract calls after pool state is committed.
let escrow_contract =
Self::escrow_contract(&env).expect("pool is not initialized: escrow contract missing");
let mut args = Vec::new(&env);
args.push_back(invoice_id.clone().into_val(&env));
args.push_back(funded_amount.into_val(&env));
args.push_back(issuer.into_val(&env));
let _: bool = env.invoke_contract(&escrow_contract, &Symbol::new(&env, "lock"), args);
let pool_address = env.current_contract_address();
let mut args = Vec::new(&env);
args.push_back(invoice_id.clone().into_val(&env));
args.push_back(pool_address.into_val(&env));
args.push_back(usdc_id.into_val(&env));
args.push_back(funded_amount.into_val(&env));
let _: bool =
env.invoke_contract(&invoice_contract, &Symbol::new(&env, "mark_funded"), args);
events::invoice_funded(&env, &invoice_id, funded_amount);
Self::extend_instance_ttl(&env);
true
}
/// Receives invoice repayment and updates pool liquidity metrics.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `invoice_id` - The invoice being repaid.
/// * `amount` - The amount repaid.
///
/// # Auth
/// Requires authorization from the configured `invoice_contract`
/// (via `invoice_contract.require_auth()`); only the invoice contract may
/// invoke this entry point.
///
/// # Panics
/// * `InvoiceNotFound` if the invoice is not funded.
/// * `InvalidAmount` if the repayment amount is less than the funded amount.
/// * `ActiveCountUnderflow` if the active-invoice counter would underflow
/// (e.g. a mismatched repayment for an invoice that was never funded
/// through this pool).
///
/// # Returns
/// * `bool` - `true` when repayment is processed.
///
/// # Example
/// ```ignore
/// client.receive_repayment(&invoice_id, 1_050);
/// ```
pub fn receive_repayment(env: Env, invoice_id: BytesN<32>, amount: u128) -> bool {
let invoice_contract = Self::invoice_contract(&env)
.expect("pool is not initialized: invoice contract missing");
invoice_contract.require_auth();
// Shared settlement path; `refund` is 0 so the whole surplus
// (amount - funded_amount) is credited to LPs as yield.
Self::settle_repayment(&env, &invoice_id, amount, 0);
true
}
/// Receives invoice repayment with a partial refund to the buyer and updates
/// pool liquidity metrics.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `invoice_id` - The invoice being repaid.
/// * `amount` - The amount repaid.
/// * `refund` - The amount to refund to the buyer.
/// * `buyer` - The buyer receiving the refund.
///
/// # Auth
/// Requires authorization from the configured `invoice_contract`
/// (via `invoice_contract.require_auth()`); only the invoice contract may
/// invoke this entry point.
///
/// # Trust boundary: the discount/refund split is invoice-computed
/// `invoice.repay()` / `invoice.repay_early()` independently compute
/// `earned_by_pool` / `refund_to_buyer` from the invoice's discount,
/// elapsed time, and term, and pass the resulting `refund` here. Pool has
/// no visibility into `funded_at`, `due_date`, or elapsed/term at all —
/// it only bounds `refund` to `[0, amount - funded_amount]` (the maximum
/// possible discount) via `InvalidAmount`. Pool does **not** independently
/// verify that `refund` is proportional to time elapsed; any `refund`
/// invoice passes within that bound is accepted unconditionally, and the
/// remainder is credited to LPs as yield. Correctness of the time-based
/// split is entirely `invoice_contract`'s responsibility.
///
/// # Panics
/// * `InvoiceNotFound` if the invoice is not funded.
/// * `InvalidAmount` if the repayment amount is less than the funded amount,
/// or if the refund exceeds the maximum allowed.
/// * `ActiveCountUnderflow` if the active-invoice counter would underflow
/// (e.g. a mismatched repayment for an invoice that was never funded
/// through this pool).
///
/// # Returns
/// * `bool` - `true` when repayment is processed.
///
/// # Example
/// ```ignore
/// client.receive_repayment_with_refund(&invoice_id, 1_050, 50, &buyer);
/// ```
pub fn receive_repayment_with_refund(
env: Env,
invoice_id: BytesN<32>,
amount: u128,
refund: u128,
buyer: Address,
) -> bool {
let invoice_contract = Self::invoice_contract(&env)
.expect("pool is not initialized: invoice contract missing");
invoice_contract.require_auth();
// Shared settlement path: `settle_repayment` owns the funded-entry
// lookup, the `amount >= funded_amount` and refund-bound validation,
// the totals update, the funded-entry removal, the event, and the
// instance TTL bump. Only the refund's USDC transfer is specific to
// this entry point and is layered on top here.
Self::settle_repayment(&env, &invoice_id, amount, refund);
// Transfer the buyer's refund out of the pool's USDC balance. Skipped
// entirely when the refund is zero.
let usdc_id = Self::usdc(&env);
let usdc = token::Client::new(&env, &usdc_id);
if refund > 0 {
usdc.transfer(&env.current_contract_address(), &buyer, &(refund as i128));
}
true
}
/// Forwards a defaulted invoice to escrow default handling and updates
/// the invoice status on the invoice contract.
///
/// This function performs the following cross-contract sequence:
/// 1. Calls `escrow.handle_default()` to release escrowed funds back
/// to the pool.
/// 2. Calls `invoice.mark_defaulted()` to persist the `Defaulted` status
/// on the invoice record, update the status index, and emit the
/// `invoice_defaulted` event.
/// 3. Updates the pool's local accounting (TotalFunded, TotalDeposits,
/// TotalLossRealised, ActiveInvoiceCount) and removes the funded
/// invoice entry.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `invoice_id` - The defaulted invoice.
///
/// # Auth
/// Requires authorization from the configured `invoice_contract`
/// (via `invoice_contract.require_auth()`); only the invoice contract may
/// invoke this entry point.
///
/// # Panics
/// * `InvoiceNotFound` if no funded invoice entry exists for `invoice_id`.
/// * `EscrowDefaultNotReleased` if `escrow.handle_default()` returns `false`
/// (e.g. no lock record exists in escrow for this invoice, so no tokens
/// were actually transferred back to the pool). Without this check, pool
/// accounting would otherwise proceed to record a loss and free up
/// utilization as if funds had been recovered, even though escrow moved
/// nothing.
/// * `ActiveCountUnderflow` if the active-invoice counter would underflow
/// (e.g. double-default of the same invoice).
///
/// # Returns
/// * `bool` - `true` when default handling completes.
///
/// # Example
/// ```ignore
/// client.handle_default(&invoice_id);
/// ```
pub fn handle_default(env: Env, invoice_id: BytesN<32>) -> bool {
let invoice_contract = Self::invoice_contract(&env)
.expect("pool is not initialized: invoice contract missing");
invoice_contract.require_auth();
let funded_key = DataKey::FundedInvoice(invoice_id.clone());
if !env.storage().persistent().has(&funded_key) {
panic_with_error!(&env, PoolError::InvoiceNotFound);
}
let funded_amount: u128 = env.storage().persistent().get(&funded_key).unwrap();
let escrow_contract =
Self::escrow_contract(&env).expect("pool is not initialized: escrow contract missing");
let pool_address = env.current_contract_address();
let mut args = Vec::new(&env);
args.push_back(invoice_id.clone().into_val(&env));
args.push_back(pool_address.into_val(&env));
let escrow_released: bool =
env.invoke_contract(&escrow_contract, &Symbol::new(&env, "handle_default"), args);
if !escrow_released {
panic_with_error!(&env, PoolError::EscrowDefaultNotReleased);
}
let totals = Self::totals(&env);
let total_funded = totals.funded;
let total_deposits = totals.deposits;
let total_loss_realised = totals.loss_realised;
env.storage()
.instance()
.set(&DataKey::TotalFunded, &(total_funded - funded_amount));
env.storage()
.instance()
.set(&DataKey::TotalDeposits, &(total_deposits - funded_amount));
env.storage().instance().set(
&DataKey::TotalLossRealised,
&(total_loss_realised + funded_amount),
);
let active_count = totals.active_invoices;
let new_active_count = active_count
.checked_sub(1)
.unwrap_or_else(|| panic_with_error!(&env, PoolError::ActiveCountUnderflow));
env.storage()
.instance()
.set(&DataKey::ActiveInvoiceCount, &new_active_count);
// Persist the Defaulted status on the invoice contract (step 2 of the
// documented cross-contract sequence). This runs after the active-count
// underflow check so a mismatched default still surfaces
// ActiveCountUnderflow (#17) rather than an invoice lookup error from
// mark_defaulted. mark_defaulted is idempotent: when
// invoice.trigger_default already transitioned the status to Defaulted
// before invoking this pool entry point, the call is a no-op.
let mut args = Vec::new(&env);
args.push_back(invoice_id.clone().into_val(&env));
let _: bool = env.invoke_contract(
&invoice_contract,
&Symbol::new(&env, "mark_defaulted"),
args,
);
env.storage().persistent().remove(&funded_key);
events::invoice_defaulted(&env, &invoice_id, funded_amount);
Self::extend_instance_ttl(&env);
true
}
/// Returns current pool statistics and utilization metrics.
///
/// # Arguments
/// * `env` - The Soroban environment.
///
/// # Auth
/// No authorization is required.
///
/// # Panics
/// * `NotInitialized` if the pool contract has not been initialized.
/// * `Overflow` if scaling `total_funded` into basis points would overflow.
///
/// # Returns
/// * `PoolStats` - The current pool statistics.
///
/// # Example
/// ```ignore
/// let stats = client.get_stats();
/// ```
pub fn get_stats(env: Env) -> PoolStats {
if Self::admin(&env).is_none() {
panic_with_error!(&env, PoolError::NotInitialized);
}
let totals = Self::totals(&env);
let total_deposits = totals.deposits;
let total_funded = totals.funded;
let available = total_deposits - total_funded;
let utilization = Self::utilization_bps_or_panic(&env, total_funded, total_deposits);
PoolStats {
total_deposits,
total_funded,
available_liquidity: available,
utilization_rate_bps: utilization,
total_yield_distributed: totals.yield_distributed,
total_loss_realised: totals.loss_realised,
active_invoice_count: totals.active_invoices,
total_shares: totals.shares,
max_utilization_bps: totals.max_utilization_bps,
}
}
/// Returns the LP's position, including shares, value, yield, and deposits.
///
/// # Arguments
/// * `env` - The Soroban environment.
/// * `lp` - The liquidity provider address.
///
/// # Auth
/// No authorization is required.
///
/// # Panics
/// * `Overflow` if `lp_shares * total_deposits` would overflow `u128`
/// while computing the position's USDC value.
///
/// All storage reads default to `0` when the LP has no recorded position,
/// so an LP without a position simply reports zeros.
///
/// # TTL maintenance
/// `get_lp_position` is a read that keeps a live position alive: every
/// surviving LP-scoped persistent entry it reads (`LPShares`,
/// `LPYieldEarned`, `LPDepositCount`, and `LPInitialDeposit`) has its TTL
/// extended using the same threshold/target as the deposit/withdraw write
/// paths. This matters for deposit-and-hold LPs who never call
/// `deposit`/`withdraw` again — without the read-triggered bump their
/// entries would lapse and become archival-eligible even though the
/// position is still economically live (#588). Entries that do not exist
/// are skipped, so reads for an LP with no position perform no writes.
///
/// # Returns
/// * `LPPosition` - The LP position details.
///
/// # Example
/// ```ignore
/// let position = client.get_lp_position(&lp);
/// ```
pub fn get_lp_position(env: Env, lp: Address) -> LPPosition {
let lp_shares: u128 = env
.storage()
.persistent()
.get(&DataKey::LPShares(lp.clone()))
.unwrap_or(0);
let totals = Self::totals(&env);
let total_shares = totals.shares;
let total_deposits = totals.deposits;
let usdc_value = if total_shares > 0 && lp_shares > 0 {
let scaled = lp_shares
.checked_mul(total_deposits)
.unwrap_or_else(|| panic_with_error!(&env, PoolError::Overflow));
scaled / total_shares
} else {
0
};
let yield_earned: u128 = env
.storage()
.persistent()
.get(&DataKey::LPYieldEarned(lp.clone()))
.unwrap_or(0);
let deposit_count: u32 = env
.storage()
.persistent()
.get(&DataKey::LPDepositCount(lp.clone()))
.unwrap_or(0);
// Read-triggered TTL bump (#588): deposit/withdraw are the only write
// paths that extend the LP-scoped persistent entries, so a
// deposit-and-hold LP's entries would otherwise lapse and become
// archival-eligible even though their position is still live. Refresh
// every surviving LP entry here, same raw policy as the write path.
// LPInitialDeposit has no field on `LPPosition`, but it is part of the
// same deposit-time write bundle, so it is refreshed too.
//
// The `has()` guard keeps reads for an LP with no recorded position
// (or a fully withdrawn one) from calling `extend_ttl` on keys that do
// not exist, which would host-panic. Entries whose TTL is already at or
// beyond the extend target are no-ops on chain, so this is cheap.
for key in [
DataKey::LPShares(lp.clone()),