xrpld
Loading...
Searching...
No Matches
LoanSetFixedPrecision_test.cpp
1#include <test/app/lending/LoanFixedPrecisionBase.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/sig.h>
8#include <test/jtx/ter.h>
9#include <test/jtx/vault.h>
10
11#include <xrpl/basics/Number.h>
12#include <xrpl/basics/chrono.h>
13#include <xrpl/beast/unit_test/suite.h>
14#include <xrpl/beast/utility/Zero.h>
15#include <xrpl/ledger/helpers/VaultHelpers.h>
16#include <xrpl/protocol/Asset.h>
17#include <xrpl/protocol/Feature.h>
18#include <xrpl/protocol/Indexes.h>
19#include <xrpl/protocol/Issue.h>
20#include <xrpl/protocol/Keylet.h>
21#include <xrpl/protocol/Protocol.h>
22#include <xrpl/protocol/SField.h>
23#include <xrpl/protocol/STAmount.h>
24#include <xrpl/protocol/SeqProxy.h>
25#include <xrpl/protocol/TER.h>
26#include <xrpl/protocol/Units.h>
27
28#include <chrono>
29#include <cstdint>
30#include <optional>
31#include <string>
32#include <utility>
33#include <vector>
34
35namespace xrpl {
36
38{
39 void
41 {
42 using namespace test::jtx;
43
44 struct Row
45 {
46 char const* name = nullptr;
47 std::vector<Number> principals;
48 };
49 Row const rows[] = {
50 {
51 .name =
52 "LoanSet on a FixedPrecision vault increments AssetsDeployed by the principal",
53 .principals = {Number{300}},
54 },
55 {
56 .name = "Two Loans on the same FixedPrecision vault sum into AssetsDeployed",
57 .principals = {Number{100}, Number{200}},
58 },
59 };
60 for (auto const& row : rows)
61 {
62 testcase(row.name);
63
64 Number const vaultDeposit{1'000};
65 constexpr std::uint32_t paymentTotal = 2;
66
67 Env env(*this, features());
68 auto const [issuer, owner, depositor, asset] = setupIou(env);
69
70 auto const fixture = setupLendingVault(env, owner, depositor, asset, vaultDeposit);
71
72 checkFixedPrecisionSync(env, fixture.vaultKeylet, vaultDeposit);
73
74 std::vector<Keylet> loanKeylets;
75 Number totalPrincipal{0};
76 for (auto const& principal : row.principals)
77 {
78 loanKeylets.push_back(openLoan(env, fixture, principal, paymentTotal));
79 totalPrincipal += principal;
80 }
81
82 auto const sle = expectVault(
83 env,
84 fixture.vaultKeylet,
85 {.available = vaultDeposit - totalPrincipal, .assetsDeployed = totalPrincipal});
86 if (!sle)
87 return;
88 // Origination books principal as debt only; AssetsTotal is unchanged.
89 BEAST_EXPECT(sle->at(sfAssetsTotal) == vaultDeposit);
90
91 Number principalOutstanding{0};
92 for (auto const& loanKeylet : loanKeylets)
93 {
94 auto const loanSle = env.le(loanKeylet);
95 if (!BEAST_EXPECT(loanSle))
96 return;
97 principalOutstanding += loanSle->at(sfPrincipalOutstanding);
98 }
99 BEAST_EXPECT(sle->at(sfAssetsDeployed) == principalOutstanding);
100 checkVaultLoanSums(env, fixture, loanKeylets, row.name);
101 }
102 }
103
104 // YieldUnrealized books only the Vault's share of the interest: gross
105 // interest less the broker's management fee. Covers IOU, XRP and MPT
106 // Vaults, since XRP and MPT use base scale 0.
107 void
109 {
110 using namespace test::jtx;
111
112 enum class AssetKind { Iou, Xrp, Mpt };
113 struct Row
114 {
115 char const* name = nullptr;
116 AssetKind kind = AssetKind::Iou;
117 Number deposit;
118 Number principal;
119 };
120 Row const rows[] = {
121 {
122 .name = "LoanSet on an IOU FixedPrecision vault books interest net of the "
123 "management fee",
124 .kind = AssetKind::Iou,
125 .deposit = Number{1'000},
126 .principal = Number{300},
127 },
128 {
129 .name = "LoanSet on an XRP FixedPrecision vault books interest net of the "
130 "management fee",
131 .kind = AssetKind::Xrp,
132 .deposit = Number{10'000'000},
133 .principal = Number{3'000'000},
134 },
135 {
136 .name = "LoanSet on an MPT FixedPrecision vault books interest net of the "
137 "management fee",
138 .kind = AssetKind::Mpt,
139 .deposit = Number{10'000'000},
140 .principal = Number{3'000'000},
141 },
142 };
143 for (auto const& row : rows)
144 {
145 testcase(row.name);
146
147 constexpr std::uint32_t paymentTotal = 2;
148 constexpr std::uint32_t paymentInterval = 30 * 24 * 60 * 60;
149 TenthBips32 const interestRate{12'000};
150 TenthBips16 const managementFeeRate{10'000};
151
152 Env env(*this, features());
153 AssetAccounts accounts;
154 switch (row.kind)
155 {
156 case AssetKind::Iou:
157 accounts = setupIou(env);
158 break;
159 case AssetKind::Xrp:
160 env.fund(XRP(1'000'000), accounts.owner, accounts.depositor);
161 env.close();
162 accounts.asset = xrpIssue();
163 break;
164 case AssetKind::Mpt:
165 accounts = setupMpt(
166 env,
167 {.maxAmt = 100'000'000, .withDepositor = true, .holderFunds = 10'000'000});
168 break;
169 }
170
171 auto const fixture = setupLendingVault(
172 env,
173 accounts.owner,
174 accounts.depositor,
175 accounts.asset,
176 row.deposit,
177 std::chrono::seconds{10'000'000},
178 std::nullopt,
179 TenthBips32(0),
180 TenthBips32(0),
181 managementFeeRate);
182
183 auto const loanKeylet = openLoan(
184 env, fixture, row.principal, paymentTotal, interestRate, 0, paymentInterval);
185
186 auto const loanSle = env.le(loanKeylet);
187 auto const vaultSle = env.le(fixture.vaultKeylet);
188 if (!BEAST_EXPECT(loanSle && vaultSle))
189 return;
190
191 Number const principal = loanSle->at(sfPrincipalOutstanding);
192 Number const grossInterest = loanSle->at(sfTotalValueOutstanding) - principal;
193 Number const managementFee = loanSle->at(sfManagementFeeOutstanding);
194 BEAST_EXPECT(principal == row.principal);
195 BEAST_EXPECT(managementFee > beast::kZero);
196 BEAST_EXPECT(grossInterest > managementFee);
197
198 BEAST_EXPECT(vaultSle->at(sfAssetsDeployed) == row.principal);
199 BEAST_EXPECT(Number(vaultSle->at(sfYieldUnrealized)) == grossInterest - managementFee);
200 // Origination books principal as debt only; AssetsTotal is unchanged.
201 BEAST_EXPECT(vaultSle->at(sfAssetsTotal) == row.deposit);
202 checkVaultLoanSums(env, fixture, {loanKeylet}, row.name);
203 }
204 }
205
206 void
208 {
209 using namespace test::jtx;
210
211 testcase("VaultClawback and partial VaultWithdraw succeed while a Loan is open");
212
213 Number const vaultDeposit{1'000};
214 std::chrono::seconds const investmentWindow{600};
215 Number const principal{400};
216 constexpr std::uint32_t paymentTotal = 2;
217 Number const clawbackAmount{100};
218 Number const withdrawAmount{100};
219
220 Env env(*this, features());
221 auto const [issuer, owner, depositor, asset] = setupIou(env, {.clawback = true});
222
223 auto const fixture =
224 setupLendingVault(env, owner, depositor, asset, vaultDeposit, investmentWindow);
225 auto const loanKeylet = openLoan(env, fixture, principal, paymentTotal);
226
227 // Withdrawals need the Redemption phase; open loans are not phase-gated.
228 env.close(fixture.redemptionDate + std::chrono::seconds{1});
229
230 // AssetsAvailable = 600, AssetsTotal = 1000, AssetsDeployed = 400. AssetsTotal
231 // must be recomputed from AssetsAvailable + AssetsDeployed, not reduced by the
232 // clawed-back amount.
233 env(fixture.vault.clawback({
234 .issuer = issuer,
235 .id = fixture.vaultKeylet.key,
236 .holder = depositor,
237 .amount = asset(clawbackAmount).value(),
238 }));
239 env.close();
240
241 Number const availableAfterClawback = vaultDeposit - principal - clawbackAmount;
242 Number const totalAfterClawback = vaultDeposit - clawbackAmount;
243 auto sle = expectVault(
244 env,
245 fixture.vaultKeylet,
246 {
247 .available = availableAfterClawback,
248 .assetsDeployed = principal,
249 .total = totalAfterClawback,
250 });
251 if (!sle)
252 return;
253 checkVaultLoanSums(env, fixture, {loanKeylet}, "after clawback");
254
255 env(fixture.vault.withdraw({
256 .depositor = depositor,
257 .id = fixture.vaultKeylet.key,
258 .amount = asset(withdrawAmount),
259 }));
260 env.close();
261
262 sle = env.le(fixture.vaultKeylet);
263 if (!BEAST_EXPECT(sle))
264 return;
265 Number const availableAfterWithdraw = availableAfterClawback - withdrawAmount;
266 Number const totalAfterWithdraw = totalAfterClawback - withdrawAmount;
267 BEAST_EXPECT(sle->at(sfAssetsAvailable) == availableAfterWithdraw);
268 BEAST_EXPECT(sle->at(sfAssetsDeployed) == principal);
269 BEAST_EXPECT(sle->at(sfAssetsTotal) == getAssetsTotal(sle));
270 BEAST_EXPECT(sle->at(sfAssetsTotal) == totalAfterWithdraw);
271 checkVaultLoanSums(env, fixture, {loanKeylet}, "after withdraw");
272 }
273
274 // A full-value VaultWithdraw exceeds AssetsAvailable while a Loan is open.
275 // FixedPrecision checks AssetsDeployed != 0 before the insufficient-funds guard, so
276 // it reports tecHAS_OBLIGATIONS; CashBasis has no such guard.
277 void
279 {
280 using namespace test::jtx;
281
282 struct Row
283 {
284 char const* name = nullptr;
285 FeatureBitset amendments;
286 TER ter;
287 bool fixedPrecision = false;
288 };
289 Row const rows[] = {
290 {
291 .name = "full-value VaultWithdraw while AssetsDeployed is non-zero hits the "
292 "FixedPrecision tecHAS_OBLIGATIONS guard",
293 .amendments = features(),
294 .ter = tecHAS_OBLIGATIONS,
295 .fixedPrecision = true,
296 },
297 {
298 .name =
299 "CashBasis: full-value VaultWithdraw while a Loan is open hits the ordinary "
300 "insufficient-funds guard",
301 .amendments = features() - featureLendingProtocolV1_2,
303 .fixedPrecision = false,
304 },
305 };
306 Number const vaultDeposit{1'000};
307 std::chrono::seconds const investmentWindow{600};
308 Number const principal{400};
309 constexpr std::uint32_t paymentTotal = 2;
310
311 for (auto const& row : rows)
312 {
313 testcase(row.name);
314
315 Env env(*this, row.amendments);
316 auto const [issuer, owner, depositor, asset] = setupIou(env);
317
318 auto const fixture =
319 setupLendingVault(env, owner, depositor, asset, vaultDeposit, investmentWindow);
320 if (!row.fixedPrecision)
321 {
322 auto const sleBefore = env.le(fixture.vaultKeylet);
323 if (!BEAST_EXPECT(sleBefore))
324 return;
325 BEAST_EXPECT(!sleBefore->isFieldPresent(sfAssetsDeployed));
326 }
327 auto const loanKeylet = openLoan(env, fixture, principal, paymentTotal);
328
329 // Withdrawals need the Redemption phase.
330 env.close(fixture.redemptionDate + std::chrono::seconds{1});
331
332 // The depositor's shares are worth the full 1000 AssetsTotal, so redeeming
333 // all of them is a final withdrawal that also exceeds AssetsAvailable (600).
334 env(fixture.vault.withdraw({
335 .depositor = depositor,
336 .id = fixture.vaultKeylet.key,
337 .amount = asset(vaultDeposit),
338 }),
339 Ter(row.ter));
340 env.close();
341
342 if (row.fixedPrecision)
343 {
345 env,
346 fixture.vaultKeylet,
347 {.available = vaultDeposit - principal, .assetsDeployed = principal});
348 }
349 checkVaultLoanSums(env, fixture, {loanKeylet}, "final withdrawal rejected");
350 }
351 }
352
353 // A full clawback of the sole holder's shares does not hit the
354 // tecHAS_OBLIGATIONS guard when the AssetsAvailable shortfall is a whole
355 // number of shares: assetsToClawback clamps to AssetsAvailable, which
356 // truncates below the full share count, so the clawback succeeds and leaves
357 // shares behind.
358 void
360 {
361 using namespace test::jtx;
362
363 testcase(
364 "full-value VaultClawback with a large AssetsDeployed clamps to "
365 "AssetsAvailable instead of tecHAS_OBLIGATIONS");
366
367 Number const vaultDeposit{1'000};
368 std::chrono::seconds const investmentWindow{600};
369 Number const principal{400};
370 constexpr std::uint32_t paymentTotal = 2;
371
372 Env env(*this, features());
373 auto const [issuer, owner, depositor, asset] = setupIou(env, {.clawback = true});
374
375 auto const fixture =
376 setupLendingVault(env, owner, depositor, asset, vaultDeposit, investmentWindow);
377 auto const loanKeylet = openLoan(env, fixture, principal, paymentTotal);
378
379 env.close(fixture.redemptionDate + std::chrono::seconds{1});
380
381 auto const sleBefore = env.le(fixture.vaultKeylet);
382 if (!BEAST_EXPECT(sleBefore))
383 return;
384 Number const assetsDeployed = sleBefore->at(sfAssetsDeployed);
385 BEAST_EXPECT(assetsDeployed == principal);
386 BEAST_EXPECT(Number(sleBefore->at(sfAssetsAvailable)) == vaultDeposit - principal);
387
388 auto const shareMPTID = sleBefore->at(sfShareMPTID);
389 auto const tokenBefore = env.le(keylet::mptoken(shareMPTID, depositor.id()));
390 auto const issuanceBefore = env.le(keylet::mptokenIssuance(shareMPTID));
391 if (!BEAST_EXPECT(tokenBefore) || !BEAST_EXPECT(issuanceBefore))
392 return;
393 std::uint64_t const sharesBefore = tokenBefore->getFieldU64(sfMPTAmount);
394 BEAST_EXPECT(sharesBefore == issuanceBefore->getFieldU64(sfOutstandingAmount));
395
396 env(fixture.vault.clawback(
397 {.issuer = issuer, .id = fixture.vaultKeylet.key, .holder = depositor}),
398 Ter(tesSUCCESS));
399 env.close();
400
401 auto const sleAfter = env.le(fixture.vaultKeylet);
402 if (!BEAST_EXPECT(sleAfter))
403 return;
404 BEAST_EXPECT(Number(sleAfter->at(sfAssetsDeployed)) == assetsDeployed);
405 BEAST_EXPECT(Number(sleAfter->at(sfAssetsAvailable)) == beast::kZero);
406
407 auto const tokenAfter = env.le(keylet::mptoken(shareMPTID, depositor.id()));
408 auto const issuanceAfter = env.le(keylet::mptokenIssuance(shareMPTID));
409 if (!BEAST_EXPECT(tokenAfter) || !BEAST_EXPECT(issuanceAfter))
410 return;
411 std::uint64_t const sharesAfter = tokenAfter->getFieldU64(sfMPTAmount);
412 BEAST_EXPECT(sharesAfter > 0);
413 BEAST_EXPECT(sharesAfter < sharesBefore);
414 BEAST_EXPECT(issuanceAfter->getFieldU64(sfOutstandingAmount) == sharesAfter);
415
417 env, fixture, {loanKeylet}, "full clawback clamps instead of HAS_OBLIGATIONS");
418 }
419
420 void
422 {
423 using namespace test::jtx;
424 using namespace loan;
425
426 testcase(
427 "CashBasis vault never gets an AssetsDeployed field through the same loan "
428 "flow");
429
430 Number const vaultDeposit{1'000};
431 Number const principal{300};
432 constexpr std::uint32_t paymentTotal = 2;
433 // Two equal repayments that together retire the whole principal.
434 Number const repaymentInstallment = principal / 2;
435
436 Env env(*this, features() - featureLendingProtocolV1_2);
437 auto const [issuer, owner, depositor, asset] = setupIou(env);
438
439 auto const fixture = setupLendingVault(env, owner, depositor, asset, vaultDeposit);
440
441 auto const sleAtCreate = env.le(fixture.vaultKeylet);
442 if (!BEAST_EXPECT(sleAtCreate))
443 return;
444 BEAST_EXPECT(sleAtCreate->at(sfLEVersion) == std::to_underlying(VaultVersion::CashBasis));
445 BEAST_EXPECT(!sleAtCreate->isFieldPresent(sfAssetsDeployed));
446
447 auto const loanKeylet = openLoan(env, fixture, principal, paymentTotal);
448
449 auto sle = env.le(fixture.vaultKeylet);
450 if (!BEAST_EXPECT(sle))
451 return;
452 BEAST_EXPECT(!sle->isFieldPresent(sfAssetsDeployed));
453 BEAST_EXPECT(sle->at(sfAssetsAvailable) == vaultDeposit - principal);
454 BEAST_EXPECT(sle->at(sfAssetsTotal) == vaultDeposit);
455
456 env(pay(depositor, loanKeylet.key, asset(repaymentInstallment).value()));
457 env.close();
458 sle = env.le(fixture.vaultKeylet);
459 if (!BEAST_EXPECT(sle))
460 return;
461 BEAST_EXPECT(!sle->isFieldPresent(sfAssetsDeployed));
462
463 env(pay(depositor, loanKeylet.key, asset(repaymentInstallment).value()));
464 env.close();
465 sle = env.le(fixture.vaultKeylet);
466 if (!BEAST_EXPECT(sle))
467 return;
468 BEAST_EXPECT(!sle->isFieldPresent(sfAssetsDeployed));
469 BEAST_EXPECT(sle->at(sfAssetsAvailable) == vaultDeposit);
470 BEAST_EXPECT(sle->at(sfAssetsTotal) == vaultDeposit);
471 }
472
473 void
475 test::jtx::Env& env,
476 LendingFixture const& fixture,
477 Number const& principal,
478 std::string const& label)
479 {
480 using namespace test::jtx;
481 using namespace loan;
482
483 auto const interestRate = percentageToTenthBips(100);
484 constexpr std::uint32_t gracePeriod = 60;
485 constexpr std::uint32_t paymentInterval = 31'536'000; // one year, in seconds
486 constexpr std::uint32_t paymentTotal = 1;
487
488 env(set(fixture.depositor, fixture.brokerKeylet.key, principal),
489 kInterestRate(interestRate),
490 kGracePeriod(gracePeriod),
491 kPaymentInterval(paymentInterval),
492 kPaymentTotal(paymentTotal),
493 Sig(sfCounterpartySignature, fixture.owner),
494 Fee(env.current()->fees().base * 2),
495 Ter(tecLIMIT_EXCEEDED));
496 env.close();
497
498 auto const vaultSle = env.le(fixture.vaultKeylet);
499 if (!BEAST_EXPECT(vaultSle))
500 return;
501 BEAST_EXPECT(getVaultScale(vaultSle) == getVaultBaseScale(vaultSle));
502 BEAST_EXPECT(vaultSle->at(sfAssetsDeployed) == beast::kZero);
503 checkVaultLoanSums(env, fixture, {}, label);
504 }
505
506 void
508 {
509 using namespace test::jtx;
510 using namespace loan_broker;
511
512 struct Row
513 {
514 char const* name = nullptr;
515 Number depositAmount;
516 // Loan principal; the vault's whole AssetsAvailable when unset.
517 std::optional<Number> principal;
518 bool withCover = false;
519 };
520 Row const rows[] = {
521 {
522 .name = "LoanSet rejects coarsening origination: 16-digit deposit",
523 .depositAmount = Number{8999999999999999LL, -10},
524 .principal = // 899999.9999999999
525 Number{800'000},
526 .withCover = false,
527 },
528 {
529 .name = "LoanSet rejects coarsening origination: cover deposited",
530 .depositAmount = Number{899'999},
531 .principal = std::nullopt,
532 .withCover = true,
533 },
534 {
535 .name = "LoanSet rejects coarsening origination: plain",
536 .depositAmount = Number{899'999},
537 .principal = std::nullopt,
538 .withCover = false,
539 },
540 };
541 for (auto const& row : rows)
542 {
543 testcase(row.name);
544
545 Env env(*this, features());
546 auto const [issuer, owner, depositor, asset] = setupIou(
547 env,
548 {
549 .depositorTrust = 3'000'000,
550 .ownerTrust = row.withCover ? 100'000 : 1'000,
551 .depositorFunds = row.depositAmount,
552 .ownerFunds = row.withCover ? std::optional<Number>{90'000} : std::nullopt,
553 });
554
555 std::chrono::seconds const investmentWindow{63'072'000}; // two years
556 std::uint8_t const vaultScale{10};
557 auto const coverRateMinimum =
558 row.withCover ? percentageToTenthBips(10) : TenthBips32(0);
559 auto const coverRateLiquidation =
560 row.withCover ? percentageToTenthBips(50) : TenthBips32(0);
561
562 // With cover, a 10% minimum leaves CoverAvailable to liquidate.
563 auto const fixture = setupLendingVault(
564 env,
565 owner,
566 depositor,
567 asset,
568 row.depositAmount,
569 investmentWindow,
570 vaultScale,
571 coverRateMinimum,
572 coverRateLiquidation);
573
574 auto const vaultSle = env.le(fixture.vaultKeylet);
575 if (!BEAST_EXPECT(vaultSle))
576 return;
577 Number const principal =
578 row.principal.value_or(Number{vaultSle->at(sfAssetsAvailable)});
579
580 if (row.withCover)
581 {
582 // The vault's 10% CoverRateMinimum: cover deposit equals a
583 // tenth of the loan principal.
584 Number const coverDepositAmount = principal / 10;
585 env(coverDeposit(owner, fixture.brokerKeylet.key, asset(coverDepositAmount)));
586 env.close();
587 }
588
589 expectCoarseningLoanRejected(env, fixture, principal, row.name);
590 }
591 }
592
593 // LoanSet transfer legs on a FixedPrecision vault, with and without an
594 // origination fee and with the asset's issuer as borrower or broker owner. An
595 // issuer leg is a no-op transfer, but the vault must still be debited once
596 // per leg.
597 void
599 {
600 using namespace test::jtx;
601 using namespace loan;
602
603 struct Row
604 {
605 char const* name = nullptr;
606 Number originationFee;
607 bool issuerIsBorrower = false;
608 bool issuerIsBrokerOwner = false;
609 };
610 // (i) no fee; (ii) origination fee; (iii) issuer is the borrower; (iv)
611 // issuer is the broker owner. The vault is debited the full principal in
612 // every case.
613 Row const rows[] = {
614 {
615 .name = "LoanSet transfer legs: no fee",
616 .originationFee = Number{0},
617 .issuerIsBorrower = false,
618 .issuerIsBrokerOwner = false,
619 },
620 {
621 .name = "LoanSet transfer legs: with fee",
622 .originationFee = Number{20},
623 .issuerIsBorrower = false,
624 .issuerIsBrokerOwner = false,
625 },
626 {
627 .name = "LoanSet transfer legs: issuer is borrower",
628 .originationFee = Number{0},
629 .issuerIsBorrower = true,
630 .issuerIsBrokerOwner = false,
631 },
632 {
633 .name = "LoanSet transfer legs: issuer is broker owner",
634 .originationFee = Number{20},
635 .issuerIsBorrower = false,
636 .issuerIsBrokerOwner = true,
637 },
638 };
639 Number const vaultDeposit{1'000};
640 Number const principal{300};
641 constexpr std::uint32_t gracePeriod = 60;
642 constexpr std::uint32_t paymentInterval = 120;
643 constexpr std::uint32_t paymentTotal = 2;
644
645 for (auto const& row : rows)
646 {
647 testcase(row.name);
648
649 Env env(*this, features());
650 auto const [issuer, owner, depositor, asset] = setupIou(env);
651 Account const& brokerOwner = row.issuerIsBrokerOwner ? issuer : owner;
652 Account const& borrower = row.issuerIsBorrower ? issuer : depositor;
653
654 auto const fixture =
655 setupLendingVault(env, brokerOwner, depositor, asset, vaultDeposit);
656 auto const before = snapshotVault(env, fixture.vaultKeylet, asset);
657 Number const ownerBalanceBefore = env.balance(brokerOwner, asset).value();
658
659 auto const loanKeylet =
660 keylet::loan(fixture.brokerKeylet.key, SeqProxy::rawSequence(1));
661 auto const submit = [&](auto&&... extra) {
662 env(set(borrower, fixture.brokerKeylet.key, principal),
663 kInterestRate(TenthBips32(0)),
664 kGracePeriod(gracePeriod),
665 kPaymentInterval(paymentInterval),
666 kPaymentTotal(paymentTotal),
667 Sig(sfCounterpartySignature, brokerOwner),
668 Fee(env.current()->fees().base * 2),
669 Ter(tesSUCCESS),
670 extra...);
671 };
672 if (row.originationFee != beast::kZero)
673 {
674 submit(kLoanOriginationFee(row.originationFee));
675 }
676 else
677 {
678 submit();
679 }
680 env.close();
681
682 auto const after = snapshotVault(env, fixture.vaultKeylet, asset);
683 BEAST_EXPECT(before.available - after.available == principal);
684 BEAST_EXPECT(after.available == after.vaultBalance);
685 if (row.originationFee != beast::kZero && !row.issuerIsBrokerOwner)
686 {
687 BEAST_EXPECT(
688 env.balance(brokerOwner, asset).value() - ownerBalanceBefore ==
689 row.originationFee);
690 }
691 checkVaultLoanSums(env, fixture, {loanKeylet}, row.name);
692 }
693 }
694
695 void
697 {
698 using namespace test::jtx;
699
700 testcase("VaultSet AssetsMaximum below the derived total (AA + DT) is refused on FP");
701
702 Number const vaultDeposit{1'000};
703 Number const principal{300};
704 constexpr std::uint32_t paymentTotal = 2;
705
706 Env env(*this, features());
707 auto const [issuer, owner, depositor, asset] = setupIou(env);
708
709 auto const fixture = setupLendingVault(env, owner, depositor, asset, vaultDeposit);
710 auto const loanKeylet = openLoan(env, fixture, principal, paymentTotal);
711
712 auto const vaultSle = env.le(fixture.vaultKeylet);
713 if (!BEAST_EXPECT(vaultSle))
714 return;
715 Number const derivedTotal = getAssetsTotal(vaultSle);
716 BEAST_EXPECT(derivedTotal == vaultDeposit);
717
718 test::jtx::Vault const vault{env};
719 struct Row
720 {
721 Number max;
722 TER ter;
723 };
724 // Below the derived total is refused; at or above it is allowed.
725 Row const rows[] = {
726 {.max = Number{999}, .ter = tecLIMIT_EXCEEDED},
727 {.max = Number{1'000}, .ter = tesSUCCESS},
728 {.max = Number{1'001}, .ter = tesSUCCESS},
729 };
730 for (auto const& row : rows)
731 {
732 auto tx = vault.set({.owner = owner, .id = fixture.vaultKeylet.key});
733 tx[sfAssetsMaximum] = row.max;
734 env(tx, Ter(row.ter));
735 env.close();
736
737 if (row.ter != tesSUCCESS)
738 continue;
739 auto const sle = env.le(fixture.vaultKeylet);
740 if (BEAST_EXPECT(sle))
741 BEAST_EXPECT(Number(sle->at(sfAssetsMaximum)) == row.max);
742 }
743
744 checkVaultLoanSums(env, fixture, {loanKeylet}, "testAssetsMaximumBelowDerivedTotalRefused");
745 }
746
747 void
749 {
750 using namespace test::jtx;
751 using namespace loan;
752
753 testcase(
754 "VaultDelete on FP with AssetsAvailable == 0 and AssetsDeployed > 0 is "
755 "refused");
756
757 Number const vaultDeposit{1'000};
758 // Borrow the whole vault, in a single payment, so AssetsAvailable is
759 // left at 0.
760 Number const principal = vaultDeposit;
761 constexpr std::uint32_t paymentTotal = 1;
762
763 Env env(*this, features());
764 auto const [issuer, owner, depositor, asset] = setupIou(env);
765
766 auto const fixture = setupLendingVault(env, owner, depositor, asset, vaultDeposit);
767 openLoan(env, fixture, principal, paymentTotal);
768
769 auto const vaultSle = env.le(fixture.vaultKeylet);
770 if (!BEAST_EXPECT(vaultSle))
771 return;
772 BEAST_EXPECT(Number(vaultSle->at(sfAssetsAvailable)) == beast::kZero);
773 BEAST_EXPECT(Number(vaultSle->at(sfAssetsDeployed)) == principal);
774
775 test::jtx::Vault const vault{env};
776 env(vault.del({.owner = owner, .id = fixture.vaultKeylet.key}), Ter(tecHAS_OBLIGATIONS));
777 env.close();
778 BEAST_EXPECT(env.le(fixture.vaultKeylet));
779 }
780
781public:
782 void
796};
797
798BEAST_DEFINE_TESTSUITE(LoanSetFixedPrecision, app, xrpl);
799
800} // 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))
void checkVaultLoanSums(test::jtx::Env &env, LendingFixture const &fixture, std::vector< Keylet > const &loanKeylets, std::string const &label={})
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 expectCoarseningLoanRejected(test::jtx::Env &env, LendingFixture const &fixture, Number const &principal, std::string const &label)
Number is a floating point type that can represent a wide range of values.
Definition Number.h:351
static Number max() noexcept
Definition Number.h:823
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)
void checkFixedPrecisionSync(test::jtx::Env const &env, Keylet const &vaultKeylet, Number const &expectedAvailable)
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
std::shared_ptr< OpenView const > current() const
Returns the current ledger.
Definition Env.h:377
constexpr Zero kZero
Definition Zero.h:30
Keylet mptoken(MPTID const &issuanceID, AccountID const &holder) noexcept
Definition Indexes.cpp:547
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 clawbackAmount(SLE::ConstRef vault, std::optional< STAmount > const &maybeAmount, AccountID const &account)
constexpr TenthBips32 percentageToTenthBips(std::uint32_t percentage)
Definition Protocol.h:127
int getVaultScale(SLE::ConstRef vault)
Return the Vault's current live exponent.
TenthBips< std::uint32_t > TenthBips32
Definition Units.h:454
TenthBips< std::uint16_t > TenthBips16
Definition Units.h:453
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.
TERSubset< CanCvtToTER > TER
Definition TER.h:657
@ tecINSUFFICIENT_FUNDS
Definition TER.h:336
@ tecLIMIT_EXCEEDED
Definition TER.h:372
@ tecHAS_OBLIGATIONS
Definition TER.h:328
Number getAssetsTotal(SLE::ConstRef vault)
Return the Vault's current assets total.
BEAST_DEFINE_TESTSUITE(AccountTxPaging, app, xrpl)
@ tesSUCCESS
Definition TER.h:253
T push_back(T... args)
UInt256 key
Definition Keylet.h:21