xrpld
Loading...
Searching...
No Matches
LoanManageFixedPrecision_test.cpp
1#include <test/app/lending/LoanManageFixedPrecisionBase.h>
2#include <test/jtx/Account.h>
3#include <test/jtx/Env.h>
4#include <test/jtx/TestHelpers.h>
5#include <test/jtx/amount.h>
6#include <test/jtx/fee.h>
7#include <test/jtx/mpt.h>
8#include <test/jtx/pay.h>
9#include <test/jtx/ter.h>
10#include <test/jtx/trust.h>
11#include <test/jtx/vault.h>
12
13#include <xrpl/basics/Number.h>
14#include <xrpl/basics/chrono.h>
15#include <xrpl/beast/unit_test/suite.h>
16#include <xrpl/beast/utility/Zero.h>
17#include <xrpl/ledger/helpers/LendingHelpers.h>
18#include <xrpl/ledger/helpers/VaultHelpers.h>
19#include <xrpl/protocol/Asset.h>
20#include <xrpl/protocol/Indexes.h>
21#include <xrpl/protocol/Issue.h>
22#include <xrpl/protocol/Keylet.h>
23#include <xrpl/protocol/LedgerFormats.h>
24#include <xrpl/protocol/MPTIssue.h>
25#include <xrpl/protocol/Protocol.h>
26#include <xrpl/protocol/SField.h>
27#include <xrpl/protocol/STAmount.h>
28#include <xrpl/protocol/SeqProxy.h>
29#include <xrpl/protocol/TER.h>
30#include <xrpl/protocol/TxFlags.h>
31#include <xrpl/protocol/Units.h>
32
33#include <algorithm>
34#include <chrono>
35#include <cstdint>
36#include <optional>
37#include <string>
38#include <utility>
39
40namespace xrpl {
41
42// LoanManage-focused FixedPrecision tests: default and impair's effect on
43// AssetsDeployed and LossUnrealized, First-Loss Capital cover on default, and
44// the sole-holder clawback scenarios that need an impaired loan to produce
45// their liquid/illiquid split.
47{
48 void
50 {
51 using namespace test::jtx;
52 using namespace loan;
53
54 testcase("Lending: defaulting a Loan reduces AssetsDeployed by its outstanding principal");
55
56 Env env(*this, features());
57 auto const [issuer, owner, depositor, asset] = setupIou(env);
58
59 auto const fixture = setupLendingVault(env, owner, depositor, asset, Number{1'000});
60 auto const loanKeylet = openLoan(env, fixture, Number{300}, 3);
61
62 defaultAfterGrace(env, owner, loanKeylet);
63
64 expectVault(env, fixture.vaultKeylet, {.assetsDeployed = Number{0}});
65 checkVaultLoanSums(env, fixture, {loanKeylet}, "default");
66 }
67
68 // Default removes only the defaulted Loan's scheduled interest from
69 // YieldUnrealized; another open Loan's interest stays.
70 void
72 {
73 using namespace test::jtx;
74 using namespace loan;
75
76 testcase("Lending: default removes only the defaulted Loan's scheduled interest");
77
78 Env env(*this, features());
79 auto const [issuer, owner, depositor, asset] = setupIou(env);
80
81 auto const fixture = setupLendingVault(env, owner, depositor, asset, Number{1'000});
82 auto const defaulted = openLoan(env, fixture, Number{300}, 3, percentageToTenthBips(10));
83 auto const kept = openLoan(env, fixture, Number{200}, 3, percentageToTenthBips(10));
84
85 auto const scheduledInterest = [&](Keylet const& k) {
86 auto const loanSle = env.le(k);
87 if (!BEAST_EXPECT(loanSle))
88 return Number{0};
89 return Number(loanSle->at(sfTotalValueOutstanding)) -
90 Number(loanSle->at(sfPrincipalOutstanding)) -
91 Number(loanSle->at(sfManagementFeeOutstanding));
92 };
93 auto const yield = [&] {
94 auto const vaultSle = env.le(fixture.vaultKeylet);
95 if (!BEAST_EXPECT(vaultSle))
96 return Number{0};
97 return Number(vaultSle->at(sfYieldUnrealized));
98 };
99
100 Number const defaultedInterest = scheduledInterest(defaulted);
101 Number const keptInterest = scheduledInterest(kept);
102 BEAST_EXPECT(defaultedInterest > beast::kZero);
103 BEAST_EXPECT(keptInterest > beast::kZero);
104 BEAST_EXPECT(yield() == defaultedInterest + keptInterest);
105
106 defaultAfterGrace(env, owner, defaulted);
107
108 BEAST_EXPECT(yield() == keptInterest);
109 BEAST_EXPECT(scheduledInterest(kept) == keptInterest);
110 expectVault(env, fixture.vaultKeylet, {.assetsDeployed = Number{200}});
111 checkVaultLoanSums(env, fixture, {defaulted, kept}, "default with interest");
112 }
113
114 void
116 {
117 using namespace test::jtx;
118 using namespace loan;
119 using namespace loan_broker;
120
121 testcase("Lending: default with partial First-Loss Capital cover");
122
123 Env env(*this, features());
124 auto const [issuer, owner, depositor, asset] = setupIou(env, {.ownerFunds = 40});
125
126 // 10% minimum cover on 300 of debt needs a deposit of 30; 50% liquidation
127 // moves only 15 on default, leaving CoverAvailable at 15.
128 auto const fixture = setupLendingVault(
129 env,
130 owner,
131 depositor,
132 asset,
133 Number{1'000},
134 std::chrono::seconds{1'000'000},
135 std::nullopt,
138
139 env(coverDeposit(owner, fixture.brokerKeylet.key, asset(30).value()));
140 env.close();
141
142 auto const loanKeylet = openLoan(env, fixture, Number{300}, 3);
143
144 auto const brokerSleBefore = env.le(fixture.brokerKeylet);
145 if (!BEAST_EXPECT(brokerSleBefore))
146 return;
147 Number const coverBefore = brokerSleBefore->at(sfCoverAvailable);
148 BEAST_EXPECT(coverBefore == Number{30});
149
150 auto const loanSle = env.le(loanKeylet);
151 if (!BEAST_EXPECT(loanSle))
152 return;
153 closePastGrace(env, loanKeylet);
154
155 auto const before = snapshotVault(env, fixture.vaultKeylet, asset);
156 Number const principalBefore = loanSle->at(sfPrincipalOutstanding);
157 BEAST_EXPECT(before.assetsDeployed == principalBefore);
158 checkVaultLoanSums(env, fixture, {loanKeylet}, "partial cover default, before default");
159
160 env(manage(owner, loanKeylet.key, tfLoanDefault));
161 env.close();
162
163 auto const after = snapshotVault(env, fixture.vaultKeylet, asset);
164 auto const brokerSleAfter = env.le(fixture.brokerKeylet);
165 if (!BEAST_EXPECT(brokerSleAfter))
166 return;
167
168 Number const coverAfter = brokerSleAfter->at(sfCoverAvailable);
169 Number const coverMoved = coverBefore - coverAfter;
170 BEAST_EXPECT(coverMoved == Number{15});
171 BEAST_EXPECT(coverAfter == Number{15});
172
173 // AssetsDeployed drops by the full principal, not just the covered part.
174 BEAST_EXPECT(before.assetsDeployed - after.assetsDeployed == principalBefore);
175 BEAST_EXPECT(after.assetsDeployed == beast::kZero);
176 BEAST_EXPECT(after.available - before.available == coverMoved);
177 BEAST_EXPECT(before.total - after.total == principalBefore - coverMoved);
178 expectVault(env, fixture.vaultKeylet, {});
179 checkVaultLoanSums(env, fixture, {loanKeylet}, "partial cover default, after default");
180 }
181
182 void
184 {
185 using namespace test::jtx;
186 using namespace loan;
187
188 testcase(
189 "Lending: defaulting an impaired Loan reverses LossUnrealized and drops "
190 "AssetsDeployed");
191
192 Env env(*this, features());
193 auto const [issuer, owner, depositor, asset] = setupIou(env);
194
195 auto const fixture = setupLendingVault(env, owner, depositor, asset, Number{1'000});
196 auto const loanKeylet = openLoan(env, fixture, Number{300}, 3);
197
198 // Impair once late, before the grace period ends.
199 impairWhenLate(env, owner, loanKeylet);
200
201 auto const vaultSle = env.le(fixture.vaultKeylet);
202 if (!BEAST_EXPECT(vaultSle))
203 return;
204 Number const lossUnrealizedAtImpair = vaultSle->at(sfLossUnrealized);
205 BEAST_EXPECT(lossUnrealizedAtImpair == Number{300});
206 Number const assetsDeployedBeforeDefault = vaultSle->at(sfAssetsDeployed);
207 BEAST_EXPECT(assetsDeployedBeforeDefault == Number{300});
208 checkVaultLoanSums(env, fixture, {loanKeylet}, "default of impaired loan, after impair");
209
210 defaultAfterGrace(env, owner, loanKeylet);
211
212 auto const vaultSleAfter = env.le(fixture.vaultKeylet);
213 if (!BEAST_EXPECT(vaultSleAfter))
214 return;
215
216 // The realized loss cancels the paper loss booked at impair time.
217 BEAST_EXPECT(vaultSleAfter->at(sfLossUnrealized) == beast::kZero);
218 BEAST_EXPECT(vaultSleAfter->at(sfAssetsDeployed) == beast::kZero);
219 BEAST_EXPECT(
220 assetsDeployedBeforeDefault - vaultSleAfter->at(sfAssetsDeployed) == Number{300});
221 BEAST_EXPECT(vaultSleAfter->at(sfAssetsTotal) == getAssetsTotal(vaultSleAfter));
222 checkVaultLoanSums(env, fixture, {loanKeylet}, "default of impaired loan, after default");
223 }
224
225 // Impair, unimpair, impair again, then default, checking
226 // checkVaultLoanSums after every step. Runs on any asset.
227 void
229 test::jtx::Env& env,
230 test::jtx::Account const& owner,
231 test::jtx::Account const& depositor,
232 PrettyAsset const& asset,
233 Number const& depositAmount,
234 Number const& principal,
235 std::string const& label)
236 {
237 using namespace test::jtx;
238 using namespace loan;
239
240 auto const fixture = setupLendingVault(env, owner, depositor, asset, depositAmount);
241 auto const loanKeylet = openLoan(env, fixture, principal, 3);
242
243 auto const expectLossAndAssetsDeployed = [&](Number const& loss,
244 Number const& assetsDeployed) {
245 auto const vaultSle = env.le(fixture.vaultKeylet);
246 if (!BEAST_EXPECT(vaultSle))
247 return;
248 BEAST_EXPECT(Number(vaultSle->at(sfLossUnrealized)) == loss);
249 BEAST_EXPECT(Number(vaultSle->at(sfAssetsDeployed)) == assetsDeployed);
250 };
251
252 impairWhenLate(env, owner, loanKeylet);
253 expectLossAndAssetsDeployed(principal, principal);
254 checkVaultLoanSums(env, fixture, {loanKeylet}, label + " after impair");
255
256 // Unimpair reverses the paper loss; AssetsDeployed is unaffected.
257 env(manage(owner, loanKeylet.key, tfLoanUnimpair));
258 env.close();
259 expectLossAndAssetsDeployed(0, principal);
260 checkVaultLoanSums(env, fixture, {loanKeylet}, label + " after unimpair");
261
262 env(manage(owner, loanKeylet.key, tfLoanImpair));
263 env.close();
264 checkVaultLoanSums(env, fixture, {loanKeylet}, label + " after second impair");
265
266 defaultAfterGrace(env, owner, loanKeylet);
267 expectLossAndAssetsDeployed(0, 0);
268 checkVaultLoanSums(env, fixture, {loanKeylet}, label + " after default");
269 }
270
271 void
273 {
274 using namespace test::jtx;
275
276 {
277 testcase("Lending: FP XRP vault -- impair, unimpair, impair, default");
278
279 Account const owner{"owner"};
280 Account const depositor{"depositor"};
281 PrettyAsset const asset = xrpIssue();
282
283 Env env(*this, features());
284 env.fund(XRP(1'000'000), owner, depositor);
285 env.close();
286
288 env, owner, depositor, asset, Number{1'000}, Number{300}, "XRP");
289 }
290
291 {
292 testcase("Lending: FP MPT vault -- impair, unimpair, impair, default");
293
294 Env env(*this, features());
295 auto const [issuer, owner, depositor, asset] =
296 setupMpt(env, {.maxAmt = 100'000, .withDepositor = true, .holderFunds = 1'000});
297
299 env, owner, depositor, asset, Number{1'000}, Number{300}, "MPT");
300 }
301 }
302
303 void
305 {
306 using namespace test::jtx;
307 using namespace loan;
308 using namespace loan_broker;
309
310 testcase("Lending: default with partial First-Loss Capital cover on a coarsened vault");
311
312 Env env(*this, features());
313 auto const [issuer, owner, depositor, asset] = setupIou(
314 env,
315 {
316 .depositorTrust = 30'000'000,
317 .ownerTrust = 1'000'000,
318 .depositorFunds = 10'000'000,
319 .ownerFunds = 200'000,
320 });
321
322 // Minimum cover is checked at every origination against the broker's
323 // cumulative DebtTotal, so it must cover the 700,000 coarsening loan too.
324 // 150,000 covers 10% of the largest cumulative DebtTotal (750,000).
325 Number const defaultLoanPrincipal{50'000};
326 auto const coarsened = coarsenVault(
327 env,
328 owner,
329 depositor,
330 asset,
331 {
332 .extraLoans =
333 {
334 ExtraLoan{
335 .principal = defaultLoanPrincipal,
336 .paymentInterval = 1000 * 24 * 60 * 60,
337 },
338 },
339 .coverRateMinimum = percentageToTenthBips(10),
340 .coverRateLiquidation = percentageToTenthBips(50),
341 .coverDeposit = Number{150'000},
342 });
343 auto const& vaultKeylet = coarsened.fixture.vaultKeylet;
344 auto const& brokerKeylet = coarsened.fixture.brokerKeylet;
345 auto const& loanKeylet = coarsened.loanKeylets[1];
346 expectCoarsened(env, coarsened);
347
348 auto const brokerSleBefore = env.le(brokerKeylet);
349 auto const loanSleBefore = env.le(loanKeylet);
350 if (!BEAST_EXPECT(brokerSleBefore) || !BEAST_EXPECT(loanSleBefore))
351 return;
352 Number const coverBefore = brokerSleBefore->at(sfCoverAvailable);
353 BEAST_EXPECT(coverBefore == Number{150'000});
354 Number const principalBefore = loanSleBefore->at(sfPrincipalOutstanding);
355 BEAST_EXPECT(principalBefore == defaultLoanPrincipal);
356
357 closePastGrace(env, loanKeylet);
358 auto const before = snapshotVault(env, vaultKeylet, asset);
359
360 env(manage(owner, loanKeylet.key, tfLoanDefault));
361 env.close();
362
363 auto const after = snapshotVault(env, vaultKeylet, asset);
364 auto const brokerSleAfter = env.le(brokerKeylet);
365 if (!BEAST_EXPECT(brokerSleAfter))
366 return;
367
368 Number const coverMoved = coverBefore - Number(brokerSleAfter->at(sfCoverAvailable));
369 // coverMoved is 50% of 10% of the broker's cumulative DebtTotal at default,
370 // capped at this loan's principal and CoverAvailable. The exact value
371 // depends on how much the coarsening loan had repaid.
372 BEAST_EXPECT(coverMoved > beast::kZero);
373 BEAST_EXPECT(coverMoved < defaultLoanPrincipal);
374 BEAST_EXPECT(coverMoved <= coverBefore);
375 // The rate amount is DebtTotal * 10% * 50%. It is rounded on the broker
376 // grid and then floored on AssetsAvailable's grid, so the cover moved is
377 // at most the rate amount and less than one live unit below it.
378 {
379 auto const vaultSle = env.le(vaultKeylet);
380 if (!BEAST_EXPECT(vaultSle))
381 return;
382 Number const rateAmount = Number(brokerSleBefore->at(sfDebtTotal)) * Number{5, -2};
383 Number const liveUnit{1, getVaultScale(vaultSle)};
384 BEAST_EXPECT(coverMoved <= rateAmount);
385 BEAST_EXPECT(rateAmount - coverMoved < liveUnit);
386 }
387 // The broker pseudo-account's balance moves by exactly the cover moved.
388 {
389 Account const brokerPseudo{"brokerPseudo", brokerSleAfter->at(sfAccount)};
390 BEAST_EXPECT(
391 Number(env.balance(brokerPseudo, asset).value()) ==
392 Number(brokerSleAfter->at(sfCoverAvailable)));
393 }
394
395 // AssetsDeployed drops by the full principal; AssetsAvailable rises by the cover
396 // moved.
397 BEAST_EXPECT(before.assetsDeployed - after.assetsDeployed == principalBefore);
398 BEAST_EXPECT(after.available - before.available == coverMoved);
399
400 checkVaultLoanSums(env, coarsened, "testCoarsenedVaultDefaultWithPartialCover");
401 }
402
403 void
405 {
406 using namespace test::jtx;
407 using namespace loan;
408
409 testcase(
410 "Lending: repeated zero-cover defaults and an impair on a coarsened vault, then "
411 "final withdrawal stays refused");
412
413 Env env(*this, features());
414 auto const [issuer, owner, depositor, asset] = setupCoarsenIou(env);
415
416 // defaultA and defaultB are off-grid (a nonzero digit below the coarsened
417 // live unit) to check AssetsDeployed stays exact through default.
418 Number const defaultAPrincipal{40'0000000003LL, -10};
419 Number const defaultBPrincipal{35'0000000007LL, -10};
420 Number const remainingPrincipal{30'000};
421 auto const coarsened = coarsenVault(
422 env,
423 owner,
424 depositor,
425 asset,
426 {
427 .loanPrincipal = Number{300'000},
428 .extraLoans =
429 {
430 ExtraLoan{.principal = defaultAPrincipal},
431 ExtraLoan{.principal = defaultBPrincipal},
432 ExtraLoan{.principal = remainingPrincipal},
433 },
434 });
435 auto const& vaultKeylet = coarsened.fixture.vaultKeylet;
436 auto const& coarseningLoanKeylet = coarsened.loanKeylets[0];
437 auto const& defaultALoanKeylet = coarsened.loanKeylets[1];
438 auto const& defaultBLoanKeylet = coarsened.loanKeylets[2];
439 auto const& remainingLoanKeylet = coarsened.loanKeylets[3];
440
441 auto const vaultSle0 = env.le(vaultKeylet);
442 if (!BEAST_EXPECT(vaultSle0))
443 return;
444 BEAST_EXPECT(getVaultScale(vaultSle0) > getVaultBaseScale(vaultSle0));
446 env, coarsened, "testCoarsenedVaultMultipleDefaultsAndImpair (after coarsening)");
447
448 // defaultA: impaired, then defaulted. Both defaults are zero-cover
449 // (coverRateMinimum is 0).
450 env(manage(owner, defaultALoanKeylet.key, tfLoanImpair));
451 env.close();
452 env(manage(owner, defaultALoanKeylet.key, tfLoanDefault));
453 env.close();
455 env, coarsened, "testCoarsenedVaultMultipleDefaultsAndImpair (after defaultA)");
456
457 env(manage(owner, defaultBLoanKeylet.key, tfLoanDefault));
458 env.close();
460 env, coarsened, "testCoarsenedVaultMultipleDefaultsAndImpair (after defaultB)");
461
462 // The coarsening loan is many periods overdue, so it can be defaulted too.
463 env(manage(owner, coarseningLoanKeylet.key, tfLoanDefault));
464 env.close();
466 env, coarsened, "testCoarsenedVaultMultipleDefaultsAndImpair (after third default)");
467
468 auto const vaultSleAfterDefaults = env.le(vaultKeylet);
469 if (!BEAST_EXPECT(vaultSleAfterDefaults))
470 return;
471 BEAST_EXPECT(
472 Number(vaultSleAfterDefaults->at(sfAssetsDeployed)) == Number(remainingPrincipal));
473
474 env(manage(owner, remainingLoanKeylet.key, tfLoanImpair));
475 env.close();
477 env, coarsened, "testCoarsenedVaultMultipleDefaultsAndImpair (after impair)");
478
479 auto const vaultSleImpaired = env.le(vaultKeylet);
480 if (!BEAST_EXPECT(vaultSleImpaired))
481 return;
482 BEAST_EXPECT(Number(vaultSleImpaired->at(sfAssetsDeployed)) != beast::kZero);
483
484 // Withdrawals need the Redemption phase.
485 env.close(coarsened.fixture.redemptionDate + std::chrono::seconds{1});
486
487 // A withdrawal of the full share value is a final withdrawal; AssetsDeployed != 0
488 // makes it report tecHAS_OBLIGATIONS.
489 Number const assetsTotal = getAssetsTotal(vaultSleImpaired);
490 env(coarsened.fixture.vault.withdraw(
491 {.depositor = depositor, .id = vaultKeylet.key, .amount = asset(assetsTotal)}),
492 Ter(tecHAS_OBLIGATIONS));
493 env.close();
494
495 auto const vaultSleFinal = env.le(vaultKeylet);
496 if (!BEAST_EXPECT(vaultSleFinal))
497 return;
498 BEAST_EXPECT(Number(vaultSleFinal->at(sfAssetsDeployed)) != beast::kZero);
499 checkVaultLoanSums(env, coarsened, "testCoarsenedVaultMultipleDefaultsAndImpair (final)");
500 }
501
508
509 // Reaches the small-AssetsDeployed state: a second loan is overpaid down to a
510 // sub-live-unit remainder dust (one base unit at Scale 10, under the 5e-10
511 // half live unit), then the coarsening loan is defaulted, leaving dust as the
512 // only AssetsDeployed. Asserts the rounding hazard: AssetsAvailable + AssetsDeployed,
513 // rounded to 16 digits, equals AssetsAvailable.
516 test::jtx::Env& env,
517 test::jtx::Account const& owner,
518 test::jtx::Account const& depositor,
519 PrettyAsset const& asset,
520 std::string const& label)
521 {
522 using namespace test::jtx;
523 using namespace loan;
524
525 Number const overpayPrincipal{1'000};
526 Number const dust{1, -10};
527 auto coarsened = coarsenVault(
528 env,
529 owner,
530 depositor,
531 asset,
532 {
533 .extraLoans =
534 {
535 ExtraLoan{
536 .principal = overpayPrincipal,
537 .flags = tfLoanOverpayment,
538 .paymentTotal = 2,
539 .paymentInterval = 1000 * 24 * 60 * 60,
540 },
541 },
542 });
543 auto const& vaultKeylet = coarsened.fixture.vaultKeylet;
544 auto const& coarseningLoanKeylet = coarsened.loanKeylets[0];
545 auto const& dustLoanKeylet = coarsened.loanKeylets[1];
546 expectCoarsened(env, coarsened);
547
548 env(
549 pay(depositor,
550 dustLoanKeylet.key,
551 asset(overpayPrincipal - dust).value(),
552 tfLoanOverpayment));
553 env.close();
554
555 auto const dustLoanSle = env.le(dustLoanKeylet);
556 if (BEAST_EXPECT(dustLoanSle))
557 {
558 BEAST_EXPECT(Number(dustLoanSle->at(sfPrincipalOutstanding)) == dust);
559 BEAST_EXPECT(dustLoanSle->at(sfPaymentRemaining) == 1);
560 }
561 checkVaultLoanSums(env, coarsened, label + " (after overpay)");
562
563 env(manage(owner, coarseningLoanKeylet.key, tfLoanDefault));
564 env.close();
565 checkVaultLoanSums(env, coarsened, label + " (after default)");
566
567 auto const vaultSle = env.le(vaultKeylet);
568 if (!BEAST_EXPECT(vaultSle))
569 {
570 return {
571 .coarsened = std::move(coarsened),
572 .assetsDeployed = Number{0},
573 .available = Number{0},
574 };
575 }
576 Number const assetsDeployed = vaultSle->at(sfAssetsDeployed);
577 Number const available = vaultSle->at(sfAssetsAvailable);
578 BEAST_EXPECT(assetsDeployed == dust);
579 BEAST_EXPECT(assetsDeployed != beast::kZero);
580 BEAST_EXPECT(getVaultScale(vaultSle) != getVaultBaseScale(vaultSle));
581
582 STAmount const roundedTotal = STAmount{asset.raw(), available + assetsDeployed};
583 STAmount const availableAmount = STAmount{asset.raw(), available};
584 BEAST_EXPECT(roundedTotal == availableAmount);
585
586 return {
587 .coarsened = std::move(coarsened),
588 .assetsDeployed = assetsDeployed,
589 .available = available,
590 };
591 }
592
593 // The tecHAS_OBLIGATIONS guard in VaultWithdraw exists for this case: with
594 // AssetsDeployed under half a live unit, AssetsAvailable + AssetsDeployed rounds to
595 // AssetsAvailable, so the insufficient-funds check would pass and the vault
596 // would end with no shares or assets but non-zero AssetsDeployed.
597 void
599 {
600 using namespace test::jtx;
601 using namespace loan;
602
603 testcase(
604 "Lending: full-value VaultWithdraw stays refused on a coarsened vault even when "
605 "AssetsDeployed is smaller than half the live unit");
606
607 Env env(*this, features());
608 auto const [issuer, owner, depositor, asset] = setupCoarsenIou(env);
609
610 auto const state = setupSmallAssetsDeployedVault(
611 env,
612 owner,
613 depositor,
614 asset,
615 "testCoarsenedVaultSmallAssetsDeployedFinalWithdrawalRejected");
616 auto const& coarsened = state.coarsened;
617 auto const& vaultKeylet = coarsened.fixture.vaultKeylet;
618
619 env.close(coarsened.fixture.redemptionDate + std::chrono::seconds{1});
620
621 // Name the full share count, not an asset amount: an asset amount equal to
622 // AssetsAvailable truncates the derived share count below the full supply and
623 // would miss isFinalWithdrawal, masking the guard under test.
624 auto const vaultSle = env.le(vaultKeylet);
625 if (!BEAST_EXPECT(vaultSle))
626 return;
627 auto const shareMPTID = vaultSle->at(sfShareMPTID);
628 auto const issuanceBefore = env.le(keylet::mptokenIssuance(shareMPTID));
629 if (!BEAST_EXPECT(issuanceBefore))
630 return;
631 STAmount const allShares{
632 MPTIssue{shareMPTID}, Number(issuanceBefore->getFieldU64(sfOutstandingAmount))};
633
634 env(coarsened.fixture.vault.withdraw(
635 {.depositor = depositor, .id = vaultKeylet.key, .amount = allShares}),
636 Ter(tecHAS_OBLIGATIONS));
637 env.close();
638
639 auto const after = snapshotVault(env, vaultKeylet, asset);
640 BEAST_EXPECT(after.assetsDeployed == state.assetsDeployed);
641 BEAST_EXPECT(after.available == state.available);
643 env, coarsened, "testCoarsenedVaultSmallAssetsDeployedFinalWithdrawalRejected (final)");
644 }
645
646 // Clawback counterpart of testCoarsenedVaultSmallAssetsDeployedFinalWithdrawalRejected:
647 // a full clawback hits the same rounding hazard, and the tecHAS_OBLIGATIONS
648 // guard fires.
649 void
651 {
652 using namespace test::jtx;
653 using namespace loan;
654
655 testcase(
656 "Lending: full-value VaultClawback stays refused on a coarsened vault even when "
657 "AssetsDeployed is smaller than half the live unit");
658
659 Env env(*this, features());
660 auto const [issuer, owner, depositor, asset] = setupCoarsenIou(env, true);
661
662 auto const state = setupSmallAssetsDeployedVault(
663 env,
664 owner,
665 depositor,
666 asset,
667 "testCoarsenedVaultSmallAssetsDeployedFullClawbackRejected");
668 auto const& coarsened = state.coarsened;
669 auto const& vaultKeylet = coarsened.fixture.vaultKeylet;
670
671 env(coarsened.fixture.vault.clawback(
672 {.issuer = issuer, .id = vaultKeylet.key, .holder = depositor}),
673 Ter(tecHAS_OBLIGATIONS));
674 env.close();
675
676 auto const after = snapshotVault(env, vaultKeylet, asset);
677 BEAST_EXPECT(after.assetsDeployed == state.assetsDeployed);
678 BEAST_EXPECT(after.available == state.available);
680 env, coarsened, "testCoarsenedVaultSmallAssetsDeployedFullClawbackRejected (final)");
681 }
682
683 void
685 {
686 using namespace test::jtx;
687 using namespace loan;
688 using namespace loan_broker;
689
690 testcase(
691 "Lending: a default's cover credit that crosses a power of ten keeps "
692 "AssetsAvailable at 16 digits");
693
694 Env env(*this, features());
695 auto const [issuer, owner, depositor, asset] = setupIou(
696 env,
697 {
698 .depositorTrust = 30'000'000,
699 .ownerTrust = 1'000'000,
700 .depositorFunds = 10'000'000,
701 .ownerFunds = 200'000,
702 });
703
704 // Replays testCoarsenedVaultDefaultWithPartialCover's setup. The loan must
705 // be an ExtraLoan: LoanSet's Open-zone guard refuses origination on a
706 // coarsened vault.
707 Number const defaultLoanPrincipal{50'000};
708 auto const coarsened = coarsenVault(
709 env,
710 owner,
711 depositor,
712 asset,
713 {
714 .extraLoans =
715 {
716 ExtraLoan{
717 .principal = defaultLoanPrincipal,
718 .paymentInterval = 1000 * 24 * 60 * 60,
719 },
720 },
721 .coverRateMinimum = percentageToTenthBips(10),
722 .coverRateLiquidation = percentageToTenthBips(50),
723 .coverDeposit = Number{150'000},
724 });
725 // Default overdueDays (800) coarsens AssetsAvailable's own grid, not just
726 // getVaultScale(); the crossing below must exercise the 17th-digit sum
727 // floor in creditToPosteriorAvailableScale, not just a 15-to-16-digit
728 // widening that every rounding mode handles identically.
729 auto const& vaultKeylet = coarsened.fixture.vaultKeylet;
730 auto const& defaultLoanKeylet = coarsened.loanKeylets[1];
731 expectCoarsened(env, coarsened);
732
733 auto const loanSleBefore = env.le(defaultLoanKeylet);
734 if (!BEAST_EXPECT(loanSleBefore))
735 return;
736 Number const principalBefore = loanSleBefore->at(sfPrincipalOutstanding);
737 closePastGrace(env, defaultLoanKeylet);
738
739 auto const brokerSle0 = env.le(coarsened.fixture.brokerKeylet);
740 if (!BEAST_EXPECT(brokerSle0))
741 return;
742 Number const cumulativeDebtTotal = brokerSle0->at(sfDebtTotal);
743 Number const coverAvailableBefore = brokerSle0->at(sfCoverAvailable);
744
745 // Mirror LoanManage::defaultLoanFixedPrecision's rawCover formula so the
746 // test can independently predict the credited amount and detect whether
747 // the grid floors below actually trimmed it.
748 Number const rawCoverUncapped = [&] {
750 Number const minimumCover =
751 tenthBipsOfValue(cumulativeDebtTotal, percentageToTenthBips(10));
752 return std::min(
753 tenthBipsOfValue(minimumCover, percentageToTenthBips(50)), principalBefore);
754 }();
755 Number const rawCoverCapped = std::min(rawCoverUncapped, coverAvailableBefore);
756
757 // rawCoverCapped is the exact pre-grid-rounding cover amount, so the
758 // shrink target can place AssetsAvailable right at the crossing instead
759 // of guessing with a conservative estimate.
760 Number const margin{1'000};
761 Number const powerOfTen{100'000};
762 Number const shrinkTarget = powerOfTen - rawCoverCapped + margin;
763 BEAST_EXPECT(shrinkTarget > beast::kZero);
764 BEAST_EXPECT(shrinkTarget < powerOfTen);
765
766 // Withdrawals need the Redemption phase.
767 env.close(coarsened.fixture.redemptionDate + std::chrono::seconds{1});
768
769 // Bring AssetsAvailable close to (but above) the boundary in one withdrawal.
770 Number const step = snapshotVault(env, vaultKeylet, asset).available - shrinkTarget;
771 if (step > beast::kZero)
772 {
773 env(coarsened.fixture.vault.withdraw(
774 {.depositor = depositor, .id = vaultKeylet.key, .amount = asset(step)}));
775 env.close();
776 }
777
778 auto const before = snapshotVault(env, vaultKeylet, asset);
779 BEAST_EXPECT(before.available < powerOfTen);
780
781 // Independently predict the credited cover using the same two-stage
782 // grid rounding defaultLoanFixedPrecision applies: round at the
783 // broker's posterior cover grid, then floor the sum at AssetsAvailable's
784 // own posterior grid. If either stage actually trims a digit, the
785 // predicted credit is strictly below rawCoverCapped.
786 auto const vaultSleBeforeDefault = env.le(vaultKeylet);
787 auto const brokerSleBeforeDefault = env.le(coarsened.fixture.brokerKeylet);
788 if (!BEAST_EXPECT(vaultSleBeforeDefault) || !BEAST_EXPECT(brokerSleBeforeDefault))
789 return;
790 STAmount const brokerRoundedCover = [&] {
793 vaultSleBeforeDefault,
794 brokerSleBeforeDefault,
795 STAmount{asset, rawCoverCapped},
797 }();
798 STAmount const expectedCoverAmount = creditToPosteriorAvailableScale(
799 vaultSleBeforeDefault, brokerRoundedCover, Number::RoundingMode::Downward);
800 // rawCoverCapped is itself an exact multiple of the grid for these
801 // numbers, so the two-stage rounding is not guaranteed to discard a
802 // digit here; the point of this test is that the production code and
803 // this independent prediction agree exactly, and that the result
804 // lands on the posterior grid across the power-of-ten crossing.
805 BEAST_EXPECT(Number(expectedCoverAmount) <= rawCoverCapped);
806
807 env(manage(owner, defaultLoanKeylet.key, tfLoanDefault));
808 env.close();
809
810 auto const after = snapshotVault(env, vaultKeylet, asset);
811 Number const coverMoved = after.available - before.available;
812
813 // AssetsDeployed drops by the full principal; the cover credited back is
814 // the grid-floored amount computed above, not the raw rate-based figure,
815 // and is large enough to cross powerOfTen upward.
816 BEAST_EXPECT(before.assetsDeployed - after.assetsDeployed == principalBefore);
817 BEAST_EXPECT(coverMoved == Number(expectedCoverAmount));
818 BEAST_EXPECT(coverMoved <= rawCoverCapped);
819 BEAST_EXPECT(expectAvailableAtSixteenDigits(env, vaultKeylet, asset) >= powerOfTen);
820
821 checkVaultLoanSums(env, coarsened, "testCoarsenedVaultDefaultCoverCrossesPowerOfTenUpward");
822 }
823
824 // A default whose cover needs finer digits than CoverAvailable's posterior
825 // grid. The Vault side stays exact and CoverAvailable rounds to nearest,
826 // the same way the broker pseudo-account's trust line does, so the
827 // LoanBroker invariant (CoverAvailable equals the pseudo-account balance)
828 // holds.
829 //
830 // CoverAvailable passes the Open limit only through LoanPay's fee redirect,
831 // which has no Open-limit check: the owner's trust line is deep frozen, so
832 // a large service fee lands in cover and coarsens its grid to 1e-5 while
833 // AssetsAvailable stays on the 1e-6 base grid.
834 void
836 {
837 using namespace test::jtx;
838 using namespace loan;
839 using namespace loan_broker;
840
841 testcase("Lending: default cover rounds on a coarsened CoverAvailable grid");
842
843 Env env(*this, features());
844 auto const [issuer, owner, depositor, asset] = setupIou(
845 env,
846 {
847 .depositorTrust = 100'000'000'000,
848 .ownerTrust = 1'000'000,
849 .depositorFunds = 30'000'000'000,
850 .ownerFunds = 10'000,
851 });
852
853 auto const fixture = setupLendingVault(
854 env,
855 owner,
856 depositor,
857 asset,
858 Number{1'000'000},
859 std::chrono::seconds{1'000'000},
860 std::uint8_t{6},
863 env(coverDeposit(owner, fixture.brokerKeylet.key, asset(1'000)));
864 env.close();
865
866 // Loan A carries the large service fee; loan B is the one defaulted.
867 // B's principal has a 1e-6 digit, so its cover does too.
868 Number const serviceFee{20'000'000'000};
869 auto const brokerSle0 = env.le(fixture.brokerKeylet);
870 if (!BEAST_EXPECT(brokerSle0))
871 return;
872 auto const loanAKeylet = keylet::loan(
873 fixture.brokerKeylet.key, SeqProxy::rawSequence(brokerSle0->at(sfLoanSequence)));
874 env(set(depositor, fixture.brokerKeylet.key, Number{1'000}),
875 kLoanServiceFee(serviceFee),
876 kGracePeriod(60),
877 kPaymentInterval(120),
878 kPaymentTotal(1),
879 Sig(sfCounterpartySignature, owner),
880 Fee(env.current()->fees().base * 2));
881 env.close();
882 Number const principalB{1234567891, -6};
883 auto const loanBKeylet = openLoan(env, fixture, principalB, 1);
884
885 // Deep freeze the owner so the service fee is redirected into cover.
886 env(trust(issuer, owner["USD"](0), tfSetFreeze | tfSetDeepFreeze));
887 env.close();
888
889 auto const loanASle = env.le(loanAKeylet);
890 if (!BEAST_EXPECT(loanASle))
891 return;
892 Number const paymentA = Number(loanASle->at(sfPeriodicPayment)) + serviceFee;
893 env(pay(depositor, loanAKeylet.key, asset(paymentA).value()));
894 env.close();
895
896 auto const brokerSleBefore = env.le(fixture.brokerKeylet);
897 auto const vaultSleBefore = env.le(fixture.vaultKeylet);
898 if (!BEAST_EXPECT(brokerSleBefore) || !BEAST_EXPECT(vaultSleBefore))
899 return;
900 Number const coverBefore = brokerSleBefore->at(sfCoverAvailable);
901 // CoverAvailable is past 1e10, so its grid is 1e-5; AssetsAvailable
902 // is still on the 1e-6 base grid.
903 BEAST_EXPECT(coverBefore > Number(1, 10));
904 BEAST_EXPECT(Number(vaultSleBefore->at(sfAssetsAvailable)) < Number(1, 10));
905
906 closePastGrace(env, loanBKeylet);
907 auto const before = snapshotVault(env, fixture.vaultKeylet, asset);
908
909 env(manage(owner, loanBKeylet.key, tfLoanDefault), Ter(tesSUCCESS));
910 env.close();
911
912 auto const after = snapshotVault(env, fixture.vaultKeylet, asset);
913 auto const brokerSleAfter = env.le(fixture.brokerKeylet);
914 if (!BEAST_EXPECT(brokerSleAfter))
915 return;
916 Number const coverAfter = brokerSleAfter->at(sfCoverAvailable);
917
918 // DebtTotal is principalB alone (loan A is paid off): cover is
919 // 5% of 1234.567891 = 61.72839455, floored on the 1e-6 grid.
920 Number const expectedCover{61728394, -6};
921 BEAST_EXPECT(after.available - before.available == expectedCover);
922 // CoverAvailable - cover needs a 1e-6 digit its 1e-5 grid cannot hold,
923 // so the broker absorbs the rounding.
924 BEAST_EXPECT(coverBefore - coverAfter != expectedCover);
925 BEAST_EXPECT(abs((coverBefore - coverAfter) - expectedCover) <= Number(5, -6));
926 // The broker pseudo-account's trust line rounds the same way.
927 Account const brokerPseudo{"brokerPseudo", brokerSleAfter->at(sfAccount)};
928 BEAST_EXPECT(Number(env.balance(brokerPseudo, asset).value()) == coverAfter);
929
931 env, fixture, {loanBKeylet}, "testDefaultCoverRoundsOnCoarsenedBrokerGrid");
932 }
933
934 // Like VaultFixedPrecisionBase::setupMpt, but the issuance also allows
935 // clawback (tfMPTCanClawback), needed for VaultClawback against an MPT
936 // vault asset. Only the owner and depositor are funded; the depositor
937 // holds the balance and is the vault's sole depositor.
938 static AssetAccounts
940 {
941 using namespace test::jtx;
942
944 env.fund(XRP(1'000'000), a.issuer, a.owner, a.depositor);
945 env.close();
946
947 MPTTester mpt{env, a.issuer, kMptInitNoFund};
948 mpt.create({.maxAmt = maxAmt, .flags = tfMPTCanTransfer | tfMPTCanClawback});
949 a.asset = mpt.issuanceID();
950 mpt.authorize({.account = a.owner});
951 mpt.authorize({.account = a.depositor});
952 env(pay(a.issuer, a.depositor, a.asset(holderFunds)));
953 env.close();
954 return a;
955 }
956
957 // A sole holder's shares are priced without the unrealized-loss
958 // discount, for VaultWithdraw and VaultClawback alike, so the smallest
959 // amount either can take is one full share's value. A request
960 // below that truncates to zero shares and is refused with
961 // tecPRECISION_LOSS. This is share granularity, by design.
962 void
964 {
965 using namespace test::jtx;
966 using namespace loan;
967
968 testcase("sole-holder VaultClawback below one share's value is tecPRECISION_LOSS");
969
970 Env env(*this, features());
971 auto const [issuer, owner, depositor, asset] = setupClawbackMpt(env, 1'000'000, 900'000);
972
973 // Deposit two MPT into an empty vault, exactly matching the scenario: the
974 // sole holder owns exactly 2 integral shares. Ten doubling cycles (100%
975 // interest, single payment, repaid in full each time) grow AssetsTotal
976 // without ever touching the share count -- the "originate, repay, and
977 // delete...loans that grow the vault" step this scenario depends on. The
978 // exact multiplier does not need to match any particular target, only the
979 // mechanism: a sole holder with an integral share count small enough that
980 // pricing without the loss discount truncates a liquid partial request to zero shares.
981 auto const fixture = setupLendingVault(
982 env, owner, depositor, asset, Number{2}, std::chrono::seconds{400'000'000});
983 compoundVaultBySoleHolderLoanCycles(env, fixture, depositor, asset, 10);
984
985 auto const vaultSle0 = env.le(fixture.vaultKeylet);
986 if (!BEAST_EXPECT(vaultSle0))
987 return;
988 BEAST_EXPECT(Number(vaultSle0->at(sfAssetsDeployed)) == beast::kZero);
989 std::uint64_t const grownTotal = toU64(vaultSle0, sfAssetsAvailable);
990 BEAST_EXPECT(grownTotal >= 512);
991
992 auto const shareMPTID = vaultSle0->at(sfShareMPTID);
993 auto const issuance0 = env.le(keylet::mptokenIssuance(shareMPTID));
994 if (!BEAST_EXPECT(issuance0))
995 return;
996 BEAST_EXPECT(issuance0->getFieldU64(sfOutstandingAmount) == 2);
997
998 // Originate a loan for half the grown vault and impair it fully:
999 // AssetsAvailable stays liquid at (grownTotal - principal), and
1000 // LossUnrealized == AssetsDeployed == principal is the illiquid half,
1001 // matching a liquid/illiquid split (AssetsAvailable=898,
1002 // LossUnrealized=902, AssetsTotal=1800) sized to the same mechanism.
1003 std::uint64_t const principal = grownTotal / 2;
1004 auto const loanKeylet =
1005 openLoan(env, fixture, Number{static_cast<std::int64_t>(principal)}, 3);
1006 impairWhenLate(env, owner, loanKeylet);
1007
1008 auto const vaultSle1 = env.le(fixture.vaultKeylet);
1009 if (!BEAST_EXPECT(vaultSle1))
1010 return;
1011 std::uint64_t const available = toU64(vaultSle1, sfAssetsAvailable);
1012 BEAST_EXPECT(available == grownTotal - principal);
1013 BEAST_EXPECT(toU64(vaultSle1, sfAssetsDeployed) == principal);
1014 BEAST_EXPECT(toU64(vaultSle1, sfLossUnrealized) == principal);
1015 BEAST_EXPECT(getAssetsTotal(vaultSle1) == Number{static_cast<std::int64_t>(grownTotal)});
1016
1017 // Half of the liquid balance is less than one share's value without the
1018 // loss discount (grownTotal / 2), so it converts to zero shares.
1019 std::uint64_t const requested = available / 2;
1020 if (!BEAST_EXPECT(requested > 0))
1021 return;
1022 BEAST_EXPECT(2 * requested < grownTotal);
1023
1024 env(fixture.vault.clawback({
1025 .issuer = issuer,
1026 .id = fixture.vaultKeylet.key,
1027 .holder = depositor,
1028 .amount = asset(requested).value(),
1029 }),
1030 Ter(tecPRECISION_LOSS));
1031 env.close();
1032
1033 auto const vaultSleAfter = env.le(fixture.vaultKeylet);
1034 auto const issuanceAfter = env.le(keylet::mptokenIssuance(shareMPTID));
1035 if (!BEAST_EXPECT(vaultSleAfter) || !BEAST_EXPECT(issuanceAfter))
1036 return;
1037 BEAST_EXPECT(toU64(vaultSleAfter, sfAssetsAvailable) == available);
1038 BEAST_EXPECT(issuanceAfter->getFieldU64(sfOutstandingAmount) == 2);
1039
1041 env, fixture, {loanKeylet}, "testSoleHolderClawbackBelowOneShareIsPrecisionLoss");
1042 }
1043
1044 // A clawback worth more than AssetsAvailable is clamped to the
1045 // whole shares AssetsAvailable can pay for. Here the request is two
1046 // shares' worth and the vault holds one share's worth in cash.
1047 void
1049 {
1050 using namespace test::jtx;
1051 using namespace loan;
1052
1053 testcase("sole-holder VaultClawback above AssetsAvailable is clamped to whole shares");
1054
1055 Env env(*this, features());
1056 auto const [issuer, owner, depositor, asset] = setupClawbackMpt(env, 1'000'000, 900'000);
1057
1058 auto const fixture = setupLendingVault(
1059 env, owner, depositor, asset, Number{2}, std::chrono::seconds{400'000'000});
1060 compoundVaultBySoleHolderLoanCycles(env, fixture, depositor, asset, 10);
1061
1062 auto const vaultSle0 = env.le(fixture.vaultKeylet);
1063 if (!BEAST_EXPECT(vaultSle0))
1064 return;
1065 std::uint64_t const grownTotal = toU64(vaultSle0, sfAssetsAvailable);
1066 std::uint64_t const principal = grownTotal / 2;
1067 auto const loanKeylet =
1068 openLoan(env, fixture, Number{static_cast<std::int64_t>(principal)}, 3);
1069 impairWhenLate(env, owner, loanKeylet);
1070
1071 auto const shareMPTID = vaultSle0->at(sfShareMPTID);
1072 auto const vaultSle1 = env.le(fixture.vaultKeylet);
1073 if (!BEAST_EXPECT(vaultSle1))
1074 return;
1075 std::uint64_t const available = toU64(vaultSle1, sfAssetsAvailable);
1076 BEAST_EXPECT(available == grownTotal - principal);
1077
1078 // Two shares' worth, without the loss discount, is the whole AssetsTotal.
1079 env(fixture.vault.clawback({
1080 .issuer = issuer,
1081 .id = fixture.vaultKeylet.key,
1082 .holder = depositor,
1083 .amount = asset(grownTotal).value(),
1084 }),
1085 Ter(tesSUCCESS));
1086 env.close();
1087
1088 auto const vaultSleAfter = env.le(fixture.vaultKeylet);
1089 auto const issuanceAfter = env.le(keylet::mptokenIssuance(shareMPTID));
1090 if (!BEAST_EXPECT(vaultSleAfter) || !BEAST_EXPECT(issuanceAfter))
1091 return;
1092 // One share burned, one share's worth recovered.
1093 BEAST_EXPECT(issuanceAfter->getFieldU64(sfOutstandingAmount) == 1);
1094 BEAST_EXPECT(toU64(vaultSleAfter, sfAssetsAvailable) == available - (grownTotal / 2));
1095 BEAST_EXPECT(toU64(vaultSleAfter, sfAssetsDeployed) == principal);
1096
1097 checkVaultLoanSums(env, fixture, {loanKeylet}, "testSoleHolderClawbackClampsToWholeShares");
1098 }
1099
1100 // Control case: the full/burn-all clawback path the sole-holder waiver
1101 // was designed for still clamps to AssetsAvailable, per
1102 // testLendingFullClawbackClampsInsteadOfHasObligations, on the same
1103 // liquid/illiquid split constructed above -- so the partial-request
1104 // failure above is not a regression of the full-recovery path the
1105 // waiver was meant to fix.
1106 void
1108 {
1109 using namespace test::jtx;
1110 using namespace loan;
1111
1112 testcase(
1113 "sole-holder full VaultClawback on a liquid/illiquid split still "
1114 "clamps to AssetsAvailable instead of tecHAS_OBLIGATIONS");
1115
1116 Env env(*this, features());
1117 auto const [issuer, owner, depositor, asset] = setupClawbackMpt(env, 1'000'000, 900'000);
1118
1119 auto const fixture = setupLendingVault(
1120 env, owner, depositor, asset, Number{2}, std::chrono::seconds{400'000'000});
1121 compoundVaultBySoleHolderLoanCycles(env, fixture, depositor, asset, 10);
1122
1123 auto const vaultSle0 = env.le(fixture.vaultKeylet);
1124 if (!BEAST_EXPECT(vaultSle0))
1125 return;
1126 std::uint64_t const grownTotal = toU64(vaultSle0, sfAssetsAvailable);
1127 std::uint64_t const principal = grownTotal / 2;
1128 auto const loanKeylet =
1129 openLoan(env, fixture, Number{static_cast<std::int64_t>(principal)}, 3);
1130 impairWhenLate(env, owner, loanKeylet);
1131
1132 auto const shareMPTID = vaultSle0->at(sfShareMPTID);
1133 auto const issuanceBefore = env.le(keylet::mptokenIssuance(shareMPTID));
1134 if (!BEAST_EXPECT(issuanceBefore))
1135 return;
1136 BEAST_EXPECT(issuanceBefore->getFieldU64(sfOutstandingAmount) == 2);
1137
1138 env(fixture.vault.clawback(
1139 {.issuer = issuer, .id = fixture.vaultKeylet.key, .holder = depositor}),
1140 Ter(tesSUCCESS));
1141 env.close();
1142
1143 auto const vaultSleAfter = env.le(fixture.vaultKeylet);
1144 auto const issuanceAfter = env.le(keylet::mptokenIssuance(shareMPTID));
1145 if (!BEAST_EXPECT(vaultSleAfter) || !BEAST_EXPECT(issuanceAfter))
1146 return;
1147 BEAST_EXPECT(toU64(vaultSleAfter, sfAssetsAvailable) == 0);
1148 BEAST_EXPECT(toU64(vaultSleAfter, sfAssetsDeployed) == principal);
1149 // Shares are left behind rather than burning every share while AssetsDeployed
1150 // is non-zero (VaultClawback::doApply's tecHAS_OBLIGATIONS guard).
1151 std::uint64_t const sharesAfter = issuanceAfter->getFieldU64(sfOutstandingAmount);
1152 // A clamped partial clawback can only ever leave the sole holder's
1153 // single remaining share outstanding.
1154 BEAST_EXPECT(sharesAfter == 1);
1155
1157 env,
1158 fixture,
1159 {loanKeylet},
1160 "testSoleHolderFullClawbackClampsWithLiquidAndIlliquidSplit");
1161 }
1162
1163 void
1165 {
1166 using namespace test::jtx;
1167 using namespace loan;
1168 using namespace loan_broker;
1169 using namespace lending;
1170
1171 testcase(
1172 "Lending: a default's cover just under one ulp on an all-nines "
1173 "AssetsAvailable is forgiven, not credited negative");
1174
1175 // An issuer with trust line clawback enabled, a depositor holding
1176 // 10,000,000 USD, and a broker owner holding 100 USD for cover.
1177 Env env(*this, features());
1178 auto const [issuer, owner, depositor, asset] = setupIou(
1179 env,
1180 {
1181 .clawback = true,
1182 .depositorTrust = 30'000'000,
1183 .ownerTrust = 1'000,
1184 .depositorFunds = 10'000'000,
1185 .ownerFunds = 100,
1186 });
1187
1188 // A closed-ended vault at Scale 10 with a 15-year investment window
1189 // and 899,999 USD deposited. The Open limit at this scale is 900,000
1190 // and the all-nines 16-digit AssetsAvailable at the base grid is
1191 // 999,999.9999999999, so the vault must grow past the Open limit
1192 // through late interest before it can reach the target.
1193 std::uint8_t const scale = 10;
1194 std::chrono::seconds const investmentWindow{15 * 365 * 24 * 60 * 60};
1195 // Both cover rates at one tenth of a basis point: cover = DebtTotal *
1196 // 1e-5 * 1e-5, so a DebtTotal in [0.995, 1) gives a cover in
1197 // [9.95e-11, 1e-10): under one unit of the base grid, but close enough
1198 // that its sum with AssetsAvailable rounds up to the next power of ten.
1199 TenthBips32 const coverRate{1};
1200 auto const fixture = setupLendingVault(
1201 env,
1202 owner,
1203 depositor,
1204 asset,
1205 Number{899'999},
1206 investmentWindow,
1207 scale,
1208 coverRate,
1209 coverRate);
1210 auto const& vaultKeylet = fixture.vaultKeylet;
1211 auto const& brokerKeylet = fixture.brokerKeylet;
1212
1213 env(coverDeposit(owner, brokerKeylet.key, asset(100).value()));
1214 env.close();
1215
1216 // The target: all nines across 16 digits at the base grid.
1217 Number const target{9'999'999'999'999'999LL, -10};
1218 std::uint32_t const gracePeriod = 60;
1219
1220 // Loan A, the coarsening loan: one late payment clears it from
1221 // DebtTotal while its penalty interest pushes AssetsAvailable past
1222 // 1,000,000.
1223 Number const loanAPrincipal{700'000};
1224 auto const loanAKeylet = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(1));
1225 env(set(depositor, brokerKeylet.key, loanAPrincipal),
1226 kInterestRate(TenthBips32(0)),
1227 kLateInterestRate(kMaxLateInterestRate),
1228 kGracePeriod(gracePeriod),
1229 kPaymentInterval(120),
1230 kPaymentTotal(1),
1231 Sig(sfCounterpartySignature, owner),
1232 Fee(env.current()->fees().base * 2));
1233 env.close();
1234
1235 // Loan B, the defaulting loan: still current when the overpayment
1236 // lands.
1237 std::uint32_t const thousandDays = 1000 * 24 * 60 * 60;
1238 Number const loanBPrincipal{100};
1239 auto const loanBKeylet = keylet::loan(brokerKeylet.key, SeqProxy::rawSequence(2));
1240 env(set(depositor, brokerKeylet.key, loanBPrincipal, tfLoanOverpayment),
1241 kInterestRate(TenthBips32(0)),
1242 kGracePeriod(gracePeriod),
1243 kPaymentInterval(thousandDays),
1244 kPaymentTotal(2),
1245 Sig(sfCounterpartySignature, owner),
1246 Fee(env.current()->fees().base * 2));
1247 env.close();
1248
1249 auto const loanASle = env.le(loanAKeylet);
1250 if (!BEAST_EXPECT(loanASle))
1251 return;
1252 std::uint32_t const loanADueDate = loanASle->at(sfNextPaymentDueDate);
1253 env.close(
1254 NetClock::time_point{NetClock::duration{loanADueDate + gracePeriod}} +
1255 std::chrono::seconds{800 * 24 * 60 * 60});
1256 env(pay(depositor, loanAKeylet.key, asset(loanAPrincipal * 10).value(), tfLoanLatePayment));
1257 env.close();
1258 Number const availableAfterLoanA = snapshotVault(env, vaultKeylet, asset).available;
1259
1260 // Claw back to about target - 99.003, so the overpayment below leaves
1261 // Loan B's principal, which is also DebtTotal, in [0.995, 1).
1262 Number const clawbackTarget = target - Number{99'003, -3};
1263 env(fixture.vault.clawback({
1264 .issuer = issuer,
1265 .id = vaultKeylet.key,
1266 .holder = depositor,
1267 .amount = asset(availableAfterLoanA - clawbackTarget).value(),
1268 }));
1269 env.close();
1270
1271 // A zero-interest overpayment credits the vault by exactly the amount
1272 // paid, so AssetsAvailable lands on the target.
1273 Number const availableAfterClawback = snapshotVault(env, vaultKeylet, asset).available;
1274 env(
1275 pay(depositor,
1276 loanBKeylet.key,
1277 asset(target - availableAfterClawback).value(),
1278 tfLoanOverpayment));
1279 env.close();
1280
1281 auto const brokerBefore = env.le(brokerKeylet);
1282 if (!BEAST_EXPECT(brokerBefore))
1283 return;
1284 Number const debtTotal = brokerBefore->at(sfDebtTotal);
1285 BEAST_EXPECT(debtTotal >= Number(995, -3) && debtTotal < Number{1});
1286 auto const before = snapshotVault(env, vaultKeylet, asset);
1287 BEAST_EXPECT(before.available == target);
1288 Account const brokerAccount{"broker", brokerBefore->at(sfAccount)};
1289 Number const coverBefore = brokerBefore->at(sfCoverAvailable);
1290 Number const brokerBalanceBefore = env.balance(brokerAccount, asset).value();
1291
1292 closePastGrace(env, loanBKeylet);
1293
1294 // The cover rounds away on the vault's grid, so the default forgives it:
1295 // nothing is credited to the vault or taken from the broker.
1296 env(manage(owner, loanBKeylet.key, tfLoanDefault), Ter(tesSUCCESS));
1297 env.close();
1298
1299 auto const loanBAfter = env.le(loanBKeylet);
1300 if (!BEAST_EXPECT(loanBAfter))
1301 return;
1302 BEAST_EXPECT(loanBAfter->isFlag(lsfLoanDefault));
1303 auto const after = snapshotVault(env, vaultKeylet, asset);
1304 BEAST_EXPECT(after.available == before.available);
1305 BEAST_EXPECT(after.vaultBalance == before.vaultBalance);
1306 auto const brokerAfter = env.le(brokerKeylet);
1307 if (!BEAST_EXPECT(brokerAfter))
1308 return;
1309 BEAST_EXPECT(brokerAfter->at(sfCoverAvailable) == coverBefore);
1310 BEAST_EXPECT(env.balance(brokerAccount, asset).value() == brokerBalanceBefore);
1311 }
1312
1313public:
1314 void
1333};
1334
1335BEAST_DEFINE_TESTSUITE(LoanManageFixedPrecision, app, xrpl);
1336
1337} // namespace xrpl
TestcaseT testcase
Memberspace for declaring test cases.
Definition suite.h:155
static LendingFixture setupLendingVault(test::jtx::Env &env, test::jtx::Account const &owner, test::jtx::Account const &depositor, PrettyAsset const &asset, Number const &depositAmount, std::chrono::seconds investmentWindow=std::chrono::seconds{1 '000 '000}, std::optional< std::uint8_t > scale=std::nullopt, TenthBips32 coverRateMinimum=TenthBips32(0), TenthBips32 coverRateLiquidation=TenthBips32(0), TenthBips16 managementFeeRate=TenthBips16(0))
static Keylet openLoan(test::jtx::Env &env, LendingFixture const &fixture, Number const &principal, std::uint32_t paymentTotal, TenthBips32 interestRate=TenthBips32(0), std::uint32_t flags=0, std::uint32_t paymentInterval=120, std::uint32_t gracePeriod=60)
void defaultAfterGrace(test::jtx::Env &env, test::jtx::Account const &owner, Keylet const &loanKeylet)
void closePastGrace(test::jtx::Env &env, Keylet const &loanKeylet)
void impairWhenLate(test::jtx::Env &env, test::jtx::Account const &owner, Keylet const &loanKeylet)
void checkImpairUnimpairDefault(test::jtx::Env &env, test::jtx::Account const &owner, test::jtx::Account const &depositor, PrettyAsset const &asset, Number const &depositAmount, Number const &principal, std::string const &label)
static AssetAccounts setupClawbackMpt(test::jtx::Env &env, std::uint64_t maxAmt, std::uint64_t holderFunds)
SmallAssetsDeployedState setupSmallAssetsDeployedVault(test::jtx::Env &env, test::jtx::Account const &owner, test::jtx::Account const &depositor, PrettyAsset const &asset, std::string const &label)
CoarsenedVault coarsenVault(test::jtx::Env &env, test::jtx::Account const &owner, test::jtx::Account const &depositor, PrettyAsset const &asset)
static AssetAccounts setupCoarsenIou(test::jtx::Env &env, bool clawback=false)
void expectCoarsened(test::jtx::Env const &env, CoarsenedVault const &coarsened)
static std::uint64_t toU64(SLE::ConstRef vault, TypedField< T > const &field)
void compoundVaultBySoleHolderLoanCycles(test::jtx::Env &env, LendingFixture const &fixture, test::jtx::Account const &depositor, PrettyAsset const &asset, int cycles)
void checkVaultLoanSums(test::jtx::Env &env, CoarsenedVault const &coarsened, std::string const &label={})
std::chrono::time_point< NetClock > time_point
Definition chrono.h:48
std::chrono::duration< rep, period > duration
Definition chrono.h:47
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
static constexpr SeqProxy rawSequence(std::uint32_t v)
Factory function to return a sequence-based SeqProxy.
Definition SeqProxy.h:62
static AssetAccounts setupIou(test::jtx::Env &env, IouParams const &params)
VaultSnapshot snapshotVault(test::jtx::Env &env, Keylet const &vaultKeylet, PrettyAsset const &asset)
SLE::const_pointer expectVault(test::jtx::Env const &env, Keylet const &vaultKeylet, VaultExpect const &expected)
static AssetAccounts setupMpt(test::jtx::Env &env, MptParams const &params)
Number expectAvailableAtSixteenDigits(test::jtx::Env const &env, Keylet const &vaultKeylet, PrettyAsset const &asset)
test::jtx::PrettyAsset PrettyAsset
Immutable cryptographic account descriptor.
Definition jtx/Account.h:21
A transaction testing environment.
Definition Env.h:161
bool close(NetClock::time_point closeTime, std::optional< std::chrono::milliseconds > consensusDelay=std::nullopt)
Close and advance the ledger.
Definition Env.cpp:133
SLE::const_pointer le(Account const &account) const
Return an account root.
Definition Env.cpp:311
void fund(bool setDefaultRipple, STAmount const &amount, Account const &account)
Definition Env.cpp:323
T min(T... args)
constexpr Zero kZero
Definition Zero.h:30
Keylet loan(UInt256 const &loanBrokerID, SeqProxy const &loanSeq) noexcept
Definition Indexes.cpp:577
Keylet mptokenIssuance(MPTID const &issuanceID) noexcept
Definition Indexes.cpp:541
Use hash_* containers for keys that do not need a cryptographically secure hashing algorithm.
Definition algorithm.h:5
bool set(T &target, std::string const &name, Section const &section)
Set a value from a configuration Section If the named value is not found or doesn't parse as a T,...
Issue const & xrpIssue()
Returns an asset specifier that represents XRP.
Definition Issue.h:108
STAmount debitToPosteriorBrokerCoverScale(SLE::ConstRef vault, SLE::ConstRef broker, STAmount const &amount, Number::RoundingMode roundingMode)
Round a cover debit (cover withdraw, cover clawback, the broker-side decrease of a default's cover cr...
constexpr TenthBips32 percentageToTenthBips(std::uint32_t percentage)
Definition Protocol.h:127
constexpr T tenthBipsOfValue(T value, TenthBips< TBips > bips)
Definition Protocol.h:139
int scale(Number const &number, Asset const &asset)
Get the scale of a Number for a given asset.
Definition STAmount.h:819
int getVaultScale(SLE::ConstRef vault)
Return the Vault's current live exponent.
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
bool after(NetClock::time_point now, std::uint32_t mark)
Has the specified time passed?
Definition View.cpp:668
int getVaultBaseScale(SLE::ConstRef vault)
Return the Vault's base exponent.
constexpr Number abs(Number x) noexcept
Definition Number.h:880
@ tecPRECISION_LOSS
Definition TER.h:374
@ tecHAS_OBLIGATIONS
Definition TER.h:328
Number getAssetsTotal(SLE::ConstRef vault)
Return the Vault's current assets total.
STAmount creditToPosteriorAvailableScale(SLE::ConstRef vault, Number const &raw, Number::RoundingMode roundingMode)
Round a FixedPrecision cash inflow (LoanPay's credit, LoanManage's default cover credit) into AssetsA...
BEAST_DEFINE_TESTSUITE(AccountTxPaging, app, xrpl)
@ tesSUCCESS
Definition TER.h:253
A pair of SHAMap key and LedgerEntryType.
Definition Keylet.h:20